A buffer class for storing raw bytes with various methods for reading and writing the bytes.
| 43 | // A buffer class for storing raw bytes with various methods for reading and |
| 44 | // writing the bytes. |
| 45 | class Buffer { |
| 46 | public: |
| 47 | Buffer(); |
| 48 | |
| 49 | Buffer(uint8_t *data, uint32_t size, bool own_data = true) |
| 50 | : data_(data), size_(size), own_data_(own_data), wrapped_vector_(nullptr), |
| 51 | input_stream_(nullptr), output_stream_(nullptr) { |
| 52 | writer_index_ = 0; |
| 53 | reader_index_ = 0; |
| 54 | } |
| 55 | |
| 56 | /// Wrap an existing vector for zero-copy serialization. |
| 57 | /// The buffer will append to the vector starting from its current size. |
| 58 | /// After serialization, the vector is resized to writer_index(). |
| 59 | /// |
| 60 | /// @param vec The vector to wrap (must outlive this Buffer). |
| 61 | explicit Buffer(std::vector<uint8_t> &vec) |
| 62 | : data_(vec.data()), size_(static_cast<uint32_t>(vec.size())), |
| 63 | own_data_(false), writer_index_(static_cast<uint32_t>(vec.size())), |
| 64 | reader_index_(0), wrapped_vector_(&vec), input_stream_(nullptr), |
| 65 | output_stream_(nullptr) {} |
| 66 | |
| 67 | explicit Buffer(InputStream &input_stream) |
| 68 | : data_(nullptr), size_(0), own_data_(false), writer_index_(0), |
| 69 | reader_index_(0), wrapped_vector_(nullptr), |
| 70 | input_stream_(&input_stream), output_stream_(nullptr) { |
| 71 | input_stream_->bind_buffer(this); |
| 72 | input_stream_owner_ = input_stream_->weak_from_this().lock(); |
| 73 | FORY_CHECK(&input_stream_->get_buffer() == this) |
| 74 | << "InputStream must hold and return the same Buffer instance"; |
| 75 | } |
| 76 | |
| 77 | Buffer(Buffer &&buffer) noexcept; |
| 78 | |
| 79 | Buffer &operator=(Buffer &&buffer) noexcept; |
| 80 | |
| 81 | virtual ~Buffer(); |
| 82 | |
| 83 | FORY_ALWAYS_INLINE void swap(Buffer &other) noexcept { |
| 84 | if (this == &other) { |
| 85 | return; |
| 86 | } |
| 87 | FORY_CHECK(output_stream_ == nullptr && other.output_stream_ == nullptr) |
| 88 | << "Cannot swap stream-writer-owned Buffer"; |
| 89 | using std::swap; |
| 90 | swap(data_, other.data_); |
| 91 | swap(size_, other.size_); |
| 92 | swap(own_data_, other.own_data_); |
| 93 | swap(writer_index_, other.writer_index_); |
| 94 | swap(reader_index_, other.reader_index_); |
| 95 | swap(wrapped_vector_, other.wrapped_vector_); |
| 96 | swap(input_stream_, other.input_stream_); |
| 97 | swap(input_stream_owner_, other.input_stream_owner_); |
| 98 | swap(output_stream_, other.output_stream_); |
| 99 | rebind_input_stream_to_this(); |
| 100 | other.rebind_input_stream_to_this(); |
| 101 | } |
| 102 |
no outgoing calls