2 * Copyright (c) 2023 Philippe Proulx <pproulx@efficios.com>
4 * SPDX-License-Identifier: MIT
7 #ifndef BABELTRACE_CPP_COMMON_BT2C_C_STRING_VIEW_HPP
8 #define BABELTRACE_CPP_COMMON_BT2C_C_STRING_VIEW_HPP
14 #include "common/assert.h"
15 #include "cpp-common/bt2s/string-view.hpp"
16 #include "cpp-common/vendor/fmt/core.h"
21 * A view on a constant null-terminated C string.
23 * Similar to `bt2s::string_view`, but len() and end() compute the
26 class CStringView final
30 * Builds an empty view (data() returns `nullptr`).
32 * Intentionally not explicit.
34 CStringView() noexcept = default;
37 * Builds a view of the C string `str` (may be `nullptr`).
39 * Intentionally not explicit.
41 CStringView(const char * const str) noexcept : _mStr {str}
46 * Makes this view view the C string `str` (may be `nullptr`).
48 * Intentionally not explicit.
50 CStringView& operator=(const char * const str) noexcept
57 * Viewed null-terminated C string (may be `nullptr`).
59 const char *data() const noexcept
67 operator const char *() const noexcept
75 const char *operator*() const noexcept
83 * data() must not return `nullptr`.
85 const char *begin() const noexcept
92 * Pointer to the null character of the viewed C string.
94 * data() must not return `nullptr`.
96 const char *end() const noexcept
99 return _mStr + this->len();
103 * Length of the viewed C string, excluding the null character.
105 * data() must not return `nullptr`.
107 std::size_t len() const noexcept
109 BT_ASSERT_DBG(_mStr);
110 return std::strlen(_mStr);
114 * Returns an `std::string` instance containing a copy of the viewed
117 * data() must not return `nullptr`.
119 std::string str() const
121 BT_ASSERT_DBG(_mStr);
122 return std::string {_mStr};
128 operator std::string() const
134 * Returns a `bt2s::string_view` instance to view the contents,
135 * excluding the null character, of the viewed C string.
137 bt2s::string_view strView() const noexcept
140 return bt2s::string_view {this->begin(), this->len()};
147 * Alias of strView().
149 operator bt2s::string_view() const noexcept
151 return this->strView();
155 * Returns the character at index `i`.
157 * `i` must be less than what len() returns.
159 * data() must not return `nullptr`.
161 char operator[](const std::size_t i) const noexcept
163 BT_ASSERT_DBG(_mStr);
164 BT_ASSERT_DBG(i < this->len());
169 const char *_mStr = nullptr;
172 } /* namespace bt2c */
177 struct formatter<bt2c::CStringView>
179 constexpr auto parse(format_parse_context& ctx) const -> format_parse_context::iterator
184 auto format(const bt2c::CStringView& str, format_context& ctx) const -> format_context::iterator
186 return str ? fmt::format_to(ctx.out(), "{}", *str) : fmt::format_to(ctx.out(), "(null)");
190 } /* namespace fmt */
192 #endif /* BABELTRACE_CPP_COMMON_BT2C_C_STRING_VIEW_HPP */