blob: 0a44810a0669d429836f5ff6c6ba3a703375d4b1 [file] [log] [blame]
Armando Montanez0bcae732020-05-27 13:28:11 -07001// 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
15#include "pw_stream/memory_stream.h"
16
17#include <cstddef>
18#include <cstring>
19
20#include "pw_status/status_with_size.h"
21
22namespace pw::stream {
23
David Rogers6d4f6302020-07-22 14:27:41 -070024Status MemoryWriter::DoWrite(ConstByteSpan data) {
25 if (ConservativeWriteLimit() == 0) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070026 return Status::OutOfRange();
David Rogers6d4f6302020-07-22 14:27:41 -070027 }
28 if (ConservativeWriteLimit() < data.size_bytes()) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070029 return Status::ResourceExhausted();
David Rogers6d4f6302020-07-22 14:27:41 -070030 }
31
32 size_t bytes_to_write = data.size_bytes();
Armando Montanez0bcae732020-05-27 13:28:11 -070033 std::memcpy(dest_.data() + bytes_written_, data.data(), bytes_to_write);
34 bytes_written_ += bytes_to_write;
35
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -080036 return OkStatus();
Armando Montanez0bcae732020-05-27 13:28:11 -070037}
38
David Rogers6d4f6302020-07-22 14:27:41 -070039StatusWithSize MemoryReader::DoRead(ByteSpan dest) {
40 if (source_.size_bytes() == bytes_read_) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070041 return StatusWithSize::OutOfRange();
David Rogers6d4f6302020-07-22 14:27:41 -070042 }
43
44 size_t bytes_to_read =
45 std::min(dest.size_bytes(), source_.size_bytes() - bytes_read_);
46
47 std::memcpy(dest.data(), source_.data() + bytes_read_, bytes_to_read);
48 bytes_read_ += bytes_to_read;
49
50 return StatusWithSize(bytes_to_read);
51}
52
53} // namespace pw::stream