1 // Copyright 2020 The Pigweed Authors
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
7 // https://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
20 #include "pw_bytes/span.h"
21 #include "pw_result/result.h"
22 #include "pw_stream/stream.h"
24 namespace pw::stream {
26 class MemoryWriter : public Writer {
28 MemoryWriter(ByteSpan dest) : dest_(dest) {}
30 size_t bytes_written() const { return bytes_written_; }
32 size_t ConservativeWriteLimit() const override {
33 return dest_.size_bytes() - bytes_written_;
36 ConstByteSpan WrittenData() const { return dest_.first(bytes_written_); }
38 const std::byte* data() const { return dest_.data(); }
41 // Implementation for writing data to this stream.
43 // If the in-memory buffer is exhausted in the middle of a write, this will
44 // perform a partial write and Status::ResourceExhausted() will be returned.
45 Status DoWrite(ConstByteSpan data) override;
48 size_t bytes_written_ = 0;
51 template <size_t size_bytes>
52 class MemoryWriterBuffer final : public MemoryWriter {
54 MemoryWriterBuffer() : MemoryWriter(buffer_) {}
57 std::array<std::byte, size_bytes> buffer_;
60 class MemoryReader final : public Reader {
62 MemoryReader(ConstByteSpan source) : source_(source), bytes_read_(0) {}
64 size_t ConservativeReadLimit() const override {
65 return source_.size_bytes() - bytes_read_;
68 size_t bytes_read() const { return bytes_read_; }
70 const std::byte* data() const { return source_.data(); }
73 // Implementation for reading data from this stream.
75 // If the in-memory buffer does not have enough remaining bytes for what was
76 // requested, this will perform a partial read and OK will still be returned.
77 StatusWithSize DoRead(ByteSpan dest) override;
79 ConstByteSpan source_;
83 } // namespace pw::stream