blob: bdcc40d3fa724f6f824683734525e14402545352 [file] [log] [blame]
Niels Möllere7547d52018-11-01 09:33:08 +01001/*
2 * Copyright 2018 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#ifndef RTC_BASE_MEMORY_STREAM_H_
12#define RTC_BASE_MEMORY_STREAM_H_
13
Yves Gerey3e707812018-11-28 16:47:49 +010014#include <stddef.h>
15
Niels Möllere7547d52018-11-01 09:33:08 +010016#include "rtc_base/stream.h"
17
18namespace rtc {
19
20// MemoryStream dynamically resizes to accomodate written data.
21
22class MemoryStream final : public StreamInterface {
23 public:
24 MemoryStream();
25 explicit MemoryStream(const char* data); // Calls SetData(data, strlen(data))
26 MemoryStream(const void* data, size_t length); // Calls SetData(data, length)
27 ~MemoryStream() override;
28
29 StreamState GetState() const override;
30 StreamResult Read(void* buffer,
31 size_t bytes,
32 size_t* bytes_read,
33 int* error) override;
34 StreamResult Write(const void* buffer,
35 size_t bytes,
36 size_t* bytes_written,
37 int* error) override;
38 void Close() override;
Niels Möller0a7d56e2019-01-10 11:24:07 +010039 bool GetSize(size_t* size) const;
Niels Möller83953e42019-01-11 10:45:11 +010040 bool ReserveSize(size_t size);
Niels Möllere7547d52018-11-01 09:33:08 +010041
Niels Möller1a86b782019-01-14 12:48:53 +010042 bool SetPosition(size_t position);
43 bool GetPosition(size_t* position) const;
44 void Rewind();
45
Niels Möllere7547d52018-11-01 09:33:08 +010046 char* GetBuffer() { return buffer_; }
47 const char* GetBuffer() const { return buffer_; }
48
49 void SetData(const void* data, size_t length);
50
51 private:
52 StreamResult DoReserve(size_t size, int* error);
53
54 // Invariant: 0 <= seek_position <= data_length_ <= buffer_length_
55 char* buffer_ = nullptr;
56 size_t buffer_length_ = 0;
57 size_t data_length_ = 0;
58 size_t seek_position_ = 0;
59};
60
61} // namespace rtc
62
63#endif // RTC_BASE_MEMORY_STREAM_H_