diff options
author | Igor Pavlov <87184205+ip7z@users.noreply.github.com> | 2021-12-27 00:00:00 +0000 |
---|---|---|
committer | Igor Pavlov <87184205+ip7z@users.noreply.github.com> | 2022-03-18 15:35:13 +0500 |
commit | f19f813537c7aea1c20749c914e756b54a9c3cf5 (patch) | |
tree | 816ba62ca7c0fa19f2eb46d9e9d6f7dd7c3a744d /CPP/Common/DynamicBuffer.h | |
parent | 98e06a519b63b81986abe76d28887f6984a7732b (diff) | |
download | 7zip-21.07.tar.gz 7zip-21.07.tar.bz2 7zip-21.07.zip |
'21.07'21.07
Diffstat (limited to '')
-rw-r--r-- | CPP/Common/DynamicBuffer.h | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/CPP/Common/DynamicBuffer.h b/CPP/Common/DynamicBuffer.h new file mode 100644 index 0000000..f6f6b15 --- /dev/null +++ b/CPP/Common/DynamicBuffer.h | |||
@@ -0,0 +1,64 @@ | |||
1 | // Common/DynamicBuffer.h | ||
2 | |||
3 | #ifndef __COMMON_DYNAMIC_BUFFER_H | ||
4 | #define __COMMON_DYNAMIC_BUFFER_H | ||
5 | |||
6 | template <class T> class CDynamicBuffer | ||
7 | { | ||
8 | T *_items; | ||
9 | size_t _size; | ||
10 | size_t _pos; | ||
11 | |||
12 | CDynamicBuffer(const CDynamicBuffer &buffer); | ||
13 | void operator=(const CDynamicBuffer &buffer); | ||
14 | |||
15 | void Grow(size_t size) | ||
16 | { | ||
17 | size_t delta = _size >= 64 ? _size : 64; | ||
18 | if (delta < size) | ||
19 | delta = size; | ||
20 | size_t newCap = _size + delta; | ||
21 | if (newCap < delta) | ||
22 | { | ||
23 | newCap = _size + size; | ||
24 | if (newCap < size) | ||
25 | throw 20120116; | ||
26 | } | ||
27 | |||
28 | T *newBuffer = new T[newCap]; | ||
29 | if (_pos != 0) | ||
30 | memcpy(newBuffer, _items, _pos * sizeof(T)); | ||
31 | delete []_items; | ||
32 | _items = newBuffer; | ||
33 | _size = newCap; | ||
34 | } | ||
35 | |||
36 | public: | ||
37 | CDynamicBuffer(): _items(0), _size(0), _pos(0) {} | ||
38 | // operator T *() { return _items; } | ||
39 | operator const T *() const { return _items; } | ||
40 | ~CDynamicBuffer() { delete []_items; } | ||
41 | |||
42 | T *GetCurPtrAndGrow(size_t addSize) | ||
43 | { | ||
44 | size_t rem = _size - _pos; | ||
45 | if (rem < addSize) | ||
46 | Grow(addSize - rem); | ||
47 | T *res = _items + _pos; | ||
48 | _pos += addSize; | ||
49 | return res; | ||
50 | } | ||
51 | |||
52 | void AddData(const T *data, size_t size) | ||
53 | { | ||
54 | memcpy(GetCurPtrAndGrow(size), data, size * sizeof(T)); | ||
55 | } | ||
56 | |||
57 | size_t GetPos() const { return _pos; } | ||
58 | |||
59 | // void Empty() { _pos = 0; } | ||
60 | }; | ||
61 | |||
62 | typedef CDynamicBuffer<unsigned char> CByteDynamicBuffer; | ||
63 | |||
64 | #endif | ||