openMSX
TemporaryString.hh
Go to the documentation of this file.
1 #ifndef TEMPORARYSTRING_HH
2 #define TEMPORARYSTRING_HH
3 
4 #include "StringStorage.hh"
5 #include "zstring_view.hh"
6 #include <iostream>
7 #include <string_view>
8 
9 
25 public:
26  static constexpr size_t BUFSIZE = 127;
27 
28  template<typename FillOp>
29  TemporaryString(size_t n_, FillOp op)
30  : n(n_)
31  {
32  if (n <= BUFSIZE) {
33  ptr = buffer;
34  } else {
35  owner = allocate_string_storage(n + 1);
36  ptr = owner.get();
37  }
38  op(ptr);
39  ptr[n] = '\0';
40  }
41  TemporaryString(const TemporaryString&) = delete;
45 
46  [[nodiscard]] char* data() { return ptr; }
47  [[nodiscard]] const char* c_str() const { return ptr; }
48 
49  [[nodiscard]] operator std::string_view() const { return {ptr, n}; }
50  [[nodiscard]] operator zstring_view() const { return {ptr, n}; }
51 
52 private:
53  size_t n;
54  char* ptr;
55  StringStorage owner;
56  char buffer[BUFSIZE + 1];
57 };
58 
59 inline std::ostream& operator<<(std::ostream& os, const TemporaryString& str)
60 {
61  os << std::string_view(str);
62  return os;
63 }
64 
65 #endif
std::unique_ptr< char, FreeStringStorage > StringStorage
StringStorage allocate_string_storage(size_t size)
Allocate a 'StringStorage' large enough for 'size' characters.
std::ostream & operator<<(std::ostream &os, const TemporaryString &str)
TemporaryString.
const char * c_str() const
static constexpr size_t BUFSIZE
TemporaryString(TemporaryString &&)=delete
TemporaryString & operator=(TemporaryString &&)=delete
TemporaryString(size_t n_, FillOp op)
TemporaryString(const TemporaryString &)=delete
TemporaryString & operator=(const TemporaryString &)=delete
Like std::string_view, but with the extra guarantee that it refers to a zero-terminated string.
Definition: zstring_view.hh:22