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 <array>
7#include <concepts>
8#include <iostream>
9#include <string_view>
10
11
27public:
28 static constexpr size_t BUFSIZE = 127;
29
30 TemporaryString(size_t n_, std::invocable<char*> auto fillOp)
31 : n(n_)
32 {
33 if (n <= BUFSIZE) {
34 ptr = buffer.data();
35 } else {
36 owner = allocate_string_storage(n + 1);
37 ptr = owner.get();
38 }
39 fillOp(ptr);
40 ptr[n] = '\0';
41 }
46
47 [[nodiscard]] char* data() { return ptr; }
48 [[nodiscard]] const char* c_str() const { return ptr; }
49
50 [[nodiscard]] operator std::string_view() const { return {ptr, n}; }
51 [[nodiscard]] operator zstring_view() const { return {ptr, n}; }
52
53private:
54 size_t n;
55 char* ptr;
56 StringStorage owner;
57 std::array<char, BUFSIZE + 1> buffer;
58};
59
60inline std::ostream& operator<<(std::ostream& os, const TemporaryString& str)
61{
62 os << std::string_view(str);
63 return os;
64}
65
66#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.
static constexpr size_t BUFSIZE
TemporaryString & operator=(TemporaryString &&)=delete
const char * c_str() const
TemporaryString(TemporaryString &&)=delete
TemporaryString(const TemporaryString &)=delete
TemporaryString & operator=(const TemporaryString &)=delete
TemporaryString(size_t n_, std::invocable< char * > auto fillOp)
Like std::string_view, but with the extra guarantee that it refers to a zero-terminated string.