Wyatt Hepler | 1927c28 | 2020-02-11 16:45:02 -0800 | [diff] [blame] | 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 | |
| 15 | #include "pw_kvs/alignment.h" |
| 16 | |
| 17 | namespace pw { |
| 18 | |
| 19 | Status AlignedWriter::Write(span<const std::byte> data) { |
| 20 | while (!data.empty()) { |
| 21 | size_t to_copy = std::min(write_size_ - bytes_in_buffer_, data.size()); |
| 22 | |
| 23 | std::memcpy(&buffer_[bytes_in_buffer_], data.data(), to_copy); |
| 24 | data = data.subspan(to_copy); |
| 25 | bytes_in_buffer_ += to_copy; |
| 26 | |
| 27 | // If the buffer is full, write it out. |
| 28 | if (bytes_in_buffer_ == write_size_) { |
Wyatt Hepler | 50f7077 | 2020-02-13 11:25:10 -0800 | [diff] [blame] | 29 | if (auto result = output_.Write(buffer_, write_size_); !result.ok()) { |
| 30 | return result.status(); |
Wyatt Hepler | 1927c28 | 2020-02-11 16:45:02 -0800 | [diff] [blame] | 31 | } |
| 32 | |
| 33 | bytes_written_ += write_size_; |
| 34 | bytes_in_buffer_ = 0; |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | return Status::OK; |
| 39 | } |
| 40 | |
| 41 | StatusWithSize AlignedWriter::Flush() { |
| 42 | static constexpr std::byte kPadByte = std::byte{0}; |
| 43 | |
| 44 | // If data remains in the buffer, pad it to the alignment size and flush the |
| 45 | // remaining data. |
| 46 | if (bytes_in_buffer_ != 0u) { |
| 47 | const size_t remaining_bytes = AlignUp(bytes_in_buffer_, alignment_bytes_); |
| 48 | std::memset(&buffer_[bytes_in_buffer_], |
| 49 | int(kPadByte), |
| 50 | remaining_bytes - bytes_in_buffer_); |
| 51 | |
Wyatt Hepler | 50f7077 | 2020-02-13 11:25:10 -0800 | [diff] [blame] | 52 | if (auto result = output_.Write(buffer_, remaining_bytes); !result.ok()) { |
| 53 | return StatusWithSize(result.status(), bytes_written_); |
Wyatt Hepler | 1927c28 | 2020-02-11 16:45:02 -0800 | [diff] [blame] | 54 | } |
| 55 | |
| 56 | bytes_written_ += remaining_bytes; // Include padding in the total. |
| 57 | } |
| 58 | |
| 59 | const StatusWithSize result(bytes_written_); |
| 60 | bytes_written_ = 0; |
| 61 | bytes_in_buffer_ = 0; |
| 62 | return result; |
| 63 | } |
| 64 | |
| 65 | } // namespace pw |