3 * Copyright (c) 2020-2021 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.
22 #include "BufferWriter.h"
26 /// Build a c-style string out of distinct parts
27 class StringBuilderBase
30 StringBuilderBase(char * buffer, size_t size) : mWriter(reinterpret_cast<uint8_t *>(buffer), size - 1)
33 buffer[0] = 0; // make c-str work by default
36 /// Append a null terminated string
37 StringBuilderBase & Add(const char * s)
44 /// Append an integer value
45 StringBuilderBase & Add(int value)
48 snprintf(buff, sizeof(buff), "%d", value);
49 buff[sizeof(buff) - 1] = 0;
53 /// did all the values fit?
54 bool Fit() const { return mWriter.Fit(); }
56 /// access the underlying value
57 const char * c_str() const { return reinterpret_cast<const char *>(mWriter.Buffer()); }
60 Encoding::BufferWriter mWriter;
66 mWriter.Buffer()[mWriter.Needed()] = 0;
70 mWriter.Buffer()[mWriter.Size()] = 0;
75 /// a preallocated sized string builder
76 template <size_t kSize>
77 class StringBuilder : public StringBuilderBase
80 StringBuilder() : StringBuilderBase(mBuffer, kSize) {}