| 1 | //===----------------------------------------------------------------------===// |
| 2 | // DuckDB |
| 3 | // |
| 4 | // duckdb/common/arrow/arrow_buffer.hpp |
| 5 | // |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #pragma once |
| 10 | |
| 11 | #include "duckdb/common/common.hpp" |
| 12 | |
| 13 | struct ArrowSchema; |
| 14 | |
| 15 | namespace duckdb { |
| 16 | |
| 17 | struct ArrowBuffer { |
| 18 | static constexpr const idx_t MINIMUM_SHRINK_SIZE = 4096; |
| 19 | |
| 20 | ArrowBuffer() : dataptr(nullptr), count(0), capacity(0) { |
| 21 | } |
| 22 | ~ArrowBuffer() { |
| 23 | if (!dataptr) { |
| 24 | return; |
| 25 | } |
| 26 | free(ptr: dataptr); |
| 27 | dataptr = nullptr; |
| 28 | count = 0; |
| 29 | capacity = 0; |
| 30 | } |
| 31 | // disable copy constructors |
| 32 | ArrowBuffer(const ArrowBuffer &other) = delete; |
| 33 | ArrowBuffer &operator=(const ArrowBuffer &) = delete; |
| 34 | //! enable move constructors |
| 35 | ArrowBuffer(ArrowBuffer &&other) noexcept { |
| 36 | std::swap(a&: dataptr, b&: other.dataptr); |
| 37 | std::swap(a&: count, b&: other.count); |
| 38 | std::swap(a&: capacity, b&: other.capacity); |
| 39 | } |
| 40 | ArrowBuffer &operator=(ArrowBuffer &&other) noexcept { |
| 41 | std::swap(a&: dataptr, b&: other.dataptr); |
| 42 | std::swap(a&: count, b&: other.count); |
| 43 | std::swap(a&: capacity, b&: other.capacity); |
| 44 | return *this; |
| 45 | } |
| 46 | |
| 47 | void reserve(idx_t bytes) { // NOLINT |
| 48 | auto new_capacity = NextPowerOfTwo(v: bytes); |
| 49 | if (new_capacity <= capacity) { |
| 50 | return; |
| 51 | } |
| 52 | ReserveInternal(bytes: new_capacity); |
| 53 | } |
| 54 | |
| 55 | void resize(idx_t bytes) { // NOLINT |
| 56 | reserve(bytes); |
| 57 | count = bytes; |
| 58 | } |
| 59 | |
| 60 | void resize(idx_t bytes, data_t value) { // NOLINT |
| 61 | reserve(bytes); |
| 62 | for (idx_t i = count; i < bytes; i++) { |
| 63 | dataptr[i] = value; |
| 64 | } |
| 65 | count = bytes; |
| 66 | } |
| 67 | |
| 68 | idx_t size() { // NOLINT |
| 69 | return count; |
| 70 | } |
| 71 | |
| 72 | data_ptr_t data() { // NOLINT |
| 73 | return dataptr; |
| 74 | } |
| 75 | |
| 76 | template <class T> |
| 77 | T *GetData() { |
| 78 | return reinterpret_cast<T *>(data()); |
| 79 | } |
| 80 | |
| 81 | private: |
| 82 | void ReserveInternal(idx_t bytes) { |
| 83 | if (dataptr) { |
| 84 | dataptr = data_ptr_cast(src: realloc(ptr: dataptr, size: bytes)); |
| 85 | } else { |
| 86 | dataptr = data_ptr_cast(src: malloc(size: bytes)); |
| 87 | } |
| 88 | capacity = bytes; |
| 89 | } |
| 90 | |
| 91 | private: |
| 92 | data_ptr_t dataptr = nullptr; |
| 93 | idx_t count = 0; |
| 94 | idx_t capacity = 0; |
| 95 | }; |
| 96 | |
| 97 | } // namespace duckdb |
| 98 | |