|
2 | 2 | #include <numeric>
|
3 | 3 |
|
4 | 4 | // Helper class - lets us move the buffer out of a String
|
5 |
| -class ReleasableString : public String { |
6 |
| - public: |
7 |
| - // Inherit constructors |
8 |
| - using String::String; |
9 |
| - ReleasableString(String&& s) : String(std::move(s)) {}; |
10 |
| - |
11 |
| - // Special feature: releease the buffer to the caller without deallocating |
12 |
| - char* release() { |
13 |
| - if (isSSO()) return nullptr; |
14 |
| - auto result = wbuffer(); |
15 |
| - init(); |
16 |
| - return result; |
17 |
| - } |
18 |
| -}; |
| 5 | +namespace { |
| 6 | + class DynamicBufferString : public String { |
| 7 | + public: |
| 8 | + // Inherit constructors |
| 9 | + using String::String; |
| 10 | + DynamicBufferString(String&& s) : String(std::move(s)) {}; |
| 11 | + DynamicBufferString(DynamicBuffer&& d) : String() { |
| 12 | + setSSO(false); |
| 13 | + setCapacity(d.size() - 1); |
| 14 | + setBuffer(d.release()); |
| 15 | + setLen(strlen(ptr.buff)); |
| 16 | + } |
| 17 | + |
| 18 | + // Special feature: releease the buffer to the caller without deallocating |
| 19 | + char* release() { |
| 20 | + if (isSSO()) return nullptr; |
| 21 | + auto result = wbuffer(); |
| 22 | + init(); |
| 23 | + return result; |
| 24 | + } |
| 25 | + }; |
| 26 | +} |
19 | 27 |
|
20 | 28 | DynamicBuffer::DynamicBuffer(String&& s) : _data(nullptr), _len(s.length()) {
|
21 |
| - auto rb = ReleasableString(std::move(s)); |
| 29 | + auto rb = DynamicBufferString(std::move(s)); |
22 | 30 | _data = rb.release();
|
23 | 31 | if (!_data) {
|
24 | 32 | *this = DynamicBuffer(rb); // use const-ref constructor to copy string
|
25 | 33 | }
|
26 | 34 | }
|
27 | 35 |
|
| 36 | +String toString(DynamicBuffer buf) { |
| 37 | + auto dbstr = DynamicBufferString(std::move(buf)); |
| 38 | + return std::move(*static_cast<String*>(&dbstr)); // Move-construct the result string from dbstr |
| 39 | +} |
| 40 | + |
28 | 41 | template<typename list_type>
|
29 | 42 | static inline list_type allocateList(size_t total, size_t max_buffer_size) {
|
30 | 43 | list_type buffers;
|
|
0 commit comments