]> git.saurik.com Git - apple/system_cmds.git/blob - CPPUtil/UtilMemoryBuffer.hpp
1bac915215532ac4ee8fe9e6413db093d675ac05
[apple/system_cmds.git] / CPPUtil / UtilMemoryBuffer.hpp
1 //
2 // UtilMemoryBuffer.h
3 // CPPUtil
4 //
5 // Created by James McIlree on 4/20/13.
6 // Copyright (c) 2013 Apple. All rights reserved.
7 //
8
9 #ifndef __CPPUtil__UtilMemoryBuffer__
10 #define __CPPUtil__UtilMemoryBuffer__
11
12 template <typename T>
13 class MemoryBuffer {
14 protected:
15 T* _data;
16 size_t _capacity;
17
18 // No copying?
19 MemoryBuffer(const MemoryBuffer& that) = delete;
20 MemoryBuffer& operator=(const MemoryBuffer& other) = delete;
21
22 public:
23 // Capacity is in units of T!
24 //
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 :
30 _data(rhs._data),
31 _capacity(rhs._capacity)
32 {
33 rhs._data = NULL;
34 rhs._capacity = 0;
35 }
36
37 ~MemoryBuffer() { if (_data) { free(_data); } }
38
39 MemoryBuffer& operator=(MemoryBuffer&& rhs) { std::swap(_data, rhs._data); std::swap(_capacity, rhs._capacity); return *this; }
40
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);
47 };
48
49 template <typename T>
50 MemoryBuffer<T>::MemoryBuffer(size_t capacity) :
51 _capacity(capacity)
52 {
53 _data = capacity ? (T*)malloc(capacity * sizeof(T)) : (T*)NULL;
54 }
55
56 template <typename T>
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);
61 }
62
63 #endif /* defined(__CPPUtil__UtilMemoryBuffer__) */