1 // Copyright 2020 The Pigweed Authors
2 //
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
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
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
13 // the License.
14 #pragma once
15 
16 #include <array>
17 #include <cstddef>
18 #include <span>
19 
20 #include "pw_bytes/span.h"
21 #include "pw_result/result.h"
22 #include "pw_stream/stream.h"
23 
24 namespace pw::stream {
25 
26 class MemoryWriter : public Writer {
27  public:
MemoryWriter(ByteSpan dest)28   MemoryWriter(ByteSpan dest) : dest_(dest) {}
29 
bytes_written()30   size_t bytes_written() const { return bytes_written_; }
31 
ConservativeWriteLimit()32   size_t ConservativeWriteLimit() const override {
33     return dest_.size_bytes() - bytes_written_;
34   }
35 
WrittenData()36   ConstByteSpan WrittenData() const { return dest_.first(bytes_written_); }
37 
data()38   const std::byte* data() const { return dest_.data(); }
39 
40  private:
41   // Implementation for writing data to this stream.
42   //
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;
46 
47   ByteSpan dest_;
48   size_t bytes_written_ = 0;
49 };
50 
51 template <size_t kSizeBytes>
52 class MemoryWriterBuffer final : public MemoryWriter {
53  public:
MemoryWriterBuffer()54   MemoryWriterBuffer() : MemoryWriter(buffer_) {}
55 
56  private:
57   std::array<std::byte, kSizeBytes> buffer_;
58 };
59 
60 class MemoryReader final : public Reader {
61  public:
MemoryReader(ConstByteSpan source)62   MemoryReader(ConstByteSpan source) : source_(source), bytes_read_(0) {}
63 
ConservativeReadLimit()64   size_t ConservativeReadLimit() const override {
65     return source_.size_bytes() - bytes_read_;
66   }
67 
bytes_read()68   size_t bytes_read() const { return bytes_read_; }
69 
data()70   const std::byte* data() const { return source_.data(); }
71 
72  private:
73   // Implementation for reading data from this stream.
74   //
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;
78 
79   ConstByteSpan source_;
80   size_t bytes_read_;
81 };
82 
83 }  // namespace pw::stream
84