Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / pigweed / repo / pw_stream / public / pw_stream / memory_stream.h
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:
28   MemoryWriter(ByteSpan dest) : dest_(dest) {}
29
30   size_t bytes_written() const { return bytes_written_; }
31
32   size_t ConservativeWriteLimit() const override {
33     return dest_.size_bytes() - bytes_written_;
34   }
35
36   ConstByteSpan WrittenData() const { return dest_.first(bytes_written_); }
37
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 size_bytes>
52 class MemoryWriterBuffer final : public MemoryWriter {
53  public:
54   MemoryWriterBuffer() : MemoryWriter(buffer_) {}
55
56  private:
57   std::array<std::byte, size_bytes> buffer_;
58 };
59
60 class MemoryReader final : public Reader {
61  public:
62   MemoryReader(ConstByteSpan source) : source_(source), bytes_read_(0) {}
63
64   size_t ConservativeReadLimit() const override {
65     return source_.size_bytes() - bytes_read_;
66   }
67
68   size_t bytes_read() const { return bytes_read_; }
69
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