3 * Copyright (c) 2020 Project CHIP Authors
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
20 * BufBound manages serial writes to a buffer, guarding that the bounds of
21 * the buffer are not exceeded.
36 * simple buffer writer
46 BufBound(uint8_t * buf, size_t len) : mBuf(buf), mSize(len), mNeeded(0) {}
47 BufBound(const BufBound & other) = default;
50 * @brief append a single byte
52 BufBound & Put(uint8_t c)
63 * @brief append a null terminated string, exclude the null term
65 BufBound & Put(const char * s)
67 static_assert(CHAR_BIT == 8, "We're assuming char and uint8_t are the same size");
70 Put(static_cast<uint8_t>(*s++));
74 BufBound & Put8(uint8_t c) { return Put(c); }
76 BufBound & Put(uint64_t x, size_t size)
88 * @brief write integer x into the buffer, least significant byte first
90 BufBound & Put64(uint64_t x) { return Put(x, sizeof(x)); }
91 BufBound & Put32(uint32_t x) { return Put(x, sizeof(x)); }
92 BufBound & Put16(uint16_t x) { return Put(x, sizeof(x)); }
94 BufBound & PutBE(uint64_t x, size_t size)
98 uint8_t c = (x >> (size * 8)) & 0xff;
105 * @brief write integer x into the buffer, most significant byte first
107 BufBound & PutBE64(uint64_t x) { return PutBE(x, sizeof(x)); }
108 BufBound & PutBE32(uint32_t x) { return PutBE(x, sizeof(x)); }
109 BufBound & PutBE16(uint16_t x) { return PutBE(x, sizeof(x)); }
112 * @brief append a buffer
114 BufBound & Put(const uint8_t * buf, size_t len) { return Put(reinterpret_cast<const void *>(buf), len); }
115 BufBound & Put(const void * buf, size_t len)
117 size_t available = Available();
119 memmove(mBuf + mNeeded, buf, available < len ? available : len);
127 * @brief number of bytes required to satisfy all calls to Put() so far
129 size_t Needed() const { return mNeeded; }
131 * @brief bytes available
133 size_t Available() const { return mSize < mNeeded ? 0 : mSize - mNeeded; }
136 * @brief whether the input fit in the buffer
145 * @brief returns whether the input fit in the buffer, outputs what was
148 bool Fit(size_t & actually_written) const
150 actually_written = mSize >= mNeeded ? mNeeded : mSize;
151 return mSize >= mNeeded;
155 * @brief Size of the buffer
157 size_t Size() const { return mSize; }