chunked_byte_buffer.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 COMPONENTS_SPEECH_CHUNKED_BYTE_BUFFER_H_
  5. #define COMPONENTS_SPEECH_CHUNKED_BYTE_BUFFER_H_
  6. #include <stddef.h>
  7. #include <stdint.h>
  8. #include <memory>
  9. #include <vector>
  10. #include "base/strings/string_piece.h"
  11. namespace speech {
  12. // Models a chunk-oriented byte buffer. The term chunk is herein defined as an
  13. // arbitrary sequence of bytes that is preceeded by N header bytes, indicating
  14. // its size. Data may be appended to the buffer with no particular respect of
  15. // chunks boundaries. However, chunks can be extracted (FIFO) only when their
  16. // content (according to their header) is fully available in the buffer.
  17. // The current implementation support only 4 byte Big Endian headers.
  18. // Empty chunks (i.e. the sequence 00 00 00 00) are NOT allowed.
  19. //
  20. // E.g. 00 00 00 04 xx xx xx xx 00 00 00 02 yy yy 00 00 00 04 zz zz zz zz
  21. // [----- CHUNK 1 -------] [--- CHUNK 2 ---] [------ CHUNK 3 ------]
  22. class ChunkedByteBuffer {
  23. public:
  24. ChunkedByteBuffer();
  25. ChunkedByteBuffer(const ChunkedByteBuffer&) = delete;
  26. ChunkedByteBuffer& operator=(const ChunkedByteBuffer&) = delete;
  27. ~ChunkedByteBuffer();
  28. // Appends |length| bytes starting from |start| to the buffer.
  29. void Append(const uint8_t* start, size_t length);
  30. // Appends bytes contained in the |string| to the buffer.
  31. void Append(base::StringPiece string);
  32. // Checks whether one or more complete chunks are available in the buffer.
  33. bool HasChunks() const;
  34. // If enough data is available, reads and removes the first complete chunk
  35. // from the buffer. Returns a NULL pointer if no complete chunk is available.
  36. std::unique_ptr<std::vector<uint8_t>> PopChunk();
  37. // Clears all the content of the buffer.
  38. void Clear();
  39. // Returns the number of raw bytes (including headers) present.
  40. size_t GetTotalLength() const { return total_bytes_stored_; }
  41. private:
  42. struct Chunk {
  43. Chunk();
  44. Chunk(const Chunk&) = delete;
  45. Chunk& operator=(const Chunk&) = delete;
  46. ~Chunk();
  47. std::vector<uint8_t> header;
  48. std::unique_ptr<std::vector<uint8_t>> content;
  49. size_t ExpectedContentLength() const;
  50. };
  51. std::vector<std::unique_ptr<Chunk>> chunks_;
  52. std::unique_ptr<Chunk> partial_chunk_;
  53. size_t total_bytes_stored_;
  54. };
  55. } // namespace speech
  56. #endif // COMPONENTS_SPEECH_CHUNKED_BYTE_BUFFER_H_