2023-03-06 14:42:04 +01:00
|
|
|
// SPDX-License-Identifier: BSD-2-Clause
|
|
|
|
// author: Max Kellermann <max.kellermann@gmail.com>
|
2017-07-05 17:20:02 +02:00
|
|
|
|
|
|
|
#include "StringStrip.hxx"
|
|
|
|
#include "CharUtil.hxx"
|
|
|
|
|
2022-06-30 17:43:12 +02:00
|
|
|
#include <algorithm>
|
2020-10-15 12:53:43 +02:00
|
|
|
#include <cstring>
|
2017-07-05 17:20:02 +02:00
|
|
|
|
|
|
|
const char *
|
|
|
|
StripLeft(const char *p) noexcept
|
|
|
|
{
|
|
|
|
while (IsWhitespaceNotNull(*p))
|
|
|
|
++p;
|
|
|
|
|
|
|
|
return p;
|
|
|
|
}
|
|
|
|
|
|
|
|
const char *
|
|
|
|
StripLeft(const char *p, const char *end) noexcept
|
|
|
|
{
|
|
|
|
while (p < end && IsWhitespaceOrNull(*p))
|
|
|
|
++p;
|
|
|
|
|
|
|
|
return p;
|
|
|
|
}
|
|
|
|
|
2022-06-30 17:43:12 +02:00
|
|
|
std::string_view
|
|
|
|
StripLeft(const std::string_view s) noexcept
|
|
|
|
{
|
|
|
|
auto i = std::find_if_not(s.begin(), s.end(),
|
|
|
|
[](auto ch){ return IsWhitespaceOrNull(ch); });
|
|
|
|
|
2022-07-01 10:45:35 +02:00
|
|
|
#ifdef __clang__
|
|
|
|
// libc++ doesn't yet support the C++20 constructor
|
|
|
|
return s.substr(std::distance(s.begin(), i));
|
|
|
|
#else
|
2022-06-30 17:43:12 +02:00
|
|
|
return {
|
|
|
|
i,
|
|
|
|
s.end(),
|
|
|
|
};
|
2022-07-01 10:45:35 +02:00
|
|
|
#endif
|
2022-06-30 17:43:12 +02:00
|
|
|
}
|
|
|
|
|
2017-07-05 17:20:02 +02:00
|
|
|
const char *
|
|
|
|
StripRight(const char *p, const char *end) noexcept
|
|
|
|
{
|
|
|
|
while (end > p && IsWhitespaceOrNull(end[-1]))
|
|
|
|
--end;
|
|
|
|
|
|
|
|
return end;
|
|
|
|
}
|
|
|
|
|
2020-10-15 12:52:44 +02:00
|
|
|
std::size_t
|
|
|
|
StripRight(const char *p, std::size_t length) noexcept
|
2017-07-05 17:20:02 +02:00
|
|
|
{
|
|
|
|
while (length > 0 && IsWhitespaceOrNull(p[length - 1]))
|
|
|
|
--length;
|
|
|
|
|
|
|
|
return length;
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
StripRight(char *p) noexcept
|
|
|
|
{
|
2020-10-15 12:53:43 +02:00
|
|
|
std::size_t old_length = std::strlen(p);
|
2020-10-15 12:52:44 +02:00
|
|
|
std::size_t new_length = StripRight(p, old_length);
|
2017-07-05 17:20:02 +02:00
|
|
|
p[new_length] = 0;
|
|
|
|
}
|
|
|
|
|
2022-06-30 17:43:12 +02:00
|
|
|
std::string_view
|
|
|
|
StripRight(std::string_view s) noexcept
|
|
|
|
{
|
|
|
|
auto i = std::find_if_not(s.rbegin(), s.rend(),
|
|
|
|
[](auto ch){ return IsWhitespaceOrNull(ch); });
|
|
|
|
|
|
|
|
return s.substr(0, std::distance(i, s.rend()));
|
|
|
|
}
|
|
|
|
|
2017-07-05 17:20:02 +02:00
|
|
|
char *
|
|
|
|
Strip(char *p) noexcept
|
|
|
|
{
|
|
|
|
p = StripLeft(p);
|
|
|
|
StripRight(p);
|
|
|
|
return p;
|
|
|
|
}
|
2022-06-30 17:43:12 +02:00
|
|
|
|
|
|
|
std::string_view
|
|
|
|
Strip(std::string_view s) noexcept
|
|
|
|
{
|
|
|
|
return StripRight(StripLeft(s));
|
|
|
|
}
|