summaryrefslogtreecommitdiffhomepage
path: root/include/unicode.h
blob: 9e0132b9fb8ffb5cee7dbe065773961616cfbdba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
// libunicode

#pragma once

#include <algorithm>
#include <stdexcept>
#include <string>

#ifdef __cpp_char8_t
// char8_t available
 typedef char8_t utf8_t;
#else
 typedef char utf8_t;
#endif

namespace unicode {

 // usually, char32_t, uint32_t etc.
 template<typename T>
 static inline bool is_valid_unicode(const T& value)
 {
   return value <= 0x10FFFF && (value <= 0xD7FF || value >= 0xE000);
 }

}

namespace unicode::detail {

 using namespace std::string_literals;

 template<typename T>
 struct utf_iterator
 {
  typedef char32_t value_type;
  typedef char32_t& reference;
  typedef std::basic_string<T> string_type;

  utf_iterator(const typename string_type::const_iterator& cbegin, const typename string_type::const_iterator& cend):
   iterator(cbegin), end_iterator(cend)
  {
   calculate_value<T>();
  }

  utf_iterator<T>(const utf_iterator<T>& other) = default;
  utf_iterator<T>& operator=(const utf_iterator<T>& other) = default;

  size_t remaining_code_units()
  {
   return end_iterator - iterator;
  }

  template<size_t index>
  T get_code_unit()
  {
   return *(iterator + index);
  }

  // set value member
  // default: char32_t for UTF-32
  // specializations for UTF-8 and UTF-16 below
  template<typename T1>
  void calculate_value()
  {
   static_assert(sizeof(T1) == 4);

   size_t remaining{remaining_code_units()};

   if (!remaining)
    return;

   value = get_code_unit<0>();
   
   if (!unicode::is_valid_unicode(value))
    throw std::invalid_argument("Invalid Unicode character: "s + std::to_string(static_cast<uint32_t>(value)));

   sequence_length = 1;
  }

  inline static bool is_continuation_byte(T b)
  {
   return (b & 0b11000000) == 0b10000000;
  }

  template<typename... Targs>
  inline static bool is_continuation_byte(T b, Targs... Fargs)
  {
   return is_continuation_byte(b) && is_continuation_byte(Fargs...);
  }

  template<size_t n>
  inline static bool is_byte0_of(T b)
  {
   return (b & static_cast<T>(0xFF << (7 - n))) == static_cast<T>(0xFF << (8 - n));
  }

  inline static char32_t continuation_value(T b)
  {
   return static_cast<char32_t>(b & 0b00111111);
  }

  template<typename... Targs>
  inline static char32_t continuation_value(T b, Targs... Fargs)
  {
   return continuation_value(b) << (6 * sizeof...(Targs)) | continuation_value(Fargs...);
  }

  template<size_t n>
  inline static char32_t value_byte0_of(T b)
  {
   return static_cast<char32_t>(b & (0b1111111 >> n)) << ((n - 1) * 6);
  }

  // GCC Bug: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85282
  // specialization for UTF-8
  template<>
  void calculate_value<utf8_t>()
  {
   size_t remaining{remaining_code_units()};
   
   if (!remaining)
    return;

   utf8_t byte0 {get_code_unit<0>()};
   if (byte0 & 0x80) { // 2-4 bytes
    if (remaining >= 2) {
     utf8_t byte1 {get_code_unit<1>()};
     if (is_byte0_of<2>(byte0) && is_continuation_byte(byte1)) { // 2 bytes
      value = value_byte0_of<2>(byte0) | continuation_value(byte1);
      sequence_length = 2;
     } else if (remaining >= 3) {
      utf8_t byte2 {get_code_unit<2>()};
      if (is_byte0_of<3>(byte0) && is_continuation_byte(byte1, byte2)) { // 3 bytes
       value = value_byte0_of<3>(byte0) | continuation_value(byte1, byte2);
       sequence_length = 3;
      } else if (remaining >= 4) {
       utf8_t byte3 {get_code_unit<3>()};
       if (is_byte0_of<4>(byte0) && is_continuation_byte(byte1, byte2, byte3)) { // 4 bytes
        value = value_byte0_of<4>(byte0) | continuation_value(byte1, byte2, byte3);
        sequence_length = 4;
       } else
        throw std::invalid_argument("Bad input: Invalid 4 byte sequence");
      } else
       throw std::invalid_argument("Bad input: Invalid 3 byte sequence");
     } else
      throw std::invalid_argument("Bad input: Invalid 2 byte sequence");
    } else
     throw std::invalid_argument("Bad input: 2nd byte expected, none found");
  
    // check only for sequences >= 2 bytes (ASCII is always compliant)
    if (!unicode::is_valid_unicode(value))
     throw std::invalid_argument("Invalid Unicode character: "s + std::to_string(static_cast<uint32_t>(value)));

   } else { // 1 byte: 7 bit ASCII
    value = byte0;
    sequence_length = 1;
   }
  }

