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
152 Status status() const { return static_cast<Status::Code>(status_); }
153
156 return StatusWithSize(status(), size());
157 }
158
160 Status last_status() const { return static_cast<Status::Code>(last_status_); }
161
163 bool ok() const { return status().ok(); }
164
166 bool empty() const { return size() == 0u; }
167
169 size_t size() const { return *size_; }
170
172 size_t max_size() const { return buffer_.empty() ? 0u : buffer_.size() - 1; }
173
175 void clear();
176
179 status_ = static_cast<unsigned char>(OkStatus().code());
180 last_status_ = static_cast<unsigned char>(OkStatus().code());
181 }
182
185 void push_back(char ch) { append(1, ch); }
186
189 void pop_back() PW_NO_SANITIZE("unsigned-integer-overflow") {
190 resize(size() - 1);
191 }
192
194 StringBuilder& append(size_t count, char ch);
195
202 StringBuilder& append(const char* str, size_t count);
203
211 StringBuilder& append(const char* str);
212
214 StringBuilder& append(std::string_view str);
215
219 StringBuilder& append(std::string_view str,
220 size_t pos,
221 size_t count = std::string_view::npos);
222
225 template <typename T>
226 StringBuilder& operator<<(const T& value) {
229 if constexpr (std::is_convertible_v<T, std::string_view>) {
230 append(value);
231 } else if constexpr (std::is_convertible_v<T, span<const std::byte>>) {
232 WriteBytes(value);
233 } else {
234 HandleStatusWithSize(ToString(value, buffer_.subspan(size())));
235 }
236 return *this;
237 }
238
241 return append(value ? "true" : "false");
242 }
243
244 StringBuilder& operator<<(char value) {
245 push_back(value);
246 return *this;
247 }
248
249 StringBuilder& operator<<(std::nullptr_t) {
250 return append(string::kNullPointerString);
251 }
252
253 StringBuilder& operator<<(Status status) { return *this << status.str(); }
254
266 PW_PRINTF_FORMAT(2, 3) StringBuilder& Format(const char* format, ...);
267
273 PW_PRINTF_FORMAT(2, 0)
274 StringBuilder& FormatVaList(const char* format, va_list args);
275
278 void resize(size_t new_size);
279
280 protected:
282 constexpr StringBuilder(span<char> buffer, const StringBuilder& other)
283 : buffer_(buffer),
284 size_(&inline_size_),
285 inline_size_(*other.size_),
286 status_(other.status_),
287 last_status_(other.last_status_) {}
288
289 void CopySizeAndStatus(const StringBuilder& other);
290
291 private:
293 static constexpr unsigned char StatusCode(Status status) {
294 return static_cast<unsigned char>(status.code());
295 }
296
297 void WriteBytes(span<const std::byte> data);
298
299 size_t ResizeAndTerminate(size_t chars_to_append);
300
301 void HandleStatusWithSize(StatusWithSize written);
302
303 constexpr void NullTerminate() {
304 if (!buffer_.empty()) {
305 buffer_[size()] = '\0';
306 }
307 }
308
309 void SetErrorStatus(Status status);
310
311 const span<char> buffer_;
312
313 InlineString<>::size_type* size_;
314
315 // Place the `inline_size_`, `status_`, and `last_status_` members together
316 // and use `unsigned char` for the status codes so these members can be
317 // packed into a single word.
318 InlineString<>::size_type inline_size_;
319 unsigned char status_ = StatusCode(OkStatus());
320 unsigned char last_status_ = StatusCode(OkStatus());
321};
322
323// StringBuffer declares a buffer along with a StringBuilder. StringBuffer
324// can be used as a statically allocated replacement for std::ostringstream or
325// std::string. For example:
326//
327// StringBuffer<32> str;
328// str << "The answer is " << number << "!"; // with number = 42
329// str.c_str(); // null terminated C string "The answer is 42."
330// str.view(); // std::string_view of "The answer is 42."
331//
332template <size_t kSizeBytes>
334 public:
335 StringBuffer() : StringBuilder(buffer_) {}
336
337 // StringBuffers of the same size may be copied and assigned into one another.
338 StringBuffer(const StringBuffer& other) : StringBuilder(buffer_, other) {
339 CopyContents(other);
340 }
341
342 // A smaller StringBuffer may be copied or assigned into a larger one.
343 template <size_t kOtherSizeBytes>
345 : StringBuilder(buffer_, other) {
346 static_assert(StringBuffer<kOtherSizeBytes>::max_size() <= max_size(),
347 "A StringBuffer cannot be copied into a smaller buffer");
348 CopyContents(other);
349 }
350
351 template <size_t kOtherSizeBytes>
352 StringBuffer& operator=(const StringBuffer<kOtherSizeBytes>& other) {
353 assign<kOtherSizeBytes>(other);
354 return *this;
355 }
356
357 StringBuffer& operator=(const StringBuffer& other) {
358 assign<kSizeBytes>(other);
359 return *this;
360 }
361
362 template <size_t kOtherSizeBytes>
363 StringBuffer& assign(const StringBuffer<kOtherSizeBytes>& other) {
364 static_assert(StringBuffer<kOtherSizeBytes>::max_size() <= max_size(),
365 "A StringBuffer cannot be copied into a smaller buffer");
366 CopySizeAndStatus(other);
367 CopyContents(other);
368 return *this;
369 }
370
372 StringBuffer(StringBuffer&& other) = delete;
373
376
377 // Returns the maximum length of the string, excluding the null terminator.
378 static constexpr size_t max_size() { return kSizeBytes - 1; }
379
380 // Returns a StringBuffer<kSizeBytes>& instead of a generic StringBuilder& for
381 // append calls and stream-style operations.
382 template <typename... Args>
383 StringBuffer& append(Args&&... args) {
384 StringBuilder::append(std::forward<Args>(args)...);
385 return *this;
386 }
387
388 template <typename T>
389 StringBuffer& operator<<(T&& value) {
390 static_cast<StringBuilder&>(*this) << std::forward<T>(value);
391 return *this;
392 }
393
394 private:
395 template <size_t kOtherSize>
396 void CopyContents(const StringBuffer<kOtherSize>& other) {
397 std::memcpy(buffer_, other.data(), other.size() + 1); // include the \0
398 }
399
400 static_assert(kSizeBytes >= 1u, "StringBuffers must be at least 1 byte long");
401 char buffer_[kSizeBytes];
402};
403
405
406namespace string_internal {
407
408// Internal code for determining the default size of StringBuffers created with
409// MakeString.
410//
411// StringBuffers created with MakeString default to at least 24 bytes. This is
412// large enough to fit the largest 64-bit integer (20 digits plus a \0), rounded
413// up to the nearest multiple of 4.
414inline constexpr size_t kDefaultMinimumStringBufferSize = 24;
415
416// By default, MakeString uses a buffer size large enough to fit all string
417// literal arguments. ArgLength uses this value as an estimate of the number of
418// characters needed to represent a non-string argument.
419inline constexpr size_t kDefaultArgumentSize = 4;
420
421// Returns a string literal's length or kDefaultArgumentSize for non-strings.
422template <typename T>
423constexpr size_t ArgLength() {
424 using Arg = std::remove_reference_t<T>;
425
426 // If the argument is an array of const char, assume it is a string literal.
427 if constexpr (std::is_array_v<Arg>) {
428 using Element = std::remove_reference_t<decltype(std::declval<Arg>()[0])>;
429
430 if constexpr (std::is_same_v<Element, const char>) {
431 return std::extent_v<Arg> > 0u ? std::extent_v<Arg> - 1 : size_t(0);
432 }
433 }
434
435 return kDefaultArgumentSize;
436}
437
438// This function returns the default string buffer size used by MakeString.
439template <typename... Args>
440constexpr size_t DefaultStringBufferSize() {
441 return std::max((size_t(1) + ... + ArgLength<Args>()),
442 kDefaultMinimumStringBufferSize);
443}
444
445// Internal version of MakeString with const reference arguments instead of
446// deduced types, which include the lengths of string literals. Having this
447// function can reduce code size.
448template <size_t kBufferSize, typename... Args>
449auto InitializeStringBuffer(const Args&... args) {
450 return (StringBuffer<kBufferSize>() << ... << args);
451}
452
453} // namespace string_internal
454
456
457// Makes a StringBuffer with a string version of a series of values. This is
458// useful for creating and initializing a StringBuffer or for conveniently
459// getting a null-terminated string. For example:
460//
461// LOG_INFO("The MAC address is %s", MakeString(mac_address).c_str());
462//
463// By default, the buffer size is 24 bytes, large enough to fit any 64-bit
464// integer. If string literal arguments are provided, the default size will be
465// large enough to fit them and a null terminator, plus 4 additional bytes for
466// each argument. To use a fixed buffer size, set the kBufferSize template
467// argument. For example:
468//
469// // Creates a default-size StringBuffer (10 + 10 + 4 + 1 + 1 = 26 bytes).
470// auto sb = MakeString("1234567890", "1234567890", number, "!");
471//
472// // Creates a 32-byte StringBuffer.
473// auto sb = MakeString<32>("1234567890", "1234567890", number, "!");
474//
475// Keep in mind that each argument to MakeString expands to a function call.
476// MakeString may increase code size more than an equivalent pw::string::Format
477// (or std::snprintf) call.
478template <size_t kBufferSize = 0u, typename... Args>
479auto MakeString(Args&&... args) {
480 constexpr size_t kSize =
481 kBufferSize == 0u ? string_internal::DefaultStringBufferSize<Args...>()
482 : kBufferSize;
483 return string_internal::InitializeStringBuffer<kSize>(args...);
484}
485
487
488} // namespace pw
Definition: status.h:109
constexpr Code code() const
Definition: status.h:209
constexpr bool ok() const
Definition: status.h:214
const char * str() const
Definition: status.h:286
Definition: status_with_size.h:51
Definition: string_builder.h:333
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:166
size_t size() const
Returns the current length of the string, excluding the null terminator.
Definition: string_builder.h:169
void push_back(char ch)
Definition: string_builder.h:185
StringBuilder & operator<<(const T &value)
Definition: string_builder.h:226
Status last_status() const
The status from the last operation. May be OK while status() is not OK.
Definition: string_builder.h:160
void clear_status()
Sets the statuses to OkStatus();.
Definition: string_builder.h:178
void resize(size_t new_size)
Status status() const
Definition: string_builder.h:152
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:155
size_t max_size() const
Returns the maximum length of the string, excluding the null terminator.
Definition: string_builder.h:172
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:189
StringBuilder & operator<<(bool value)
Provide a few additional operator<< overloads that reduce code size.
Definition: string_builder.h:240
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:163
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
Definition: status.h:38
constexpr Status OkStatus()
Definition: status.h:297
The Pigweed namespace.
Definition: alignment.h:27
pw::InlineBasicString and pw::InlineString are safer alternatives to std::basic_string and std::strin...