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/format.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 constexpr CStringView() noexcept = default;
37 * Builds a view of the C string `str` (may be `nullptr`).
39 * Intentionally not explicit.
41 constexpr CStringView(const char * const str) noexcept : _mStr {str}
46 * Builds a view of the string `str`.
48 * Intentionally not explicit.
50 CStringView(const std::string& str) noexcept : _mStr {str.c_str()}
55 * Makes this view view the C string `str` (may be `nullptr`).
57 * Intentionally not explicit.
59 CStringView& operator=(const char * const str) noexcept
66 * Viewed null-terminated C string (may be `nullptr`).
68 const char *data() const noexcept
76 operator const char *() const noexcept
84 const char *operator*() const noexcept
92 * data() must not return `nullptr`.
94 const char *begin() const noexcept
101 * Pointer to the null character of the viewed C string.
103 * data() must not return `nullptr`.
105 const char *end() const noexcept
107 BT_ASSERT_DBG(_mStr);
108 return _mStr + this->len();
112 * Length of the viewed C string, excluding the null character.
114 * data() must not return `nullptr`.
116 std::size_t len() const noexcept
118 BT_ASSERT_DBG(_mStr);
119 return std::strlen(_mStr);
123 * Returns an `std::string` instance containing a copy of the viewed
126 * data() must not return `nullptr`.
128 std::string str() const
130 BT_ASSERT_DBG(_mStr);
131 return std::string {_mStr};
137 operator std::string() const
143 * Returns a `bt2s::string_view` instance to view the contents,
144 * excluding the null character, of the viewed C string.
146 bt2s::string_view strView() const noexcept
149 return bt2s::string_view {this->begin(), this->len()};
156 * Alias of strView().
158 operator bt2s::string_view() const noexcept
160 return this->strView();
164 * Returns the character at index `i`.
166 * `i` must be less than what len() returns.
168 * data() must not return `nullptr`.
170 char operator[](const std::size_t i) const noexcept
172 BT_ASSERT_DBG(_mStr);
173 BT_ASSERT_DBG(i < this->len());
178 const char *_mStr = nullptr;
181 static inline const char *format_as(const CStringView& str)
183 return str ? *str : "(null)";
186 } /* namespace bt2c */
188 #endif /* BABELTRACE_CPP_COMMON_BT2C_C_STRING_VIEW_HPP */