Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / src / lib / support / StringBuilder.h
1 /*
2  *
3  *    Copyright (c) 2020-2021 Project CHIP Authors
4  *
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
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  */
17
18 #pragma once
19
20 #include <nlassert.h>
21
22 #include "BufferWriter.h"
23
24 namespace chip {
25
26 /// Build a c-style string out of distinct parts
27 class StringBuilderBase
28 {
29 public:
30     StringBuilderBase(char * buffer, size_t size) : mWriter(reinterpret_cast<uint8_t *>(buffer), size - 1)
31     {
32         nlASSERT(size > 0);
33         buffer[0] = 0; // make c-str work by default
34     }
35
36     /// Append a null terminated string
37     StringBuilderBase & Add(const char * s)
38     {
39         mWriter.Put(s);
40         NullTerminate();
41         return *this;
42     }
43
44     /// Append an integer value
45     StringBuilderBase & Add(int value)
46     {
47         char buff[32];
48         snprintf(buff, sizeof(buff), "%d", value);
49         buff[sizeof(buff) - 1] = 0;
50         return Add(buff);
51     }
52
53     /// did all the values fit?
54     bool Fit() const { return mWriter.Fit(); }
55
56     /// access the underlying value
57     const char * c_str() const { return reinterpret_cast<const char *>(mWriter.Buffer()); }
58
59 private:
60     Encoding::BufferWriter mWriter;
61
62     void NullTerminate()
63     {
64         if (mWriter.Fit())
65         {
66             mWriter.Buffer()[mWriter.Needed()] = 0;
67         }
68         else
69         {
70             mWriter.Buffer()[mWriter.Size()] = 0;
71         }
72     }
73 };
74
75 /// a preallocated sized string builder
76 template <size_t kSize>
77 class StringBuilder : public StringBuilderBase
78 {
79 public:
80     StringBuilder() : StringBuilderBase(mBuffer, kSize) {}
81
82 private:
83     char mBuffer[kSize];
84 };
85
86 } // namespace chip