| 1 |
#include "utils/string_view.hpp" |
| 2 |
|
| 3 |
#include "utils/error.hpp" |
| 4 |
#include "utils/microfmt.hpp" |
| 5 |
|
| 6 |
#include <algorithm> |
| 7 |
#include <cstring> |
| 8 |
|
| 9 |
CPPTRACE_BEGIN_NAMESPACE |
| 10 |
namespace detail { |
| 11 |
constexpr std::size_t string_view::npos; |
| 12 |
|
| 13 |
char string_view::operator[](size_t i) const { |
| 14 |
ASSERT(i < size()); |
| 15 |
return ptr[i]; |
| 16 |
} |
| 17 |
char string_view::at(size_t i) const { |
| 18 |
if(i >= size()) { |
| 19 |
throw std::runtime_error(microfmt::format("Out of bounds access {} >= {}", i, size())); |
| 20 |
} |
| 21 |
return ptr[i]; |
| 22 |
} |
| 23 |
|
| 24 |
bool string_view::starts_with(string_view str) const { |
| 25 |
return substr(0, str.size()) == str; |
| 26 |
} |
| 27 |
|
| 28 |
bool string_view::ends_with(string_view str) const { |
| 29 |
if(size() < str.size()) { |
| 30 |
return false; |
| 31 |
} |
| 32 |
return substr(size() - str.size(), str.size()) == str; |
| 33 |
} |
| 34 |
|
| 35 |
std::size_t string_view::find_last_of(string_view chars) const { |
| 36 |
if(empty() || chars.empty()) { |
| 37 |
return npos; |
| 38 |
} |
| 39 |
std::size_t pos = size(); |
| 40 |
while(pos-- > 0) { |
| 41 |
if(std::find(chars.begin(), chars.end(), ptr[pos]) != chars.end()) { |
| 42 |
return pos; |
| 43 |
} |
| 44 |
} |
| 45 |
return npos; |
| 46 |
} |
| 47 |
|
| 48 |
bool operator==(string_view a, string_view b) { |
| 49 |
return a.size() == b.size() && std::memcmp(a.data(), b.data(), a.size()) == 0; |
| 50 |
} |
| 51 |
|
| 52 |
constexpr std::size_t cstring_view::npos; |
| 53 |
|
| 54 |
cstring_view cstring_view::substr(std::size_t pos) const { |
| 55 |
ASSERT(pos <= count); |
| 56 |
return {ptr + pos, count - pos}; |
| 57 |
} |
| 58 |
|
| 59 |
void cstring_view::check_null() const { |
| 60 |
ASSERT(ptr[count] == 0); |
| 61 |
} |
| 62 |
} |
| 63 |
CPPTRACE_END_NAMESPACE |