Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : *
3 : * Permission is hereby granted, free of charge, to any person obtaining
4 : * a copy of this software and associated documentation files (the
5 : * "Software"), to deal in the Software without restriction, including
6 : * without limitation the rights to use, copy, modify, merge, publish,
7 : * distribute, sublicense, and/or sell copies of the Software, and to
8 : * permit persons to whom the Software is furnished to do so, subject to
9 : * the following conditions:
10 : *
11 : * The above copyright notice and this permission notice shall be included
12 : * in all copies or substantial portions of the Software.
13 : *
14 : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 : * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 : * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 : * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18 : * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19 : * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20 : * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 : */
22 :
23 : #include "precompiled.h"
24 :
25 : #include "utf8.h"
26 :
27 : #include "lib/code_annotation.h"
28 : #include "lib/debug.h"
29 :
30 : #include <cstddef>
31 :
32 : static const StatusDefinition utf8StatusDefinitions[] = {
33 : { ERR::UTF8_SURROGATE, L"UTF-16 surrogate pairs aren't supported" },
34 : { ERR::UTF8_OUTSIDE_BMP, L"Code point outside BMP (> 0x10000)" },
35 : { ERR::UTF8_NONCHARACTER, L"Noncharacter (e.g. WEOF)" },
36 : { ERR::UTF8_INVALID_UTF8, L"Invalid UTF-8 sequence" }
37 : };
38 : STATUS_ADD_DEFINITIONS(utf8StatusDefinitions);
39 :
40 :
41 : // adapted from http://unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
42 : // which bears the following notice:
43 : /*
44 : * Copyright 2001-2004 Unicode, Inc.
45 : *
46 : * Disclaimer
47 : *
48 : * This source code is provided as is by Unicode, Inc. No claims are
49 : * made as to fitness for any particular purpose. No warranties of any
50 : * kind are expressed or implied. The recipient agrees to determine
51 : * applicability of information provided. If this file has been
52 : * purchased on magnetic or optical media from Unicode, Inc., the
53 : * sole remedy for any claim will be exchange of defective media
54 : * within 90 days of receipt.
55 : *
56 : * Limitations on Rights to Redistribute This Code
57 : *
58 : * Unicode, Inc. hereby grants the right to freely use the information
59 : * supplied in this file in the creation of products supporting the
60 : * Unicode Standard, and to make copies of this file in any form
61 : * for internal or external distribution as long as this notice
62 : * remains attached.
63 : */
64 :
65 : // design rationale:
66 : // - to cope with wchar_t differences between VC (UTF-16) and
67 : // GCC (UCS-4), we only allow codepoints in the BMP.
68 : // encoded UTF-8 sequences are therefore no longer than 3 bytes.
69 : // - surrogates are disabled because variable-length strings
70 : // violate the purpose of using wchar_t instead of UTF-8.
71 : // - replacing disallowed characters instead of aborting outright
72 : // avoids overly inconveniencing users and eases debugging.
73 :
74 : // this implementation survives http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
75 :
76 : // (must be unsigned to avoid sign extension)
77 : typedef std::uint8_t UTF8;
78 : typedef std::uint32_t UTF32;
79 :
80 :
81 : // called from ReplaceIfInvalid and UTF8Codec::Decode
82 16 : static UTF32 RaiseError(Status err, Status* perr)
83 : {
84 16 : if(perr) // caller wants return code, not warning dialog
85 : {
86 16 : if(*perr == INFO::OK) // only return the first error (see header)
87 8 : *perr = err;
88 : }
89 : else
90 : {
91 0 : wchar_t error[200];
92 0 : debug_printf("UTF8 error: %s\n", utf8_from_wstring(StatusDescription(err, error, ARRAY_SIZE(error))).c_str());
93 : }
94 :
95 16 : return 0xFFFDul; // replacement character
96 : }
97 :
98 :
99 2786091 : static UTF32 ReplaceIfInvalid(UTF32 u, Status* err)
100 : {
101 : // disallow surrogates
102 2786091 : if(0xD800ul <= u && u <= 0xDFFFul)
103 0 : return RaiseError(ERR::UTF8_SURROGATE, err);
104 : // outside BMP (UTF-16 representation would require surrogates)
105 2786091 : if(u > 0xFFFFul)
106 0 : return RaiseError(ERR::UTF8_OUTSIDE_BMP, err);
107 : // noncharacter (note: WEOF (0xFFFF) causes VC's swprintf to fail)
108 2786091 : if(u == 0xFFFEul || u == 0xFFFFul || (0xFDD0ul <= u && u <= 0xFDEFul))
109 0 : return RaiseError(ERR::UTF8_NONCHARACTER, err);
110 : return u;
111 : }
112 :
113 :
114 : class UTF8Codec
115 : {
116 : public:
117 899943 : static void Encode(UTF32 u, UTF8*& dstPos)
118 : {
119 1799886 : switch (Size(u))
120 : {
121 899878 : case 1:
122 899878 : *dstPos++ = UTF8(u);
123 899878 : break;
124 50 : case 2:
125 50 : *dstPos++ = UTF8((u >> 6) | 0xC0);
126 50 : *dstPos++ = UTF8((u | 0x80u) & 0xBFu);
127 50 : break;
128 15 : case 3:
129 15 : *dstPos++ = UTF8((u >> 12) | 0xE0);
130 15 : *dstPos++ = UTF8(((u >> 6) | 0x80u) & 0xBFu);
131 15 : *dstPos++ = UTF8((u | 0x80u) & 0xBFu);
132 15 : break;
133 : }
134 899943 : }
135 :
136 : // @return decoded scalar, or replacementCharacter on error
137 1886148 : static UTF32 Decode(const UTF8*& srcPos, const UTF8* const srcEnd, Status* err)
138 : {
139 3772296 : const size_t size = SizeFromFirstByte(*srcPos);
140 1886148 : if(!IsValid(srcPos, size, srcEnd))
141 : {
142 16 : srcPos += 1; // only skip the offending byte (increases chances of resynchronization)
143 16 : return RaiseError(ERR::UTF8_INVALID_UTF8, err);
144 : }
145 :
146 : UTF32 u = 0;
147 1887636 : for(size_t i = 0; i < size-1; i++)
148 : {
149 1504 : u += UTF32(*srcPos++);
150 1504 : u <<= 6;
151 : }
152 1886132 : u += UTF32(*srcPos++);
153 :
154 1886132 : static const UTF32 offsets[1+4] = { 0, 0x00000000ul, 0x00003080ul, 0x000E2080ul, 0x03C82080UL };
155 1886132 : u -= offsets[size];
156 1886132 : return u;
157 : }
158 :
159 : private:
160 899943 : static inline size_t Size(UTF32 u)
161 : {
162 899943 : if(u < 0x80)
163 : return 1;
164 65 : if(u < 0x800)
165 50 : return 2;
166 : // ReplaceIfInvalid ensures > 3 byte encodings are never used.
167 : return 3;
168 : }
169 :
170 1886148 : static inline size_t SizeFromFirstByte(UTF8 firstByte)
171 : {
172 1886148 : if(firstByte < 0xC0)
173 : return 1;
174 936 : if(firstByte < 0xE0)
175 : return 2;
176 584 : if(firstByte < 0xF0)
177 582 : return 3;
178 : // IsValid rejects firstByte values that would cause > 4 byte encodings.
179 : return 4;
180 : }
181 :
182 : // c.f. Unicode 3.1 Table 3-7
183 : // @param size obtained via SizeFromFirstByte (our caller also uses it)
184 1886148 : static bool IsValid(const UTF8* const src, size_t size, const UTF8* const srcEnd)
185 : {
186 1886148 : if(src+size > srcEnd) // not enough data
187 : return false;
188 :
189 1886144 : if(src[0] < 0x80)
190 : return true;
191 940 : if(!(0xC2 <= src[0] && src[0] <= 0xF4))
192 : return false;
193 :
194 : // special cases (stricter than the loop)
195 930 : if(src[0] == 0xE0 && src[1] < 0xA0)
196 : return false;
197 930 : if(src[0] == 0xED && src[1] > 0x9F)
198 : return false;
199 930 : if(src[0] == 0xF0 && src[1] < 0x90)
200 : return false;
201 930 : if(src[0] == 0xF4 && src[1] > 0x8F)
202 : return false;
203 :
204 2436 : for(size_t i = 1; i < size; i++)
205 : {
206 1508 : if(!(0x80 <= src[i] && src[i] <= 0xBF))
207 : return false;
208 : }
209 :
210 : return true;
211 : }
212 : };
213 :
214 :
215 : //-----------------------------------------------------------------------------
216 :
217 43410 : std::string utf8_from_wstring(const std::wstring_view src, Status* err)
218 : {
219 43410 : if(err)
220 43050 : *err = INFO::OK;
221 :
222 43410 : std::string dst(src.size()*3+1, ' '); // see UTF8Codec::Size; +1 ensures &dst[0] is valid
223 43410 : UTF8* dstPos = (UTF8*)&dst[0];
224 943353 : for(size_t i = 0; i < src.size(); i++)
225 : {
226 899943 : const UTF32 u = ReplaceIfInvalid(UTF32(src[i]), err);
227 899943 : UTF8Codec::Encode(u, dstPos);
228 : }
229 43410 : dst.resize(dstPos - (UTF8*)&dst[0]);
230 43410 : return dst;
231 0 : }
232 :
233 :
234 38299 : std::wstring wstring_from_utf8(const std::string_view src, Status* err)
235 : {
236 38299 : if(err)
237 10436 : *err = INFO::OK;
238 :
239 38299 : std::wstring dst;
240 38299 : dst.reserve(src.size());
241 38299 : const UTF8* srcPos = (const UTF8*)src.data();
242 38299 : const UTF8* const srcEnd = srcPos + src.size();
243 1924447 : while(srcPos < srcEnd)
244 : {
245 1886148 : const UTF32 u = UTF8Codec::Decode(srcPos, srcEnd, err);
246 1886148 : dst.push_back((wchar_t)ReplaceIfInvalid(u, err));
247 : }
248 38299 : return dst;
249 0 : }
|