aboutsummaryrefslogtreecommitdiff
path: root/pw_string
diff options
context:
space:
mode:
authorKayce Basques <kayce@google.com>2023-03-09 23:32:38 +0000
committerCQ Bot Account <pigweed-scoped@luci-project-accounts.iam.gserviceaccount.com>2023-03-09 23:32:38 +0000
commit8a235f0f7cc61f04d69fde58ff8ab4f149ec6b5d (patch)
tree432ca1dcf52205e1c63ebcb75c209fbd1a3d9eaf /pw_string
parent84fa1a64710625ab801e392f15756040d4c34edf (diff)
downloadpigweed-8a235f0f7cc61f04d69fde58ff8ab4f149ec6b5d.tar.gz
docs: Generate pw_string API reference from Doxygen
Change-Id: Ifef8536b068a5f95b6a0453b7faa1c6a1e0b8d45 Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/131314 Reviewed-by: Kayce Basques <kayce@google.com> Pigweed-Auto-Submit: Kayce Basques <kayce@google.com> Commit-Queue: Auto-Submit <auto-submit@pigweed.google.com.iam.gserviceaccount.com> Reviewed-by: Wyatt Hepler <hepler@google.com> Commit-Queue: Kayce Basques <kayce@google.com>
Diffstat (limited to 'pw_string')
-rw-r--r--pw_string/api.rst147
-rw-r--r--pw_string/public/pw_string/format.h28
-rw-r--r--pw_string/public/pw_string/string.h51
-rw-r--r--pw_string/public/pw_string/string_builder.h144
-rw-r--r--pw_string/public/pw_string/util.h88
5 files changed, 220 insertions, 238 deletions
diff --git a/pw_string/api.rst b/pw_string/api.rst
index 3dc701df4..cead6428f 100644
--- a/pw_string/api.rst
+++ b/pw_string/api.rst
@@ -4,91 +4,49 @@
pw_string API reference
=======================
-.. _pw_inlinebasicstring-api:
+--------
+Overview
+--------
+.. doxygenfile:: pw_string/string.h
+ :sections: briefdescription
+.. doxygenfile:: pw_string/util.h
+ :sections: briefdescription
+.. doxygenfile:: pw_string/string_builder.h
+ :sections: briefdescription
---------------------
pw::InlineBasicString
---------------------
-:cpp:class:`pw::InlineBasicString` and :cpp:type:`pw::InlineString` are
-C++14-compatible, fixed-capacity, null-terminated string classes. They are
-equivalent to ``std::basic_string<T>`` and ``std::string``, but store the string
-contents inline and use no dynamic memory.
+.. doxygenfile:: pw_string/string.h
+ :sections: detaileddescription
-:cpp:type:`pw::InlineString` takes the fixed capacity as a template argument,
-but may be used generically without specifying the capacity. The capacity value
-is stored in a member variable, which the generic ``pw::InlineString<>`` /
-``pw::InlineBasicString<T>`` specialization uses in place of the template
-parameter.
-
-:cpp:type:`pw::InlineString` is efficient and compact. The current size and
-capacity are stored in a single word. Accessing the contents of a
-:cpp:type:`pw::InlineString` is a simple array access within the object, with no
-pointer indirection, even when working from a generic ``pw::InlineString<>``
-reference.
-
-.. cpp:class:: template <typename T, unsigned short kCapacity> pw::InlineBasicString
-
- Represents a fixed-capacity string of a generic character type. Equivalent to
- ``std::basic_string<T>``. Always null (``T()``) terminated.
-
-----------------
-pw::InlineString
-----------------
-See also :ref:`pw_inlinebasicstring-api`.
-
-.. cpp:type:: template <unsigned short kCapacity> pw::InlineString = pw::InlineBasicString<char, kCapacity>
+.. doxygenclass:: pw::InlineBasicString
+ :members:
- Represents a fixed-capacity string of ``char`` characters. Equivalent to
- ``std::string``. Always null (``'\0'``) terminated.
+.. doxygentypedef:: pw::InlineString
----------
pw::string
----------
-pw::string::Assign
-------------------
-.. cpp:function:: pw::Status pw::string::Assign(pw::InlineString<>& string, const std::string_view& view)
-
- Assigns ``view`` to ``string``. Truncates and returns ``RESOURCE_EXHAUSTED``
- if ``view`` is too large for ``string``.
-
-pw::string::Append
-------------------
-.. cpp:function:: pw::Status pw::string::Append(pw::InlineString<>& string, const std::string_view& view)
-
- Appends ``view`` to ``string``. Truncates and returns ``RESOURCE_EXHAUSTED``
- if ``view`` does not fit within the remaining capacity of ``string``.
-
-pw::string::ClampedCString
---------------------------
-.. cpp:function:: constexpr std::string_view pw::string::ClampedCString(span<const char> str)
-.. cpp:function:: constexpr std::string_view pw::string::ClampedCString(const char* str, size_t max_len)
+pw::string::Assign()
+--------------------
+.. doxygenfunction:: pw::string::Assign(InlineString<> &string, const std::string_view &view)
- Safe alternative to the string_view constructor to avoid the risk of an
- unbounded implicit or explicit use of strlen.
+pw::string::Append()
+--------------------
+.. doxygenfunction:: pw::string::Append(InlineString<>& string, const std::string_view& view)
- This is strongly recommended over using something like C11's strnlen_s as
- a string_view does not require null-termination.
+pw::string::ClampedCString()
+----------------------------
+.. doxygenfunction:: pw::string::ClampedCString(const char* str, size_t max_len)
+.. doxygenfunction:: pw::string::ClampedCString(span<const char> str)
-pw::string::Copy
-----------------
-The ``pw::string::Copy`` functions provide a safer alternative to
-``std::strncpy`` as it always null-terminates whenever the destination
-buffer has a non-zero size.
-
-.. cpp:function:: StatusWithSize Copy(const std::string_view& source, span<char> dest)
-.. cpp:function:: StatusWithSize Copy(const char* source, span<char> dest)
-.. cpp:function:: StatusWithSize Copy(const char* source, char* dest, size_t num)
-.. cpp:function:: StatusWithSize Copy(const pw::Vector<char>& source, span<char> dest)
-
- Copies the source string to the dest, truncating if the full string does not
- fit. Always null terminates if dest.size() or num > 0.
-
- Returns the number of characters written, excluding the null terminator. If
- the string is truncated, the status is ResourceExhausted.
-
- Precondition: The destination and source shall not overlap.
- Precondition: The source shall be a valid pointer.
+pw::string::Copy()
+------------------
+.. doxygenfunction:: pw::string::Copy(const char* source, char* dest, size_t num)
+.. doxygenfunction:: pw::string::Copy(const char* source, Span&& dest)
+.. doxygenfunction:: pw::string::Copy(const std::string_view& source, Span&& dest)
It also has variants that provide a destination of ``pw::Vector<char>``
(see :ref:`module-pw_containers` for details) that do not store the null
@@ -97,43 +55,26 @@ terminator in the vector.
.. cpp:function:: StatusWithSize Copy(const std::string_view& source, pw::Vector<char>& dest)
.. cpp:function:: StatusWithSize Copy(const char* source, pw::Vector<char>& dest)
-pw::string::NullTerminatedLength
---------------------------------
-.. cpp:function:: constexpr pw::Result<size_t> pw::string::NullTerminatedLength(span<const char> str)
-.. cpp:function:: pw::Result<size_t> pw::string::NullTerminatedLength(const char* str, size_t max_len)
-
- Safe alternative to strlen to calculate the null-terminated length of the
- string within the specified span, excluding the null terminator. Like C11's
- strnlen_s, the scan for the null-terminator is bounded.
+pw::string::Format()
+--------------------
+.. doxygenfile:: pw_string/format.h
+ :sections: briefdescription
+.. doxygenfunction:: pw::string::Format
+.. doxygenfunction:: pw::string::FormatVaList
- Returns:
- null-terminated length of the string excluding the null terminator.
- OutOfRange - if the string is not null-terminated.
+pw::string::NullTerminatedLength()
+----------------------------------
+.. doxygenfunction:: pw::string::NullTerminatedLength(const char* str, size_t max_len)
+.. doxygenfunction:: pw::string::NullTerminatedLength(span<const char> str)
- Precondition: The string shall be at a valid pointer.
-
-pw::string::PrintableCopy
--------------------------
-The ``pw::string::PrintableCopy`` function provides a safe printable copy of a
-string. It functions with the same safety of ``pw::string::Copy`` while also
-converting any non-printable characters to a ``.`` char.
-
-.. cpp:function:: StatusWithSize PrintableCopy(const std::string_view& source, span<char> dest)
+pw::string::PrintableCopy()
+---------------------------
+.. doxygenfunction:: pw::string::PrintableCopy(const std::string_view& source, span<char> dest)
-----------------
pw::StringBuilder
-----------------
-.. cpp:namespace-push:: pw::StringBuilder
-
-:cpp:class:`StringBuilder` facilitates creating formatted strings in a
-fixed-sized buffer or :cpp:type:`pw::InlineString`. It is designed to give the
-flexibility of ``std::ostringstream``, but with a small footprint.
-
-:cpp:class:`StringBuilder` supports C++ ``<<``-style output, printf formatting,
-and a few ``std::string`` functions (:cpp:func:`append()`,
-:cpp:func:`push_back()`, :cpp:func:`pop_back`.
-
-.. cpp:namespace-pop::
-
+.. doxygenfile:: pw_string/string_builder.h
+ :sections: briefdescription
.. doxygenclass:: pw::StringBuilder
:members:
diff --git a/pw_string/public/pw_string/format.h b/pw_string/public/pw_string/format.h
index 7d05fe0c2..205210a8c 100644
--- a/pw_string/public/pw_string/format.h
+++ b/pw_string/public/pw_string/format.h
@@ -29,22 +29,24 @@
namespace pw::string {
-// Writes a printf-style formatted string to the provided buffer, similarly to
-// std::snprintf. Returns the number of characters written, excluding the null
-// terminator. The buffer is always null-terminated unless it is empty.
-//
-// The status is
-//
-// OkStatus() if the operation succeeded,
-// Status::ResourceExhausted() if the buffer was too small to fit the output,
-// Status::InvalidArgument() if there was a formatting error.
-//
+/// @brief Writes a printf-style formatted string to the provided buffer,
+/// similarly to `std::snprintf()`.
+///
+/// The `std::snprintf()` return value is awkward to interpret, and
+/// misinterpreting it can lead to serious bugs.
+///
+/// @returns The number of characters written, excluding the null
+/// terminator. The buffer is always null-terminated unless it is empty.
+/// The status is `OkStatus()` if the operation succeeded,
+/// `Status::ResourceExhausted()` if the buffer was too small to fit the output,
+/// or `Status::InvalidArgument()` if there was a formatting error.
PW_PRINTF_FORMAT(2, 3)
StatusWithSize Format(span<char> buffer, const char* format, ...);
-// Writes a printf-style formatted string with va_list-packed arguments to the
-// provided buffer, similarly to std::vsnprintf. The return value is the same as
-// above.
+/// @brief Writes a printf-style formatted string with va_list-packed arguments
+/// to the provided buffer, similarly to `std::vsnprintf()`.
+///
+/// @returns See `pw::string::Format()`.
PW_PRINTF_FORMAT(2, 0)
StatusWithSize FormatVaList(span<char> buffer,
const char* format,
diff --git a/pw_string/public/pw_string/string.h b/pw_string/public/pw_string/string.h
index 441b218d1..daaa9a900 100644
--- a/pw_string/public/pw_string/string.h
+++ b/pw_string/public/pw_string/string.h
@@ -13,6 +13,11 @@
// the License.
#pragma once
+/// @file pw_string/string.h
+///
+/// @brief `pw::InlineBasicString` and `pw::InlineString` are safer alternatives
+/// to `std::basic_string` and `std::string`.
+
#include <cstddef>
#include <initializer_list>
#include <iterator>
@@ -36,21 +41,23 @@
namespace pw {
-// pw::InlineBasicString<T, kCapacity> is a fixed-capacity version of
-// std::basic_string. It implements mostly the same API as std::basic_string,
-// but the capacity of the string is fixed at construction and cannot grow.
-// Attempting to increase the size beyond the capacity triggers an assert.
-//
-// A pw::InlineString alias of pw::InlineBasicString<char>, equivalent to
-// std::string, is defined below.
-//
-// pw::InlineBasicString has a template parameter for the capacity, but the
-// capacity does not have to be known to use the string. The
-// pw::InlineBasicString template inherits from a pw::InlineBasicString
-// specialization with capacity of the reserved value pw::InlineString<>::npos.
-// The actual capacity is stored in a single word alongside the size. This
-// allows code to work with strings of any capacity through a pw::InlineString<>
-// or pw::InlineBasicString<T> reference.
+/// @brief `pw::InlineBasicString` is a fixed-capacity version of
+/// `std::basic_string`.
+///
+/// It is C++14-compatible and null-terminated. It stores the string contents
+/// inline and uses no dynamic memory. It implements mostly the same API as
+/// `std::basic_string`, but the capacity of the string is fixed at construction
+/// and cannot grow. Attempting to increase the size beyond the capacity
+/// triggers an assert. `pw::InlineBasicString` has a template parameter for the
+/// capacity, but the capacity does not have to be known to use the string. The
+/// `pw::InlineBasicString` template inherits from a `pw::InlineBasicString`
+/// specialization with capacity of the reserved value
+/// `pw::InlineString<>::npos`. The actual capacity is stored in a single word
+/// alongside the size. This allows code to work with strings of any capacity
+/// through a `pw::InlineString<>` or `pw::InlineBasicString<T>` reference.
+///
+/// See also `pw::InlineString`, which is an alias of
+/// `pw::InlineBasicString<char>` and is equivalent to `std::string`.
template <typename T, string_impl::size_type kCapacity = string_impl::kGeneric>
class InlineBasicString final
: public InlineBasicString<T, string_impl::kGeneric> {
@@ -566,6 +573,20 @@ constexpr bool operator>=(const T* lhs,
// TODO(b/239996007): Implement other comparison operator overloads.
// Aliases
+
+/// @brief `pw::InlineString` is an alias of `pw::InlineBasicString<char>` and
+/// is equivalent to `std::string`.
+///
+/// `pw::InlineString` takes the fixed capacity as a template argument, but may
+/// be used generically without specifying the capacity. The capacity value is
+/// stored in a member variable, which the generic `pw::InlineString<>` /
+/// `pw::InlineBasicString<T>` specialization uses in place of the template
+/// parameter.
+///
+/// `pw::InlineString` is efficient and compact. The current size and capacity
+/// are stored in a single word. Accessing the contents of a `pw::InlineString`
+/// is a simple array access within the object, with no pointer indirection,
+/// even when working from a generic `pw::InlineString<>` reference.
template <string_impl::size_type kCapacity = string_impl::kGeneric>
using InlineString = InlineBasicString<char, kCapacity>;
diff --git a/pw_string/public/pw_string/string_builder.h b/pw_string/public/pw_string/string_builder.h
index 886aa609f..322546485 100644
--- a/pw_string/public/pw_string/string_builder.h
+++ b/pw_string/public/pw_string/string_builder.h
@@ -12,6 +12,11 @@
// License for the specific language governing permissions and limitations under
// the License.
#pragma once
+/// @file pw_string/string_builder.h
+///
+/// @brief `pw::StringBuilder` facilitates creating formatted strings in a
+/// fixed-sized buffer or `pw::InlineString`. It is designed to give the
+/// flexibility of `std::ostringstream`, but with a small footprint.
#include <algorithm>
#include <cstdarg>
@@ -32,19 +37,18 @@ namespace pw {
/// @class StringBuilder
///
-/// `StringBuilder` facilitates building formatted strings in a fixed-size
-/// buffer. StringBuilders are always null terminated (unless they are
+/// `pw::StringBuilder` instances are always null-terminated (unless they are
/// constructed with an empty buffer) and never overflow. Status is tracked for
/// each operation and an overall status is maintained, which reflects the most
/// recent error.
///
-/// A `StringBuilder` does not own the buffer it writes to. It can be used to
-/// write strings to any buffer. The StringBuffer template class, defined below,
-/// allocates a buffer alongside a `StringBuilder`.
+/// `pw::StringBuilder` does not own the buffer it writes to. It can be used
+/// to write strings to any buffer. The `pw::StringBuffer` template class,
+/// defined below, allocates a buffer alongside a `pw::StringBuilder`.
///
-/// `StringBuilder` supports C++-style << output, similar to
-/// `std::ostringstream`. It also supports std::string-like append functions and
-/// printf-style output.
+/// `pw::StringBuilder` supports C++-style `<<` output, similar to
+/// `std::ostringstream`. It also supports append functions like `std::string`
+/// and `printf`-style output.
///
/// Support for custom types is added by overloading `operator<<` in the same
/// namespace as the custom type. For example:
@@ -65,8 +69,8 @@ namespace pw {
/// } // namespace my_project
/// @endcode
///
-/// The ToString template function can be specialized to support custom types
-/// with `StringBuilder`, though overloading `operator<<` is generally
+/// The `ToString` template function can be specialized to support custom types
+/// with `pw::StringBuilder`, though overloading `operator<<` is generally
/// preferred. For example:
///
/// @code
@@ -82,7 +86,7 @@ namespace pw {
///
class StringBuilder {
public:
- /// Creates an empty StringBuilder.
+ /// Creates an empty `pw::StringBuilder`.
explicit constexpr StringBuilder(span<char> buffer)
: buffer_(buffer), size_(&inline_size_), inline_size_(0) {
NullTerminate();
@@ -98,7 +102,7 @@ class StringBuilder {
inline_size_(0) {}
/// Disallow copy/assign to avoid confusion about where the string is actually
- /// stored. StringBuffers may be copied into one another.
+ /// stored. `pw::StringBuffer` instances may be copied into one another.
StringBuilder(const StringBuilder&) = delete;
StringBuilder& operator=(const StringBuilder&) = delete;
@@ -110,40 +114,41 @@ class StringBuilder {
const char* data() const { return buffer_.data(); }
const char* c_str() const { return data(); }
- /// Returns a std::string_view of the contents of this StringBuilder. The
- /// std::string_view is invalidated if the StringBuilder contents change.
+ /// Returns a `std::string_view` of the contents of this `pw::StringBuilder`.
+ /// The `std::string_view` is invalidated if the `pw::StringBuilder` contents
+ /// change.
std::string_view view() const { return std::string_view(data(), size()); }
- /// Allow implicit conversions to std::string_view so StringBuilders can be
- /// passed into functions that take a std::string_view.
+ /// Allow implicit conversions to `std::string_view` so `pw::StringBuilder`
+ /// instances can be passed into functions that take a `std::string_view`.
operator std::string_view() const { return view(); }
- /// Returns a span<const std::byte> representation of this StringBuffer.
+ /// Returns a `span<const std::byte>` representation of this
+ /// `pw::StringBuffer`.
span<const std::byte> as_bytes() const {
return span(reinterpret_cast<const std::byte*>(buffer_.data()), size());
}
- /// Returns the StringBuilder's status, which reflects the most recent error
- /// that occurred while updating the string. After an update fails, the status
- /// remains non-OK until it is cleared with clear() or clear_status().
- /// Returns:
- ///
- /// OK if no errors have occurred
- /// RESOURCE_EXHAUSTED if output to the StringBuilder was truncated
- /// INVALID_ARGUMENT if printf-style formatting failed
- /// OUT_OF_RANGE if an operation outside the buffer was attempted
+ /// Returns the status of `pw::StringBuilder`, which reflects the most recent
+ /// error that occurred while updating the string. After an update fails, the
+ /// status remains non-OK until it is cleared with
+ /// `pw::StringBuilder::clear()` or `pw::StringBuilder::clear_status()`.
///
+ /// @returns `OK` if no errors have occurred; `RESOURCE_EXHAUSTED` if output
+ /// to the `StringBuilder` was truncated; `INVALID_ARGUMENT` if `printf`-style
+ /// formatting failed; `OUT_OF_RANGE` if an operation outside the buffer was
+ /// attempted.
Status status() const { return static_cast<Status::Code>(status_); }
- /// Returns status() and size() as a StatusWithSize.
+ /// Returns `status()` and `size()` as a `StatusWithSize`.
StatusWithSize status_with_size() const {
return StatusWithSize(status(), size());
}
- /// The status from the last operation. May be OK while status() is not OK.
+ /// The status from the last operation. May be OK while `status()` is not OK.
Status last_status() const { return static_cast<Status::Code>(last_status_); }
- /// True if status() is OkStatus().
+ /// True if `status()` is `OkStatus()`.
bool ok() const { return status().ok(); }
/// True if the string is empty.
@@ -158,57 +163,58 @@ class StringBuilder {
/// Clears the string and resets its error state.
void clear();
- /// Sets the statuses to OkStatus();
+ /// Sets the statuses to `OkStatus()`;
void clear_status() {
status_ = static_cast<unsigned char>(OkStatus().code());
last_status_ = static_cast<unsigned char>(OkStatus().code());
}
- /// Appends a single character. Stets the status to RESOURCE_EXHAUSTED if the
+ /// Appends a single character. Sets the status to `RESOURCE_EXHAUSTED` if the
/// character cannot be added because the buffer is full.
void push_back(char ch) { append(1, ch); }
- /// Removes the last character. Sets the status to OUT_OF_RANGE if the buffer
- /// is empty (in which case the unsigned overflow is intentional).
+ /// Removes the last character. Sets the status to `OUT_OF_RANGE` if the
+ /// buffer is empty (in which case the unsigned overflow is intentional).
void pop_back() PW_NO_SANITIZE("unsigned-integer-overflow") {
resize(size() - 1);
}
- /// Appends the provided character count times.
+ /// Appends the provided character `count` times.
StringBuilder& append(size_t count, char ch);
- /// Appends count characters from str to the end of the StringBuilder. If
- /// count exceeds the remaining space in the StringBuffer, max_size() - size()
- /// characters are appended and the status is set to RESOURCE_EXHAUSTED.
+ /// Appends `count` characters from `str` to the end of the `StringBuilder`.
+ /// If count exceeds the remaining space in the `StringBuffer`,
+ /// `max_size() - size()` characters are appended and the status is set to
+ /// `RESOURCE_EXHAUSTED`.
///
- /// str is not considered null-terminated and may contain null characters.
+ /// `str` is not considered null-terminated and may contain null characters.
StringBuilder& append(const char* str, size_t count);
/// Appends characters from the null-terminated string to the end of the
- /// StringBuilder. If the string's length exceeds the remaining space in the
- /// buffer, max_size() - size() characters are copied and the status is set to
- /// RESOURCE_EXHAUSTED.
+ /// `StringBuilder`. If the string's length exceeds the remaining space in the
+ /// buffer, `max_size() - size()` characters are copied and the status is
+ /// set to `RESOURCE_EXHAUSTED`.
///
- /// This function uses string::Length instead of std::strlen to avoid
- /// unbounded reads if the string is not null terminated.
+ /// This function uses `string::Length` instead of `std::strlen` to avoid
+ /// unbounded reads if the string is not null-terminated.
StringBuilder& append(const char* str);
- /// Appends a std::string_view to the end of the StringBuilder.
+ /// Appends a `std::string_view` to the end of the `StringBuilder`.
StringBuilder& append(const std::string_view& str);
- /// Appends a substring from the std::string_view to the StringBuilder. Copies
- /// up to count characters starting from pos to the end of the StringBuilder.
- /// If pos > str.size(), sets the status to OUT_OF_RANGE.
+ /// Appends a substring from the `std::string_view` to the `StringBuilder`.
+ /// Copies up to count characters starting from `pos` to the end of the
+ /// `StringBuilder`. If `pos > str.size()`, sets the status to `OUT_OF_RANGE`.
StringBuilder& append(const std::string_view& str,
size_t pos,
size_t count = std::string_view::npos);
- /// Appends to the end of the StringBuilder using the << operator. This
- /// enables C++ stream-style formatted to StringBuilders.
+ /// Appends to the end of the `StringBuilder` using the `<<` operator. This
+ /// enables C++ stream-style formatted to `StringBuilder` instances.
template <typename T>
StringBuilder& operator<<(const T& value) {
- /// For std::string_view-compatible types, use the append function, which
- /// gives smaller code size.
+ /// For types compatible with `std::string_view`, use the `append` function,
+ /// which gives smaller code size.
if constexpr (std::is_convertible_v<T, std::string_view>) {
append(value);
} else if constexpr (std::is_convertible_v<T, span<const std::byte>>) {
@@ -219,7 +225,7 @@ class StringBuilder {
return *this;
}
- /// Provide a few additional operator<< overloads that reduce code size.
+ /// Provide a few additional `operator<<` overloads that reduce code size.
StringBuilder& operator<<(bool value) {
return append(value ? "true" : "false");
}
@@ -236,32 +242,32 @@ class StringBuilder {
StringBuilder& operator<<(Status status) { return *this << status.str(); }
/// @fn pw::StringBuilder::Format
- /// Appends a printf-style string to the end of the StringBuilder. If the
+ /// Appends a `printf`-style string to the end of the `StringBuilder`. If the
/// formatted string does not fit, the results are truncated and the status is
- /// set to RESOURCE_EXHAUSTED.
+ /// set to `RESOURCE_EXHAUSTED`.
///
/// @param format The format string
/// @param ... Arguments for format specification
///
- /// @return StringBuilder&
+ /// @returns `StringBuilder&`
///
- /// @note Internally, calls string::Format, which calls std::vsnprintf.
+ /// @note Internally, calls `string::Format`, which calls `std::vsnprintf`.
PW_PRINTF_FORMAT(2, 3) StringBuilder& Format(const char* format, ...);
- /// Appends a vsnprintf-style string with va_list arguments to the end of the
- /// StringBuilder. If the formatted string does not fit, the results are
- /// truncated and the status is set to RESOURCE_EXHAUSTED.
+ /// Appends a `vsnprintf`-style string with `va_list` arguments to the end of
+ /// the `StringBuilder`. If the formatted string does not fit, the results are
+ /// truncated and the status is set to `RESOURCE_EXHAUSTED`.
///
- /// Internally, calls string::Format, which calls std::vsnprintf.
+ /// @note Internally, calls `string::Format`, which calls `std::vsnprintf`.
PW_PRINTF_FORMAT(2, 0)
StringBuilder& FormatVaList(const char* format, va_list args);
- /// Sets the StringBuilder's size. This function only truncates; if
- /// new_size > size(), it sets status to OUT_OF_RANGE and does nothing.
+ /// Sets the size of the `StringBuilder`. This function only truncates; if
+ /// `new_size > size()`, it sets status to `OUT_OF_RANGE` and does nothing.
void resize(size_t new_size);
protected:
- /// Functions to support StringBuffer copies.
+ /// Functions to support `StringBuffer` copies.
constexpr StringBuilder(span<char> buffer, const StringBuilder& other)
: buffer_(buffer),
size_(&inline_size_),
@@ -272,7 +278,7 @@ class StringBuilder {
void CopySizeAndStatus(const StringBuilder& other);
private:
- /// Statuses are stored as an unsigned char so they pack into a single word.
+ /// Statuses are stored as an `unsigned char` so they pack into a single word.
static constexpr unsigned char StatusCode(Status status) {
return static_cast<unsigned char>(status.code());
}
@@ -295,16 +301,16 @@ class StringBuilder {
InlineString<>::size_type* size_;
- /// Place the inline_size_, status_, and last_status_ members together and use
- /// unsigned char for the status codes so these members can be packed into a
- /// single word.
+ // Place the `inline_size_`, `status_`, and `last_status_` members together
+ // and use `unsigned char` for the status codes so these members can be
+ // packed into a single word.
InlineString<>::size_type inline_size_;
unsigned char status_ = StatusCode(OkStatus());
unsigned char last_status_ = StatusCode(OkStatus());
};
-// StringBuffers declare a buffer along with a StringBuilder. StringBuffer can
-// be used as a statically allocated replacement for std::ostringstream or
+// StringBuffer declares a buffer along with a StringBuilder. StringBuffer
+// can be used as a statically allocated replacement for std::ostringstream or
// std::string. For example:
//
// StringBuffer<32> str;
diff --git a/pw_string/public/pw_string/util.h b/pw_string/public/pw_string/util.h
index 2e06b6e9f..d95bb798f 100644
--- a/pw_string/public/pw_string/util.h
+++ b/pw_string/public/pw_string/util.h
@@ -12,6 +12,10 @@
// License for the specific language governing permissions and limitations under
// the License.
#pragma once
+/// @file pw_string/util.h
+///
+/// @brief The `pw::string::*` functions provide safer alternatives to
+/// C++ standard library string functions.
#include <cctype>
#include <cstddef>
@@ -46,11 +50,11 @@ PW_CONSTEXPR_CPP20 inline StatusWithSize CopyToSpan(
} // namespace internal
-// Safe alternative to the string_view constructor to avoid the risk of an
-// unbounded implicit or explicit use of strlen.
-//
-// This is strongly recommended over using something like C11's strnlen_s as
-// a string_view does not require null-termination.
+/// @brief Safe alternative to the `string_view` constructor that avoids the
+/// risk of an unbounded implicit or explicit use of `strlen`.
+///
+/// This is strongly recommended over using something like C11's `strnlen_s` as
+/// a `string_view` does not require null-termination.
constexpr std::string_view ClampedCString(span<const char> str) {
return std::string_view(str.data(),
internal::ClampedLength(str.data(), str.size()));
@@ -60,15 +64,16 @@ constexpr std::string_view ClampedCString(const char* str, size_t max_len) {
return ClampedCString(span<const char>(str, max_len));
}
-// Safe alternative to strlen to calculate the null-terminated length of the
-// string within the specified span, excluding the null terminator. Like C11's
-// strnlen_s, the scan for the null-terminator is bounded.
-//
-// Returns:
-// null-terminated length of the string excluding the null terminator.
-// OutOfRange - if the string is not null-terminated.
-//
-// Precondition: The string shall be at a valid pointer.
+/// @brief `pw::string::NullTerminatedLength` is a safer alternative to
+/// `strlen` for calculating the null-terminated length of the
+/// string within the specified span, excluding the null terminator.
+///
+/// Like `strnlen_s` in C11, the scan for the null-terminator is bounded.
+///
+/// @pre The string shall be at a valid pointer.
+///
+/// @returns the null-terminated length of the string excluding the null
+/// terminator or `OutOfRange` if the string is not null-terminated.
constexpr Result<size_t> NullTerminatedLength(span<const char> str) {
PW_DASSERT(str.data() != nullptr);
@@ -84,14 +89,17 @@ constexpr Result<size_t> NullTerminatedLength(const char* str, size_t max_len) {
return NullTerminatedLength(span<const char>(str, max_len));
}
-// Copies the source string to the dest, truncating if the full string does not
-// fit. Always null terminates if dest.size() or num > 0.
-//
-// Returns the number of characters written, excluding the null terminator. If
-// the string is truncated, the status is ResourceExhausted.
-//
-// Precondition: The destination and source shall not overlap.
-// Precondition: The source shall be a valid pointer.
+/// @brief `pw::string::Copy` is a safer alternative to `std::strncpy` as it
+/// always null-terminates whenever the destination buffer has a non-zero size.
+///
+/// Copies the `source` string to the `dest`, truncating if the full string does
+/// not fit. Always null terminates if `dest.size()` or `num` is greater than 0.
+///
+/// @pre The destination and source shall not overlap. The source
+/// shall be a valid pointer.
+///
+/// @returns the number of characters written, excluding the null terminator. If
+/// the string is truncated, the status is `RESOURCE_EXHAUSTED`.
template <typename Span>
PW_CONSTEXPR_CPP20 inline StatusWithSize Copy(const std::string_view& source,
Span&& dest) {
@@ -116,13 +124,14 @@ PW_CONSTEXPR_CPP20 inline StatusWithSize Copy(const char* source,
return Copy(source, span<char>(dest, num));
}
-// Assigns a std::string_view to a pw::InlineString, truncating if it does not
-// fit. pw::InlineString's assign() function asserts if the string's requested
-// size exceeds its capacity; pw::string::Assign() returns a Status instead.
-//
-// Returns:
-// OK - the entire std::string_view was copied to the end of the InlineString
-// RESOURCE_EXHAUSTED - the std::string_view was truncated to fit
+/// Assigns a `std::string_view` to a `pw::InlineString`, truncating if it does
+/// not fit. The `assign()` function of `pw::InlineString` asserts if the
+/// string's requested size exceeds its capacity; `pw::string::Assign()`
+/// returns a `Status` instead.
+///
+/// @return `OK` if the entire `std::string_view` was copied to the end of the
+/// `pw::InlineString`. `RESOURCE_EXHAUSTED` if the `std::string_view` was
+/// truncated to fit.
inline Status Assign(InlineString<>& string, const std::string_view& view) {
const size_t chars_copied =
std::min(view.size(), static_cast<size_t>(string.capacity()));
@@ -136,13 +145,13 @@ inline Status Assign(InlineString<>& string, const char* c_string) {
return Assign(string, ClampedCString(c_string, string.capacity() + 1));
}
-// Appends a std::string_view to a pw::InlineString, truncating if it does not
-// fit. pw::InlineString's append() function asserts if the string's requested
-// size exceeds its capacity; pw::string::Append() returns a Status instead.
-//
-// Returns:
-// OK - the entire std::string_view was assigned
-// RESOURCE_EXHAUSTED - the std::string_view was truncated to fit
+/// Appends a `std::string_view` to a `pw::InlineString`, truncating if it
+/// does not fit. The `append()` function of `pw::InlineString` asserts if the
+/// string's requested size exceeds its capacity; `pw::string::Append()` returns
+/// a `Status` instead.
+///
+/// @return `OK` if the entire `std::string_view` was assigned.
+/// `RESOURCE_EXHAUSTED` if the `std::string_view` was truncated to fit.
inline Status Append(InlineString<>& string, const std::string_view& view) {
const size_t chars_copied = std::min(
view.size(), static_cast<size_t>(string.capacity() - string.size()));
@@ -156,8 +165,11 @@ inline Status Append(InlineString<>& string, const char* c_string) {
return Append(string, ClampedCString(c_string, string.capacity() + 1));
}
-// Copies source string to the dest with same behavior as Copy, with the
-// difference that any non-printable characters are changed to '.'.
+/// @brief Provides a safe, printable copy of a string.
+///
+/// Copies the `source` string to the `dest` string with same behavior as
+/// `pw::string::Copy`, with the difference that any non-printable characters
+/// are changed to `.`.
PW_CONSTEXPR_CPP20 inline StatusWithSize PrintableCopy(
const std::string_view& source, span<char> dest) {
StatusWithSize copy_result = Copy(source, dest);