| 172 | /// \return a new Buffer instance |
| 173 | template <typename T, typename Func = DefaultGetData> |
| 174 | static auto TakeOwnership(T container, int64_t nbytes, Func&& get_data = {}) { |
| 175 | using DataPtr = decltype(std::forward<Func>(get_data)(container)); |
| 176 | constexpr bool kIsMutable = !std::is_const_v<std::remove_pointer_t<DataPtr>>; |
| 177 | using BufferType = std::conditional_t<kIsMutable, MutableBuffer, Buffer>; |
| 178 | using Byte = std::conditional_t<kIsMutable, uint8_t, const uint8_t>; |
| 179 | |
| 180 | // Hold the container and the Buffer in a single allocation. Declaration order |
| 181 | // matters: the container is constructed first and destroyed last, so the Buffer |
| 182 | // never outlives the memory it points into. |
| 183 | struct ControlBlock { |
| 184 | T container; |
| 185 | BufferType buffer; |
| 186 | |
| 187 | ControlBlock(T container, int64_t nbytes, Func&& get_data) |
| 188 | : container(std::move(container)), |
| 189 | // Read the data pointer only once the container has reached its final |
| 190 | // address, since moving it may invalidate the pointer (e.g. in a small |
| 191 | // string optimization). |
| 192 | buffer(reinterpret_cast<Byte*>(std::forward<Func>(get_data)(this->container)), |
| 193 | nbytes) {} |
| 194 | }; |
| 195 | |
| 196 | auto owner = std::make_shared<ControlBlock>(std::move(container), nbytes, |
| 197 | std::forward<Func>(get_data)); |
| 198 | // Aliasing constructor |
| 199 | auto* buffer = &owner->buffer; |
| 200 | return std::shared_ptr<BufferType>{std::move(owner), buffer}; |
| 201 | } |
| 202 | |
| 203 | /// \brief Construct a mutable buffer that takes ownership of the contents |
| 204 | /// of an std::string (without copying it). |
no outgoing calls
no test coverage detected