blob: 623c1be72306195b709a76c8e949d8ad4e0ed643 (
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
|
#include "utf16.hh"
#include "utf_error.hh"
namespace utf {
namespace {
inline bool is_high_surrogate(uint16_t c) {
return c >= 0xd800 && c <= 0xdbff;
}
inline bool is_low_surrogate(uint16_t c) {
return c >= 0xdc00 && c <= 0xdfff;
}
} // namespace
uint32_t read16be(std::span<uint8_t const> data, std::size_t& offset) {
if (offset > data.size() || data.size() - offset < 2)
return NEED_MORE;
uint16_t c = static_cast<uint16_t>(data[offset]) << 8
| static_cast<uint16_t>(data[offset + 1] & 0xff);
if (is_high_surrogate(c)) {
if (data.size() - offset < 4)
return NEED_MORE;
uint16_t d = static_cast<uint16_t>(data[offset + 2]) << 8
| static_cast<uint16_t>(data[offset + 3] & 0xff);
if (is_low_surrogate(d)) {
offset += 4;
return 0x10000
+ (static_cast<uint32_t>(c & 0x3ff) << 10
| (d & 0x3ff));
}
return INVALID;
} else if (is_low_surrogate(c)) {
return INVALID;
}
offset += 2;
return c;
}
uint32_t read16le(std::span<uint8_t const> data, std::size_t& offset) {
if (offset > data.size() || data.size() - offset < 2)
return NEED_MORE;
uint16_t c = static_cast<uint16_t>(data[offset + 1]) << 8
| static_cast<uint16_t>(data[offset] & 0xff);
if (is_high_surrogate(c)) {
if (data.size() - offset < 4)
return NEED_MORE;
uint16_t d = static_cast<uint16_t>(data[offset + 3]) << 8
| static_cast<uint16_t>(data[offset + 2] & 0xff);
if (is_low_surrogate(d)) {
offset += 4;
return 0x10000
+ (static_cast<uint32_t>(c & 0x3ff) << 10
| (d & 0x3ff));
}
return INVALID;
} else if (is_low_surrogate(c)) {
return INVALID;
}
offset += 2;
return c;
}
} // namespace utf
|