1 // Copyright 2019 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 #pragma once
15 
16 #include <algorithm>
17 #include <cstdarg>
18 #include <cstddef>
19 #include <cstring>
20 #include <span>
21 #include <string_view>
22 #include <type_traits>
23 #include <utility>
24 
25 #include "pw_preprocessor/compiler.h"
26 #include "pw_status/status.h"
27 #include "pw_status/status_with_size.h"
28 #include "pw_string/to_string.h"
29 
30 namespace pw {
31 
32 // StringBuilder facilitates building formatted strings in a fixed-size buffer.
33 // StringBuilders are always null terminated (unless they are constructed with
34 // an empty buffer) and never overflow. Status is tracked for each operation and
35 // an overall status is maintained, which reflects the most recent error.
36 //
37 // A StringBuilder does not own the buffer it writes to. It can be used to write
38 // strings to any buffer. The StringBuffer template class, defined below,
39 // allocates a buffer alongside a StringBuilder.
40 //
41 // StringBuilder supports C++-style << output, similar to std::ostringstream. It
42 // also supports std::string-like append functions and printf-style output.
43 //
44 // Support for custom types is added by overloading operator<< in the same
45 // namespace as the custom type. For example:
46 //
47 //   namespace my_project {
48 //
49 //   struct MyType {
50 //     int foo;
51 //     const char* bar;
52 //   };
53 //
54 //   pw::StringBuilder& operator<<(pw::StringBuilder& sb, const MyType& value) {
55 //     return sb << "MyType(" << value.foo << ", " << value.bar << ')';
56 //   }
57 //
58 //   }  // namespace my_project
59 //
60 // The ToString template function can be specialized to support custom types
61 // with StringBuilder, though overloading operator<< is generally preferred. For
62 // example:
63 //
64 //   namespace pw {
65 //
66 //   template <>
67 //   StatusWithSize ToString<MyStatus>(MyStatus value, std::span<char> buffer) {
68 //     return CopyString(MyStatusString(value), buffer);
69 //   }
70 //
71 //   }  // namespace pw
72 //
73 class StringBuilder {
74  public:
75   // Creates an empty StringBuilder.
StringBuilder(std::span<char> buffer)76   constexpr StringBuilder(std::span<char> buffer) : buffer_(buffer), size_(0) {
77     NullTerminate();
78   }
StringBuilder(std::span<std::byte> buffer)79   StringBuilder(std::span<std::byte> buffer)
80       : StringBuilder(
81             {reinterpret_cast<char*>(buffer.data()), buffer.size_bytes()}) {}
82 
83   // Disallow copy/assign to avoid confusion about where the string is actually
84   // stored. StringBuffers may be copied into one another.
85   StringBuilder(const StringBuilder&) = delete;
86 
87   StringBuilder& operator=(const StringBuilder&) = delete;
88 
89   // Returns the contents of the string buffer. Always null-terminated.
data()90   const char* data() const { return buffer_.data(); }
c_str()91   const char* c_str() const { return data(); }
92 
93   // Returns a std::string_view of the contents of this StringBuilder. The
94   // std::string_view is invalidated if the StringBuilder contents change.
view()95   std::string_view view() const { return std::string_view(data(), size()); }
96 
97   // Allow implicit conversions to std::string_view so StringBuilders can be
98   // passed into functions that take a std::string_view.
string_view()99   operator std::string_view() const { return view(); }
100 
101   // Returns a std::span<const std::byte> representation of this StringBuffer.
as_bytes()102   std::span<const std::byte> as_bytes() const {
103     return std::span(reinterpret_cast<const std::byte*>(buffer_.data()), size_);
104   }
105 
106   // Returns the StringBuilder's status, which reflects the most recent error
107   // that occurred while updating the string. After an update fails, the status
108   // remains non-OK until it is cleared with clear() or clear_status(). Returns:
109   //
110   //     OK if no errors have occurred
111   //     RESOURCE_EXHAUSTED if output to the StringBuilder was truncated
112   //     INVALID_ARGUMENT if printf-style formatting failed
113   //     OUT_OF_RANGE if an operation outside the buffer was attempted
114   //
status()115   Status status() const { return status_; }
116 
117   // Returns status() and size() as a StatusWithSize.
status_with_size()118   StatusWithSize status_with_size() const {
119     return StatusWithSize(status_, size_);
120   }
121 
122   // The status from the last operation. May be OK while status() is not OK.
last_status()123   Status last_status() const { return last_status_; }
124 
125   // True if status() is OkStatus().
ok()126   bool ok() const { return status_.ok(); }
127 
128   // True if the string is empty.
empty()129   bool empty() const { return size() == 0u; }
130 
131   // Returns the current length of the string, excluding the null terminator.
size()132   size_t size() const { return size_; }
133 
134   // Returns the maximum length of the string, excluding the null terminator.
max_size()135   size_t max_size() const { return buffer_.empty() ? 0u : buffer_.size() - 1; }
136 
137   // Clears the string and resets its error state.
138   void clear();
139 
140   // Sets the statuses to OkStatus();
clear_status()141   void clear_status() {
142     status_ = OkStatus();
143     last_status_ = OkStatus();
144   }
145 
146   // Appends a single character. Stets the status to RESOURCE_EXHAUSTED if the
147   // character cannot be added because the buffer is full.
push_back(char ch)148   void push_back(char ch) { append(1, ch); }
149 
150   // Removes the last character. Sets the status to OUT_OF_RANGE if the buffer
151   // is empty (in which case the unsigned overflow is intentional).
pop_back()152   void pop_back() PW_NO_SANITIZE("unsigned-integer-overflow") {
153     resize(size() - 1);
154   }
155 
156   // Appends the provided character count times.
157   StringBuilder& append(size_t count, char ch);
158 
159   // Appends count characters from str to the end of the StringBuilder. If count
160   // exceeds the remaining space in the StringBuffer, max_size() - size()
161   // characters are appended and the status is set to RESOURCE_EXHAUSTED.
162   //
163   // str is not considered null-terminated and may contain null characters.
164   StringBuilder& append(const char* str, size_t count);
165 
166   // Appends characters from the null-terminated string to the end of the
167   // StringBuilder. If the string's length exceeds the remaining space in the
168   // buffer, max_size() - size() characters are copied and the status is set to
169   // RESOURCE_EXHAUSTED.
170   //
171   // This function uses string::Length instead of std::strlen to avoid unbounded
172   // reads if the string is not null terminated.
173   StringBuilder& append(const char* str);
174 
175   // Appends a std::string_view to the end of the StringBuilder.
176   StringBuilder& append(const std::string_view& str);
177 
178   // Appends a substring from the std::string_view to the StringBuilder. Copies
179   // up to count characters starting from pos to the end of the StringBuilder.
180   // If pos > str.size(), sets the status to OUT_OF_RANGE.
181   StringBuilder& append(const std::string_view& str,
182                         size_t pos,
183                         size_t count = std::string_view::npos);
184 
185   // Appends to the end of the StringBuilder using the << operator. This enables
186   // C++ stream-style formatted to StringBuilders.
187   template <typename T>
188   StringBuilder& operator<<(const T& value) {
189     // For std::string_view-compatible types, use the append function, which
190     // gives smaller code size.
191     if constexpr (std::is_convertible_v<T, std::string_view>) {
192       append(value);
193     } else {
194       HandleStatusWithSize(ToString(value, buffer_.subspan(size_)));
195     }
196     return *this;
197   }
198 
199   // Provide a few additional operator<< overloads that reduce code size.
200   StringBuilder& operator<<(bool value) {
201     return append(value ? "true" : "false");
202   }
203 
204   StringBuilder& operator<<(char value) {
205     push_back(value);
206     return *this;
207   }
208 
209   StringBuilder& operator<<(std::nullptr_t) {
210     return append(string::kNullPointerString);
211   }
212 
213   StringBuilder& operator<<(Status status) { return *this << status.str(); }
214 
215   // Appends a printf-style string to the end of the StringBuilder. If the
216   // formatted string does not fit, the results are truncated and the status is
217   // set to RESOURCE_EXHAUSTED.
218   //
219   // Internally, calls string::Format, which calls std::vsnprintf.
220   PW_PRINTF_FORMAT(2, 3) StringBuilder& Format(const char* format, ...);
221 
222   // Appends a vsnprintf-style string with va_list arguments to the end of the
223   // StringBuilder. If the formatted string does not fit, the results are
224   // truncated and the status is set to RESOURCE_EXHAUSTED.
225   //
226   // Internally, calls string::Format, which calls std::vsnprintf.
227   StringBuilder& FormatVaList(const char* format, va_list args);
228 
229   // Sets the StringBuilder's size. This function only truncates; if
230   // new_size > size(), it sets status to OUT_OF_RANGE and does nothing.
231   void resize(size_t new_size);
232 
233  protected:
234   // Functions to support StringBuffer copies.
StringBuilder(std::span<char> buffer,const StringBuilder & other)235   constexpr StringBuilder(std::span<char> buffer, const StringBuilder& other)
236       : buffer_(buffer),
237         size_(other.size_),
238         status_(other.status_),
239         last_status_(other.last_status_) {}
240 
241   void CopySizeAndStatus(const StringBuilder& other);
242 
243  private:
244   size_t ResizeAndTerminate(size_t chars_to_append);
245 
246   void HandleStatusWithSize(StatusWithSize written);
247 
NullTerminate()248   constexpr void NullTerminate() {
249     if (!buffer_.empty()) {
250       buffer_[size_] = '\0';
251     }
252   }
253 
254   void SetErrorStatus(Status status);
255 
256   const std::span<char> buffer_;
257 
258   size_t size_;
259   Status status_;
260   Status last_status_;
261 };
262 
263 // StringBuffers declare a buffer along with a StringBuilder. StringBuffer can
264 // be used as a statically allocated replacement for std::ostringstream or
265 // std::string. For example:
266 //
267 //   StringBuffer<32> str;
268 //   str << "The answer is " << number << "!";  // with number = 42
269 //   str.c_str();  // null terminated C string "The answer is 42."
270 //   str.view();   // std::string_view of "The answer is 42."
271 //
272 template <size_t kSizeBytes>
273 class StringBuffer : public StringBuilder {
274  public:
StringBuffer()275   StringBuffer() : StringBuilder(buffer_) {}
276 
277   // StringBuffers of the same size may be copied and assigned into one another.
StringBuffer(const StringBuffer & other)278   StringBuffer(const StringBuffer& other) : StringBuilder(buffer_, other) {
279     CopyContents(other);
280   }
281 
282   // A smaller StringBuffer may be copied or assigned into a larger one.
283   template <size_t kOtherSizeBytes>
StringBuffer(const StringBuffer<kOtherSizeBytes> & other)284   StringBuffer(const StringBuffer<kOtherSizeBytes>& other)
285       : StringBuilder(buffer_, other) {
286     static_assert(StringBuffer<kOtherSizeBytes>::max_size() <= max_size(),
287                   "A StringBuffer cannot be copied into a smaller buffer");
288     CopyContents(other);
289   }
290 
291   template <size_t kOtherSizeBytes>
292   StringBuffer& operator=(const StringBuffer<kOtherSizeBytes>& other) {
293     assign<kOtherSizeBytes>(other);
294     return *this;
295   }
296 
297   StringBuffer& operator=(const StringBuffer& other) {
298     assign<kSizeBytes>(other);
299     return *this;
300   }
301 
302   template <size_t kOtherSizeBytes>
assign(const StringBuffer<kOtherSizeBytes> & other)303   StringBuffer& assign(const StringBuffer<kOtherSizeBytes>& other) {
304     static_assert(StringBuffer<kOtherSizeBytes>::max_size() <= max_size(),
305                   "A StringBuffer cannot be copied into a smaller buffer");
306     CopySizeAndStatus(other);
307     CopyContents(other);
308     return *this;
309   }
310 
311   // Returns the maximum length of the string, excluding the null terminator.
max_size()312   static constexpr size_t max_size() { return kSizeBytes - 1; }
313 
314   // Returns a StringBuffer<kSizeBytes>& instead of a generic StringBuilder& for
315   // append calls and stream-style operations.
316   template <typename... Args>
append(Args &&...args)317   StringBuffer& append(Args&&... args) {
318     StringBuilder::append(std::forward<Args>(args)...);
319     return *this;
320   }
321 
322   template <typename T>
323   StringBuffer& operator<<(T&& value) {
324     static_cast<StringBuilder&>(*this) << std::forward<T>(value);
325     return *this;
326   }
327 
328  private:
329   template <size_t kOtherSize>
CopyContents(const StringBuffer<kOtherSize> & other)330   void CopyContents(const StringBuffer<kOtherSize>& other) {
331     std::memcpy(buffer_, other.data(), other.size() + 1);  // include the \0
332   }
333 
334   static_assert(kSizeBytes >= 1u, "StringBuffers must be at least 1 byte long");
335   char buffer_[kSizeBytes];
336 };
337 
338 namespace string_internal {
339 
340 // Internal code for determining the default size of StringBuffers created with
341 // MakeString.
342 //
343 // StringBuffers created with MakeString default to at least 24 bytes. This is
344 // large enough to fit the largest 64-bit integer (20 digits plus a \0), rounded
345 // up to the nearest multiple of 4.
346 inline constexpr size_t kDefaultMinimumStringBufferSize = 24;
347 
348 // By default, MakeString uses a buffer size large enough to fit all string
349 // literal arguments. ArgLength uses this value as an estimate of the number of
350 // characters needed to represent a non-string argument.
351 inline constexpr size_t kDefaultArgumentSize = 4;
352 
353 // Returns a string literal's length or kDefaultArgumentSize for non-strings.
354 template <typename T>
ArgLength()355 constexpr size_t ArgLength() {
356   using Arg = std::remove_reference_t<T>;
357 
358   // If the argument is an array of const char, assume it is a string literal.
359   if constexpr (std::is_array_v<Arg>) {
360     using Element = std::remove_reference_t<decltype(std::declval<Arg>()[0])>;
361 
362     if constexpr (std::is_same_v<Element, const char>) {
363       return std::extent_v<Arg> > 0u ? std::extent_v<Arg> - 1 : size_t(0);
364     }
365   }
366 
367   return kDefaultArgumentSize;
368 }
369 
370 // This function returns the default string buffer size used by MakeString.
371 template <typename... Args>
DefaultStringBufferSize()372 constexpr size_t DefaultStringBufferSize() {
373   return std::max((size_t(1) + ... + ArgLength<Args>()),
374                   kDefaultMinimumStringBufferSize);
375 }
376 
377 // Internal version of MakeString with const reference arguments instead of
378 // deduced types, which include the lengths of string literals. Having this
379 // function can reduce code size.
380 template <size_t kBufferSize, typename... Args>
InitializeStringBuffer(const Args &...args)381 auto InitializeStringBuffer(const Args&... args) {
382   return (StringBuffer<kBufferSize>() << ... << args);
383 }
384 
385 }  // namespace string_internal
386 
387 // Makes a StringBuffer with a string version of a series of values. This is
388 // useful for creating and initializing a StringBuffer or for conveniently
389 // getting a null-terminated string. For example:
390 //
391 //     LOG_INFO("The MAC address is %s", MakeString(mac_address).c_str());
392 //
393 // By default, the buffer size is 24 bytes, large enough to fit any 64-bit
394 // integer. If string literal arguments are provided, the default size will be
395 // large enough to fit them and a null terminator, plus 4 additional bytes for
396 // each argument. To use a fixed buffer size, set the kBufferSize template
397 // argument. For example:
398 //
399 //   // Creates a default-size StringBuffer (10 + 10 + 4 + 1 + 1 = 26 bytes).
400 //   auto sb = MakeString("1234567890", "1234567890", number, "!");
401 //
402 //   // Creates a 32-byte StringBuffer.
403 //   auto sb = MakeString<32>("1234567890", "1234567890", number, "!");
404 //
405 // Keep in mind that each argument to MakeString expands to a function call.
406 // MakeString may increase code size more than an equivalent pw::string::Format
407 // (or std::snprintf) call.
408 template <size_t kBufferSize = 0u, typename... Args>
MakeString(Args &&...args)409 auto MakeString(Args&&... args) {
410   constexpr size_t kSize =
411       kBufferSize == 0u ? string_internal::DefaultStringBufferSize<Args...>()
412                         : kBufferSize;
413   return string_internal::InitializeStringBuffer<kSize>(args...);
414 }
415 
416 }  // namespace pw
417