partial_circular_buffer.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2013 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 COMPONENTS_WEBRTC_LOGGING_COMMON_PARTIAL_CIRCULAR_BUFFER_H_
  5. #define COMPONENTS_WEBRTC_LOGGING_COMMON_PARTIAL_CIRCULAR_BUFFER_H_
  6. #include <stdint.h>
  7. #include "base/memory/raw_ptr.h"
  8. namespace webrtc_logging {
  9. // A wrapper around a memory buffer that allows circular read and write with a
  10. // selectable wrapping position. Buffer layout (after wrap; H is header):
  11. // -----------------------------------------------------------
  12. // | H | Beginning | End | Middle |
  13. // -----------------------------------------------------------
  14. // ^---- Non-wrapping -----^ ^--------- Wrapping ----------^
  15. // The non-wrapping part is never overwritten. The wrapping part will be
  16. // circular. The very first part is the header (see the BufferData struct
  17. // below). It consists of the following information:
  18. // - Length written to the buffer (not including header).
  19. // - Wrapping position.
  20. // - End position of buffer. (If the last byte is at x, this will be x + 1.)
  21. // Users of wrappers around the same underlying buffer must ensure that writing
  22. // is finished before reading is started.
  23. class PartialCircularBuffer {
  24. public:
  25. // Use for reading. |buffer_size| is in bytes and must be larger than the
  26. // header size (see above).
  27. PartialCircularBuffer(void* buffer, uint32_t buffer_size);
  28. // Use for writing. |buffer_size| is in bytes and must be larger than the
  29. // header size (see above). If |append| is true, the header data is not reset
  30. // and writing will continue were left off, |wrap_position| is then ignored.
  31. PartialCircularBuffer(void* buffer,
  32. uint32_t buffer_size,
  33. uint32_t wrap_position,
  34. bool append);
  35. uint32_t Read(void* buffer, uint32_t buffer_size);
  36. void Write(const void* buffer, uint32_t buffer_size);
  37. private:
  38. friend class PartialCircularBufferTest;
  39. #pragma pack(push)
  40. #pragma pack(4)
  41. struct BufferData {
  42. uint32_t total_written;
  43. uint32_t wrap_position;
  44. uint32_t end_position;
  45. uint8_t data[1];
  46. };
  47. #pragma pack(pop)
  48. void DoWrite(const uint8_t* input, uint32_t input_size);
  49. // Used for reading and writing.
  50. raw_ptr<BufferData> buffer_data_;
  51. uint32_t memory_buffer_size_;
  52. uint32_t data_size_;
  53. uint32_t position_;
  54. // Used for reading.
  55. uint32_t total_read_;
  56. };
  57. } // namespace webrtc_logging
  58. #endif // COMPONENTS_WEBRTC_LOGGING_COMMON_PARTIAL_CIRCULAR_BUFFER_H_