From 0c391fdbce5a079cf03e483eb6174dd47806163d Mon Sep 17 00:00:00 2001 From: chai Date: Wed, 7 Aug 2019 21:08:47 +0800 Subject: *misc --- .../modules/asura-base/FileSystem/DataBuffer.cpp | 156 +++++++++++++++++++++ 1 file changed, 156 insertions(+) create mode 100644 Source/modules/asura-base/FileSystem/DataBuffer.cpp (limited to 'Source/modules/asura-base/FileSystem/DataBuffer.cpp') diff --git a/Source/modules/asura-base/FileSystem/DataBuffer.cpp b/Source/modules/asura-base/FileSystem/DataBuffer.cpp new file mode 100644 index 0000000..71431e1 --- /dev/null +++ b/Source/modules/asura-base/FileSystem/DataBuffer.cpp @@ -0,0 +1,156 @@ +#include +#include +#include "DataBuffer.h" + +using namespace AEThreading; + +namespace AsuraEngine +{ + namespace FileSystem + { + + DataBuffer::DataBuffer(DataBuffer& src) + : m_Size(0) + , m_Capacity(0) + , m_Bytes(nullptr) + { + // 初始化容量 + lock(m_Mutex) + { + m_Capacity = src.m_Size; + m_Bytes = new byte[m_Capacity]; + Clear(); + + Load(src); + } + } + + DataBuffer::DataBuffer(std::size_t capacity) + : m_Size(0) + , m_Capacity(0) + , m_Bytes(nullptr) + { + lock(m_Mutex) + { + m_Capacity = capacity; + m_Bytes = new byte[m_Capacity]; + Clear(); + } + } + + DataBuffer::DataBuffer(const void* data, std::size_t size) + : m_Capacity(0) + , m_Size(0) + , m_Bytes(nullptr) + { + lock(m_Mutex) + { + m_Capacity = size; + m_Bytes = new byte[m_Capacity]; + Clear(); + + Load(data, size); + } + } + + DataBuffer::~DataBuffer() + { + lock(m_Mutex) + { + delete[] m_Bytes; + } + } + + void DataBuffer::Refactor(size_t capacity) + { + lock(m_Mutex) + { + if (!m_Bytes || m_Capacity != capacity) + { + if(m_Bytes) + delete[] m_Bytes; + m_Capacity = capacity; + m_Bytes = new byte[m_Capacity]; + m_Size = 0; + } + Clear(); + } + } + + void DataBuffer::Load(DataBuffer& db) + { + lock(m_Mutex) + { + Load(db.GetData(), db.GetSize()); + } + } + + void DataBuffer::Load(const void* data, std::size_t size) + { + lock(m_Mutex) + { + ASSERT(m_Capacity >= size); + memcpy(m_Bytes, data, size); + m_Size = size; + } + } + + void DataBuffer::Move(void* bytes, std::size_t size) + { + lock(m_Mutex) + { + if (m_Bytes == bytes) + { + // 如果是自身,代表更新size值,在读文件时会这样 + m_Size = size; + } + else + { + if (m_Bytes) + delete[] m_Bytes; + m_Bytes = (byte*)bytes; + m_Size = size; + m_Capacity = size; + } + } + } + + byte* DataBuffer::GetData() + { + return m_Bytes; + } + + void DataBuffer::Clear() + { + lock(m_Mutex) + { + if (m_Bytes) + { + memset(m_Bytes, 0, m_Size); + m_Size = 0; + } + } + } + + std::size_t DataBuffer::GetSize() + { + return m_Size; + } + + std::size_t DataBuffer::GetCapacity() + { + return m_Capacity; + } + + void DataBuffer::Lock() + { + m_Mutex.Lock(); + } + + void DataBuffer::Unlock() + { + m_Mutex.Unlock(); + } + + } +} \ No newline at end of file -- cgit v1.1-26-g67d0