typed_buffer.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef REMOTING_BASE_TYPED_BUFFER_H_
  5. #define REMOTING_BASE_TYPED_BUFFER_H_
  6. #include <assert.h>
  7. #include <stdint.h>
  8. #include <algorithm>
  9. #include "base/memory/raw_ptr.h"
  10. namespace remoting {
  11. // A scoper for a variable-length structure such as SID, SECURITY_DESCRIPTOR and
  12. // similar. These structures typically consist of a header followed by variable-
  13. // length data, so the size may not match sizeof(T). The class supports
  14. // move-only semantics and typed buffer getters.
  15. template <typename T>
  16. class TypedBuffer {
  17. public:
  18. TypedBuffer() : TypedBuffer(0) {}
  19. // Creates an instance of the object allocating a buffer of the given size.
  20. explicit TypedBuffer(uint32_t length) : buffer_(nullptr), length_(length) {
  21. if (length_ > 0)
  22. buffer_ = reinterpret_cast<T*>(new uint8_t[length_]);
  23. }
  24. TypedBuffer(TypedBuffer&& rvalue) : TypedBuffer() { Swap(rvalue); }
  25. TypedBuffer(const TypedBuffer&) = delete;
  26. TypedBuffer& operator=(const TypedBuffer&) = delete;
  27. ~TypedBuffer() {
  28. if (buffer_) {
  29. delete[] reinterpret_cast<uint8_t*>(buffer_.get());
  30. buffer_ = nullptr;
  31. }
  32. }
  33. TypedBuffer& operator=(TypedBuffer&& rvalue) {
  34. Swap(rvalue);
  35. return *this;
  36. }
  37. // Accessors to get the owned buffer.
  38. // operator* and operator-> will assert() if there is no current buffer.
  39. T& operator*() const {
  40. assert(buffer_);
  41. return *buffer_;
  42. }
  43. T* operator->() const {
  44. assert(buffer_);
  45. return buffer_;
  46. }
  47. T* get() const { return buffer_; }
  48. uint32_t length() const { return length_; }
  49. // Helper returning a pointer to the structure starting at a specified byte
  50. // offset.
  51. T* GetAtOffset(uint32_t offset) {
  52. return reinterpret_cast<T*>(reinterpret_cast<uint8_t*>(buffer_.get()) +
  53. offset);
  54. }
  55. // Allow TypedBuffer<T> to be used in boolean expressions.
  56. explicit operator bool() const { return buffer_ != nullptr; }
  57. // Swap two buffers.
  58. void Swap(TypedBuffer& other) {
  59. std::swap(buffer_, other.buffer_);
  60. std::swap(length_, other.length_);
  61. }
  62. private:
  63. // Points to the owned buffer.
  64. raw_ptr<T> buffer_;
  65. // Length of the owned buffer in bytes.
  66. uint32_t length_;
  67. };
  68. } // namespace remoting
  69. #endif // REMOTING_BASE_TYPED_BUFFER_H_