HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
pickle.hpp
1// Copyright Take Vos 2021.
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
4
5#pragma once
6
7#include "required.hpp"
8#include "assert.hpp"
9#include "datum.hpp"
10#include "concepts.hpp"
11#include <string>
12#include <limits>
13
14namespace hi::inline v1 {
15
21template<typename T>
22struct pickle {
28 [[nodiscard]] datum encode(T const &rhs) const noexcept;
29
36 [[nodiscard]] T decode(datum rhs) const;
37};
38
39template<numeric_integral T>
40struct pickle<T> {
41 [[nodiscard]] datum encode(T const &rhs) const noexcept
42 {
43 return datum{rhs};
44 }
45
46 [[nodiscard]] T decode(datum rhs) const
47 {
48 if (auto *i = get_if<long long>(rhs)) {
50 throw parse_error(std::format("Encoded value is to out of range, got {}", rhs));
51 }
52 return static_cast<T>(*i);
53 } else {
54 throw parse_error(std::format("Expecting numeric integrals to be encoded as a long long, got {}", rhs));
55 }
56 }
57};
58
59template<std::floating_point T>
60struct pickle<T> {
61 [[nodiscard]] datum encode(T const &rhs) const noexcept
62 {
63 return datum{rhs};
64 }
65
66 [[nodiscard]] T decode(datum rhs) const
67 {
68 if (auto *f = get_if<double>(rhs)) {
69 return static_cast<T>(*f);
70
71 } else if (auto *i = get_if<long long>(rhs)) {
72 return static_cast<T>(*i);
73
74 } else {
75 throw parse_error(std::format("Expecting floating point to be encoded as a double or long long, got {}", rhs));
76 }
77 }
78};
79
80template<>
81struct pickle<bool> {
82 [[nodiscard]] datum encode(bool const &rhs) const noexcept
83 {
84 return datum{rhs};
85 }
86
87 [[nodiscard]] bool decode(datum rhs) const
88 {
89 if (auto *b = get_if<bool>(rhs)) {
90 return *b;
91
92 } else {
93 throw parse_error(std::format("Expecting bool to be encoded as a bool, got {}", rhs));
94 }
95 }
96};
97
98template<>
99struct pickle<std::string> {
100 [[nodiscard]] datum encode(std::string const &rhs) const noexcept
101 {
102 return datum{rhs};
103 }
104
105 [[nodiscard]] std::string decode(datum rhs) const
106 {
107 if (auto *b = get_if<std::string>(rhs)) {
108 return *b;
109
110 } else {
111 throw parse_error(std::format("Expecting std::string to be encoded as a string, got {}", rhs));
112 }
113 }
114};
115
116
117} // namespace hi::inline v1
This file includes required definitions.
STL namespace.
A dynamic data type.
Definition datum.hpp:209
Exception thrown during parsing on an error.
Definition exception.hpp:25
Encode and decode a type to and from a UTF-8 string.
Definition pickle.hpp:22
datum encode(T const &rhs) const noexcept
Encode the value of a type into a UTF-8 string.
T decode(datum rhs) const
Decode a UTF-8 string into a value of a given type.