blob: c3f2f7da8ba6e6dbff286ab7e92af6509a5db4b5 [file] [log] [blame]
shaneajg9c19db42020-06-11 15:49:51 -04001// 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_bytes/byte_builder.h"
16
17namespace pw {
18
shaneajg9c19db42020-06-11 15:49:51 -040019ByteBuilder& ByteBuilder::append(size_t count, std::byte b) {
20 std::byte* const append_destination = &buffer_[size_];
shaneajg9c19db42020-06-11 15:49:51 -040021 std::memset(append_destination, static_cast<int>(b), ResizeForAppend(count));
22 return *this;
23}
24
25ByteBuilder& ByteBuilder::append(const void* bytes, size_t count) {
26 std::byte* const append_destination = &buffer_[size_];
27 std::memcpy(append_destination, bytes, ResizeForAppend(count));
28 return *this;
29}
30
31size_t ByteBuilder::ResizeForAppend(size_t bytes_to_append) {
shaneajg3181d182020-06-17 20:17:23 -040032 if (!status_.ok()) {
33 return 0;
shaneajg9c19db42020-06-11 15:49:51 -040034 }
35
shaneajg3181d182020-06-17 20:17:23 -040036 if (bytes_to_append > max_size() - size()) {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070037 status_ = Status::ResourceExhausted();
shaneajg3181d182020-06-17 20:17:23 -040038 return 0;
39 }
40
41 size_ += bytes_to_append;
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -080042 status_ = OkStatus();
shaneajg3181d182020-06-17 20:17:23 -040043 return bytes_to_append;
shaneajg9c19db42020-06-11 15:49:51 -040044}
45
46void ByteBuilder::resize(size_t new_size) {
47 if (new_size <= size_) {
48 size_ = new_size;
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -080049 status_ = OkStatus();
shaneajg9c19db42020-06-11 15:49:51 -040050 } else {
Wyatt Heplerd78f7c62020-09-28 14:27:32 -070051 status_ = Status::OutOfRange();
shaneajg9c19db42020-06-11 15:49:51 -040052 }
53}
54
shaneajg9c19db42020-06-11 15:49:51 -040055} // namespace pw