-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstring.hpp
More file actions
68 lines (58 loc) · 2.52 KB
/
string.hpp
File metadata and controls
68 lines (58 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#ifndef POLYNET_STRING_HPP_
#define POLYNET_STRING_HPP_
#include <memory>
#include <stddef.h>
#include <string>
#include <string_view>
#include <type_traits>
namespace pn {
// A derivative of std::basic_string_view that is always null-terminated
template <typename CharT, typename Traits = std::char_traits<CharT>>
class BasicStringView : public std::basic_string_view<CharT, Traits> {
protected:
static constexpr const CharT* empty_string() {
static_assert(
std::is_same_v<CharT, char> ||
std::is_same_v<CharT, wchar_t> ||
std::is_same_v<CharT, char16_t> ||
std::is_same_v<CharT, char32_t>,
"CharT must be char, wchar_t, char16_t, or char32_t");
if constexpr (std::is_same_v<CharT, char>) {
return "";
} else if constexpr (std::is_same_v<CharT, wchar_t>) {
return L"";
} else if constexpr (std::is_same_v<CharT, char16_t>) {
return u"";
} else if constexpr (std::is_same_v<CharT, char32_t>) {
return U"";
}
return nullptr;
}
public:
constexpr BasicStringView(const CharT* str = empty_string()):
std::basic_string_view<CharT, Traits>(str) {}
BasicStringView(decltype(nullptr)) = delete;
template <typename Alloc>
constexpr BasicStringView(const std::basic_string<CharT, Traits, Alloc>& str):
std::basic_string_view<CharT, Traits>(str.c_str(), str.size()) {}
constexpr const CharT* c_str() const noexcept {
return this->data();
}
constexpr std::basic_string_view<CharT, Traits> substr(size_t pos = 0) const {
return std::basic_string_view<CharT, Traits>::substr(pos);
}
template <typename Alloc = std::allocator<CharT>>
constexpr std::basic_string<CharT, Traits, Alloc> substr(size_t pos, size_t count) const {
auto ret = std::basic_string_view<CharT, Traits>::substr(pos, count);
return std::basic_string<CharT, Traits, Alloc>(ret.begin(), ret.end());
}
private:
// This function destroys the guarantee of null-termination
using std::basic_string_view<CharT, Traits>::remove_suffix;
};
using StringView = BasicStringView<char>;
using WStringView = BasicStringView<wchar_t>;
using U16StringView = BasicStringView<char16_t>;
using U32StringView = BasicStringView<char32_t>;
} // namespace pn
#endif