diff options
Diffstat (limited to 'source/core/slang-blob.h')
| -rw-r--r-- | source/core/slang-blob.h | 88 |
1 files changed, 77 insertions, 11 deletions
diff --git a/source/core/slang-blob.h b/source/core/slang-blob.h index aab131a36..8bf02512d 100644 --- a/source/core/slang-blob.h +++ b/source/core/slang-blob.h @@ -69,30 +69,96 @@ protected: void operator=(const ThisType& rhs) = delete; }; + +class ScopedAllocation +{ +public: + typedef ScopedAllocation ThisType; + // Returns the allocation if successful. + void* allocate(size_t size) + { + deallocate(); + m_data = ::malloc(size); + m_sizeInBytes = size; + return m_data; + } + /// Deallocates if holds an allocation + void deallocate() + { + if (m_data) + { + ::free(m_data); + m_data = nullptr; + } + m_sizeInBytes = 0; + } + /// Makes this no longer own the allocation. Returns the allocated data (or nullptr if no allocation) + void* detach() + { + void* data = m_data; + m_data = nullptr; + m_sizeInBytes = 0; + return data; + } + /// Attach some data. + /// NOTE! data must be a pointer that was returned from malloc, otherwise will incorrectly free. + void attach(void* data, size_t size) + { + deallocate(); + m_data = data; + m_sizeInBytes = size; + } + + /// Get the allocated data. Returns nullptr if there is no allocated data + void* getData() const { return m_data; } + /// Get the size of the allocated data. + size_t getSizeInBytes() const { return m_sizeInBytes; } + + ScopedAllocation() : + m_data(nullptr), + m_sizeInBytes(0) + { + } + +private: + // disable + ScopedAllocation(const ThisType& rhs) = delete; + void operator=(const ThisType& rhs) = delete; + + void* m_data; + size_t m_sizeInBytes; +}; + /** A blob that manages some raw data that it owns. */ class RawBlob : public BlobBase { public: // ISlangBlob - SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() SLANG_OVERRIDE { return m_data; } - SLANG_NO_THROW size_t SLANG_MCALL getBufferSize() SLANG_OVERRIDE { return m_size; } + SLANG_NO_THROW void const* SLANG_MCALL getBufferPointer() SLANG_OVERRIDE { return m_data.getData(); } + SLANG_NO_THROW size_t SLANG_MCALL getBufferSize() SLANG_OVERRIDE { return m_data.getSizeInBytes(); } - // Ctor - RawBlob(const void* data, size_t size) : - m_size(size) + // Ctor + // NOTE! Takes a copy of the input data + RawBlob(const void* data, size_t size) { - m_data = malloc(size); - memcpy(m_data, data, size); + memcpy(m_data.allocate(size), data, size); } - ~RawBlob() + + /// Moves ownership of data and dataCount to the blob + /// data must be a pointer returned by ::malloc. + static RefPtr<RawBlob> moveCreate(uint8_t* data, size_t dataCount) { - free(m_data); + RawBlob* blob = new RawBlob; + blob->m_data.attach(data, dataCount); + return blob; } protected: - void* m_data; - size_t m_size; + RawBlob() = default; + + ScopedAllocation m_data; + }; /// Create a blob that will retain (a copy of) raw data. |
