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 ~TemporaryString() = default;
47
48 [[nodiscard]] char* data() { return ptr; }
49 [[nodiscard]] const char* c_str() const { return ptr; }
50
51 [[nodiscard]] operator std::string_view() const { return {ptr, n}; }
52 [[nodiscard]] operator zstring_view() const { return {ptr, n}; }
53
54private:
55 size_t n;
56 char* ptr;
57 StringStorage owner;
58 std::array<char, BUFSIZE + 1> buffer;
59};
60
61inline std::ostream& operator<<(std::ostream& os, const TemporaryString& str)
62{
63 os << std::string_view(str);
64 return os;
65}
66
67#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)
~TemporaryString()=default
Like std::string_view, but with the extra guarantee that it refers to a zero-terminated string.