summaryrefslogtreecommitdiffhomepage
path: root/include/unicode.h
blob: 6d7ef161e8d9f94993a0610d1472929069d40673 (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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
// libunicode
//
// Author: Roland Reichwein
//
// Available under the conditions of CC0 1.0 Universal
// https://creativecommons.org/publicdomain/zero/1.0/

#pragma once

#include <algorithm>
#include <iterator>
#include <memory>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <unordered_map>

#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, typename Container=std::basic_string<T>>
 struct utf_iterator
 {
  static_assert(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4);

  typedef T input_type;
  typedef char32_t value_type;
  typedef char32_t& reference;
  typedef char32_t* pointer;
  typedef size_t difference_type;
  typedef std::input_iterator_tag iterator_category;
  typedef Container 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();
  }

  utf_iterator(const utf_iterator& other) = default;
  utf_iterator& operator=(const utf_iterator& other) = default;

  size_t remaining_code_units() const
  {
   return std::distance(iterator, end_iterator);
  }

  template<size_t index>
  T get_code_unit() const
  {
   if constexpr (std::is_same<Container, typename std::list<T>>::value) {
    // std::list doesn't support it + n
    auto it{iterator};
    std::advance(it, index);
    return *it;
   } else {
    return *(iterator + index);
   }
  }

  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);
  }

  void calculate_value_utf8()
  {
   size_t remaining{remaining_code_units()};
   
   if (!remaining)
    return;

   utf8_t byte0 {static_cast<utf8_t>(get_code_unit<0>())};
   if (byte0 & 0x80) { // 2-4 bytes
    if (remaining >= 2) {
     utf8_t byte1 {static_cast<utf8_t>(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 {static_cast<utf8_t>(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 {static_cast<utf8_t>(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;
   }
  }

  void calculate_value_utf16()
  {
   size_t remaining{remaining_code_units()};
   
   if (!remaining)
    return;

   char16_t unit0 {static_cast<char16_t>(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 {static_cast<char16_t>(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;
   }
  }

  void calculate_value_utf32()
  {
   size_t remaining{remaining_code_units()};

   if (!remaining)
    return;

   value = static_cast<char32_t>(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;
  }

  // set value member
  void calculate_value()
  {
   if constexpr(sizeof(T) == 1) {
    calculate_value_utf8();
   } else if constexpr (sizeof(T) == 2) {
    calculate_value_utf16();
   } else if constexpr (sizeof(T) == 4) {
    calculate_value_utf32();
   } else {
    throw std::runtime_error("Invalid character size: "s + std::to_string(sizeof(T)));
   }
  }

  // pre-increment
  utf_iterator& operator++()
  {
   std::advance(iterator, sequence_length);
   calculate_value();
   return *this;
  }

  bool operator!=(const utf_iterator& other) const
  {
   return std::distance(iterator, end_iterator) != std::distance(other.iterator, other.end_iterator);
  }

  reference operator*()
  {
   return value;
  }

 private:
  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, typename Container=std::basic_string<T>>
 struct utf_back_insert_iterator
 {
  static_assert(sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4);

  typedef T value_type;
  typedef Container string_type;
  typedef utf_back_insert_iterator& reference;
  typedef utf_back_insert_iterator* pointer;
  typedef size_t difference_type;
  typedef std::output_iterator_tag iterator_category;

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

  utf_back_insert_iterator<T>& operator=(const utf_back_insert_iterator<T>& other)
  {
   if (std::addressof(other.s) != std::addressof(s))
    throw std::runtime_error("utf_back_insert_iterator assignment operator actually called! Iterator should not be assigned to.");

   return *this;
  }

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

  // support *x = value, together with operator=()
  reference operator*()
  {
   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);
  }

  void append_utf8(const char32_t& value)
  {
   if (value < 0x80) { // 1 byte
    s.push_back(static_cast<value_type>(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)));
  }

  void append_utf16(const char32_t& value)
  {
   if (value <= 0xFFFF) { // expect value to be already valid Unicode values
    s.push_back(static_cast<value_type>(value));
   } else {
    char32_t value_reduced{value - 0x10000};
    s.push_back((value_reduced >> 10) + 0xD800);
    s.push_back((value_reduced & 0x3FF) + 0xDC00);
   }
  }

  void append_utf32(const char32_t& value)
  {
   // expect value to be already valid Unicode values
   s.push_back(value);
  }

  reference operator=(const char32_t& value)
  {
   if constexpr(sizeof(T) == 1) {
    append_utf8(value);
   } else if constexpr(sizeof(T) == 2) {
    append_utf16(value);
   } else if constexpr(sizeof(T) == 4) {
    append_utf32(value);
   } else {
    throw std::runtime_error("Invalid type size: "s + std::to_string(sizeof(T)));
   }
   return *this;
  }

 private:
  typename utf_back_insert_iterator::string_type& s;
 };

 typedef std::unordered_map<utf8_t, char32_t> iso_map_type;
 typedef std::unordered_map<char32_t, utf8_t> iso_map_type_reverse;

 // ISO-8859-1 is lower 8-bit of Unicode, so no exceptions necessary
 iso_map_type iso_8859_1_map;

 // ISO-8859-15 is lower 8-bit of Unicode, except for:
 iso_map_type iso_8859_15_map {
  { '\xA4', U'\u20AC' }, // €
  { '\xA6', U'\u0160' }, // Š
  { '\xA8', U'\u0161' }, // š
  { '\xB4', U'\u017D' }, // Ž
  { '\xB8', U'\u017E' }, // ž
  { '\xBC', U'\u0152' }, // Œ
  { '\xBD', U'\u0153' }, // œ
  { '\xBE', U'\u0178' }, // Ÿ
 };

 iso_map_type_reverse reverse_iso_map(const iso_map_type& map) {
  iso_map_type_reverse result;
  std::for_each(map.cbegin(), map.cend(),
                [&](const iso_map_type::value_type& pair)
                 {
                  result.emplace(pair.second, pair.first);
                 });
  return result;
 }

 iso_map_type_reverse iso_8859_15_map_reverse { reverse_iso_map(iso_8859_15_map) };
 iso_map_type_reverse iso_8859_1_map_reverse { reverse_iso_map(iso_8859_1_map) };

} // namespace unicode::detail

namespace unicode {

 using namespace detail;

 template<unicode::detail::iso_map_type& Map=iso_8859_1_map, typename Container=std::basic_string<utf8_t>>
 struct iso_iterator {
  typedef utf8_t input_type;
  typedef char32_t value_type;
  typedef char32_t& reference;
  typedef char32_t* pointer;
  typedef size_t difference_type;
  typedef std::input_iterator_tag iterator_category;
  typedef typename Container::const_iterator iterator;
  typedef Container string_type;

  iso_iterator(const iterator& it): m_it(it) {}

  // pre-increment
  iso_iterator& operator++()
  {
   ++m_it;
   return *this;
  }

  bool operator!=(const iso_iterator& other) const
  {
   return m_it != other.m_it;
  }

  // return reference?
  value_type operator*()
  {
   utf8_t value{*m_it};

   if constexpr(std::addressof(Map) != std::addressof(iso_8859_1_map)) // mapping of 128 <= x <= 255 needed
   {
    auto it{Map.find(value)};
    if (it != Map.end())
     return it->second;
   }
   return static_cast<value_type>(static_cast<uint8_t>(value));
  }

 private:
  iterator m_it;
 };

 template<unicode::detail::iso_map_type_reverse& Map=iso_8859_1_map_reverse, typename Container=std::basic_string<utf8_t>>
 struct iso_back_insert_iterator {
  typedef iso_back_insert_iterator& reference;
  typedef iso_back_insert_iterator* pointer;
  typedef size_t difference_type;
  typedef utf8_t value_type;
  typedef std::output_iterator_tag iterator_category;
  typedef Container string_type;
  
  iso_back_insert_iterator(string_type& s): s(s) {}

  iso_back_insert_iterator& operator=(const iso_back_insert_iterator& other)
  {
   if (std::addressof(other.s) != std::addressof(s))
    throw std::runtime_error("iso_back_insert_iterator assignment operator actually called! Iterator should not be assigned to.");

   return *this;
  }

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

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

  reference operator=(const char32_t& value)
  {
   if constexpr(std::addressof(Map) != std::addressof(iso_8859_1_map_reverse)) // mapping of 128 <= x <= 255 needed
   {
    auto it{Map.find(value)};
    if (it != Map.end()) {
     s.push_back(it->second);
     return *this;
    }
   }

   if (value > 255)
    throw std::invalid_argument("Bad Unicode value above 255: "s + std::to_string(static_cast<uint32_t>(value)));

   s.push_back(static_cast<utf8_t>(value));
   return *this;
  }

 private:
  typename iso_back_insert_iterator::string_type& s;
 };

 // Facet for convert() and ISO-8859-*
 template<typename InputIt, typename OutputIt>
 struct ISO_8859
 {
  typedef utf8_t value_type;
  typedef typename InputIt::string_type string_type;

  static InputIt begin(const typename InputIt::string_type& s)
  {
   return InputIt(s.cbegin());
  }

  static InputIt end(const typename InputIt::string_type& s)
  {
   return InputIt(s.cend());
  }

  static OutputIt back_inserter(typename OutputIt::string_type& s)
  {
   return OutputIt(s);
  }
 };

 // Facet for convert() and UTF-*
 template<typename InputIt, typename OutputIt>
 struct UTF
 {
  typedef typename OutputIt::value_type value_type;
  typedef typename InputIt::string_type string_type;

  static InputIt begin(const typename InputIt::string_type& s)
  {
   return InputIt{s.cbegin(), s.cend()};
  }

  static InputIt end(const typename InputIt::string_type& s)
  {
   return InputIt{s.cend(), s.cend()};
  }

  static OutputIt back_inserter(typename OutputIt::string_type& s)
  {
   return OutputIt(s);
  }
 };

 // Facet for convert()
 typedef ISO_8859<iso_iterator<>, iso_back_insert_iterator<>> ISO_8859_1;
 typedef ISO_8859<iso_iterator<iso_8859_15_map>, iso_back_insert_iterator<iso_8859_15_map_reverse>> ISO_8859_15;
 
 typedef UTF<utf_iterator<utf8_t>, utf_back_insert_iterator<utf8_t>> UTF_8;
 typedef UTF<utf_iterator<char16_t>, utf_back_insert_iterator<char16_t>> UTF_16;
 typedef UTF<utf_iterator<char32_t>, utf_back_insert_iterator<char32_t>> UTF_32;

 // From and To are facets
 template<typename From, typename To, std::enable_if_t<std::is_empty<From>::value, bool> = true>
 typename To::string_type convert(const typename From::string_type& s)
 {
  typename To::string_type result;

  std::copy(From::begin(s), From::end(s), To::back_inserter(result));

  return result;
 }

 // Helper to get correct Facet from char type, e.g. Encoding<typename decltype(s)::value_type>::Facet
 template<typename T>
 struct Encoding
 {
 };

 template<>
 struct Encoding<utf8_t>
 {
  typedef UTF_8 Facet;
 };

 template<>
 struct Encoding<char16_t>
 {
  typedef UTF_16 Facet;
 };

 template<>
 struct Encoding<char32_t>
 {
  typedef UTF_32 Facet;
 };

 // From and To are from: utf8_t (i.e. char or char8_t (C++20)), char16_t and char32_t, char, wchar_t, uint8_t, uint16_t, uint32_t
 template<typename From, typename To,
  typename FromContainer=std::basic_string<From>,
  typename ToContainer=std::basic_string<To>,
  std::enable_if_t<std::is_trivial<From>::value && std::is_scalar<From>::value && !std::is_empty<From>::value, bool> = true>
 ToContainer convert(const FromContainer& s)
 {
  typedef UTF<utf_iterator<From>, utf_back_insert_iterator<To>> UTF_Trait;
  
  ToContainer result;

  std::copy(UTF_Trait::begin(s), UTF_Trait::end(s), UTF_Trait::back_inserter(result));

  return result;
 }

 // From and To are containers
 template<typename FromContainer, typename ToContainer,
  std::enable_if_t<!std::is_empty<FromContainer>::value && !std::is_empty<ToContainer>::value, bool> = true
 >
 ToContainer convert(const FromContainer& s)
 {
  typedef UTF<utf_iterator<typename FromContainer::value_type, FromContainer>, utf_back_insert_iterator<typename ToContainer::value_type, ToContainer>> UTF_Trait;
  
  ToContainer result;

  std::copy(UTF_Trait::begin(s), UTF_Trait::end(s), UTF_Trait::back_inserter(result));

  return result;
 }

 // Container version
 template<typename Container, std::enable_if_t<!std::is_empty<Container>::value, bool> = true>
 bool is_valid_utf(const Container& s)
 {
  typedef UTF<utf_iterator<typename Container::value_type, Container>, utf_back_insert_iterator<typename Container::value_type, Container>> UTF_Trait;
  
  try {
   std::for_each(UTF_Trait::begin(s), UTF_Trait::end(s), [](const char32_t& c){});
  } catch (const std::invalid_argument&) {
   return false;
  }
  return true;
 }

 // basic type version
 template<typename T,
  typename Container=std::basic_string<T>,
  std::enable_if_t<std::is_trivial<T>::value && !std::is_empty<T>::value, bool> = true>
 bool is_valid_utf(const Container& s)
 {
  typedef UTF<utf_iterator<T>, utf_back_insert_iterator<T>> UTF_Trait;
  
  try {
   std::for_each(UTF_Trait::begin(s), UTF_Trait::end(s), [](const char32_t& c){});
  } catch (const std::invalid_argument&) {
   return false;
  }
  return true;
 }

 // Facet version
 template<typename Facet, std::enable_if_t<std::is_empty<Facet>::value, bool> = true>
 bool is_valid_utf(const typename Facet::string_type& s)
 {
  try {
   std::for_each(Facet::begin(s), Facet::end(s), [](const char32_t& c){});
  } catch (const std::invalid_argument&) {
   return false;
  }
  return true;
 }

} // namespace unicode