SDEngine
Game Engine
Loading...
Searching...
No Matches
FixedString.hpp
Go to the documentation of this file.
1#pragma once
2#include <algorithm>
3#include <array>
4#include <string_view>
5
6#include <fmt/core.h>
7
8#include "SD/core/types.hpp"
9
10// todo: move
12 const char* msg); // a bit ugly, but since we dont have exceptions on, we could possibly turn on
13// exceptions for compile time stuff, but that makes it harder to catch
14// accidental exceptions in other stuff
15
16
17template<USize MAX_SIZE>
19 std::array<char, MAX_SIZE> data{};
21 constexpr FixedString() = default;
22 consteval explicit FixedString(std::string_view sv) {
23 if (sv.size() > MAX_SIZE)
24 compile_time_assert_failed("Provided string doesnt fit in type");
25
26 std::ranges::copy_n(
27 sv.begin(),
28 sv.size(),
29 data.begin()); // i get no matchin function to call for typpe const __copy_n_fn
30 size = sv.size();
31 }
32
33 consteval explicit FixedString(const char ch) {
34 data = {ch};
35 size = 1;
36 }
37 constexpr explicit operator std::string_view() const {
38 return std::string_view(data.data(), size);
39 }
40};
41template<USize N>
42struct fmt::formatter<FixedString<N>> {
43 constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }
44 auto format(const FixedString<N>& value, format_context& ctx) {
45 return std::copy(value.data.begin(),
46 value.data.begin() + static_cast<std::ptrdiff_t>(value.size),
47 ctx.out());
48 }
49};
50
51// NOTE: We dont want + operator to create new types automatically, we rather that to be explicit
52// when needed
53template<std::size_t MAX_SIZE>
55 auto new_size = lhs.size + rhs.size;
56 if (new_size > MAX_SIZE)
57 compile_time_assert_failed("Sizes of lhs and rhs cant exceed type MAX_SIZE");
59
60 std::ranges::copy_n(lhs.data.begin(), lhs.size, buffer.data.begin());
61 std::ranges::copy_n(rhs.data.begin(), rhs.size, buffer.data.begin() + lhs.size);
62 buffer.size = new_size;
63
64 return buffer;
65}
consteval auto operator+(FixedString< MAX_SIZE > lhs, FixedString< MAX_SIZE > rhs)
Definition FixedString.hpp:54
void compile_time_assert_failed(const char *msg)
Definition FixedString.hpp:18
USize size
Definition FixedString.hpp:20
constexpr FixedString()=default
consteval FixedString(std::string_view sv)
Definition FixedString.hpp:22
std::array< char, MAX_SIZE > data
Definition FixedString.hpp:19
consteval FixedString(const char ch)
Definition FixedString.hpp:33
constexpr auto parse(format_parse_context &ctx)
Definition FixedString.hpp:43
auto format(const FixedString< N > &value, format_context &ctx)
Definition FixedString.hpp:44
consteval U64 type_id_of()
Definition type_id.hpp:6
std::size_t USize
Definition types.hpp:18