1
0
mirror of https://github.com/SerenityOS/serenity synced 2024-07-05 21:49:58 +00:00
serenity/AK/FlyString.h
Linus Groh 85414d9338 AK: Add operator""_{short_,}string to create a String from a literal
We briefly discussed this when adding the new String type but couldn't
settle on a name. However, having to use String::from_utf8() on every
literal string is a bit unwieldy, so let's have these options available!

Naming-wise '_string' is not as short as 'sv' but should be relatively
clear; it also matches '_bigint' and '_ubigint' in length.
'_short_string' may be longer than the actual string itself, but it's
still an improvement over the static function :^)

Since our C++ source files are UTF-8 encoded anyway, it should be
impossible to create a string literal with invalid UTF-8, so including
that in the name is not as important as in the function that can receive
arbitrary data.
2023-02-25 20:51:49 +01:00

80 lines
2.0 KiB
C++

/*
* Copyright (c) 2023, Tim Flynn <trflynn89@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Error.h>
#include <AK/Format.h>
#include <AK/Platform.h>
#include <AK/String.h>
#include <AK/Traits.h>
#include <AK/Types.h>
namespace AK {
class FlyString {
public:
FlyString();
~FlyString();
static ErrorOr<FlyString> from_utf8(StringView);
FlyString(String const&);
FlyString& operator=(String const&);
FlyString(FlyString const&);
FlyString& operator=(FlyString const&);
FlyString(FlyString&&);
FlyString& operator=(FlyString&&);
[[nodiscard]] bool is_empty() const;
[[nodiscard]] unsigned hash() const;
explicit operator String() const;
String to_string() const;
[[nodiscard]] Utf8View code_points() const;
[[nodiscard]] ReadonlyBytes bytes() const;
[[nodiscard]] StringView bytes_as_string_view() const;
[[nodiscard]] bool operator==(FlyString const& other) const;
[[nodiscard]] bool operator==(String const&) const;
[[nodiscard]] bool operator==(StringView) const;
[[nodiscard]] bool operator==(char const*) const;
static void did_destroy_fly_string_data(Badge<Detail::StringData>, StringView);
[[nodiscard]] uintptr_t data(Badge<String>) const;
// This is primarily interesting to unit tests.
[[nodiscard]] static size_t number_of_fly_strings();
private:
// This will hold either the pointer to the Detail::StringData it represents or the raw bytes of
// an inlined short string.
uintptr_t m_data { 0 };
};
template<>
struct Traits<FlyString> : public GenericTraits<FlyString> {
static unsigned hash(FlyString const&);
};
template<>
struct Formatter<FlyString> : Formatter<StringView> {
ErrorOr<void> format(FormatBuilder&, FlyString const&);
};
}
[[nodiscard]] ALWAYS_INLINE AK::ErrorOr<AK::FlyString> operator""_fly_string(char const* cstring, size_t length)
{
return AK::FlyString::from_utf8(AK::StringView(cstring, length));
}
#if USING_AK_GLOBALLY
using AK::FlyString;
#endif