diff options
author | Brian Gianforcaro <bgianf@serenityos.org> | 2021-09-27 18:28:46 -0700 |
---|---|---|
committer | Andreas Kling <kling@serenityos.org> | 2021-09-28 10:57:00 +0200 |
commit | f71f1d66d6545fff6c10b1e30648901bf1c4b795 (patch) | |
tree | f541a890a06c00b5e0427ffda804acb9acc9e707 | |
parent | ad33efbc8cc081a10b45afa9f1a845a959c0dba1 (diff) | |
download | serenity-f71f1d66d6545fff6c10b1e30648901bf1c4b795.zip |
Documentation: Add operator"" sv pattern to Patterns.md
-rw-r--r-- | Documentation/Patterns.md | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/Documentation/Patterns.md b/Documentation/Patterns.md index 9870321e11..425d7c6324 100644 --- a/Documentation/Patterns.md +++ b/Documentation/Patterns.md @@ -80,3 +80,35 @@ struct Empty { }; static_assert(AssertSize<Empty, 1>()); ``` + +## String View Literals + +`AK::StringView` support for `operator"" sv` which is a special string literal operator that was added as of +[C++17 to enable `std::string_view` literals](https://en.cppreference.com/w/cpp/string/basic_string_view/operator%22%22sv). + +```cpp +[[nodiscard]] ALWAYS_INLINE constexpr AK::StringView operator"" sv(const char* cstring, size_t length) +{ + return AK::StringView(cstring, length); +} +``` + +This allows `AK::StringView` to be constructed from string literals with no runtime +cost to find the string length, and the data the `AK::StringView` points to will +reside in the data section of the binary. + +Example Usage: +```cpp +#include <AK/String.h> +#include <AK/StringView.h> +#include <LibTest/TestCase.h> + +TEST_CASE(string_view_literal_operator) +{ + StringView literal_view = "foo"sv; + String test_string = "foo"; + + EXPECT_EQ(literal_view.length(), test_string.length()); + EXPECT_EQ(literal_view, test_string); +} +``` |