AStringView#
Non-owning view into a UTF-8 string - a lightweight const reference to character data you don't own.
| Header: | #include <AUI/Common/AStringView.h> |
| CMake: | aui_link(my_target PUBLIC aui::core) |
Detailed Description#
AStringView is the read-only counterpart to AString. It inherits from std::string_view and holds
only a pointer and a length - no heap allocation, no copy. This makes it the correct type to use
for any function parameter that only needs to read a string, regardless of whether the caller holds
an AString, a std::string, a const char*, or a string literal.
Why AStringView exists#
Before non-owning views, a function that accepted a string had two bad options:
- Take const AString& - forces the caller to own an AString; a raw const char* or std::string
triggers a silent heap allocation just to call the function.
- Take const char* - loses the length, breaks on embedded nulls, and can't accept std::string
without .c_str().
AStringView eliminates both problems. It constructs implicitly from const char*, std::string_view,
AString, and char8_t* with zero overhead, so callers pass whatever they already have:
void log(AStringView message); // one signature, every string type accepted
log("literal"); // const char* - no allocation
log(some_astring); // AString - no copy
log(some_std_string_view); // string_view - no copy
Lifetime responsibility#
AStringView does not own its data. It is only valid as long as the underlying string is alive.
Never store an AStringView that outlives its source, and never return one that points into a local:
AStringView bad() {
AString local = "hello";
return local.trim(); // dangling - local is destroyed on return
}
Typical usage#
AStringView s = " Hello, World! ";
s = s.trim() // "Hello, World!" (returns a new view, no allocation)
s.startsWith("Hello") // true
s.contains("World") // true
AString upper = s.uppercase(); // " HELLO, WORLD! " (allocates only here)
auto parts = s.trim().split(", "); // AStringVector{"Hello", "World!"}
Numeric parsing#
AStringView("42").toInt() // AOptional<int32_t>{42}
AStringView("0xFF").toInt() // AOptional<int32_t>{255} (hex prefix auto-detected)
AStringView("bad").toInt() // AOptional<int32_t>{nullopt}
Note
Methods that must produce a new string - uppercase(), lowercase(), replacedAll(), split(), encode() -
return an AString or AStringVector and allocate only at that point. Pure view operations (trim, substr,
startsWith, contains) return AStringView and never allocate.
See also: AString, AUtf8View, AByteBuffer, AStringVector.
Examples#
examples/7guis/flight_booker/src/main.cpp
7GUIs Flight Booker — Flight Booker.
};
auto formatDate(system_clock::time_point date) { return "{0:%d}.{0:%m}.{0:%G}"_format(date); }
AOptional<system_clock::time_point> parseDate(AStringView s) {
auto std = s.bytes();
auto match = REGEX_DATE.match(std);
if (!match) {
return std::nullopt;
}
Public Methods#
data#
constexpr const char* AStringView::data()
Raw const char* pointer to the string.
- Returns
- A pointer to the first character of the string.
The returned pointer is not guaranteed to be valid C-style string, because we can't insert a null character at the end.
Examples:
examples/ui/views/src/ExampleWindow.cpp
Views Example — All-in-one views building example.
void ExampleWindow::onDragDrop(const ADragNDrop::DropEvent& event) {
ASurface::onDragDrop(event);
for (const auto& [k, v] : event.data.data()) {
ALogger::info("Drop") << "[" << k << "] = " << AString::fromUtf8(v);
}
auto surface = createOverlappingSurface({ 0, 0 }, { 100, 100 }, false);
_<AViewContainer> popup = Vertical {
encode#
AByteBuffer AStringView::encode(AStringEncoding encoding)
Encodes the string into a null-terminated byte buffer using the specified encoding.
See also: bytes, toUtf16, toUtf32.
substr#
Returns a substring [pos, pos + count).
- Arguments
posThe starting position of the substring.countThe number of bytes to include in the substring. If the requested substring extends past the end of the string, i.e. the count is greater than `size() - pos` (e.g. if `count == npos`), the returned substring is `[pos, size())`. `pos` and `count` are interpreted as byte positions. Be careful not to cut a multibyte character in half; use `utf8().substr()` to count in Unicode characters.
toBool#
Converts the string to boolean value.
- Returns
- If the string equals to "true", true returned, false otherwise.
toDouble#
AOptional<double> AStringView::toDouble()
Converts the string to a double number.
- Returns
- The string converted to a double number. If conversion to int is not possible, nullopt is returned.
Examples:
examples/7guis/cells/src/Formula.cpp
7GUIs Cells — Spreadsheet processor (Excel).
formula::Precompiled formula::precompile(const AString& expression) {
if (expression.empty()) {
return [](const Spreadsheet&) { return std::nullopt; };
}
if (auto d = expression.toDouble()) {
return [d = *d](const Spreadsheet&) { return d; };
}
if (!expression.startsWith('=')) {
return [stringConstant = expression](const Spreadsheet&) { return stringConstant; };
}
toFloat#
AOptional<float> AStringView::toFloat()
Converts the string to a float number.
- Returns
- The string converted to a float number. If conversion to int is not possible, nullopt is returned.
toInt#
AOptional<int32_t> AStringView::toInt()
Converts the string to int value.
- Returns
- The string converted to an integer value using base 10. If the string starts with 0x or 0X, the base 16 used. If conversion to int is not possible, nullopt is returned.
toLong#
AOptional<int64_t> AStringView::toLong()
Converts the string to long value.
- Returns
- The string converted to an integer value using base 10. If the string starts with 0x or 0X, the base 16 used. If conversion to long is not possible, nullopt is returned.
toNumber#
Returns the string converted to an int using base. Returns std::nullopt if the conversion fails.
See also: toNumberOrException.
toUInt#
AOptional<uint32_t> AStringView::toUInt()
Converts the string to unsigned int value.
- Returns
- The string converted to an integer value using base 10. If the string starts with 0x or 0X, the base 16 used. If conversion to unsigned int is not possible, exception is thrown.
toULong#
AOptional<uint64_t> AStringView::toULong()
Converts the string to unsigned long value.
- Returns
- The string converted to an integer value using base 10. If the string starts with 0x or 0X, the base 16 used. If conversion to unsigned long is not possible, exception is thrown.
toUtf16#
Encodes the UTF-8 string into a UTF-16 string
See also: bytes, encode.
toUtf32#
Encodes the UTF-8 string into a UTF-32 string
See also: bytes, encode.
trim#
constexpr AStringView AStringView::trim(AChar symbol = ' ')
Removes leading and trailing occurrences of symbol.
- Arguments
symbolsymbol to remove.- Returns
- trimmed view.
Removes only the single symbol. To remove several symbols at once, use trim(AStringView).
Removes leading and trailing symbols that belong to the set symbols (like str.strip(chars) in
Python).
- Arguments
symbolsset of symbols to remove. Any symbol of this string is removed in any order and quantity.- Returns
- trimmed view.
Removes leading occurrences of `symbol`.
AStringView(" \t a b \r\n").trim(" \t\r\n"); // "a b" AStringView("xyhixyx").trim("xy"); // "hi" ```</dd> </dl> <div style="position:absolute;opacity:0" markdown> ### trimLeft { #AStringView::trimLeft AStringView::trimLeft() } </div> --- ```cpp constexpr AStringView AStringView::trimLeft(AChar symbol = ' ')- Arguments
symbolsymbol to remove.- Returns
- view without leading `symbol`s.
- Arguments
symbolsset of symbols to remove. Not a prefix: any symbol of this string is removed in any order and quantity. Empty set removes nothing.- Returns
- view without leading `symbols`.
### trimRight { #AStringView::trimRight AStringView::trimRight() }---Removes trailing occurrences of `symbol`.constexpr AStringView AStringView::trimRight(AChar symbol = ' ')- Arguments
symbolsymbol to remove.- Returns
- view without trailing `symbol`s.
- Arguments
symbolsset of symbols to remove. Not a suffix: any symbol of this string is removed in any order and quantity. Empty set removes nothing.- Returns
- view without trailing `symbols`.