openMSX
static_string_view.hh
Go to the documentation of this file.
1#ifndef STATIC_STRING_VIEW_HH
2#define STATIC_STRING_VIEW_HH
3
4#include "ranges.hh"
5#include "StringStorage.hh"
6#include <cassert>
7#include <string_view>
8#include <utility>
9
28{
29public:
30 // Disallow construction from non-const char array.
31 template<size_t N>
32 constexpr static_string_view(char (&buf)[N]) = delete;
33
34 // Construct from string-literal (a const char array).
35 template<size_t N>
36 constexpr static_string_view(const char (&buf)[N])
37 : s(buf, N-1)
38 {
39 assert(buf[N - 1] == '\0');
40 }
41
42 // Used by make_string_storage().
43 struct lifetime_ok_tag {};
44 constexpr static_string_view(lifetime_ok_tag, std::string_view v)
45 : s(v) {}
46
47 // Allow (implicit) conversion to std::string_view.
48 constexpr operator std::string_view() const { return s; }
49
50private:
51 std::string_view s;
52};
53
63inline auto make_string_storage(std::string_view sv)
64{
65 auto storage = allocate_string_storage(sv.size());
66 char* p = storage.get();
67 ranges::copy(sv, p);
68 return std::pair{std::move(storage),
70 std::string_view(p, sv.size()))};
71}
72
73#endif
StringStorage allocate_string_storage(size_t size)
Allocate a 'StringStorage' large enough for 'size' characters.
static_string_view
constexpr static_string_view(lifetime_ok_tag, std::string_view v)
constexpr static_string_view(const char(&buf)[N])
constexpr static_string_view(char(&buf)[N])=delete
constexpr auto copy(InputRange &&range, OutputIter out)
Definition ranges.hh:252
auto make_string_storage(std::string_view sv)
Take a string_view, make a copy of it, and return a pair of.