Line data Source code
1 : /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 : /* vim: set ts=2 et sw=2 tw=80: */
3 : /* This Source Code Form is subject to the terms of the Mozilla Public
4 : * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5 : * You can obtain one at http://mozilla.org/MPL/2.0/. */
6 :
7 : // Original author: ekr@rtfm.com
8 :
9 : #ifndef databuffer_h__
10 : #define databuffer_h__
11 : #include <algorithm>
12 : #include <mozilla/UniquePtr.h>
13 : #include <m_cpp_utils.h>
14 : #include <nsISupportsImpl.h>
15 :
16 : namespace mozilla {
17 :
18 0 : class DataBuffer {
19 : public:
20 : DataBuffer() : data_(nullptr), len_(0), capacity_(0) {}
21 0 : DataBuffer(const uint8_t *data, size_t len) {
22 0 : Assign(data, len, len);
23 0 : }
24 0 : DataBuffer(const uint8_t *data, size_t len, size_t capacity) {
25 0 : Assign(data, len, capacity);
26 0 : }
27 :
28 : // to ensure extra space for expansion
29 0 : void Assign(const uint8_t *data, size_t len, size_t capacity) {
30 0 : MOZ_RELEASE_ASSERT(len <= capacity);
31 0 : Allocate(capacity); // sets len_ = capacity
32 0 : memcpy(static_cast<void *>(data_.get()),
33 0 : static_cast<const void *>(data), len);
34 0 : len_ = len;
35 0 : }
36 :
37 0 : void Allocate(size_t capacity) {
38 0 : data_.reset(new uint8_t[capacity ? capacity : 1]); // Don't depend on new [0].
39 0 : len_ = capacity_ = capacity;
40 0 : }
41 :
42 : void EnsureCapacity(size_t capacity) {
43 : if (capacity_ < capacity) {
44 : uint8_t *new_data = new uint8_t[ capacity ? capacity : 1];
45 : memcpy(static_cast<void *>(new_data),
46 : static_cast<const void *>(data_.get()), len_);
47 : data_.reset(new_data); // after copying! Deletes old data
48 : capacity_ = capacity;
49 : }
50 : }
51 :
52 : // used when something writes to the buffer (having checked
53 : // capacity() or used EnsureCapacity()) and increased the length.
54 0 : void SetLength(size_t len) {
55 0 : MOZ_RELEASE_ASSERT(len <= capacity_);
56 0 : len_ = len;
57 0 : }
58 :
59 : const uint8_t *data() const { return data_.get(); }
60 0 : uint8_t *data() { return data_.get(); }
61 0 : size_t len() const { return len_; }
62 0 : size_t capacity() const { return capacity_; }
63 :
64 : private:
65 : UniquePtr<uint8_t[]> data_;
66 : size_t len_;
67 : size_t capacity_;
68 :
69 : DISALLOW_COPY_ASSIGN(DataBuffer);
70 : };
71 :
72 : }
73 :
74 : #endif
|