Cogs.Core
ImmutableString.h
1#pragma once
2
3#include "StringView.h"
4
5#include <cstring>
6
7namespace Cogs {
8
22 {
23 public:
24
26 constexpr ImmutableString() noexcept = default;
27
30
32 ImmutableString& operator=(const ImmutableString&) = delete;
33
35 constexpr ImmutableString(ImmutableString&& other) noexcept { this->swap(other); }
36
38 constexpr ImmutableString& operator=(ImmutableString&& other) noexcept { this->swap(other); return *this; }
39
41 COGSFOUNDATION_API ImmutableString(const Cogs::StringView& view);
42
45
47 constexpr operator const char* () const noexcept { return c_str(); }
48
50 constexpr operator Cogs::StringView() const noexcept { return asView(); }
51
53 constexpr void swap(ImmutableString& other) noexcept { std::swap(ptr, other.ptr); }
54
56 constexpr Cogs::StringView asView() const noexcept { return ptr ? Cogs::StringView(ptr + sizeof(size_t), *reinterpret_cast<size_t*>(ptr)) : Cogs::StringView(); }
57
59 constexpr bool empty() const noexcept { return ptr == nullptr; }
60
62 void clear() { if (ptr) release(); }
63
65 constexpr const char* c_str() const noexcept { return ptr ? (ptr + sizeof(size_t)) : nullptr; }
66
68 constexpr size_t size() const noexcept { size_t size = 0; if (ptr) { std::memcpy(&size, ptr, sizeof(size)); } return size; }
69
70 private:
71
72 COGSFOUNDATION_API void release();
73
74 char* ptr = nullptr;
75 };
76 static_assert(sizeof(ImmutableString) == sizeof(char*));
77}
Represents a non-copyable immutable string.
constexpr ImmutableString & operator=(ImmutableString &&other) noexcept
Take ownership of another string.
constexpr void swap(ImmutableString &other) noexcept
Swap contents with another string.
constexpr const char * c_str() const noexcept
Get the string as C-string.
constexpr ImmutableString() noexcept=default
Create an empty string.
constexpr Cogs::StringView asView() const noexcept
Explicitly view the string as a string view.
constexpr size_t size() const noexcept
Get the string length.
constexpr bool empty() const noexcept
Check if string is empty.
~ImmutableString()
Destructor.
void clear()
Set contents to the empty string.
Provides a weakly referenced view over the contents of a string.
Definition: StringView.h:24
Contains all Cogs related functionality.
Definition: FieldSetter.h:23