Cogs.Core
ImmutableString.h
1#pragma once
2
3#include "StringView.h"
4
5#include <cstring>
6
7namespace Cogs {
8
39 {
40 public:
41
43 constexpr ImmutableString() noexcept = default;
44
47
49 ImmutableString& operator=(const ImmutableString&) = delete;
50
52 constexpr ImmutableString(ImmutableString&& other) noexcept { this->swap(other); }
53
55 constexpr ImmutableString& operator=(ImmutableString&& other) noexcept { this->swap(other); return *this; }
56
58 COGSFOUNDATION_API ImmutableString(const Cogs::StringView& view);
59
62
64 constexpr operator const char* () const noexcept { return c_str(); }
65
67 constexpr operator Cogs::StringView() const noexcept { return asView(); }
68
70 constexpr void swap(ImmutableString& other) noexcept { std::swap(ptr, other.ptr); }
71
73 constexpr Cogs::StringView asView() const noexcept { return ptr ? Cogs::StringView(ptr + sizeof(size_t), *reinterpret_cast<size_t*>(ptr)) : Cogs::StringView(); }
74
76 constexpr bool empty() const noexcept { return ptr == nullptr; }
77
79 void clear() { if (ptr) release(); }
80
82 constexpr const char* c_str() const noexcept { return ptr ? (ptr + sizeof(size_t)) : nullptr; }
83
85 constexpr size_t size() const noexcept { size_t size = 0; if (ptr) { std::memcpy(&size, ptr, sizeof(size)); } return size; }
86
87 private:
88
89 COGSFOUNDATION_API void release();
90
91 char* ptr = nullptr;
92 };
93 static_assert(sizeof(ImmutableString) == sizeof(char*));
94}
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:50
Contains all Cogs related functionality.
Definition: FieldSetter.h:23