databuffer.h 2.1 KB

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