Commit 6df06185213fad16f6a758014acd0ecd7b1cc751
1 parent
9ff713f4
Add `Buffer::move()` to transfer ownership of buffer content
Refactor `Buffer`: implement `move()` method to enable efficient transfer of content to a string, leaving the buffer empty. Include unit tests for `move()` functionality to ensure correctness. Remove redundant `#include <cstring>` for cleanup.
Showing
3 changed files
with
25 additions
and
2 deletions
include/qpdf/Buffer.hh
| ... | ... | @@ -66,6 +66,11 @@ class Buffer |
| 66 | 66 | QPDF_DLL |
| 67 | 67 | Buffer copy() const; |
| 68 | 68 | |
| 69 | + // Move the content of the Buffer. After calling this method, the Buffer will be empty if the | |
| 70 | + // buffer owns its memory. Otherwise, the Buffer will be unchanged. | |
| 71 | + QPDF_DLL | |
| 72 | + std::string move(); | |
| 73 | + | |
| 69 | 74 | private: |
| 70 | 75 | class Members; |
| 71 | 76 | ... | ... |
libqpdf/Buffer.cc
| ... | ... | @@ -2,8 +2,6 @@ |
| 2 | 2 | |
| 3 | 3 | #include <qpdf/Buffer.hh> |
| 4 | 4 | |
| 5 | -#include <cstring> | |
| 6 | - | |
| 7 | 5 | class Buffer::Members |
| 8 | 6 | { |
| 9 | 7 | friend class Buffer; |
| ... | ... | @@ -96,3 +94,17 @@ Buffer::copy() const |
| 96 | 94 | } |
| 97 | 95 | return {std::string(m->buf, m->size)}; |
| 98 | 96 | } |
| 97 | + | |
| 98 | +std::string | |
| 99 | +Buffer::move() | |
| 100 | +{ | |
| 101 | + if (m->size == 0) { | |
| 102 | + return {}; | |
| 103 | + } | |
| 104 | + if (!m->str.empty()) { | |
| 105 | + m->size = 0; | |
| 106 | + m->buf = nullptr; | |
| 107 | + return std::move(m->str); | |
| 108 | + } | |
| 109 | + return {m->buf, m->size}; | |
| 110 | +} | ... | ... |
libtests/buffer.cc
| ... | ... | @@ -35,6 +35,12 @@ main() |
| 35 | 35 | assert(bc2p[0] == 'R'); |
| 36 | 36 | assert(bc2p[1] == 'W'); |
| 37 | 37 | |
| 38 | + // Test move method | |
| 39 | + auto s1 = bc1.move(); | |
| 40 | + assert(bc1.getBuffer() == nullptr); | |
| 41 | + assert(bc1.getSize() == 0); | |
| 42 | + assert(s1 == "RW"); | |
| 43 | + | |
| 38 | 44 | // Test Buffer(std:string&&) |
| 39 | 45 | Buffer bc3("QW"); |
| 40 | 46 | unsigned char* bc3p = bc3.getBuffer(); | ... | ... |