Armando Montanez | b90d9b2 | 2021-03-18 16:26:52 -0700 | [diff] [blame] | 1 | // Copyright 2021 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 | #include "pw_persistent_ram/persistent_buffer.h" |
| 15 | |
| 16 | #include "pw_bytes/span.h" |
| 17 | #include "pw_checksum/crc16_ccitt.h" |
| 18 | #include "pw_status/status.h" |
| 19 | |
| 20 | namespace pw::persistent_ram { |
| 21 | |
| 22 | Status PersistentBufferWriter::DoWrite(ConstByteSpan data) { |
| 23 | if (ConservativeWriteLimit() == 0) { |
| 24 | return Status::OutOfRange(); |
| 25 | } |
| 26 | if (ConservativeWriteLimit() < data.size_bytes()) { |
| 27 | return Status::ResourceExhausted(); |
| 28 | } |
| 29 | if (data.empty()) { |
| 30 | return OkStatus(); |
| 31 | } |
| 32 | |
| 33 | std::memcpy(buffer_.data() + size_, data.data(), data.size_bytes()); |
| 34 | |
| 35 | // Only checksum newly written data. |
| 36 | checksum_ = checksum::Crc16Ccitt::Calculate( |
| 37 | ByteSpan(buffer_.data() + size_, data.size_bytes()), checksum_); |
| 38 | size_ += data.size_bytes(); |
| 39 | |
| 40 | return OkStatus(); |
| 41 | } |
| 42 | |
| 43 | } // namespace pw::persistent_ram |