Debian Codegraph @

lib/mcel.h

raw
1 /* Multi-byte characters, Error encodings, and Lengths (MCELs)
2 Copyright 2023-2025 Free Software Foundation, Inc.
3
4 This file is free software: you can redistribute it and/or modify
5 it under the terms of the GNU Lesser General Public License as
6 published by the Free Software Foundation; either version 2.1 of the
7 License, or (at your option) any later version.
8
9 This file is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
16
17 /* Written by Paul Eggert. */
18
19 /* The macros in this file implement multi-byte character representation
20 and forward iteration through a multi-byte string.
21 They are simpler and can be faster than the mbiter family.
22 However, they do not support obsolescent encodings like CP864,
23 EBCDIC, Johab, and Shift JIS that glibc also does not support,
24 and it is up to the caller to coalesce encoding-error bytes if desired.
25
26 The mcel_scan function lets code iterate through an array of bytes,
27 supporting character encodings in practical use
28 more simply than using plain mbrtoc32.
29
30 Instead of this single-byte code:
31
32 char *p = ..., *lim = ...;
33 for (; p < lim; p++)
34 process (*p);
35
36 You can use this multi-byte code:
37
38 char *p = ..., *lim = ...;
39 for (mcel_t g; p < lim; p += g.len)
40 {
41 g = mcel_scan (p, lim);
42 process (g);
43 }
44
45 You can select from G using G.ch, G.err, and G.len.
46 G is an encoding error if G.err is nonzero, a character otherwise.
47
48 The mcel_scanz function is similar except it works with a
49 string of unknown but positive length that is terminated with '\0'.
50 Instead of this single-byte code:
51
52 char *p = ...;
53 for (; *p; p++)
54 process (*p);
55
56 You can use this multi-byte code:
57
58 char *p = ...;
59 for (mcel_t g; *p; p += g.len)
60 {
61 g = mcel_scanz (p);
62 process (g);
63 }
64
65 mcel_scant (P, TERMINATOR) is like mcel_scanz (P) except the
66 string is terminated by TERMINATOR. The C standard says that the
67 TERMINATORs '\0', '\r', '\n', '.', '/' are safe, as they cannot be
68 a part (even a trailing byte) of a multi-byte character.
69 In practice TERMINATOR is safe if 0 <= TERMINATOR <= 0x2f (ASCII '/').
70
71 mcel_ch (CH, LEN) and mcel_err (ERR) construct mcel_t values.
72
73 mcel_cmp (G1, G2) compares two mcel_t values lexicographically by
74 character or by encoding byte value, with encoding bytes sorting
75 after characters.
76
77 Calls like c32isalpha (G.ch) test G; they return false for encoding
78 errors since calls like c32isalpha (0) return false. Calls like
79 mcel_tocmp (c32tolower, G1, G2) are like mcel_cmp (G1, G2),
80 but transliterate first.
81
82 Although ISO C and POSIX allow encodings that have shift states or
83 that can produce multiple characters from an indivisible byte sequence,
84 POSIX does not require support for these encodings,
85 they are not in practical use on GNUish platforms,
86 and omitting support for them simplifies the API. */
87
88 #ifndef _MCEL_H
89 #define _MCEL_H 1
90
91 #if !_GL_CONFIG_H_INCLUDED
92 #error "Please include config.h first."
93 #endif
94
95 #include <verify.h>
96
97 #include <limits.h>
98 #include <stddef.h>
99 #include <uchar.h>
100
101 _GL_INLINE_HEADER_BEGIN
102 #ifndef MCEL_INLINE
103 # define MCEL_INLINE _GL_INLINE
104 #endif
105
106 #ifdef __cplusplus
107 extern "C" {
108 #endif
109
110
111 /* Pacify GCC re type limits. */
112 #if 4 < __GNUC__ + (3 <= __GNUC_MINOR__) && !defined __clang__
113 # pragma GCC diagnostic ignored "-Wtype-limits"
114 #endif
115
116 /* The maximum multi-byte character length supported on any platform.
117 This can be less than MB_LEN_MAX because many platforms have a
118 large MB_LEN_MAX to allow for stateful encodings, and mcel does not
119 support these encodings. MCEL_LEN_MAX is enough for UTF-8, EUC,
120 Shift-JIS, GB18030, etc. In all multi-byte encodings supported by glibc,
121 0 < MB_CUR_MAX <= MCEL_LEN_MAX <= MB_LEN_MAX. */
122 enum { MCEL_LEN_MAX = MB_LEN_MAX < 4 ? MB_LEN_MAX : 4 };
123
124 /* Bounds for mcel_t members. */
125 enum { MCEL_CHAR_MAX = 0x10FFFF };
126 enum { MCEL_ERR_MIN = 0x80 };
127
128 /* mcel_t is a type representing a character CH or an encoding error byte ERR,
129 along with a count of the LEN bytes that represent CH or ERR.
130 If ERR is zero, CH is a valid character and 0 < LEN <= MCEL_LEN_MAX;
131 otherwise ERR is an encoding error byte, MCEL_ERR_MIN <= ERR,
132 CH == 0, and LEN == 1. */
133 typedef struct
134 {
135 char32_t ch;
136 unsigned char err;
137 unsigned char len;
138 } mcel_t;
139
140 /* Every multi-byte character length fits in mcel_t's LEN. */
141 static_assert (MB_LEN_MAX <= UCHAR_MAX);
142
143 /* Shifting an encoding error byte left by this value
144 suffices to sort encoding errors after characters. */
145 enum { MCEL_ERR_SHIFT = 14 };
146 static_assert (MCEL_CHAR_MAX < MCEL_ERR_MIN << MCEL_ERR_SHIFT);
147
148 /* Unsigned char promotes to int. */
149 static_assert (UCHAR_MAX <= INT_MAX);
150
151 /* Bytes have 8 bits, as POSIX requires. */
152 static_assert (CHAR_BIT == 8);
153
154 #ifndef _GL_LIKELY
155 /* Rely on __builtin_expect, as provided by the module 'builtin-expect'. */
156 # define _GL_LIKELY(cond) __builtin_expect ((cond), 1)
157 # define _GL_UNLIKELY(cond) __builtin_expect ((cond), 0)
158 #endif
159
160 /* mcel_t constructors. */
161 MCEL_INLINE mcel_t
162 mcel_ch (char32_t ch, size_t len)
163 {
164 assume (0 < len);
165 assume (len <= MCEL_LEN_MAX);
166 assume (ch <= MCEL_CHAR_MAX);
167 return (mcel_t) {.ch = ch, .len = len};
168 }
169 MCEL_INLINE mcel_t
170 mcel_err (unsigned char err)
171 {
172 assume (MCEL_ERR_MIN <= err);
173 return (mcel_t) {.err = err, .len = 1};
174 }
175
176 /* Compare C1 and C2, with encoding errors sorting after characters.
177 Return <0, 0, >0 for <, =, >. */
178 MCEL_INLINE int
179 mcel_cmp (mcel_t c1, mcel_t c2)
180 {
181 int ch1 = c1.ch, ch2 = c2.ch;
182 return ((c1.err - c2.err) * (1 << MCEL_ERR_SHIFT)) + (ch1 - ch2);
183 }
184
185 /* Apply the uchar translator TO to C1 and C2 and compare the results,
186 with encoding errors sorting after characters,
187 Return <0, 0, >0 for <, =, >. */
188 MCEL_INLINE int
189 mcel_tocmp (wint_t (*to) (wint_t), mcel_t c1, mcel_t c2)
190 {
191 int cmp = mcel_cmp (c1, c2);
192 if (_GL_LIKELY ((c1.err - c2.err) | !cmp))
193 return cmp;
194 int ch1 = to (c1.ch), ch2 = to (c2.ch);
195 return ch1 - ch2;
196 }
197
198 /* Whether C represents itself as a Unicode character
199 when it is the first byte of a single- or multi-byte character.
200 These days it is safe to assume ASCII, so do not support
201 obsolescent encodings like CP864, EBCDIC, Johab, and Shift JIS. */
202 MCEL_INLINE bool
203 mcel_isbasic (char c)
204 {
205 return _GL_LIKELY (0 <= c && c < MCEL_ERR_MIN);
206 }
207
208 /* With mcel there should be no need for the performance overhead of
209 replacing glibc mbrtoc32, as callers shouldn't care whether the
210 C locale treats a byte with the high bit set as an encoding error. */
211 #ifdef __GLIBC__
212 # undef mbrtoc32
213 #endif
214
215 /* Scan bytes from P inclusive to LIM exclusive. P must be less than LIM.
216 Return the character or encoding error starting at P. */
217 MCEL_INLINE mcel_t
218 mcel_scan (char const *p, char const *lim)
219 {
220 /* Handle ASCII quickly to avoid the overhead of calling mbrtoc32.
221 In supported encodings, the first byte of a multi-byte character
222 cannot be an ASCII byte. */
223 char c = *p;
224 if (mcel_isbasic (c))
225 return mcel_ch (c, 1);
226
227 /* An initial mbstate_t; initialization optimized for some platforms.
228 For details about these and other platforms, see wchar.in.h. */
229 #if (defined __GLIBC__ && 2 < __GLIBC__ + (2 <= __GLIBC_MINOR__) \
230 && !defined __UCLIBC__)
231 /* Although only a trivial optimization, it's worth it for GNU. */
232 mbstate_t mbs; mbs.__count = 0;
233 #elif (defined __FreeBSD__ || defined __DragonFly__ || defined __OpenBSD__ \
234 || (defined __APPLE__ && defined __MACH__))
235 /* These platforms have 128-byte mbstate_t. What were they thinking?
236 Initialize just for supported encodings (UTF-8, EUC, etc.).
237 Avoid memset because some compilers generate function call code. */
238 struct mbhidden { char32_t ch; int utf8_want, euc_want; }
239 _GL_ATTRIBUTE_MAY_ALIAS;
240 union { mbstate_t m; struct mbhidden s; } u;
241 u.s.ch = u.s.utf8_want = u.s.euc_want = 0;
242 # define mbs u.m
243 #elif defined __NetBSD__
244 /* Experiments on both 32- and 64-bit NetBSD platforms have
245 shown that it doesn't work to clear fewer than 24 bytes. */
246 struct mbhidden { long long int a, b, c; } _GL_ATTRIBUTE_MAY_ALIAS;
247 union { mbstate_t m; struct mbhidden s; } u;
248 u.s.a = u.s.b = u.s.c = 0;
249 # define mbs u.m
250 #else
251 /* mbstate_t has unknown structure or is not worth optimizing. */
252 mbstate_t mbs = {0};
253 #endif
254
255 char32_t ch;
256 size_t len = mbrtoc32 (&ch, p, lim - p, &mbs);
257
258 #undef mbs
259
260 /* Any LEN with top bit set is an encoding error, as LEN == (size_t) -3
261 is not supported and MB_LEN_MAX is small. */
262 if (_GL_UNLIKELY ((size_t) -1 / 2 < len))
263 return mcel_err (c);
264
265 /* A multi-byte character. LEN must be positive,
266 as *P != '\0' and shift sequences are not supported. */
267 return mcel_ch (ch, len);
268 }
269
270 /* Scan bytes from P, a byte sequence terminated by TERMINATOR.
271 If *P == TERMINATOR, scan just that byte; otherwise scan
272 bytes up to but not including TERMINATOR.
273 TERMINATOR must be ASCII, and should be '\0', '\r', '\n', '.', or '/'.
274 Return the character or encoding error starting at P. */
275 MCEL_INLINE mcel_t
276 mcel_scant (char const *p, char terminator)
277 {
278 /* Handle ASCII quickly for speed. */
279 if (mcel_isbasic (*p))
280 return mcel_ch (*p, 1);
281
282 /* Defer to mcel_scan for non-ASCII. Compute length with code that
283 is typically faster than strnlen. */
284 char const *lim = p + 1;
285 for (int i = 0; i < MCEL_LEN_MAX - 1; i++)
286 lim += *lim != terminator;
287 return mcel_scan (p, lim);
288 }
289
290 /* Scan bytes from P, a byte sequence terminated by '\0'.
291 If *P == '\0', scan just that byte; otherwise scan
292 bytes up to but not including '\0'.
293 Return the character or encoding error starting at P. */
294 MCEL_INLINE mcel_t
295 mcel_scanz (char const *p)
296 {
297 return mcel_scant (p, '\0');
298 }
299
300
301 #ifdef __cplusplus
302 }
303 #endif
304
305 _GL_INLINE_HEADER_END
306
307 #endif /* _MCEL_H */