CsString  2.0.0
cs_char.h
1 /***********************************************************************
2 *
3 * Copyright (c) 2017-2025 Barbara Geller
4 * Copyright (c) 2017-2025 Ansel Sermersheim
5 *
6 * This file is part of CsString.
7 *
8 * CsString is free software which is released under the BSD 2-Clause license.
9 * For license details refer to the LICENSE provided with this project.
10 *
11 * CsString is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14 *
15 * https://opensource.org/licenses/BSD-2-Clause
16 *
17 ***********************************************************************/
18 
19 #ifndef LIB_CS_CHAR_H
20 #define LIB_CS_CHAR_H
21 
22 #include <stdint.h>
23 
24 #include <compare>
25 #include <functional>
26 #include <memory>
27 
28 namespace CsString {
29 
30 #ifdef _WIN32
31 
32 #ifdef BUILDING_LIB_CS_STRING
33 # define LIB_CS_STRING_EXPORT __declspec(dllexport)
34 #else
35 # define LIB_CS_STRING_EXPORT __declspec(dllimport)
36 #endif
37 
38 #else
39 # define LIB_CS_STRING_EXPORT
40 
41 #endif
42 
43 template <typename E, typename A = std::allocator<typename E::storage_unit>>
44 class CsBasicString;
45 
46 class CsChar
47 {
48  public:
49  CsChar()
50  : m_char(0)
51  {
52  }
53 
54  template <typename T = int>
55  CsChar(char c)
56  : m_char(static_cast<unsigned char>(c))
57  {
58 #ifndef CS_STRING_ALLOW_UNSAFE
59  static_assert(! std::is_same<T, T>::value, "Unsafe operations not allowed, unknown encoding for this operation");
60 #endif
61  }
62 
63  CsChar(char32_t c)
64  : m_char(c)
65  {
66  }
67 
68  CsChar(int c)
69  : m_char(c)
70  {
71  }
72 
73  CsChar(const CsChar &other)
74  : m_char(other.m_char)
75  {
76  }
77 
78  CsChar(char8_t c)
79  : m_char(c)
80  {
81  }
82 
83  auto operator<=>(const CsChar &other) const = default;
84 
85  inline CsChar &operator=(char c) &;
86  inline CsChar &operator=(char32_t c) &;
87  inline CsChar &operator=(CsChar c) &;
88 
89  inline uint32_t unicode() const;
90 
91  private:
92  uint32_t m_char;
93 };
94 
95 inline CsChar &CsChar::operator=(char c) &
96 {
97  m_char = c;
98  return *this;
99 }
100 
101 inline CsChar &CsChar::operator=(char32_t c) &
102 {
103  m_char = c;
104  return *this;
105 }
106 
107 inline CsChar &CsChar::operator=(CsChar c) &
108 {
109  m_char = c.m_char;
110  return *this;
111 }
112 
113 inline uint32_t CsChar::unicode() const
114 {
115  return m_char;
116 }
117 
118 } // namespace
119 
120 namespace std {
121  template<>
122  struct hash<CsString::CsChar>
123  {
124  inline size_t operator()(const CsString::CsChar &key) const
125  {
126  return key.unicode();
127  }
128  };
129 }
130 
131 #endif