C/C++ API Reference
Loading...
Searching...
No Matches
string_builder.h
Go to the documentation of this file.
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
20
21#include <algorithm>
22#include <cstdarg>
23#include <cstddef>
24#include <cstring>
25#include <string_view>
26#include <type_traits>
27#include <utility>
28
29#include "pw_preprocessor/compiler.h"
30#include "pw_span/span.h"
31#include "pw_status/status.h"
32#include "pw_status/status_with_size.h"
33#include "pw_string/string.h"
34#include "pw_string/to_string.h"
35
36namespace pw {
37
39
90 public:
92 explicit constexpr StringBuilder(span<char> buffer)
93 : buffer_(buffer), size_(&inline_size_), inline_size_(0) {
94 NullTerminate();
95 }
96
97 explicit StringBuilder(span<std::byte> buffer)
99 {reinterpret_cast<char*>(buffer.data()), buffer.size_bytes()}) {}
100
101 explicit constexpr StringBuilder(InlineString<>& string)
102 : buffer_(string.data(), string.max_size() + 1),
103 size_(&string.length_),
104 inline_size_(0) {}
105
108 StringBuilder(const StringBuilder&) = delete;
109
110 StringBuilder& operator=(const StringBuilder&) = delete;
111
116 const char* data() const { return buffer_.data(); }
117 const char* c_str() const { return data(); }
118
122 std::string_view view() const { return std::string_view(data(), size()); }
123
126 operator std::string_view() const { return view(); }
127
131 return span(reinterpret_cast<const std::byte*>(buffer_.data()), size());
132 }
133
144 Status status() const { return static_cast<Status::Code>(status_); }
145
148 return StatusWithSize(status(), size());
149 }
150
152 Status last_status() const { return static_cast<Status::Code>(last_status_); }
153
155 bool ok() const { return status().ok(); }
156
158 bool empty() const { return size() == 0u; }
159
161 size_t size() const { return *size_; }
162
164 size_t max_size() const { return buffer_.empty() ? 0u : buffer_.size() - 1; }
165
167 void clear();
168
171 status_ = static_cast<unsigned char>(OkStatus().code());
172 last_status_ = static_cast<unsigned char>(OkStatus().code());
173 }
174
177 void push_back(char ch) { append(1, ch); }
178
181 void pop_back() PW_NO_SANITIZE("unsigned-integer-overflow") {
182 resize(size() - 1);
183 }
184
186 StringBuilder& append(size_t count, char ch);
187
194 StringBuilder& append(const char* str, size_t count);
195
203 StringBuilder& append(const char* str);
204
206 StringBuilder& append(std::string_view str);
207
211 StringBuilder& append(std::string_view str,
212 size_t pos,
213 size_t count = std::string_view::npos);
214
217 template <typename T>
218 StringBuilder& operator<<(const T& value) {
221 if constexpr (std::is_convertible_v<T, std::string_view>) {
222 append(value);
223 } else if constexpr (std::is_convertible_v<T, span<const std::byte>>) {
224 WriteBytes(value);
225 } else {
226 HandleStatusWithSize(ToString(value, buffer_.subspan(size())));
227 }
228 return *this;
229 }
230
233 return append(value ? "true" : "false");
234 }
235
236 StringBuilder& operator<<(char value) {
237 push_back(value);
238 return *this;
239 }
240
241 StringBuilder& operator<<(std::nullptr_t) {
242 return append(string::kNullPointerString);
243 }
244
245 StringBuilder& operator<<(Status status) { return *this << status.str(); }
246
258 PW_PRINTF_FORMAT(2, 3) StringBuilder& Format(const char* format, ...);
259
265 PW_PRINTF_FORMAT(2, 0)
266 StringBuilder& FormatVaList(const char* format, va_list args);
267
270 void resize(size_t new_size);
271
272 protected:
274 constexpr StringBuilder(span<char> buffer, const StringBuilder& other)
275 : buffer_(buffer),
276 size_(&inline_size_),
277 inline_size_(*other.size_),
278 status_(other.status_),
279 last_status_(other.last_status_) {}
280
281 void CopySizeAndStatus(const StringBuilder& other);
282
283 private:
285 static constexpr unsigned char StatusCode(Status status) {
286 return static_cast<unsigned char>(status.code());
287 }
288
289 void WriteBytes(span<const std::byte> data);
290
291 size_t ResizeAndTerminate(size_t chars_to_append);
292
293 void HandleStatusWithSize(StatusWithSize written);
294
295 constexpr void NullTerminate() {
296 if (!buffer_.empty()) {
297 buffer_[size()] = '\0';
298 }
299 }
300
301 void SetErrorStatus(Status status);
302
303 const span<char> buffer_;
304
305 InlineString<>::size_type* size_;
306
307 // Place the `inline_size_`, `status_`, and `last_status_` members together
308 // and use `unsigned char` for the status codes so these members can be
309 // packed into a single word.
310 InlineString<>::size_type inline_size_;
311 unsigned char status_ = StatusCode(OkStatus());
312 unsigned char last_status_ = StatusCode(OkStatus());
313};
314
315// StringBuffer declares a buffer along with a StringBuilder. StringBuffer
316// can be used as a statically allocated replacement for std::ostringstream or
317// std::string. For example:
318//
319// StringBuffer<32> str;
320// str << "The answer is " << number << "!"; // with number = 42
321// str.c_str(); // null terminated C string "The answer is 42."
322// str.view(); // std::string_view of "The answer is 42."
323//
324template <size_t kSizeBytes>
326 public:
327 StringBuffer() : StringBuilder(buffer_) {}
328
329 // StringBuffers of the same size may be copied and assigned into one another.
330 StringBuffer(const StringBuffer& other) : StringBuilder(buffer_, other) {
331 CopyContents(other);
332 }
333
334 // A smaller StringBuffer may be copied or assigned into a larger one.
335 template <size_t kOtherSizeBytes>
337 : StringBuilder(buffer_, other) {
338 static_assert(StringBuffer<kOtherSizeBytes>::max_size() <= max_size(),
339 "A StringBuffer cannot be copied into a smaller buffer");
340 CopyContents(other);
341 }
342
343 template <size_t kOtherSizeBytes>
344 StringBuffer& operator=(const StringBuffer<kOtherSizeBytes>& other) {
345 assign<kOtherSizeBytes>(other);
346 return *this;
347 }
348
349 StringBuffer& operator=(const StringBuffer& other) {
350 assign<kSizeBytes>(other);
351 return *this;
352 }
353
354 template <size_t kOtherSizeBytes>
355 StringBuffer& assign(const StringBuffer<kOtherSizeBytes>& other) {
356 static_assert(StringBuffer<kOtherSizeBytes>::max_size() <= max_size(),
357 "A StringBuffer cannot be copied into a smaller buffer");
358 CopySizeAndStatus(other);
359 CopyContents(other);
360 return *this;
361 }
362
364 StringBuffer(StringBuffer&& other) = delete;
365
368
369 // Returns the maximum length of the string, excluding the null terminator.
370 static constexpr size_t max_size() { return kSizeBytes - 1; }
371
372 // Returns a StringBuffer<kSizeBytes>& instead of a generic StringBuilder& for
373 // append calls and stream-style operations.
374 template <typename... Args>
375 StringBuffer& append(Args&&... args) {
376 StringBuilder::append(std::forward<Args>(args)...);
377 return *this;
378 }
379
380 template <typename T>
381 StringBuffer& operator<<(T&& value) {
382 static_cast<StringBuilder&>(*this) << std::forward<T>(value);
383 return *this;
384 }
385
386 private:
387 template <size_t kOtherSize>
388 void CopyContents(const StringBuffer<kOtherSize>& other) {
389 std::memcpy(buffer_, other.data(), other.size() + 1); // include the \0
390 }
391
392 static_assert(kSizeBytes >= 1u, "StringBuffers must be at least 1 byte long");
393 char buffer_[kSizeBytes];
394};
395
397
398namespace string_internal {
399
400// Internal code for determining the default size of StringBuffers created with
401// MakeString.
402//
403// StringBuffers created with MakeString default to at least 24 bytes. This is
404// large enough to fit the largest 64-bit integer (20 digits plus a \0), rounded
405// up to the nearest multiple of 4.
406inline constexpr size_t kDefaultMinimumStringBufferSize = 24;
407
408// By default, MakeString uses a buffer size large enough to fit all string
409// literal arguments. ArgLength uses this value as an estimate of the number of
410// characters needed to represent a non-string argument.
411inline constexpr size_t kDefaultArgumentSize = 4;
412
413// Returns a string literal's length or kDefaultArgumentSize for non-strings.
414template <typename T>
415constexpr size_t ArgLength() {
416 using Arg = std::remove_reference_t<T>;
417
418 // If the argument is an array of const char, assume it is a string literal.
419 if constexpr (std::is_array_v<Arg>) {
420 using Element = std::remove_reference_t<decltype(std::declval<Arg>()[0])>;
421
422 if constexpr (std::is_same_v<Element, const char>) {
423 return std::extent_v<Arg> > 0u ? std::extent_v<Arg> - 1 : size_t(0);
424 }
425 }
426
427 return kDefaultArgumentSize;
428}
429
430// This function returns the default string buffer size used by MakeString.
431template <typename... Args>
432constexpr size_t DefaultStringBufferSize() {
433 return std::max((size_t(1) + ... + ArgLength<Args>()),
434 kDefaultMinimumStringBufferSize);
435}
436
437// Internal version of MakeString with const reference arguments instead of
438// deduced types, which include the lengths of string literals. Having this
439// function can reduce code size.
440template <size_t kBufferSize, typename... Args>
441auto InitializeStringBuffer(const Args&... args) {
442 return (StringBuffer<kBufferSize>() << ... << args);
443}
444
445} // namespace string_internal
446
448
449// Makes a StringBuffer with a string version of a series of values. This is
450// useful for creating and initializing a StringBuffer or for conveniently
451// getting a null-terminated string. For example:
452//
453// LOG_INFO("The MAC address is %s", MakeString(mac_address).c_str());
454//
455// By default, the buffer size is 24 bytes, large enough to fit any 64-bit
456// integer. If string literal arguments are provided, the default size will be
457// large enough to fit them and a null terminator, plus 4 additional bytes for
458// each argument. To use a fixed buffer size, set the kBufferSize template
459// argument. For example:
460//
461// // Creates a default-size StringBuffer (10 + 10 + 4 + 1 + 1 = 26 bytes).
462// auto sb = MakeString("1234567890", "1234567890", number, "!");
463//
464// // Creates a 32-byte StringBuffer.
465// auto sb = MakeString<32>("1234567890", "1234567890", number, "!");
466//
467// Keep in mind that each argument to MakeString expands to a function call.
468// MakeString may increase code size more than an equivalent pw::string::Format
469// (or std::snprintf) call.
470template <size_t kBufferSize = 0u, typename... Args>
471auto MakeString(Args&&... args) {
472 constexpr size_t kSize =
473 kBufferSize == 0u ? string_internal::DefaultStringBufferSize<Args...>()
474 : kBufferSize;
475 return string_internal::InitializeStringBuffer<kSize>(args...);
476}
477
479
480} // namespace pw
Definition: status.h:120
constexpr Code code() const
Definition: status.h:341
constexpr bool ok() const
Definition: status.h:346
const char * str() const
Definition: status.h:433
Definition: status_with_size.h:51
Definition: string_builder.h:325
StringBuffer(StringBuffer &&other)=delete
StringBuffers are not movable: the underlying data must be copied.
StringBuffer & operator=(StringBuffer &&other)=delete
StringBuffers are not movable: the underlying data must be copied.
Definition: string_builder.h:89
StringBuilder & Format(const char *format,...)
bool empty() const
True if the string is empty.
Definition: string_builder.h:158
size_t size() const
Returns the current length of the string, excluding the null terminator.
Definition: string_builder.h:161
void push_back(char ch)
Definition: string_builder.h:177
StringBuilder & operator<<(const T &value)
Definition: string_builder.h:218
Status last_status() const
The status from the last operation. May be OK while status() is not OK.
Definition: string_builder.h:152
void clear_status()
Sets the statuses to OkStatus();.
Definition: string_builder.h:170
void resize(size_t new_size)
Status status() const
Definition: string_builder.h:144
span< const std::byte > as_bytes() const
Definition: string_builder.h:130
StringBuilder & append(size_t count, char ch)
Appends the provided character count times.
void clear()
Clears the string and resets its error state.
StatusWithSize status_with_size() const
Returns status() and size() as a StatusWithSize.
Definition: string_builder.h:147
size_t max_size() const
Returns the maximum length of the string, excluding the null terminator.
Definition: string_builder.h:164
StringBuilder & append(std::string_view str, size_t pos, size_t count=std::string_view::npos)
StringBuilder & FormatVaList(const char *format, va_list args)
void pop_back()
Definition: string_builder.h:181
StringBuilder & operator<<(bool value)
Provide a few additional operator<< overloads that reduce code size.
Definition: string_builder.h:232
constexpr StringBuilder(span< char > buffer)
Creates an empty pw::StringBuilder.
Definition: string_builder.h:92
const char * c_str() const
Definition: string_builder.h:117
bool ok() const
True if status() is OkStatus().
Definition: string_builder.h:155
StringBuilder & append(const char *str, size_t count)
StringBuilder(const StringBuilder &)=delete
StringBuilder & append(const char *str)
StringBuilder & append(std::string_view str)
Appends a std::string_view to the end of the StringBuilder.
std::string_view view() const
Definition: string_builder.h:122
Definition: span_impl.h:235
#define PW_PRINTF_FORMAT(format_index, parameter_index)
Definition: compiler.h:89
#define PW_NO_SANITIZE(check)
Definition: compiler.h:158
pw_Status
C API for status codes. In C++, use the pw::Status class instead.
Definition: status.h:40
constexpr Status OkStatus()
Definition: status.h:450
The Pigweed namespace.
Definition: alignment.h:27
pw::InlineBasicString and pw::InlineString are safer alternatives to std::basic_string and std::strin...