  // specialization for UTF-16
  template<>
  void calculate_value<char16_t>()
  {
   size_t remaining{remaining_code_units()};
   
   if (!remaining)
    return;

   char16_t unit0 {get_code_unit<0>()};

   if (unit0 <= 0xD7FF || unit0 >= 0xE000) { // 1 unit (BMP Basic Multilingual Plane)
    value = unit0;
    sequence_length = 1;
   } else {
    if (remaining < 2)
     throw std::invalid_argument("Bad input: Continuation of first UTF-16 unit missing");

    char16_t unit1 {get_code_unit<1>()};
    if ((unit0 & 0xFC00) != 0xD800 || (unit1 & 0xFC00) != 0xDC00)
     throw std::invalid_argument("Bad input: 2 malformed UTF-16 surrogates");

    value = (static_cast<char32_t>(unit0 & 0x03FF) << 10 | (unit1 & 0x03FF)) + 0x10000;
    sequence_length = 2;
   }
  }

  // pre-increment
  utf_iterator<T>& operator++()
  {
   iterator += sequence_length;
   calculate_value<T>();
   return *this;
  }

  bool operator!=(const utf_iterator<T>& other) const
  {
   return iterator != other.iterator;
  }

  reference operator*()
  {
   return value;
  }

  typename string_type::const_iterator iterator;
  typename string_type::const_iterator end_iterator;

  char32_t value{}; // always save complete unicode code point at this point
  size_t sequence_length{};
 };

 template<typename T>
 struct utf_back_insert_iterator
 {
  typedef std::basic_string<T> string_type;
  typedef utf_back_insert_iterator& reference;

  utf_back_insert_iterator(string_type& s): s(s) {}

  // no-op
  utf_back_insert_iterator& operator++()
  {
   return *this;
  }

  // support *x = value, together with operator=()
  reference operator*()
  {
   return *this;
  }

  // default: utf-32 code unit for UTF-32
  // specializations for UTF-8 and UTF-16 below
  template<typename T1=T>
  reference operator=(const char32_t& value)
  {
   // expect value to be already valid Unicode values
   s.push_back(value);
   return *this;
  }

  // n is number of UTF-8 bytes in sequence
  template<size_t n>
  inline static T byte0_of(char32_t value)
  {
   return (value >> 6 * (n - 1)) | (0xFF << (8 - n));
  }

  // n is index of 6-bit groups, counting from bit 0
  template<size_t n>
  inline static T trailing_byte(char32_t value)
  {
   return ((value >> n * 6) & 0b111111) | 0b10000000;
  }

  // calculate UTF-8 sequence byte for m >= 2 bytes sequences (i.e. non-ASCII)
  // assume value to be valid Unicode value for given byte position
  template<size_t n, size_t m>
  inline static T byte_n_of_m(char32_t value)
  {
   if constexpr (n == 0)
    return byte0_of<m>(value);
   else
    return trailing_byte<m - n - 1>(value);
  }

  // specialization for UTF-8
  // append utf-8 byte sequence
  template<>
  reference operator=<utf8_t>(const char32_t& value)
  {
   if (value < 0x80) { // 1 byte
    s.push_back(value);
   } else if (value < 0x800) { // 2 bytes
    s.push_back(byte_n_of_m<0,2>(value));
    s.push_back(byte_n_of_m<1,2>(value));
   } else if (value < 0x10000) { // 3 bytes
    s.push_back(byte_n_of_m<0,3>(value));
    s.push_back(byte_n_of_m<1,3>(value));
    s.push_back(byte_n_of_m<2,3>(value));
   } else if (value < 0x110000) { // 4 bytes
    s.push_back(byte_n_of_m<0,4>(value));
    s.push_back(byte_n_of_m<1,4>(value));
    s.push_back(byte_n_of_m<2,4>(value));
    s.push_back(byte_n_of_m<3,4>(value));
   } else
    throw std::runtime_error("Invalid internal Unicode value: "s + std::to_string(static_cast<uint32_t>(value)));
   return *this;
  }

  // specialization for UTF-16
  // append utf-16 word sequence
  template<>
  reference operator=<char16_t>(const char32_t& value)
  {
   if (value <= 0xFFFF) { // expect value to be already valid Unicode values
    s.push_back(value);
   } else {
    char32_t value_reduced{value - 0x10000};
    s.push_back((value_reduced >> 10) + 0xD800);
    s.push_back((value_reduced & 0x3FF) + 0xDC00);
   }
   return *this;
  }

  typename utf_back_insert_iterator::string_type& s;
 };

 template<typename T>
 utf_back_insert_iterator<T> utf_back_inserter(std::basic_string<T>& s)
 {
  return utf_back_insert_iterator<T>(s);
 }

 template<typename T>
 utf_iterator<T> utf_begin(const std::basic_string<T>& s)
 {
  return utf_iterator<T>{s.cbegin(), s.cend()};
 }

 template<typename T>
 utf_iterator<T> utf_end(const std::basic_string<T>& s)
 {
  return utf_iterator<T>{s.cend(), s.cend()};
 }

} // namespace

namespace unicode {

 using namespace detail;

 template<typename From, typename To>
 std::basic_string<To> utf_to_utf(const std::basic_string<From>& s)
 {
  std::basic_string<To> result;

  std::copy(utf_begin<From>(s), utf_end<From>(s), utf_back_inserter<To>(result));

  return result;
 }

} // namespace unicode