5 // Created by James McIlree on 4/20/13.
6 // Copyright (c) 2013 Apple. All rights reserved.
9 #ifndef __CPPUtil__UtilMemoryBuffer__
10 #define __CPPUtil__UtilMemoryBuffer__
19 MemoryBuffer(const MemoryBuffer& that) = delete;
20 MemoryBuffer& operator=(const MemoryBuffer& other) = delete;
23 // Capacity is in units of T!
25 // MemoryBuffer<char>(1); // 1 byte
26 // MemoryBuffer<uint32_t>(1); // 4 bytes
27 MemoryBuffer() { _data = NULL; _capacity = 0; }
28 MemoryBuffer(size_t capacity);
29 MemoryBuffer(MemoryBuffer&& rhs) noexcept :
31 _capacity(rhs._capacity)
37 ~MemoryBuffer() { if (_data) { free(_data); } }
39 MemoryBuffer& operator=(MemoryBuffer&& rhs) { std::swap(_data, rhs._data); std::swap(_capacity, rhs._capacity); return *this; }
41 T* data() { return _data; }
42 size_t capacity() const { return _capacity; }
43 size_t capacity_in_bytes() const { return _capacity * sizeof(T); }
44 // This always results in an allocation and copy.
45 // If the new capacity is smaller, data is truncated.
46 void set_capacity(size_t capacity);
50 MemoryBuffer<T>::MemoryBuffer(size_t capacity) :
53 _data = capacity ? (T*)malloc(capacity * sizeof(T)) : (T*)NULL;
57 void MemoryBuffer<T>::set_capacity(size_t capacity) {
58 MemoryBuffer<T> newbuf(capacity);
59 memcpy(newbuf.data(), _data, std::min(_capacity * sizeof(T), newbuf.capacity() * sizeof(T)));
60 *this = std::move(newbuf);
63 #endif /* defined(__CPPUtil__UtilMemoryBuffer__) */