This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
utf8.c: Extract some code into macros
[perl5.git] / utf8.c
<
CommitLineData
a0ed51b3
LW
1/* utf8.c
2 *
1129b882 3 * Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
b94e2f88 4 * by Larry Wall and others
a0ed51b3
LW
5 *
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Artistic License, as specified in the README file.
8 *
9 */
10
11/*
4ac71550
TC
12 * 'What a fix!' said Sam. 'That's the one place in all the lands we've ever
13 * heard of that we don't want to see any closer; and that's the one place
14 * we're trying to get to! And that's just where we can't get, nohow.'
15 *
cdad3b53 16 * [p.603 of _The Lord of the Rings_, IV/I: "The Taming of Sméagol"]
a0ed51b3
LW
17 *
18 * 'Well do I understand your speech,' he answered in the same language;
19 * 'yet few strangers do so. Why then do you not speak in the Common Tongue,
4ac71550 20 * as is the custom in the West, if you wish to be answered?'
cdad3b53 21 * --Gandalf, addressing Théoden's door wardens
4ac71550
TC
22 *
23 * [p.508 of _The Lord of the Rings_, III/vi: "The King of the Golden Hall"]
a0ed51b3
LW
24 *
25 * ...the travellers perceived that the floor was paved with stones of many
26 * hues; branching runes and strange devices intertwined beneath their feet.
4ac71550
TC
27 *
28 * [p.512 of _The Lord of the Rings_, III/vi: "The King of the Golden Hall"]
a0ed51b3
LW
29 */
30
31#include "EXTERN.h"
864dbfa3 32#define PERL_IN_UTF8_C
a0ed51b3 33#include "perl.h"
b992490d 34#include "invlist_inline.h"
a0ed51b3 35
27da23d5
JH
36static const char unees[] =
37 "Malformed UTF-8 character (unexpected end of string)";
760c7c2f
KW
38static const char cp_above_legal_max[] =
39 "It is deprecated to use code point 0x%"UVXf"; the permissible max is 0x%"UVXf"";
40
41#define MAX_NON_DEPRECATED_CP (IV_MAX)
901b21bf 42
48ef279e 43/*
ccfc67b7 44=head1 Unicode Support
7fefc6c1 45These are various utility functions for manipulating UTF8-encoded
72d33970 46strings. For the uninitiated, this is a method of representing arbitrary
61296642 47Unicode characters as a variable number of bytes, in such a way that
56da48f7
DM
48characters in the ASCII range are unmodified, and a zero byte never appears
49within non-zero characters.
166f8a29 50
eaf7a4d2
CS
51=cut
52*/
53
54/*
7bbfa158 55=for apidoc is_invariant_string
eaf7a4d2 56
b8ed1ca9
KW
57Returns true iff the first C<len> bytes of the string C<s> are the same
58regardless of the UTF-8 encoding of the string (or UTF-EBCDIC encoding on
59EBCDIC machines). That is, if they are UTF-8 invariant. On ASCII-ish
60machines, all the ASCII characters and only the ASCII characters fit this
7bbfa158 61definition. On EBCDIC machines, the ASCII-range characters are invariant, but
b8ed1ca9
KW
62so also are the C1 controls and C<\c?> (which isn't in the ASCII range on
63EBCDIC).
eaf7a4d2 64
75200dff
KW
65If C<len> is 0, it will be calculated using C<strlen(s)>, (which means if you
66use this option, that C<s> can't have embedded C<NUL> characters and has to
67have a terminating C<NUL> byte).
9f7e3d64 68
a1433954 69See also L</is_utf8_string>(), L</is_utf8_string_loclen>(), and L</is_utf8_string_loc>().
eaf7a4d2
CS
70
71=cut
72*/
73
74bool
7bbfa158 75Perl_is_invariant_string(const U8 *s, STRLEN len)
eaf7a4d2
CS
76{
77 const U8* const send = s + (len ? len : strlen((const char *)s));
78 const U8* x = s;
79
7bbfa158 80 PERL_ARGS_ASSERT_IS_INVARIANT_STRING;
eaf7a4d2
CS
81
82 for (; x < send; ++x) {
83 if (!UTF8_IS_INVARIANT(*x))
84 break;
85 }
86
87 return x == send;
88}
89
90/*
378516de 91=for apidoc uvoffuni_to_utf8_flags
eebe1485 92
a27992cc 93THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES.
de69f3af
KW
94Instead, B<Almost all code should use L</uvchr_to_utf8> or
95L</uvchr_to_utf8_flags>>.
a27992cc 96
de69f3af
KW
97This function is like them, but the input is a strict Unicode
98(as opposed to native) code point. Only in very rare circumstances should code
99not be using the native code point.
949cf498 100
efa9cd84 101For details, see the description for L</uvchr_to_utf8_flags>.
949cf498 102
eebe1485
SC
103=cut
104*/
105
8ee1cdcb
KW
106#define HANDLE_UNICODE_SURROGATE(uv, flags) \
107 STMT_START { \
108 if (flags & UNICODE_WARN_SURROGATE) { \
109 Perl_ck_warner_d(aTHX_ packWARN(WARN_SURROGATE), \
110 "UTF-16 surrogate U+%04"UVXf, uv); \
111 } \
112 if (flags & UNICODE_DISALLOW_SURROGATE) { \
113 return NULL; \
114 } \
115 } STMT_END;
116
117#define HANDLE_UNICODE_NONCHAR(uv, flags) \
118 STMT_START { \
119 if (flags & UNICODE_WARN_NONCHAR) { \
120 Perl_ck_warner_d(aTHX_ packWARN(WARN_NONCHAR), \
121 "Unicode non-character U+%04"UVXf" is not " \
122 "recommended for open interchange", uv); \
123 } \
124 if (flags & UNICODE_DISALLOW_NONCHAR) { \
125 return NULL; \
126 } \
127 } STMT_END;
128
dfe13c55 129U8 *
378516de 130Perl_uvoffuni_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags)
a0ed51b3 131{
378516de 132 PERL_ARGS_ASSERT_UVOFFUNI_TO_UTF8_FLAGS;
7918f24d 133
2d1545e5 134 if (OFFUNI_IS_INVARIANT(uv)) {
4c8cd605 135 *d++ = LATIN1_TO_NATIVE(uv);
d9432125
KW
136 return d;
137 }
3ea68d71
KW
138 if (uv <= MAX_UTF8_TWO_BYTE) {
139 *d++ = UTF8_TWO_BYTE_HI(uv);
140 *d++ = UTF8_TWO_BYTE_LO(uv);
141 return d;
142 }
d9432125 143
979f77b6 144 /* The first problematic code point is the first surrogate */
a5bf80e0 145 if (uv >= UNICODE_SURROGATE_FIRST) {
8ee1cdcb
KW
146 if (UNLIKELY(UNICODE_IS_NONCHAR(uv))) {
147 HANDLE_UNICODE_NONCHAR(uv, flags);
148 }
149 else if (UNLIKELY(UNICODE_IS_SURROGATE(uv))) {
150 HANDLE_UNICODE_SURROGATE(uv, flags);
760c7c2f 151 }
a5bf80e0
KW
152 else if (UNLIKELY(UNICODE_IS_SUPER(uv))) {
153 if ( UNLIKELY(uv > MAX_NON_DEPRECATED_CP)
154 && ckWARN_d(WARN_DEPRECATED))
155 {
156 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),
157 cp_above_legal_max, uv, MAX_NON_DEPRECATED_CP);
158 }
159 if ( (flags & UNICODE_WARN_SUPER)
160 || ( UNICODE_IS_ABOVE_31_BIT(uv)
161 && (flags & UNICODE_WARN_ABOVE_31_BIT)))
162 {
163 Perl_ck_warner_d(aTHX_ packWARN(WARN_NON_UNICODE),
164
165 /* Choose the more dire applicable warning */
166 (UNICODE_IS_ABOVE_31_BIT(uv))
167 ? "Code point 0x%"UVXf" is not Unicode, and not portable"
168 : "Code point 0x%"UVXf" is not Unicode, may not be portable",
169 uv);
170 }
171 if (flags & UNICODE_DISALLOW_SUPER
172 || ( UNICODE_IS_ABOVE_31_BIT(uv)
173 && (flags & UNICODE_DISALLOW_ABOVE_31_BIT)))
174 {
175 return NULL;
176 }
177 }
507b9800 178 }
d9432125 179
2d331972 180#if defined(EBCDIC)
d9432125 181 {
5aaebcb3 182 STRLEN len = OFFUNISKIP(uv);
1d72bdf6
NIS
183 U8 *p = d+len-1;
184 while (p > d) {
4c8cd605 185 *p-- = I8_TO_NATIVE_UTF8((uv & UTF_CONTINUATION_MASK) | UTF_CONTINUATION_MARK);
1d72bdf6
NIS
186 uv >>= UTF_ACCUMULATION_SHIFT;
187 }
4c8cd605 188 *p = I8_TO_NATIVE_UTF8((uv & UTF_START_MASK(len)) | UTF_START_MARK(len));
1d72bdf6
NIS
189 return d+len;
190 }
191#else /* Non loop style */
a0ed51b3 192 if (uv < 0x10000) {
eb160463
GS
193 *d++ = (U8)(( uv >> 12) | 0xe0);
194 *d++ = (U8)(((uv >> 6) & 0x3f) | 0x80);
195 *d++ = (U8)(( uv & 0x3f) | 0x80);
a0ed51b3
LW
196 return d;
197 }
198 if (uv < 0x200000) {
eb160463
GS
199 *d++ = (U8)(( uv >> 18) | 0xf0);
200 *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
201 *d++ = (U8)(((uv >> 6) & 0x3f) | 0x80);
202 *d++ = (U8)(( uv & 0x3f) | 0x80);
a0ed51b3
LW
203 return d;
204 }
205 if (uv < 0x4000000) {
eb160463
GS
206 *d++ = (U8)(( uv >> 24) | 0xf8);
207 *d++ = (U8)(((uv >> 18) & 0x3f) | 0x80);
208 *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
209 *d++ = (U8)(((uv >> 6) & 0x3f) | 0x80);
210 *d++ = (U8)(( uv & 0x3f) | 0x80);
a0ed51b3
LW
211 return d;
212 }
213 if (uv < 0x80000000) {
eb160463
GS
214 *d++ = (U8)(( uv >> 30) | 0xfc);
215 *d++ = (U8)(((uv >> 24) & 0x3f) | 0x80);
216 *d++ = (U8)(((uv >> 18) & 0x3f) | 0x80);
217 *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
218 *d++ = (U8)(((uv >> 6) & 0x3f) | 0x80);
219 *d++ = (U8)(( uv & 0x3f) | 0x80);
a0ed51b3
LW
220 return d;
221 }
6588300d 222#ifdef UTF8_QUAD_MAX
d7578b48 223 if (uv < UTF8_QUAD_MAX)
a0ed51b3
LW
224#endif
225 {
eb160463
GS
226 *d++ = 0xfe; /* Can't match U+FEFF! */
227 *d++ = (U8)(((uv >> 30) & 0x3f) | 0x80);
228 *d++ = (U8)(((uv >> 24) & 0x3f) | 0x80);
229 *d++ = (U8)(((uv >> 18) & 0x3f) | 0x80);
230 *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
231 *d++ = (U8)(((uv >> 6) & 0x3f) | 0x80);
232 *d++ = (U8)(( uv & 0x3f) | 0x80);
a0ed51b3
LW
233 return d;
234 }
6588300d 235#ifdef UTF8_QUAD_MAX
a0ed51b3 236 {
eb160463
GS
237 *d++ = 0xff; /* Can't match U+FFFE! */
238 *d++ = 0x80; /* 6 Reserved bits */
239 *d++ = (U8)(((uv >> 60) & 0x0f) | 0x80); /* 2 Reserved bits */
240 *d++ = (U8)(((uv >> 54) & 0x3f) | 0x80);
241 *d++ = (U8)(((uv >> 48) & 0x3f) | 0x80);
242 *d++ = (U8)(((uv >> 42) & 0x3f) | 0x80);
243 *d++ = (U8)(((uv >> 36) & 0x3f) | 0x80);
244 *d++ = (U8)(((uv >> 30) & 0x3f) | 0x80);
245 *d++ = (U8)(((uv >> 24) & 0x3f) | 0x80);
246 *d++ = (U8)(((uv >> 18) & 0x3f) | 0x80);
247 *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
248 *d++ = (U8)(((uv >> 6) & 0x3f) | 0x80);
249 *d++ = (U8)(( uv & 0x3f) | 0x80);
a0ed51b3
LW
250 return d;
251 }
252#endif
537124e4 253#endif /* Non loop style */
a0ed51b3 254}
a5bf80e0 255
646ca15d 256/*
07693fe6
KW
257=for apidoc uvchr_to_utf8
258
bcb1a2d4 259Adds the UTF-8 representation of the native code point C<uv> to the end
f2fc1b45 260of the string C<d>; C<d> should have at least C<UVCHR_SKIP(uv)+1> (up to
c749c9fd
KW
261C<UTF8_MAXBYTES+1>) free bytes available. The return value is the pointer to
262the byte after the end of the new character. In other words,
07693fe6
KW
263
264 d = uvchr_to_utf8(d, uv);
265
266is the recommended wide native character-aware way of saying
267
268 *(d++) = uv;
269
760c7c2f
KW
270This function accepts any UV as input, but very high code points (above
271C<IV_MAX> on the platform) will raise a deprecation warning. This is
272typically 0x7FFF_FFFF in a 32-bit word.
273
274It is possible to forbid or warn on non-Unicode code points, or those that may
275be problematic by using L</uvchr_to_utf8_flags>.
de69f3af 276
07693fe6
KW
277=cut
278*/
279
de69f3af
KW
280/* This is also a macro */
281PERL_CALLCONV U8* Perl_uvchr_to_utf8(pTHX_ U8 *d, UV uv);
282
07693fe6
KW
283U8 *
284Perl_uvchr_to_utf8(pTHX_ U8 *d, UV uv)
285{
de69f3af 286 return uvchr_to_utf8(d, uv);
07693fe6
KW
287}
288
de69f3af
KW
289/*
290=for apidoc uvchr_to_utf8_flags
291
292Adds the UTF-8 representation of the native code point C<uv> to the end
f2fc1b45 293of the string C<d>; C<d> should have at least C<UVCHR_SKIP(uv)+1> (up to
c749c9fd
KW
294C<UTF8_MAXBYTES+1>) free bytes available. The return value is the pointer to
295the byte after the end of the new character. In other words,
de69f3af
KW
296
297 d = uvchr_to_utf8_flags(d, uv, flags);
298
299or, in most cases,
300
301 d = uvchr_to_utf8_flags(d, uv, 0);
302
303This is the Unicode-aware way of saying
304
305 *(d++) = uv;
306
760c7c2f
KW
307If C<flags> is 0, this function accepts any UV as input, but very high code
308points (above C<IV_MAX> for the platform) will raise a deprecation warning.
309This is typically 0x7FFF_FFFF in a 32-bit word.
310
311Specifying C<flags> can further restrict what is allowed and not warned on, as
312follows:
de69f3af 313
796b6530 314If C<uv> is a Unicode surrogate code point and C<UNICODE_WARN_SURROGATE> is set,
7ee537e6
KW
315the function will raise a warning, provided UTF8 warnings are enabled. If
316instead C<UNICODE_DISALLOW_SURROGATE> is set, the function will fail and return
317NULL. If both flags are set, the function will both warn and return NULL.
de69f3af 318
760c7c2f
KW
319Similarly, the C<UNICODE_WARN_NONCHAR> and C<UNICODE_DISALLOW_NONCHAR> flags
320affect how the function handles a Unicode non-character.
93e6dbd6 321
760c7c2f
KW
322And likewise, the C<UNICODE_WARN_SUPER> and C<UNICODE_DISALLOW_SUPER> flags
323affect the handling of code points that are above the Unicode maximum of
3240x10FFFF. Languages other than Perl may not be able to accept files that
325contain these.
93e6dbd6
KW
326
327The flag C<UNICODE_WARN_ILLEGAL_INTERCHANGE> selects all three of
328the above WARN flags; and C<UNICODE_DISALLOW_ILLEGAL_INTERCHANGE> selects all
329three DISALLOW flags.
330
ab8e6d41
KW
331Code points above 0x7FFF_FFFF (2**31 - 1) were never specified in any standard,
332so using them is more problematic than other above-Unicode code points. Perl
333invented an extension to UTF-8 to represent the ones above 2**36-1, so it is
334likely that non-Perl languages will not be able to read files that contain
335these that written by the perl interpreter; nor would Perl understand files
336written by something that uses a different extension. For these reasons, there
337is a separate set of flags that can warn and/or disallow these extremely high
338code points, even if other above-Unicode ones are accepted. These are the
760c7c2f
KW
339C<UNICODE_WARN_ABOVE_31_BIT> and C<UNICODE_DISALLOW_ABOVE_31_BIT> flags. These
340are entirely independent from the deprecation warning for code points above
341C<IV_MAX>. On 32-bit machines, it will eventually be forbidden to have any
342code point that needs more than 31 bits to represent. When that happens,
343effectively the C<UNICODE_DISALLOW_ABOVE_31_BIT> flag will always be set on
34432-bit machines. (Of course C<UNICODE_DISALLOW_SUPER> will treat all
ab8e6d41
KW
345above-Unicode code points, including these, as malformations; and
346C<UNICODE_WARN_SUPER> warns on these.)
347
348On EBCDIC platforms starting in Perl v5.24, the Perl extension for representing
349extremely high code points kicks in at 0x3FFF_FFFF (2**30 -1), which is lower
350than on ASCII. Prior to that, code points 2**31 and higher were simply
351unrepresentable, and a different, incompatible method was used to represent
352code points between 2**30 and 2**31 - 1. The flags C<UNICODE_WARN_ABOVE_31_BIT>
353and C<UNICODE_DISALLOW_ABOVE_31_BIT> have the same function as on ASCII
354platforms, warning and disallowing 2**31 and higher.
de69f3af 355
de69f3af
KW
356=cut
357*/
358
359/* This is also a macro */
360PERL_CALLCONV U8* Perl_uvchr_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags);
361
07693fe6
KW
362U8 *
363Perl_uvchr_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags)
364{
de69f3af 365 return uvchr_to_utf8_flags(d, uv, flags);
07693fe6
KW
366}
367
368/*
87cea99e 369=for apidoc is_utf8_string
6662521e 370
a1433954 371Returns true if the first C<len> bytes of string C<s> form a valid
9f7e3d64 372UTF-8 string, false otherwise. If C<len> is 0, it will be calculated
75200dff
KW
373using C<strlen(s)> (which means if you use this option, that C<s> can't have
374embedded C<NUL> characters and has to have a terminating C<NUL> byte). Note
375that all characters being ASCII constitute 'a valid UTF-8 string'.
6662521e 376
7bbfa158 377See also L</is_invariant_string>(), L</is_utf8_string_loclen>(), and L</is_utf8_string_loc>().
768c67ee 378
6662521e
GS
379=cut
380*/
381
8e84507e 382bool
668b6d8d 383Perl_is_utf8_string(const U8 *s, STRLEN len)
6662521e 384{
35da51f7 385 const U8* const send = s + (len ? len : strlen((const char *)s));
7fc63493 386 const U8* x = s;
067a85ef 387
7918f24d 388 PERL_ARGS_ASSERT_IS_UTF8_STRING;
1aa99e6b 389
6662521e 390 while (x < send) {
6302f837
KW
391 STRLEN len = isUTF8_CHAR(x, send);
392 if (UNLIKELY(! len)) {
393 return FALSE;
394 }
395 x += len;
6662521e 396 }
768c67ee 397
067a85ef 398 return TRUE;
6662521e
GS
399}
400
67e989fb 401/*
814fafa7
NC
402Implemented as a macro in utf8.h
403
87cea99e 404=for apidoc is_utf8_string_loc
814fafa7 405
a1433954
KW
406Like L</is_utf8_string> but stores the location of the failure (in the
407case of "utf8ness failure") or the location C<s>+C<len> (in the case of
814fafa7
NC
408"utf8ness success") in the C<ep>.
409
a1433954 410See also L</is_utf8_string_loclen>() and L</is_utf8_string>().
814fafa7 411
87cea99e 412=for apidoc is_utf8_string_loclen
81cd54e3 413
a1433954
KW
414Like L</is_utf8_string>() but stores the location of the failure (in the
415case of "utf8ness failure") or the location C<s>+C<len> (in the case of
768c67ee
JH
416"utf8ness success") in the C<ep>, and the number of UTF-8
417encoded characters in the C<el>.
418
a1433954 419See also L</is_utf8_string_loc>() and L</is_utf8_string>().
81cd54e3
JH
420
421=cut
422*/
423
424bool
668b6d8d 425Perl_is_utf8_string_loclen(const U8 *s, STRLEN len, const U8 **ep, STRLEN *el)
81cd54e3 426{
35da51f7 427 const U8* const send = s + (len ? len : strlen((const char *)s));
7fc63493 428 const U8* x = s;
3ebfea28 429 STRLEN outlen = 0;
7918f24d
NC
430
431 PERL_ARGS_ASSERT_IS_UTF8_STRING_LOCLEN;
81cd54e3 432
81cd54e3 433 while (x < send) {
6302f837
KW
434 STRLEN len = isUTF8_CHAR(x, send);
435 if (UNLIKELY(! len)) {
436 goto out;
437 }
438 x += len;
439 outlen++;
81cd54e3 440 }
768c67ee
JH
441
442 out:
3ebfea28
AL
443 if (el)
444 *el = outlen;
445
768c67ee
JH
446 if (ep)
447 *ep = x;
3ebfea28 448 return (x == send);
81cd54e3
JH
449}
450
451/*
768c67ee 452
de69f3af 453=for apidoc utf8n_to_uvchr
378516de
KW
454
455THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES.
de69f3af 456Most code should use L</utf8_to_uvchr_buf>() rather than call this directly.
67e989fb 457
9041c2e3 458Bottom level UTF-8 decode routine.
de69f3af 459Returns the native code point value of the first character in the string C<s>,
746afd53
KW
460which is assumed to be in UTF-8 (or UTF-EBCDIC) encoding, and no longer than
461C<curlen> bytes; C<*retlen> (if C<retlen> isn't NULL) will be set to
462the length, in bytes, of that character.
949cf498
KW
463
464The value of C<flags> determines the behavior when C<s> does not point to a
465well-formed UTF-8 character. If C<flags> is 0, when a malformation is found,
524080c4
KW
466zero is returned and C<*retlen> is set so that (S<C<s> + C<*retlen>>) is the
467next possible position in C<s> that could begin a non-malformed character.
468Also, if UTF-8 warnings haven't been lexically disabled, a warning is raised.
949cf498
KW
469
470Various ALLOW flags can be set in C<flags> to allow (and not warn on)
471individual types of malformations, such as the sequence being overlong (that
472is, when there is a shorter sequence that can express the same code point;
473overlong sequences are expressly forbidden in the UTF-8 standard due to
474potential security issues). Another malformation example is the first byte of
475a character not being a legal first byte. See F<utf8.h> for the list of such
524080c4
KW
476flags. For allowed 0 length strings, this function returns 0; for allowed
477overlong sequences, the computed code point is returned; for all other allowed
478malformations, the Unicode REPLACEMENT CHARACTER is returned, as these have no
479determinable reasonable value.
949cf498 480
796b6530 481The C<UTF8_CHECK_ONLY> flag overrides the behavior when a non-allowed (by other
949cf498
KW
482flags) malformation is found. If this flag is set, the routine assumes that
483the caller will raise a warning, and this function will silently just set
d088425d
KW
484C<retlen> to C<-1> (cast to C<STRLEN>) and return zero.
485
75200dff 486Note that this API requires disambiguation between successful decoding a C<NUL>
796b6530 487character, and an error return (unless the C<UTF8_CHECK_ONLY> flag is set), as
d088425d 488in both cases, 0 is returned. To disambiguate, upon a zero return, see if the
75200dff
KW
489first byte of C<s> is 0 as well. If so, the input was a C<NUL>; if not, the
490input had an error.
949cf498
KW
491
492Certain code points are considered problematic. These are Unicode surrogates,
746afd53 493Unicode non-characters, and code points above the Unicode maximum of 0x10FFFF.
949cf498 494By default these are considered regular code points, but certain situations
5eafe189 495warrant special handling for them. If C<flags> contains
796b6530
KW
496C<UTF8_DISALLOW_ILLEGAL_INTERCHANGE>, all three classes are treated as
497malformations and handled as such. The flags C<UTF8_DISALLOW_SURROGATE>,
498C<UTF8_DISALLOW_NONCHAR>, and C<UTF8_DISALLOW_SUPER> (meaning above the legal
499Unicode maximum) can be set to disallow these categories individually.
500
501The flags C<UTF8_WARN_ILLEGAL_INTERCHANGE>, C<UTF8_WARN_SURROGATE>,
502C<UTF8_WARN_NONCHAR>, and C<UTF8_WARN_SUPER> will cause warning messages to be
503raised for their respective categories, but otherwise the code points are
504considered valid (not malformations). To get a category to both be treated as
505a malformation and raise a warning, specify both the WARN and DISALLOW flags.
949cf498 506(But note that warnings are not raised if lexically disabled nor if
796b6530 507C<UTF8_CHECK_ONLY> is also specified.)
949cf498 508
760c7c2f
KW
509It is now deprecated to have very high code points (above C<IV_MAX> on the
510platforms) and this function will raise a deprecation warning for these (unless
511such warnings are turned off). This value, is typically 0x7FFF_FFFF (2**31 -1)
512in a 32-bit word.
ab8e6d41
KW
513
514Code points above 0x7FFF_FFFF (2**31 - 1) were never specified in any standard,
515so using them is more problematic than other above-Unicode code points. Perl
516invented an extension to UTF-8 to represent the ones above 2**36-1, so it is
517likely that non-Perl languages will not be able to read files that contain
518these that written by the perl interpreter; nor would Perl understand files
519written by something that uses a different extension. For these reasons, there
520is a separate set of flags that can warn and/or disallow these extremely high
521code points, even if other above-Unicode ones are accepted. These are the
760c7c2f
KW
522C<UTF8_WARN_ABOVE_31_BIT> and C<UTF8_DISALLOW_ABOVE_31_BIT> flags. These
523are entirely independent from the deprecation warning for code points above
524C<IV_MAX>. On 32-bit machines, it will eventually be forbidden to have any
525code point that needs more than 31 bits to represent. When that happens,
526effectively the C<UTF8_DISALLOW_ABOVE_31_BIT> flag will always be set on
52732-bit machines. (Of course C<UTF8_DISALLOW_SUPER> will treat all
ab8e6d41
KW
528above-Unicode code points, including these, as malformations; and
529C<UTF8_WARN_SUPER> warns on these.)
530
531On EBCDIC platforms starting in Perl v5.24, the Perl extension for representing
532extremely high code points kicks in at 0x3FFF_FFFF (2**30 -1), which is lower
533than on ASCII. Prior to that, code points 2**31 and higher were simply
534unrepresentable, and a different, incompatible method was used to represent
535code points between 2**30 and 2**31 - 1. The flags C<UTF8_WARN_ABOVE_31_BIT>
536and C<UTF8_DISALLOW_ABOVE_31_BIT> have the same function as on ASCII
537platforms, warning and disallowing 2**31 and higher.
949cf498
KW
538
539All other code points corresponding to Unicode characters, including private
540use and those yet to be assigned, are never considered malformed and never
541warn.
67e989fb 542
37607a96
PK
543=cut
544*/
67e989fb 545
a0ed51b3 546UV
de69f3af 547Perl_utf8n_to_uvchr(pTHX_ const U8 *s, STRLEN curlen, STRLEN *retlen, U32 flags)
a0ed51b3 548{
d4c19fe8 549 const U8 * const s0 = s;
eb83ed87 550 U8 overflow_byte = '\0'; /* Save byte in case of overflow */
0b8d30e8 551 U8 * send;
eb83ed87
KW
552 UV uv = *s;
553 STRLEN expectlen;
949cf498 554 SV* sv = NULL;
eb83ed87
KW
555 UV outlier_ret = 0; /* return value when input is in error or problematic
556 */
557 UV pack_warn = 0; /* Save result of packWARN() for later */
558 bool unexpected_non_continuation = FALSE;
559 bool overflowed = FALSE;
2f8f112e 560 bool do_overlong_test = TRUE; /* May have to skip this test */
a0dbb045 561
eb83ed87 562 const char* const malformed_text = "Malformed UTF-8 character";
7918f24d 563
de69f3af 564 PERL_ARGS_ASSERT_UTF8N_TO_UVCHR;
a0dbb045 565
eb83ed87
KW
566 /* The order of malformation tests here is important. We should consume as
567 * few bytes as possible in order to not skip any valid character. This is
568 * required by the Unicode Standard (section 3.9 of Unicode 6.0); see also
569 * http://unicode.org/reports/tr36 for more discussion as to why. For
570 * example, once we've done a UTF8SKIP, we can tell the expected number of
571 * bytes, and could fail right off the bat if the input parameters indicate
572 * that there are too few available. But it could be that just that first
573 * byte is garbled, and the intended character occupies fewer bytes. If we
574 * blindly assumed that the first byte is correct, and skipped based on
575 * that number, we could skip over a valid input character. So instead, we
576 * always examine the sequence byte-by-byte.
577 *
578 * We also should not consume too few bytes, otherwise someone could inject
579 * things. For example, an input could be deliberately designed to
580 * overflow, and if this code bailed out immediately upon discovering that,
e2660c54 581 * returning to the caller C<*retlen> pointing to the very next byte (one
eb83ed87
KW
582 * which is actually part of of the overflowing sequence), that could look
583 * legitimate to the caller, which could discard the initial partial
584 * sequence and process the rest, inappropriately */
585
586 /* Zero length strings, if allowed, of necessity are zero */
b5b9af04 587 if (UNLIKELY(curlen == 0)) {
eb83ed87
KW
588 if (retlen) {
589 *retlen = 0;
590 }
a0dbb045 591
eb83ed87
KW
592 if (flags & UTF8_ALLOW_EMPTY) {
593 return 0;
594 }
595 if (! (flags & UTF8_CHECK_ONLY)) {
596 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (empty string)", malformed_text));
597 }
0c443dc2
JH
598 goto malformed;
599 }
600
eb83ed87
KW
601 expectlen = UTF8SKIP(s);
602
603 /* A well-formed UTF-8 character, as the vast majority of calls to this
604 * function will be for, has this expected length. For efficiency, set
605 * things up here to return it. It will be overriden only in those rare
606 * cases where a malformation is found */
607 if (retlen) {
608 *retlen = expectlen;
609 }
610
611 /* An invariant is trivially well-formed */
1d72bdf6 612 if (UTF8_IS_INVARIANT(uv)) {
de69f3af 613 return uv;
a0ed51b3 614 }
67e989fb 615
eb83ed87 616 /* A continuation character can't start a valid sequence */
b5b9af04 617 if (UNLIKELY(UTF8_IS_CONTINUATION(uv))) {
eb83ed87
KW
618 if (flags & UTF8_ALLOW_CONTINUATION) {
619 if (retlen) {
620 *retlen = 1;
621 }
622 return UNICODE_REPLACEMENT;
623 }
ba210ebe 624
eb83ed87
KW
625 if (! (flags & UTF8_CHECK_ONLY)) {
626 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (unexpected continuation byte 0x%02x, with no preceding start byte)", malformed_text, *s0));
627 }
628 curlen = 1;
ba210ebe
JH
629 goto malformed;
630 }
9041c2e3 631
dcd27b3c
KW
632 /* Here is not a continuation byte, nor an invariant. The only thing left
633 * is a start byte (possibly for an overlong) */
634
1d72bdf6 635#ifdef EBCDIC
bc3632a8 636 uv = NATIVE_UTF8_TO_I8(uv);
1d72bdf6
NIS
637#endif
638
eb83ed87
KW
639 /* Remove the leading bits that indicate the number of bytes in the
640 * character's whole UTF-8 sequence, leaving just the bits that are part of
641 * the value */
642 uv &= UTF_START_MASK(expectlen);
ba210ebe 643
eb83ed87
KW
644 /* Now, loop through the remaining bytes in the character's sequence,
645 * accumulating each into the working value as we go. Be sure to not look
646 * past the end of the input string */
0b8d30e8
KW
647 send = (U8*) s0 + ((expectlen <= curlen) ? expectlen : curlen);
648
eb83ed87 649 for (s = s0 + 1; s < send; s++) {
b5b9af04 650 if (LIKELY(UTF8_IS_CONTINUATION(*s))) {
eb83ed87
KW
651 if (uv & UTF_ACCUMULATION_OVERFLOW_MASK) {
652
653 /* The original implementors viewed this malformation as more
654 * serious than the others (though I, khw, don't understand
655 * why, since other malformations also give very very wrong
656 * results), so there is no way to turn off checking for it.
657 * Set a flag, but keep going in the loop, so that we absorb
658 * the rest of the bytes that comprise the character. */
659 overflowed = TRUE;
660 overflow_byte = *s; /* Save for warning message's use */
661 }
8850bf83 662 uv = UTF8_ACCUMULATE(uv, *s);
eb83ed87
KW
663 }
664 else {
665 /* Here, found a non-continuation before processing all expected
666 * bytes. This byte begins a new character, so quit, even if
667 * allowing this malformation. */
668 unexpected_non_continuation = TRUE;
669 break;
670 }
671 } /* End of loop through the character's bytes */
672
673 /* Save how many bytes were actually in the character */
674 curlen = s - s0;
675
676 /* The loop above finds two types of malformations: non-continuation and/or
677 * overflow. The non-continuation malformation is really a too-short
678 * malformation, as it means that the current character ended before it was
679 * expected to (being terminated prematurely by the beginning of the next
680 * character, whereas in the too-short malformation there just are too few
681 * bytes available to hold the character. In both cases, the check below
682 * that we have found the expected number of bytes would fail if executed.)
683 * Thus the non-continuation malformation is really unnecessary, being a
684 * subset of the too-short malformation. But there may be existing
685 * applications that are expecting the non-continuation type, so we retain
686 * it, and return it in preference to the too-short malformation. (If this
687 * code were being written from scratch, the two types might be collapsed
688 * into one.) I, khw, am also giving priority to returning the
689 * non-continuation and too-short malformations over overflow when multiple
690 * ones are present. I don't know of any real reason to prefer one over
691 * the other, except that it seems to me that multiple-byte errors trumps
692 * errors from a single byte */
b5b9af04 693 if (UNLIKELY(unexpected_non_continuation)) {
eb83ed87
KW
694 if (!(flags & UTF8_ALLOW_NON_CONTINUATION)) {
695 if (! (flags & UTF8_CHECK_ONLY)) {
696 if (curlen == 1) {
697 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (unexpected non-continuation byte 0x%02x, immediately after start byte 0x%02x)", malformed_text, *s, *s0));
698 }
699 else {
700 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (unexpected non-continuation byte 0x%02x, %d bytes after start byte 0x%02x, expected %d bytes)", malformed_text, *s, (int) curlen, *s0, (int)expectlen));
a0dbb045
JH
701 }
702 }
eb83ed87
KW
703 goto malformed;
704 }
705 uv = UNICODE_REPLACEMENT;
2f8f112e
KW
706
707 /* Skip testing for overlongs, as the REPLACEMENT may not be the same
708 * as what the original expectations were. */
709 do_overlong_test = FALSE;
eb83ed87
KW
710 if (retlen) {
711 *retlen = curlen;
712 }
713 }
b5b9af04 714 else if (UNLIKELY(curlen < expectlen)) {
eb83ed87
KW
715 if (! (flags & UTF8_ALLOW_SHORT)) {
716 if (! (flags & UTF8_CHECK_ONLY)) {
717 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (%d byte%s, need %d, after start byte 0x%02x)", malformed_text, (int)curlen, curlen == 1 ? "" : "s", (int)expectlen, *s0));
a0dbb045 718 }
eb83ed87
KW
719 goto malformed;
720 }
721 uv = UNICODE_REPLACEMENT;
2f8f112e 722 do_overlong_test = FALSE;
eb83ed87
KW
723 if (retlen) {
724 *retlen = curlen;
725 }
726 }
727
b5b9af04 728 if (UNLIKELY(overflowed)) {
eb83ed87 729 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (overflow at byte 0x%02x, after start byte 0x%02x)", malformed_text, overflow_byte, *s0));
ba210ebe 730 goto malformed;
eb83ed87 731 }
eb83ed87 732
2f8f112e 733 if (do_overlong_test
5aaebcb3 734 && expectlen > (STRLEN) OFFUNISKIP(uv)
2f8f112e
KW
735 && ! (flags & UTF8_ALLOW_LONG))
736 {
eb83ed87
KW
737 /* The overlong malformation has lower precedence than the others.
738 * Note that if this malformation is allowed, we return the actual
739 * value, instead of the replacement character. This is because this
740 * value is actually well-defined. */
741 if (! (flags & UTF8_CHECK_ONLY)) {
5aaebcb3 742 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (%d byte%s, need %d, after start byte 0x%02x)", malformed_text, (int)expectlen, expectlen == 1 ? "": "s", OFFUNISKIP(uv), *s0));
eb83ed87
KW
743 }
744 goto malformed;
745 }
746
1a89bb6c 747 /* Here, the input is considered to be well-formed, but it still could be a
eb83ed87
KW
748 * problematic code point that is not allowed by the input parameters. */
749 if (uv >= UNICODE_SURROGATE_FIRST /* isn't problematic if < this */
760c7c2f
KW
750 && ((flags & ( UTF8_DISALLOW_NONCHAR
751 |UTF8_DISALLOW_SURROGATE
752 |UTF8_DISALLOW_SUPER
753 |UTF8_DISALLOW_ABOVE_31_BIT
754 |UTF8_WARN_NONCHAR
755 |UTF8_WARN_SURROGATE
756 |UTF8_WARN_SUPER
757 |UTF8_WARN_ABOVE_31_BIT))
758 || ( UNLIKELY(uv > MAX_NON_DEPRECATED_CP)
759 && ckWARN_d(WARN_DEPRECATED))))
eb83ed87 760 {
949cf498 761 if (UNICODE_IS_SURROGATE(uv)) {
ea5ced44
KW
762
763 /* By adding UTF8_CHECK_ONLY to the test, we avoid unnecessary
764 * generation of the sv, since no warnings are raised under CHECK */
eb83ed87 765 if ((flags & (UTF8_WARN_SURROGATE|UTF8_CHECK_ONLY)) == UTF8_WARN_SURROGATE
54f4afef 766 && ckWARN_d(WARN_SURROGATE))
eb83ed87 767 {
111d382d 768 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "UTF-16 surrogate U+%04"UVXf"", uv));
54f4afef 769 pack_warn = packWARN(WARN_SURROGATE);
949cf498
KW
770 }
771 if (flags & UTF8_DISALLOW_SURROGATE) {
772 goto disallowed;
773 }
774 }
949cf498 775 else if ((uv > PERL_UNICODE_MAX)) {
eb83ed87 776 if ((flags & (UTF8_WARN_SUPER|UTF8_CHECK_ONLY)) == UTF8_WARN_SUPER
ea5ced44 777 && ckWARN_d(WARN_NON_UNICODE))
eb83ed87 778 {
0bcdd8f6
KW
779 sv = sv_2mortal(Perl_newSVpvf(aTHX_
780 "Code point 0x%04"UVXf" is not Unicode, may not be portable",
781 uv));
54f4afef 782 pack_warn = packWARN(WARN_NON_UNICODE);
949cf498 783 }
c0236afe
KW
784
785 /* The maximum code point ever specified by a standard was
786 * 2**31 - 1. Anything larger than that is a Perl extension that
787 * very well may not be understood by other applications (including
788 * earlier perl versions on EBCDIC platforms). On ASCII platforms,
789 * these code points are indicated by the first UTF-8 byte being
d35f2ca5
KW
790 * 0xFE or 0xFF. We test for these after the regular SUPER ones,
791 * and before possibly bailing out, so that the slightly more dire
c0236afe
KW
792 * warning will override the regular one. */
793 if (
794#ifndef EBCDIC
795 (*s0 & 0xFE) == 0xFE /* matches both FE, FF */
796#else
797 /* The I8 for 2**31 (U+80000000) is
798 * \xFF\xA0\xA0\xA0\xA0\xA0\xA0\xA2\xA0\xA0\xA0\xA0\xA0\xA0
799 * and it turns out that on all EBCDIC pages recognized that
800 * the UTF-EBCDIC for that code point is
801 * \xFE\x41\x41\x41\x41\x41\x41\x43\x41\x41\x41\x41\x41\x41
802 * For the next lower code point, the 1047 UTF-EBCDIC is
803 * \xFE\x41\x41\x41\x41\x41\x41\x42\x73\x73\x73\x73\x73\x73
804 * The other code pages differ only in the bytes following
805 * \x42. Thus the following works (the minimum continuation
806 * byte is \x41). */
807 *s0 == 0xFE && send - s0 > 7 && ( s0[1] > 0x41
808 || s0[2] > 0x41
809 || s0[3] > 0x41
810 || s0[4] > 0x41
811 || s0[5] > 0x41
812 || s0[6] > 0x41
813 || s0[7] > 0x42)
814#endif
d35f2ca5
KW
815 && (flags & (UTF8_WARN_ABOVE_31_BIT|UTF8_WARN_SUPER
816 |UTF8_DISALLOW_ABOVE_31_BIT)))
ea5ced44 817 {
0bcdd8f6 818 if ( ! (flags & UTF8_CHECK_ONLY)
d35f2ca5 819 && (flags & (UTF8_WARN_ABOVE_31_BIT|UTF8_WARN_SUPER))
0bcdd8f6 820 && ckWARN_d(WARN_UTF8))
ea5ced44 821 {
0bcdd8f6
KW
822 sv = sv_2mortal(Perl_newSVpvf(aTHX_
823 "Code point 0x%"UVXf" is not Unicode, and not portable",
824 uv));
ea5ced44
KW
825 pack_warn = packWARN(WARN_UTF8);
826 }
d35f2ca5 827 if (flags & UTF8_DISALLOW_ABOVE_31_BIT) {
ea5ced44
KW
828 goto disallowed;
829 }
830 }
c0236afe 831
949cf498
KW
832 if (flags & UTF8_DISALLOW_SUPER) {
833 goto disallowed;
834 }
760c7c2f
KW
835
836 /* The deprecated warning overrides any non-deprecated one */
837 if (UNLIKELY(uv > MAX_NON_DEPRECATED_CP) && ckWARN_d(WARN_DEPRECATED))
838 {
839 sv = sv_2mortal(Perl_newSVpvf(aTHX_ cp_above_legal_max,
840 uv, MAX_NON_DEPRECATED_CP));
841 pack_warn = packWARN(WARN_DEPRECATED);
842 }
949cf498 843 }
4190d317
KW
844 else if (UNICODE_IS_NONCHAR(uv)) {
845 if ((flags & (UTF8_WARN_NONCHAR|UTF8_CHECK_ONLY)) == UTF8_WARN_NONCHAR
54f4afef 846 && ckWARN_d(WARN_NONCHAR))
4190d317 847 {
ba707cdc 848 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "Unicode non-character U+%04"UVXf" is not recommended for open interchange", uv));
54f4afef 849 pack_warn = packWARN(WARN_NONCHAR);
4190d317
KW
850 }
851 if (flags & UTF8_DISALLOW_NONCHAR) {
852 goto disallowed;
853 }
854 }
949cf498 855
eb83ed87 856 if (sv) {
de69f3af
KW
857 outlier_ret = uv; /* Note we don't bother to convert to native,
858 as all the outlier code points are the same
859 in both ASCII and EBCDIC */
eb83ed87
KW
860 goto do_warn;
861 }
862
949cf498
KW
863 /* Here, this is not considered a malformed character, so drop through
864 * to return it */
a0ed51b3 865 }
ba210ebe 866
de69f3af 867 return UNI_TO_NATIVE(uv);
ba210ebe 868
eb83ed87
KW
869 /* There are three cases which get to beyond this point. In all 3 cases:
870 * <sv> if not null points to a string to print as a warning.
871 * <curlen> is what <*retlen> should be set to if UTF8_CHECK_ONLY isn't
872 * set.
873 * <outlier_ret> is what return value to use if UTF8_CHECK_ONLY isn't set.
874 * This is done by initializing it to 0, and changing it only
875 * for case 1).
876 * The 3 cases are:
877 * 1) The input is valid but problematic, and to be warned about. The
878 * return value is the resultant code point; <*retlen> is set to
879 * <curlen>, the number of bytes that comprise the code point.
880 * <pack_warn> contains the result of packWARN() for the warning
881 * types. The entry point for this case is the label <do_warn>;
882 * 2) The input is a valid code point but disallowed by the parameters to
883 * this function. The return value is 0. If UTF8_CHECK_ONLY is set,
884 * <*relen> is -1; otherwise it is <curlen>, the number of bytes that
885 * comprise the code point. <pack_warn> contains the result of
886 * packWARN() for the warning types. The entry point for this case is
887 * the label <disallowed>.
888 * 3) The input is malformed. The return value is 0. If UTF8_CHECK_ONLY
889 * is set, <*relen> is -1; otherwise it is <curlen>, the number of
890 * bytes that comprise the malformation. All such malformations are
891 * assumed to be warning type <utf8>. The entry point for this case
892 * is the label <malformed>.
893 */
949cf498 894
7b52d656 895 malformed:
ba210ebe 896
eb83ed87
KW
897 if (sv && ckWARN_d(WARN_UTF8)) {
898 pack_warn = packWARN(WARN_UTF8);
899 }
900
7b52d656 901 disallowed:
eb83ed87 902
fcc8fcf6 903 if (flags & UTF8_CHECK_ONLY) {
ba210ebe 904 if (retlen)
10edeb5d 905 *retlen = ((STRLEN) -1);
ba210ebe
JH
906 return 0;
907 }
908
7b52d656 909 do_warn:
5b311467 910
eb83ed87
KW
911 if (pack_warn) { /* <pack_warn> was initialized to 0, and changed only
912 if warnings are to be raised. */
f555bc63 913 const char * const string = SvPVX_const(sv);
a0dbb045 914
f555bc63
KW
915 if (PL_op)
916 Perl_warner(aTHX_ pack_warn, "%s in %s", string, OP_DESC(PL_op));
917 else
918 Perl_warner(aTHX_ pack_warn, "%s", string);
a0dbb045
JH
919 }
920
eb83ed87
KW
921 if (retlen) {
922 *retlen = curlen;
923 }
ba210ebe 924
eb83ed87 925 return outlier_ret;
a0ed51b3
LW
926}
927
8e84507e 928/*
ec5f19d0
KW
929=for apidoc utf8_to_uvchr_buf
930
931Returns the native code point of the first character in the string C<s> which
932is assumed to be in UTF-8 encoding; C<send> points to 1 beyond the end of C<s>.
524080c4 933C<*retlen> will be set to the length, in bytes, of that character.
ec5f19d0 934
524080c4
KW
935If C<s> does not point to a well-formed UTF-8 character and UTF8 warnings are
936enabled, zero is returned and C<*retlen> is set (if C<retlen> isn't
796b6530 937C<NULL>) to -1. If those warnings are off, the computed value, if well-defined
173db420 938(or the Unicode REPLACEMENT CHARACTER if not), is silently returned, and
796b6530 939C<*retlen> is set (if C<retlen> isn't C<NULL>) so that (S<C<s> + C<*retlen>>) is
173db420 940the next possible position in C<s> that could begin a non-malformed character.
de69f3af 941See L</utf8n_to_uvchr> for details on when the REPLACEMENT CHARACTER is
173db420 942returned.
ec5f19d0 943
760c7c2f
KW
944Code points above the platform's C<IV_MAX> will raise a deprecation warning,
945unless those are turned off.
946
ec5f19d0
KW
947=cut
948*/
949
950
951UV
952Perl_utf8_to_uvchr_buf(pTHX_ const U8 *s, const U8 *send, STRLEN *retlen)
953{
ec5f19d0
KW
954 assert(s < send);
955
956 return utf8n_to_uvchr(s, send - s, retlen,
957 ckWARN_d(WARN_UTF8) ? 0 : UTF8_ALLOW_ANY);
958}
959
27d6c58a 960/* Like L</utf8_to_uvchr_buf>(), but should only be called when it is known that
3986bb7c 961 * there are no malformations in the input UTF-8 string C<s>. surrogates,
57b0056d 962 * non-character code points, and non-Unicode code points are allowed. */
27d6c58a
KW
963
964UV
965Perl_valid_utf8_to_uvchr(pTHX_ const U8 *s, STRLEN *retlen)
966{
010ab96b
KW
967 UV expectlen = UTF8SKIP(s);
968 const U8* send = s + expectlen;
9ff2f0f7 969 UV uv = *s;
3986bb7c 970
27d6c58a 971 PERL_ARGS_ASSERT_VALID_UTF8_TO_UVCHR;
81611534 972 PERL_UNUSED_CONTEXT;
27d6c58a 973
010ab96b
KW
974 if (retlen) {
975 *retlen = expectlen;
976 }
977
978 /* An invariant is trivially returned */
979 if (expectlen == 1) {
9ff2f0f7 980 return uv;
010ab96b
KW
981 }
982
9ff2f0f7
KW
983#ifdef EBCDIC
984 uv = NATIVE_UTF8_TO_I8(uv);
985#endif
986
010ab96b
KW
987 /* Remove the leading bits that indicate the number of bytes, leaving just
988 * the bits that are part of the value */
989 uv &= UTF_START_MASK(expectlen);
990
991 /* Now, loop through the remaining bytes, accumulating each into the
992 * working total as we go. (I khw tried unrolling the loop for up to 4
993 * bytes, but there was no performance improvement) */
994 for (++s; s < send; s++) {
995 uv = UTF8_ACCUMULATE(uv, *s);
996 }
997
3986bb7c 998 return UNI_TO_NATIVE(uv);
010ab96b 999
27d6c58a
KW
1000}
1001
ec5f19d0 1002/*
ec5f19d0
KW
1003=for apidoc utf8_to_uvuni_buf
1004
de69f3af
KW
1005Only in very rare circumstances should code need to be dealing in Unicode
1006(as opposed to native) code points. In those few cases, use
1007C<L<NATIVE_TO_UNI(utf8_to_uvchr_buf(...))|/utf8_to_uvchr_buf>> instead.
4f83cdcd
KW
1008
1009Returns the Unicode (not-native) code point of the first character in the
1010string C<s> which
ec5f19d0
KW
1011is assumed to be in UTF-8 encoding; C<send> points to 1 beyond the end of C<s>.
1012C<retlen> will be set to the length, in bytes, of that character.
1013
524080c4
KW
1014If C<s> does not point to a well-formed UTF-8 character and UTF8 warnings are
1015enabled, zero is returned and C<*retlen> is set (if C<retlen> isn't
1016NULL) to -1. If those warnings are off, the computed value if well-defined (or
1017the Unicode REPLACEMENT CHARACTER, if not) is silently returned, and C<*retlen>
1018is set (if C<retlen> isn't NULL) so that (S<C<s> + C<*retlen>>) is the
1019next possible position in C<s> that could begin a non-malformed character.
de69f3af 1020See L</utf8n_to_uvchr> for details on when the REPLACEMENT CHARACTER is returned.
ec5f19d0 1021
760c7c2f
KW
1022Code points above the platform's C<IV_MAX> will raise a deprecation warning,
1023unless those are turned off.
1024
ec5f19d0
KW
1025=cut
1026*/
1027
1028UV
1029Perl_utf8_to_uvuni_buf(pTHX_ const U8 *s, const U8 *send, STRLEN *retlen)
1030{
1031 PERL_ARGS_ASSERT_UTF8_TO_UVUNI_BUF;
1032
1033 assert(send > s);
1034
1035 /* Call the low level routine asking for checks */
de69f3af
KW
1036 return NATIVE_TO_UNI(Perl_utf8n_to_uvchr(aTHX_ s, send -s, retlen,
1037 ckWARN_d(WARN_UTF8) ? 0 : UTF8_ALLOW_ANY));
ec5f19d0
KW
1038}
1039
b76347f2 1040/*
87cea99e 1041=for apidoc utf8_length
b76347f2
JH
1042
1043Return the length of the UTF-8 char encoded string C<s> in characters.
02eb7b47
JH
1044Stops at C<e> (inclusive). If C<e E<lt> s> or if the scan would end
1045up past C<e>, croaks.
b76347f2
JH
1046
1047=cut
1048*/
1049
1050STRLEN
35a4481c 1051Perl_utf8_length(pTHX_ const U8 *s, const U8 *e)
b76347f2
JH
1052{
1053 STRLEN len = 0;
1054
7918f24d
NC
1055 PERL_ARGS_ASSERT_UTF8_LENGTH;
1056
8850bf83
JH
1057 /* Note: cannot use UTF8_IS_...() too eagerly here since e.g.
1058 * the bitops (especially ~) can create illegal UTF-8.
1059 * In other words: in Perl UTF-8 is not just for Unicode. */
1060
a3b680e6
AL
1061 if (e < s)
1062 goto warn_and_return;
b76347f2 1063 while (s < e) {
4cbf4130 1064 s += UTF8SKIP(s);
8e91ec7f
AV
1065 len++;
1066 }
1067
1068 if (e != s) {
1069 len--;
1070 warn_and_return:
9b387841
NC
1071 if (PL_op)
1072 Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
1073 "%s in %s", unees, OP_DESC(PL_op));
1074 else
61a12c31 1075 Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8), "%s", unees);
b76347f2
JH
1076 }
1077
1078 return len;
1079}
1080
b06226ff 1081/*
87cea99e 1082=for apidoc utf8_distance
b06226ff 1083
1e54db1a 1084Returns the number of UTF-8 characters between the UTF-8 pointers C<a>
b06226ff
JH
1085and C<b>.
1086
1087WARNING: use only if you *know* that the pointers point inside the
1088same UTF-8 buffer.
1089
37607a96
PK
1090=cut
1091*/
a0ed51b3 1092
02eb7b47 1093IV
35a4481c 1094Perl_utf8_distance(pTHX_ const U8 *a, const U8 *b)
a0ed51b3 1095{
7918f24d
NC
1096 PERL_ARGS_ASSERT_UTF8_DISTANCE;
1097
bf1665bc 1098 return (a < b) ? -1 * (IV) utf8_length(a, b) : (IV) utf8_length(b, a);
a0ed51b3
LW
1099}
1100
b06226ff 1101/*
87cea99e 1102=for apidoc utf8_hop
b06226ff 1103
8850bf83
JH
1104Return the UTF-8 pointer C<s> displaced by C<off> characters, either
1105forward or backward.
b06226ff
JH
1106
1107WARNING: do not use the following unless you *know* C<off> is within
8850bf83
JH
1108the UTF-8 data pointed to by C<s> *and* that on entry C<s> is aligned
1109on the first byte of character or just after the last byte of a character.
b06226ff 1110
37607a96
PK
1111=cut
1112*/
a0ed51b3
LW
1113
1114U8 *
ddeaf645 1115Perl_utf8_hop(const U8 *s, I32 off)
a0ed51b3 1116{
7918f24d
NC
1117 PERL_ARGS_ASSERT_UTF8_HOP;
1118
8850bf83
JH
1119 /* Note: cannot use UTF8_IS_...() too eagerly here since e.g
1120 * the bitops (especially ~) can create illegal UTF-8.
1121 * In other words: in Perl UTF-8 is not just for Unicode. */
1122
a0ed51b3
LW
1123 if (off >= 0) {
1124 while (off--)
1125 s += UTF8SKIP(s);
1126 }
1127 else {
1128 while (off++) {
1129 s--;
8850bf83
JH
1130 while (UTF8_IS_CONTINUATION(*s))
1131 s--;
a0ed51b3
LW
1132 }
1133 }
4373e329 1134 return (U8 *)s;
a0ed51b3
LW
1135}
1136
6940069f 1137/*
fed3ba5d
NC
1138=for apidoc bytes_cmp_utf8
1139
a1433954 1140Compares the sequence of characters (stored as octets) in C<b>, C<blen> with the
72d33970
FC
1141sequence of characters (stored as UTF-8)
1142in C<u>, C<ulen>. Returns 0 if they are
fed3ba5d
NC
1143equal, -1 or -2 if the first string is less than the second string, +1 or +2
1144if the first string is greater than the second string.
1145
1146-1 or +1 is returned if the shorter string was identical to the start of the
72d33970
FC
1147longer string. -2 or +2 is returned if
1148there was a difference between characters
fed3ba5d
NC
1149within the strings.
1150
1151=cut
1152*/
1153
1154int
1155Perl_bytes_cmp_utf8(pTHX_ const U8 *b, STRLEN blen, const U8 *u, STRLEN ulen)
1156{
1157 const U8 *const bend = b + blen;
1158 const U8 *const uend = u + ulen;
1159
1160 PERL_ARGS_ASSERT_BYTES_CMP_UTF8;
fed3ba5d
NC
1161
1162 while (b < bend && u < uend) {
1163 U8 c = *u++;
1164 if (!UTF8_IS_INVARIANT(c)) {
1165 if (UTF8_IS_DOWNGRADEABLE_START(c)) {
1166 if (u < uend) {
1167 U8 c1 = *u++;
1168 if (UTF8_IS_CONTINUATION(c1)) {
a62b247b 1169 c = EIGHT_BIT_UTF8_TO_NATIVE(c, c1);
fed3ba5d
NC
1170 } else {
1171 Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
1172 "Malformed UTF-8 character "
1173 "(unexpected non-continuation byte 0x%02x"
1174 ", immediately after start byte 0x%02x)"
1175 /* Dear diag.t, it's in the pod. */
1176 "%s%s", c1, c,
1177 PL_op ? " in " : "",
1178 PL_op ? OP_DESC(PL_op) : "");
1179 return -2;
1180 }
1181 } else {
1182 if (PL_op)
1183 Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
1184 "%s in %s", unees, OP_DESC(PL_op));
1185 else
61a12c31 1186 Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8), "%s", unees);
fed3ba5d
NC
1187 return -2; /* Really want to return undef :-) */
1188 }
1189 } else {
1190 return -2;
1191 }
1192 }
1193 if (*b != c) {
1194 return *b < c ? -2 : +2;
1195 }
1196 ++b;
1197 }
1198
1199 if (b == bend && u == uend)
1200 return 0;
1201
1202 return b < bend ? +1 : -1;
1203}
1204
1205/*
87cea99e 1206=for apidoc utf8_to_bytes
6940069f 1207
2bbc8d55 1208Converts a string C<s> of length C<len> from UTF-8 into native byte encoding.
a1433954
KW
1209Unlike L</bytes_to_utf8>, this over-writes the original string, and
1210updates C<len> to contain the new length.
67e989fb 1211Returns zero on failure, setting C<len> to -1.
6940069f 1212
a1433954 1213If you need a copy of the string, see L</bytes_from_utf8>.
95be277c 1214
6940069f
GS
1215=cut
1216*/
1217
1218U8 *
37607a96 1219Perl_utf8_to_bytes(pTHX_ U8 *s, STRLEN *len)
6940069f 1220{
d4c19fe8
AL
1221 U8 * const save = s;
1222 U8 * const send = s + *len;
6940069f 1223 U8 *d;
246fae53 1224
7918f24d 1225 PERL_ARGS_ASSERT_UTF8_TO_BYTES;
81611534 1226 PERL_UNUSED_CONTEXT;
7918f24d 1227
1e54db1a 1228 /* ensure valid UTF-8 and chars < 256 before updating string */
d4c19fe8 1229 while (s < send) {
d59937ca
KW
1230 if (! UTF8_IS_INVARIANT(*s)) {
1231 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(s, send)) {
1232 *len = ((STRLEN) -1);
1233 return 0;
1234 }
1235 s++;
dcad2880 1236 }
d59937ca 1237 s++;
246fae53 1238 }
dcad2880
JH
1239
1240 d = s = save;
6940069f 1241 while (s < send) {
80e0b38f
KW
1242 U8 c = *s++;
1243 if (! UTF8_IS_INVARIANT(c)) {
1244 /* Then it is two-byte encoded */
a62b247b 1245 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *s);
80e0b38f
KW
1246 s++;
1247 }
1248 *d++ = c;
6940069f
GS
1249 }
1250 *d = '\0';
246fae53 1251 *len = d - save;
6940069f
GS
1252 return save;
1253}
1254
1255/*
87cea99e 1256=for apidoc bytes_from_utf8
f9a63242 1257
2bbc8d55 1258Converts a string C<s> of length C<len> from UTF-8 into native byte encoding.
a1433954 1259Unlike L</utf8_to_bytes> but like L</bytes_to_utf8>, returns a pointer to
ef9edfd0
JH
1260the newly-created string, and updates C<len> to contain the new
1261length. Returns the original string if no conversion occurs, C<len>
72d33970 1262is unchanged. Do nothing if C<is_utf8> points to 0. Sets C<is_utf8> to
2bbc8d55 12630 if C<s> is converted or consisted entirely of characters that are invariant
4a4088c4 1264in UTF-8 (i.e., US-ASCII on non-EBCDIC machines).
f9a63242 1265
37607a96
PK
1266=cut
1267*/
f9a63242
JH
1268
1269U8 *
e1ec3a88 1270Perl_bytes_from_utf8(pTHX_ const U8 *s, STRLEN *len, bool *is_utf8)
f9a63242 1271{
f9a63242 1272 U8 *d;
e1ec3a88
AL
1273 const U8 *start = s;
1274 const U8 *send;
f9a63242
JH
1275 I32 count = 0;
1276
7918f24d 1277 PERL_ARGS_ASSERT_BYTES_FROM_UTF8;
96a5add6 1278 PERL_UNUSED_CONTEXT;
f9a63242 1279 if (!*is_utf8)
73d840c0 1280 return (U8 *)start;
f9a63242 1281
1e54db1a 1282 /* ensure valid UTF-8 and chars < 256 before converting string */
f9a63242 1283 for (send = s + *len; s < send;) {
d59937ca
KW
1284 if (! UTF8_IS_INVARIANT(*s)) {
1285 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(s, send)) {
73d840c0 1286 return (U8 *)start;
d59937ca
KW
1287 }
1288 count++;
1289 s++;
db42d148 1290 }
d59937ca 1291 s++;
f9a63242
JH
1292 }
1293
35da51f7 1294 *is_utf8 = FALSE;
f9a63242 1295
212542aa 1296 Newx(d, (*len) - count + 1, U8);
ef9edfd0 1297 s = start; start = d;
f9a63242
JH
1298 while (s < send) {
1299 U8 c = *s++;
1a91c45d 1300 if (! UTF8_IS_INVARIANT(c)) {
c4d5f83a 1301 /* Then it is two-byte encoded */
a62b247b 1302 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *s);
1a91c45d 1303 s++;
c4d5f83a
NIS
1304 }
1305 *d++ = c;
f9a63242
JH
1306 }
1307 *d = '\0';
1308 *len = d - start;
73d840c0 1309 return (U8 *)start;
f9a63242
JH
1310}
1311
1312/*
87cea99e 1313=for apidoc bytes_to_utf8
6940069f 1314
ff97e5cf
KW
1315Converts a string C<s> of length C<len> bytes from the native encoding into
1316UTF-8.
6662521e 1317Returns a pointer to the newly-created string, and sets C<len> to
ff97e5cf 1318reflect the new length in bytes.
6940069f 1319
75200dff 1320A C<NUL> character will be written after the end of the string.
2bbc8d55
SP
1321
1322If you want to convert to UTF-8 from encodings other than
1323the native (Latin1 or EBCDIC),
a1433954 1324see L</sv_recode_to_utf8>().
c9ada85f 1325
497711e7 1326=cut
6940069f
GS
1327*/
1328
c682ebef
FC
1329/* This logic is duplicated in sv_catpvn_flags, so any bug fixes will
1330 likewise need duplication. */
1331
6940069f 1332U8*
35a4481c 1333Perl_bytes_to_utf8(pTHX_ const U8 *s, STRLEN *len)
6940069f 1334{
35a4481c 1335 const U8 * const send = s + (*len);
6940069f
GS
1336 U8 *d;
1337 U8 *dst;
7918f24d
NC
1338
1339 PERL_ARGS_ASSERT_BYTES_TO_UTF8;
96a5add6 1340 PERL_UNUSED_CONTEXT;
6940069f 1341
212542aa 1342 Newx(d, (*len) * 2 + 1, U8);
6940069f
GS
1343 dst = d;
1344
1345 while (s < send) {
55d09dc8
KW
1346 append_utf8_from_native_byte(*s, &d);
1347 s++;
6940069f
GS
1348 }
1349 *d = '\0';
6662521e 1350 *len = d-dst;
6940069f
GS
1351 return dst;
1352}
1353
a0ed51b3 1354/*
dea0fc0b 1355 * Convert native (big-endian) or reversed (little-endian) UTF-16 to UTF-8.
a0ed51b3
LW
1356 *
1357 * Destination must be pre-extended to 3/2 source. Do not use in-place.
1358 * We optimize for native, for obvious reasons. */
1359
1360U8*
dea0fc0b 1361Perl_utf16_to_utf8(pTHX_ U8* p, U8* d, I32 bytelen, I32 *newlen)
a0ed51b3 1362{
dea0fc0b
JH
1363 U8* pend;
1364 U8* dstart = d;
1365
7918f24d
NC
1366 PERL_ARGS_ASSERT_UTF16_TO_UTF8;
1367
dea0fc0b 1368 if (bytelen & 1)
f5992bc4 1369 Perl_croak(aTHX_ "panic: utf16_to_utf8: odd bytelen %"UVuf, (UV)bytelen);
dea0fc0b
JH
1370
1371 pend = p + bytelen;
1372
a0ed51b3 1373 while (p < pend) {
dea0fc0b
JH
1374 UV uv = (p[0] << 8) + p[1]; /* UTF-16BE */
1375 p += 2;
2d1545e5 1376 if (OFFUNI_IS_INVARIANT(uv)) {
56d37426 1377 *d++ = LATIN1_TO_NATIVE((U8) uv);
a0ed51b3
LW
1378 continue;
1379 }
56d37426
KW
1380 if (uv <= MAX_UTF8_TWO_BYTE) {
1381 *d++ = UTF8_TWO_BYTE_HI(UNI_TO_NATIVE(uv));
1382 *d++ = UTF8_TWO_BYTE_LO(UNI_TO_NATIVE(uv));
a0ed51b3
LW
1383 continue;
1384 }
46956fad
KW
1385#define FIRST_HIGH_SURROGATE UNICODE_SURROGATE_FIRST
1386#define LAST_HIGH_SURROGATE 0xDBFF
1387#define FIRST_LOW_SURROGATE 0xDC00
1388#define LAST_LOW_SURROGATE UNICODE_SURROGATE_LAST
e23c50db
KW
1389
1390 /* This assumes that most uses will be in the first Unicode plane, not
1391 * needing surrogates */
1392 if (UNLIKELY(uv >= UNICODE_SURROGATE_FIRST
1393 && uv <= UNICODE_SURROGATE_LAST))
1394 {
1395 if (UNLIKELY(p >= pend) || UNLIKELY(uv > LAST_HIGH_SURROGATE)) {
1396 Perl_croak(aTHX_ "Malformed UTF-16 surrogate");
1397 }
1398 else {
01ea242b 1399 UV low = (p[0] << 8) + p[1];
e23c50db
KW
1400 if ( UNLIKELY(low < FIRST_LOW_SURROGATE)
1401 || UNLIKELY(low > LAST_LOW_SURROGATE))
1402 {
01ea242b 1403 Perl_croak(aTHX_ "Malformed UTF-16 surrogate");
e23c50db
KW
1404 }
1405 p += 2;
46956fad
KW
1406 uv = ((uv - FIRST_HIGH_SURROGATE) << 10)
1407 + (low - FIRST_LOW_SURROGATE) + 0x10000;
01ea242b 1408 }
a0ed51b3 1409 }
56d37426
KW
1410#ifdef EBCDIC
1411 d = uvoffuni_to_utf8_flags(d, uv, 0);
1412#else
a0ed51b3 1413 if (uv < 0x10000) {
eb160463
GS
1414 *d++ = (U8)(( uv >> 12) | 0xe0);
1415 *d++ = (U8)(((uv >> 6) & 0x3f) | 0x80);
1416 *d++ = (U8)(( uv & 0x3f) | 0x80);
a0ed51b3
LW
1417 continue;
1418 }
1419 else {
eb160463
GS
1420 *d++ = (U8)(( uv >> 18) | 0xf0);
1421 *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
1422 *d++ = (U8)(((uv >> 6) & 0x3f) | 0x80);
1423 *d++ = (U8)(( uv & 0x3f) | 0x80);
a0ed51b3
LW
1424 continue;
1425 }
56d37426 1426#endif
a0ed51b3 1427 }
dea0fc0b 1428 *newlen = d - dstart;
a0ed51b3
LW
1429 return d;
1430}
1431
1432/* Note: this one is slightly destructive of the source. */
1433
1434U8*
dea0fc0b 1435Perl_utf16_to_utf8_reversed(pTHX_ U8* p, U8* d, I32 bytelen, I32 *newlen)
a0ed51b3
LW
1436{
1437 U8* s = (U8*)p;
d4c19fe8 1438 U8* const send = s + bytelen;
7918f24d
NC
1439
1440 PERL_ARGS_ASSERT_UTF16_TO_UTF8_REVERSED;
1441
e0ea5e2d
NC
1442 if (bytelen & 1)
1443 Perl_croak(aTHX_ "panic: utf16_to_utf8_reversed: odd bytelen %"UVuf,
1444 (UV)bytelen);
1445
a0ed51b3 1446 while (s < send) {
d4c19fe8 1447 const U8 tmp = s[0];
a0ed51b3
LW
1448 s[0] = s[1];
1449 s[1] = tmp;
1450 s += 2;
1451 }
dea0fc0b 1452 return utf16_to_utf8(p, d, bytelen, newlen);
a0ed51b3
LW
1453}
1454
922e8cb4
KW
1455bool
1456Perl__is_uni_FOO(pTHX_ const U8 classnum, const UV c)
1457{
1458 U8 tmpbuf[UTF8_MAXBYTES+1];
1459 uvchr_to_utf8(tmpbuf, c);
1460 return _is_utf8_FOO(classnum, tmpbuf);
1461}
1462
f9ae8fb6
JD
1463/* Internal function so we can deprecate the external one, and call
1464 this one from other deprecated functions in this file */
1465
f2645549
KW
1466bool
1467Perl__is_utf8_idstart(pTHX_ const U8 *p)
61b19385 1468{
f2645549 1469 PERL_ARGS_ASSERT__IS_UTF8_IDSTART;
61b19385
KW
1470
1471 if (*p == '_')
1472 return TRUE;
f25ce844 1473 return is_utf8_common(p, &PL_utf8_idstart, "IdStart", NULL);
61b19385
KW
1474}
1475
5092f92a 1476bool
eba68aa0
KW
1477Perl__is_uni_perl_idcont(pTHX_ UV c)
1478{
1479 U8 tmpbuf[UTF8_MAXBYTES+1];
1480 uvchr_to_utf8(tmpbuf, c);
1481 return _is_utf8_perl_idcont(tmpbuf);
1482}
1483
1484bool
f91dcd13
KW
1485Perl__is_uni_perl_idstart(pTHX_ UV c)
1486{
1487 U8 tmpbuf[UTF8_MAXBYTES+1];
1488 uvchr_to_utf8(tmpbuf, c);
1489 return _is_utf8_perl_idstart(tmpbuf);
1490}
1491
3a4c58c9
KW
1492UV
1493Perl__to_upper_title_latin1(pTHX_ const U8 c, U8* p, STRLEN *lenp, const char S_or_s)
1494{
1495 /* We have the latin1-range values compiled into the core, so just use
4a4088c4 1496 * those, converting the result to UTF-8. The only difference between upper
3a4c58c9
KW
1497 * and title case in this range is that LATIN_SMALL_LETTER_SHARP_S is
1498 * either "SS" or "Ss". Which one to use is passed into the routine in
1499 * 'S_or_s' to avoid a test */
1500
1501 UV converted = toUPPER_LATIN1_MOD(c);
1502
1503 PERL_ARGS_ASSERT__TO_UPPER_TITLE_LATIN1;
1504
1505 assert(S_or_s == 'S' || S_or_s == 's');
1506
6f2d5cbc 1507 if (UVCHR_IS_INVARIANT(converted)) { /* No difference between the two for
f4cd282c 1508 characters in this range */
3a4c58c9
KW
1509 *p = (U8) converted;
1510 *lenp = 1;
1511 return converted;
1512 }
1513
1514 /* toUPPER_LATIN1_MOD gives the correct results except for three outliers,
1515 * which it maps to one of them, so as to only have to have one check for
1516 * it in the main case */
1517 if (UNLIKELY(converted == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
1518 switch (c) {
1519 case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
1520 converted = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
1521 break;
1522 case MICRO_SIGN:
1523 converted = GREEK_CAPITAL_LETTER_MU;
1524 break;
79e064b9
KW
1525#if UNICODE_MAJOR_VERSION > 2 \
1526 || (UNICODE_MAJOR_VERSION == 2 && UNICODE_DOT_VERSION >= 1 \
1527 && UNICODE_DOT_DOT_VERSION >= 8)
3a4c58c9
KW
1528 case LATIN_SMALL_LETTER_SHARP_S:
1529 *(p)++ = 'S';
1530 *p = S_or_s;
1531 *lenp = 2;
1532 return 'S';
79e064b9 1533#endif
3a4c58c9
KW
1534 default:
1535 Perl_croak(aTHX_ "panic: to_upper_title_latin1 did not expect '%c' to map to '%c'", c, LATIN_SMALL_LETTER_Y_WITH_DIAERESIS);
e5964223 1536 NOT_REACHED; /* NOTREACHED */
3a4c58c9
KW
1537 }
1538 }
1539
1540 *(p)++ = UTF8_TWO_BYTE_HI(converted);
1541 *p = UTF8_TWO_BYTE_LO(converted);
1542 *lenp = 2;
1543
1544 return converted;
1545}
1546
50bda2c3
KW
1547/* Call the function to convert a UTF-8 encoded character to the specified case.
1548 * Note that there may be more than one character in the result.
1549 * INP is a pointer to the first byte of the input character
1550 * OUTP will be set to the first byte of the string of changed characters. It
1551 * needs to have space for UTF8_MAXBYTES_CASE+1 bytes
1552 * LENP will be set to the length in bytes of the string of changed characters
1553 *
1554 * The functions return the ordinal of the first character in the string of OUTP */
4a8240a3
KW
1555#define CALL_UPPER_CASE(INP, OUTP, LENP) Perl_to_utf8_case(aTHX_ INP, OUTP, LENP, &PL_utf8_toupper, "ToUc", "")
1556#define CALL_TITLE_CASE(INP, OUTP, LENP) Perl_to_utf8_case(aTHX_ INP, OUTP, LENP, &PL_utf8_totitle, "ToTc", "")
1557#define CALL_LOWER_CASE(INP, OUTP, LENP) Perl_to_utf8_case(aTHX_ INP, OUTP, LENP, &PL_utf8_tolower, "ToLc", "")
50bda2c3
KW
1558
1559/* This additionally has the input parameter SPECIALS, which if non-zero will
1560 * cause this to use the SPECIALS hash for folding (meaning get full case
1561 * folding); otherwise, when zero, this implies a simple case fold */
4a8240a3 1562#define CALL_FOLD_CASE(INP, OUTP, LENP, SPECIALS) Perl_to_utf8_case(aTHX_ INP, OUTP, LENP, &PL_utf8_tofold, "ToCf", (SPECIALS) ? "" : NULL)
c3fd2246 1563
84afefe6
JH
1564UV
1565Perl_to_uni_upper(pTHX_ UV c, U8* p, STRLEN *lenp)
a0ed51b3 1566{
a1433954
KW
1567 /* Convert the Unicode character whose ordinal is <c> to its uppercase
1568 * version and store that in UTF-8 in <p> and its length in bytes in <lenp>.
1569 * Note that the <p> needs to be at least UTF8_MAXBYTES_CASE+1 bytes since
c3fd2246
KW
1570 * the changed version may be longer than the original character.
1571 *
1572 * The ordinal of the first character of the changed version is returned
1573 * (but note, as explained above, that there may be more.) */
1574
7918f24d
NC
1575 PERL_ARGS_ASSERT_TO_UNI_UPPER;
1576
3a4c58c9
KW
1577 if (c < 256) {
1578 return _to_upper_title_latin1((U8) c, p, lenp, 'S');
1579 }
1580
0ebc6274 1581 uvchr_to_utf8(p, c);
3a4c58c9 1582 return CALL_UPPER_CASE(p, p, lenp);
a0ed51b3
LW
1583}
1584
84afefe6
JH
1585UV
1586Perl_to_uni_title(pTHX_ UV c, U8* p, STRLEN *lenp)
a0ed51b3 1587{
7918f24d
NC
1588 PERL_ARGS_ASSERT_TO_UNI_TITLE;
1589
3a4c58c9
KW
1590 if (c < 256) {
1591 return _to_upper_title_latin1((U8) c, p, lenp, 's');
1592 }
1593
0ebc6274 1594 uvchr_to_utf8(p, c);
3a4c58c9 1595 return CALL_TITLE_CASE(p, p, lenp);
a0ed51b3
LW
1596}
1597
afc16117 1598STATIC U8
81611534 1599S_to_lower_latin1(const U8 c, U8* p, STRLEN *lenp)
afc16117
KW
1600{
1601 /* We have the latin1-range values compiled into the core, so just use
4a4088c4 1602 * those, converting the result to UTF-8. Since the result is always just
a1433954 1603 * one character, we allow <p> to be NULL */
afc16117
KW
1604
1605 U8 converted = toLOWER_LATIN1(c);
1606
1607 if (p != NULL) {
6f2d5cbc 1608 if (NATIVE_BYTE_IS_INVARIANT(converted)) {
afc16117
KW
1609 *p = converted;
1610 *lenp = 1;
1611 }
1612 else {
430c9760
KW
1613 /* Result is known to always be < 256, so can use the EIGHT_BIT
1614 * macros */
1615 *p = UTF8_EIGHT_BIT_HI(converted);
1616 *(p+1) = UTF8_EIGHT_BIT_LO(converted);
afc16117
KW
1617 *lenp = 2;
1618 }
1619 }
1620 return converted;
1621}
1622
84afefe6
JH
1623UV
1624Perl_to_uni_lower(pTHX_ UV c, U8* p, STRLEN *lenp)
a0ed51b3 1625{
7918f24d
NC
1626 PERL_ARGS_ASSERT_TO_UNI_LOWER;
1627
afc16117
KW
1628 if (c < 256) {
1629 return to_lower_latin1((U8) c, p, lenp);
bca00c02
KW
1630 }
1631
afc16117 1632 uvchr_to_utf8(p, c);
968c5e6a 1633 return CALL_LOWER_CASE(p, p, lenp);
a0ed51b3
LW
1634}
1635
84afefe6 1636UV
51910141 1637Perl__to_fold_latin1(pTHX_ const U8 c, U8* p, STRLEN *lenp, const unsigned int flags)
a1dde8de 1638{
51910141 1639 /* Corresponds to to_lower_latin1(); <flags> bits meanings:
1ca267a5 1640 * FOLD_FLAGS_NOMIX_ASCII iff non-ASCII to ASCII folds are prohibited
51910141 1641 * FOLD_FLAGS_FULL iff full folding is to be used;
1ca267a5
KW
1642 *
1643 * Not to be used for locale folds
51910141 1644 */
f673fad4 1645
a1dde8de
KW
1646 UV converted;
1647
1648 PERL_ARGS_ASSERT__TO_FOLD_LATIN1;
81611534 1649 PERL_UNUSED_CONTEXT;
a1dde8de 1650
1ca267a5
KW
1651 assert (! (flags & FOLD_FLAGS_LOCALE));
1652
a1dde8de
KW
1653 if (c == MICRO_SIGN) {
1654 converted = GREEK_SMALL_LETTER_MU;
1655 }
9b63e895
KW
1656#if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
1657 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
1658 || UNICODE_DOT_DOT_VERSION > 0)
51910141 1659 else if ((flags & FOLD_FLAGS_FULL) && c == LATIN_SMALL_LETTER_SHARP_S) {
1ca267a5
KW
1660
1661 /* If can't cross 127/128 boundary, can't return "ss"; instead return
1662 * two U+017F characters, as fc("\df") should eq fc("\x{17f}\x{17f}")
1663 * under those circumstances. */
1664 if (flags & FOLD_FLAGS_NOMIX_ASCII) {
1665 *lenp = 2 * sizeof(LATIN_SMALL_LETTER_LONG_S_UTF8) - 2;
1666 Copy(LATIN_SMALL_LETTER_LONG_S_UTF8 LATIN_SMALL_LETTER_LONG_S_UTF8,
1667 p, *lenp, U8);
1668 return LATIN_SMALL_LETTER_LONG_S;
1669 }
1670 else {
4f489194
KW
1671 *(p)++ = 's';
1672 *p = 's';
1673 *lenp = 2;
1674 return 's';
1ca267a5 1675 }
a1dde8de 1676 }
9b63e895 1677#endif
a1dde8de
KW
1678 else { /* In this range the fold of all other characters is their lower
1679 case */
1680 converted = toLOWER_LATIN1(c);
1681 }
1682
6f2d5cbc 1683 if (UVCHR_IS_INVARIANT(converted)) {
a1dde8de
KW
1684 *p = (U8) converted;
1685 *lenp = 1;
1686 }
1687 else {
1688 *(p)++ = UTF8_TWO_BYTE_HI(converted);
1689 *p = UTF8_TWO_BYTE_LO(converted);
1690 *lenp = 2;
1691 }
1692
1693 return converted;
1694}
1695
1696UV
31f05a37 1697Perl__to_uni_fold_flags(pTHX_ UV c, U8* p, STRLEN *lenp, U8 flags)
84afefe6 1698{
4b593389 1699
a0270393
KW
1700 /* Not currently externally documented, and subject to change
1701 * <flags> bits meanings:
1702 * FOLD_FLAGS_FULL iff full folding is to be used;
31f05a37
KW
1703 * FOLD_FLAGS_LOCALE is set iff the rules from the current underlying
1704 * locale are to be used.
a0270393
KW
1705 * FOLD_FLAGS_NOMIX_ASCII iff non-ASCII to ASCII folds are prohibited
1706 */
4b593389 1707
36bb2ab6 1708 PERL_ARGS_ASSERT__TO_UNI_FOLD_FLAGS;
7918f24d 1709
780fcc9f
KW
1710 if (flags & FOLD_FLAGS_LOCALE) {
1711 /* Treat a UTF-8 locale as not being in locale at all */
1712 if (IN_UTF8_CTYPE_LOCALE) {
1713 flags &= ~FOLD_FLAGS_LOCALE;
1714 }
1715 else {
1716 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
e7b7ac46 1717 goto needs_full_generality;
780fcc9f 1718 }
31f05a37
KW
1719 }
1720
a1dde8de 1721 if (c < 256) {
e7b7ac46 1722 return _to_fold_latin1((U8) c, p, lenp,
31f05a37 1723 flags & (FOLD_FLAGS_FULL | FOLD_FLAGS_NOMIX_ASCII));
a1dde8de
KW
1724 }
1725
2f306ab9 1726 /* Here, above 255. If no special needs, just use the macro */
a0270393
KW
1727 if ( ! (flags & (FOLD_FLAGS_LOCALE|FOLD_FLAGS_NOMIX_ASCII))) {
1728 uvchr_to_utf8(p, c);
1729 return CALL_FOLD_CASE(p, p, lenp, flags & FOLD_FLAGS_FULL);
1730 }
1731 else { /* Otherwise, _to_utf8_fold_flags has the intelligence to deal with
1732 the special flags. */
1733 U8 utf8_c[UTF8_MAXBYTES + 1];
e7b7ac46
KW
1734
1735 needs_full_generality:
a0270393 1736 uvchr_to_utf8(utf8_c, c);
445bf929 1737 return _to_utf8_fold_flags(utf8_c, p, lenp, flags);
a0270393 1738 }
84afefe6
JH
1739}
1740
26483009 1741PERL_STATIC_INLINE bool
5141f98e 1742S_is_utf8_common(pTHX_ const U8 *const p, SV **swash,
f25ce844 1743 const char *const swashname, SV* const invlist)
bde6a22d 1744{
ea317ccb
KW
1745 /* returns a boolean giving whether or not the UTF8-encoded character that
1746 * starts at <p> is in the swash indicated by <swashname>. <swash>
1747 * contains a pointer to where the swash indicated by <swashname>
1748 * is to be stored; which this routine will do, so that future calls will
f25ce844
KW
1749 * look at <*swash> and only generate a swash if it is not null. <invlist>
1750 * is NULL or an inversion list that defines the swash. If not null, it
1751 * saves time during initialization of the swash.
ea317ccb
KW
1752 *
1753 * Note that it is assumed that the buffer length of <p> is enough to
1754 * contain all the bytes that comprise the character. Thus, <*p> should
1755 * have been checked before this call for mal-formedness enough to assure
1756 * that. */
1757
7918f24d
NC
1758 PERL_ARGS_ASSERT_IS_UTF8_COMMON;
1759
492a624f 1760 /* The API should have included a length for the UTF-8 character in <p>,
28123549 1761 * but it doesn't. We therefore assume that p has been validated at least
492a624f
KW
1762 * as far as there being enough bytes available in it to accommodate the
1763 * character without reading beyond the end, and pass that number on to the
1764 * validating routine */
6302f837 1765 if (! isUTF8_CHAR(p, p + UTF8SKIP(p))) {
28123549
KW
1766 if (ckWARN_d(WARN_UTF8)) {
1767 Perl_warner(aTHX_ packWARN2(WARN_DEPRECATED,WARN_UTF8),
9816f121 1768 "Passing malformed UTF-8 to \"%s\" is deprecated", swashname);
28123549
KW
1769 if (ckWARN(WARN_UTF8)) { /* This will output details as to the
1770 what the malformation is */
1771 utf8_to_uvchr_buf(p, p + UTF8SKIP(p), NULL);
1772 }
1773 }
1774 return FALSE;
1775 }
87367d5f
KW
1776 if (!*swash) {
1777 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
f25ce844
KW
1778 *swash = _core_swash_init("utf8",
1779
1780 /* Only use the name if there is no inversion
1781 * list; otherwise will go out to disk */
1782 (invlist) ? "" : swashname,
1783
1784 &PL_sv_undef, 1, 0, invlist, &flags);
87367d5f 1785 }
28123549 1786
bde6a22d
NC
1787 return swash_fetch(*swash, p, TRUE) != 0;
1788}
1789
1790bool
922e8cb4
KW
1791Perl__is_utf8_FOO(pTHX_ const U8 classnum, const U8 *p)
1792{
922e8cb4
KW
1793 PERL_ARGS_ASSERT__IS_UTF8_FOO;
1794
1795 assert(classnum < _FIRST_NON_SWASH_CC);
1796
f25ce844
KW
1797 return is_utf8_common(p,
1798 &PL_utf8_swash_ptrs[classnum],
1799 swash_property_names[classnum],
1800 PL_XPosix_ptrs[classnum]);
922e8cb4
KW
1801}
1802
1803bool
f2645549 1804Perl__is_utf8_perl_idstart(pTHX_ const U8 *p)
a0ed51b3 1805{
f2645549 1806 SV* invlist = NULL;
7918f24d 1807
f2645549 1808 PERL_ARGS_ASSERT__IS_UTF8_PERL_IDSTART;
7918f24d 1809
f2645549
KW
1810 if (! PL_utf8_perl_idstart) {
1811 invlist = _new_invlist_C_array(_Perl_IDStart_invlist);
1812 }
60071a22 1813 return is_utf8_common(p, &PL_utf8_perl_idstart, "_Perl_IDStart", invlist);
82686b01
JH
1814}
1815
1816bool
f2645549 1817Perl__is_utf8_xidstart(pTHX_ const U8 *p)
c11ff943 1818{
f2645549 1819 PERL_ARGS_ASSERT__IS_UTF8_XIDSTART;
c11ff943
KW
1820
1821 if (*p == '_')
1822 return TRUE;
f25ce844 1823 return is_utf8_common(p, &PL_utf8_xidstart, "XIdStart", NULL);
c11ff943
KW
1824}
1825
1826bool
eba68aa0
KW
1827Perl__is_utf8_perl_idcont(pTHX_ const U8 *p)
1828{
b24b43f7 1829 SV* invlist = NULL;
eba68aa0
KW
1830
1831 PERL_ARGS_ASSERT__IS_UTF8_PERL_IDCONT;
1832
b24b43f7
KW
1833 if (! PL_utf8_perl_idcont) {
1834 invlist = _new_invlist_C_array(_Perl_IDCont_invlist);
1835 }
60071a22 1836 return is_utf8_common(p, &PL_utf8_perl_idcont, "_Perl_IDCont", invlist);
eba68aa0
KW
1837}
1838
eba68aa0 1839bool
f2645549 1840Perl__is_utf8_idcont(pTHX_ const U8 *p)
82686b01 1841{
f2645549 1842 PERL_ARGS_ASSERT__IS_UTF8_IDCONT;
7918f24d 1843
f25ce844 1844 return is_utf8_common(p, &PL_utf8_idcont, "IdContinue", NULL);
a0ed51b3
LW
1845}
1846
1847bool
f2645549 1848Perl__is_utf8_xidcont(pTHX_ const U8 *p)
c11ff943 1849{
f2645549 1850 PERL_ARGS_ASSERT__IS_UTF8_XIDCONT;
c11ff943 1851
f25ce844 1852 return is_utf8_common(p, &PL_utf8_idcont, "XIdContinue", NULL);
c11ff943
KW
1853}
1854
1855bool
7dbf68d2
KW
1856Perl__is_utf8_mark(pTHX_ const U8 *p)
1857{
7dbf68d2
KW
1858 PERL_ARGS_ASSERT__IS_UTF8_MARK;
1859
f25ce844 1860 return is_utf8_common(p, &PL_utf8_mark, "IsM", NULL);
7dbf68d2
KW
1861}
1862
6b5c0936 1863/*
87cea99e 1864=for apidoc to_utf8_case
6b5c0936 1865
6fae5207 1866C<p> contains the pointer to the UTF-8 string encoding
a1433954
KW
1867the character that is being converted. This routine assumes that the character
1868at C<p> is well-formed.
6b5c0936 1869
6fae5207
KW
1870C<ustrp> is a pointer to the character buffer to put the
1871conversion result to. C<lenp> is a pointer to the length
6b5c0936
JH
1872of the result.
1873
6fae5207 1874C<swashp> is a pointer to the swash to use.
6b5c0936 1875
a1433954 1876Both the special and normal mappings are stored in F<lib/unicore/To/Foo.pl>,
796b6530 1877and loaded by C<SWASHNEW>, using F<lib/utf8_heavy.pl>. C<special> (usually,
0134edef 1878but not always, a multicharacter mapping), is tried first.
6b5c0936 1879
4a8240a3
KW
1880C<special> is a string, normally C<NULL> or C<"">. C<NULL> means to not use
1881any special mappings; C<""> means to use the special mappings. Values other
1882than these two are treated as the name of the hash containing the special
1883mappings, like C<"utf8::ToSpecLower">.
6b5c0936 1884
796b6530
KW
1885C<normal> is a string like C<"ToLower"> which means the swash
1886C<%utf8::ToLower>.
0134edef 1887
760c7c2f
KW
1888Code points above the platform's C<IV_MAX> will raise a deprecation warning,
1889unless those are turned off.
1890
0134edef 1891=cut */
6b5c0936 1892
2104c8d9 1893UV
9a957fbc
AL
1894Perl_to_utf8_case(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp,
1895 SV **swashp, const char *normal, const char *special)
a0ed51b3 1896{
0134edef 1897 STRLEN len = 0;
f4cd282c 1898 const UV uv1 = valid_utf8_to_uvchr(p, NULL);
7918f24d
NC
1899
1900 PERL_ARGS_ASSERT_TO_UTF8_CASE;
1901
9ae3ac1a
KW
1902 /* Note that swash_fetch() doesn't output warnings for these because it
1903 * assumes we will */
8457b38f 1904 if (uv1 >= UNICODE_SURROGATE_FIRST) {
9ae3ac1a 1905 if (uv1 <= UNICODE_SURROGATE_LAST) {
8457b38f
KW
1906 if (ckWARN_d(WARN_SURROGATE)) {
1907 const char* desc = (PL_op) ? OP_DESC(PL_op) : normal;
1908 Perl_warner(aTHX_ packWARN(WARN_SURROGATE),
1909 "Operation \"%s\" returns its argument for UTF-16 surrogate U+%04"UVXf"", desc, uv1);
1910 }
9ae3ac1a
KW
1911 }
1912 else if (UNICODE_IS_SUPER(uv1)) {
760c7c2f
KW
1913 if ( UNLIKELY(uv1 > MAX_NON_DEPRECATED_CP)
1914 && ckWARN_d(WARN_DEPRECATED))
1915 {
1916 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),
1917 cp_above_legal_max, uv1, MAX_NON_DEPRECATED_CP);
1918 }
8457b38f
KW
1919 if (ckWARN_d(WARN_NON_UNICODE)) {
1920 const char* desc = (PL_op) ? OP_DESC(PL_op) : normal;
1921 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
1922 "Operation \"%s\" returns its argument for non-Unicode code point 0x%04"UVXf"", desc, uv1);
1923 }
9ae3ac1a
KW
1924 }
1925
1926 /* Note that non-characters are perfectly legal, so no warning should
1927 * be given */
1928 }
1929
0134edef 1930 if (!*swashp) /* load on-demand */
5ab9d2ef 1931 *swashp = _core_swash_init("utf8", normal, &PL_sv_undef, 4, 0, NULL, NULL);
0134edef 1932
a6f87d8c 1933 if (special) {
0134edef 1934 /* It might be "special" (sometimes, but not always,
2a37f04d 1935 * a multicharacter mapping) */
4a8240a3 1936 HV *hv = NULL;
b08cf34e
JH
1937 SV **svp;
1938
4a8240a3
KW
1939 /* If passed in the specials name, use that; otherwise use any
1940 * given in the swash */
1941 if (*special != '\0') {
1942 hv = get_hv(special, 0);
1943 }
1944 else {
1945 svp = hv_fetchs(MUTABLE_HV(SvRV(*swashp)), "SPECIALS", 0);
1946 if (svp) {
1947 hv = MUTABLE_HV(SvRV(*svp));
1948 }
1949 }
1950
176fe009 1951 if (hv
5f560d8a 1952 && (svp = hv_fetch(hv, (const char*)p, UVCHR_SKIP(uv1), FALSE))
176fe009
KW
1953 && (*svp))
1954 {
cfd0369c 1955 const char *s;
47654450 1956
cfd0369c 1957 s = SvPV_const(*svp, len);
47654450 1958 if (len == 1)
f4cd282c 1959 /* EIGHTBIT */
c80e42f3 1960 len = uvchr_to_utf8(ustrp, *(U8*)s) - ustrp;
2a37f04d 1961 else {
d2dcd0fb 1962 Copy(s, ustrp, len, U8);
29e98929 1963 }
983ffd37 1964 }
0134edef
JH
1965 }
1966
1967 if (!len && *swashp) {
4a4088c4 1968 const UV uv2 = swash_fetch(*swashp, p, TRUE /* => is UTF-8 */);
d4c19fe8 1969
0134edef
JH
1970 if (uv2) {
1971 /* It was "normal" (a single character mapping). */
f4cd282c 1972 len = uvchr_to_utf8(ustrp, uv2) - ustrp;
2a37f04d
JH
1973 }
1974 }
1feea2c7 1975
cbe07460
KW
1976 if (len) {
1977 if (lenp) {
1978 *lenp = len;
1979 }
1980 return valid_utf8_to_uvchr(ustrp, 0);
1981 }
1982
1983 /* Here, there was no mapping defined, which means that the code point maps
1984 * to itself. Return the inputs */
bfdf22ec 1985 len = UTF8SKIP(p);
ca9fab46
KW
1986 if (p != ustrp) { /* Don't copy onto itself */
1987 Copy(p, ustrp, len, U8);
1988 }
0134edef 1989
2a37f04d
JH
1990 if (lenp)
1991 *lenp = len;
1992
f4cd282c 1993 return uv1;
cbe07460 1994
a0ed51b3
LW
1995}
1996
051a06d4 1997STATIC UV
357aadde 1998S_check_locale_boundary_crossing(pTHX_ const U8* const p, const UV result, U8* const ustrp, STRLEN *lenp)
051a06d4 1999{
4a4088c4 2000 /* This is called when changing the case of a UTF-8-encoded character above
31f05a37
KW
2001 * the Latin1 range, and the operation is in a non-UTF-8 locale. If the
2002 * result contains a character that crosses the 255/256 boundary, disallow
2003 * the change, and return the original code point. See L<perlfunc/lc> for
2004 * why;
051a06d4 2005 *
a1433954
KW
2006 * p points to the original string whose case was changed; assumed
2007 * by this routine to be well-formed
051a06d4
KW
2008 * result the code point of the first character in the changed-case string
2009 * ustrp points to the changed-case string (<result> represents its first char)
2010 * lenp points to the length of <ustrp> */
2011
2012 UV original; /* To store the first code point of <p> */
2013
2014 PERL_ARGS_ASSERT_CHECK_LOCALE_BOUNDARY_CROSSING;
2015
a4f12ed7 2016 assert(UTF8_IS_ABOVE_LATIN1(*p));
051a06d4
KW
2017
2018 /* We know immediately if the first character in the string crosses the
2019 * boundary, so can skip */
2020 if (result > 255) {
2021
2022 /* Look at every character in the result; if any cross the
2023 * boundary, the whole thing is disallowed */
2024 U8* s = ustrp + UTF8SKIP(ustrp);
2025 U8* e = ustrp + *lenp;
2026 while (s < e) {
a4f12ed7 2027 if (! UTF8_IS_ABOVE_LATIN1(*s)) {
051a06d4
KW
2028 goto bad_crossing;
2029 }
2030 s += UTF8SKIP(s);
2031 }
2032
613abc6d
KW
2033 /* Here, no characters crossed, result is ok as-is, but we warn. */
2034 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(p, p + UTF8SKIP(p));
051a06d4
KW
2035 return result;
2036 }
2037
7b52d656 2038 bad_crossing:
051a06d4
KW
2039
2040 /* Failed, have to return the original */
4b88fb76 2041 original = valid_utf8_to_uvchr(p, lenp);
ab0b796c
KW
2042
2043 /* diag_listed_as: Can't do %s("%s") on non-UTF-8 locale; resolved to "%s". */
2044 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2045 "Can't do %s(\"\\x{%"UVXf"}\") on non-UTF-8 locale; "
2046 "resolved to \"\\x{%"UVXf"}\".",
357aadde 2047 OP_DESC(PL_op),
ab0b796c
KW
2048 original,
2049 original);
051a06d4
KW
2050 Copy(p, ustrp, *lenp, char);
2051 return original;
2052}
2053
d3e79532 2054/*
87cea99e 2055=for apidoc to_utf8_upper
d3e79532 2056
1f607577 2057Instead use L</toUPPER_utf8>.
a1433954 2058
d3e79532
JH
2059=cut */
2060
051a06d4 2061/* Not currently externally documented, and subject to change:
31f05a37
KW
2062 * <flags> is set iff iff the rules from the current underlying locale are to
2063 * be used. */
051a06d4 2064
2104c8d9 2065UV
31f05a37 2066Perl__to_utf8_upper_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, bool flags)
a0ed51b3 2067{
051a06d4
KW
2068 UV result;
2069
2070 PERL_ARGS_ASSERT__TO_UTF8_UPPER_FLAGS;
7918f24d 2071
780fcc9f
KW
2072 if (flags) {
2073 /* Treat a UTF-8 locale as not being in locale at all */
2074 if (IN_UTF8_CTYPE_LOCALE) {
2075 flags = FALSE;
2076 }
2077 else {
2078 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2079 }
31f05a37
KW
2080 }
2081
3a4c58c9 2082 if (UTF8_IS_INVARIANT(*p)) {
051a06d4
KW
2083 if (flags) {
2084 result = toUPPER_LC(*p);
2085 }
2086 else {
81c6c7ce 2087 return _to_upper_title_latin1(*p, ustrp, lenp, 'S');
051a06d4 2088 }
3a4c58c9
KW
2089 }
2090 else if UTF8_IS_DOWNGRADEABLE_START(*p) {
051a06d4 2091 if (flags) {
a62b247b 2092 U8 c = EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1));
68067e4e 2093 result = toUPPER_LC(c);
051a06d4
KW
2094 }
2095 else {
a62b247b 2096 return _to_upper_title_latin1(EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1)),
81c6c7ce 2097 ustrp, lenp, 'S');
051a06d4
KW
2098 }
2099 }
4a4088c4 2100 else { /* UTF-8, ord above 255 */
051a06d4
KW
2101 result = CALL_UPPER_CASE(p, ustrp, lenp);
2102
2103 if (flags) {
357aadde 2104 result = check_locale_boundary_crossing(p, result, ustrp, lenp);
051a06d4
KW
2105 }
2106 return result;
2107 }
2108
4a4088c4 2109 /* Here, used locale rules. Convert back to UTF-8 */
051a06d4
KW
2110 if (UTF8_IS_INVARIANT(result)) {
2111 *ustrp = (U8) result;
2112 *lenp = 1;
2113 }
2114 else {
62cb07ea
KW
2115 *ustrp = UTF8_EIGHT_BIT_HI((U8) result);
2116 *(ustrp + 1) = UTF8_EIGHT_BIT_LO((U8) result);
051a06d4 2117 *lenp = 2;
3a4c58c9 2118 }
baa60164 2119
051a06d4 2120 return result;
983ffd37 2121}
a0ed51b3 2122
d3e79532 2123/*
87cea99e 2124=for apidoc to_utf8_title
d3e79532 2125
1f607577 2126Instead use L</toTITLE_utf8>.
a1433954 2127
d3e79532
JH
2128=cut */
2129
051a06d4 2130/* Not currently externally documented, and subject to change:
31f05a37
KW
2131 * <flags> is set iff the rules from the current underlying locale are to be
2132 * used. Since titlecase is not defined in POSIX, for other than a
2133 * UTF-8 locale, uppercase is used instead for code points < 256.
445bf929 2134 */
051a06d4 2135
983ffd37 2136UV
31f05a37 2137Perl__to_utf8_title_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, bool flags)
983ffd37 2138{
051a06d4
KW
2139 UV result;
2140
2141 PERL_ARGS_ASSERT__TO_UTF8_TITLE_FLAGS;
7918f24d 2142
780fcc9f
KW
2143 if (flags) {
2144 /* Treat a UTF-8 locale as not being in locale at all */
2145 if (IN_UTF8_CTYPE_LOCALE) {
2146 flags = FALSE;
2147 }
2148 else {
2149 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2150 }
31f05a37
KW
2151 }
2152
3a4c58c9 2153 if (UTF8_IS_INVARIANT(*p)) {
051a06d4
KW
2154 if (flags) {
2155 result = toUPPER_LC(*p);
2156 }
2157 else {
81c6c7ce 2158 return _to_upper_title_latin1(*p, ustrp, lenp, 's');
051a06d4 2159 }
3a4c58c9
KW
2160 }
2161 else if UTF8_IS_DOWNGRADEABLE_START(*p) {
051a06d4 2162 if (flags) {
a62b247b 2163 U8 c = EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1));
68067e4e 2164 result = toUPPER_LC(c);
051a06d4
KW
2165 }
2166 else {
a62b247b 2167 return _to_upper_title_latin1(EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1)),
81c6c7ce 2168 ustrp, lenp, 's');
051a06d4
KW
2169 }
2170 }
4a4088c4 2171 else { /* UTF-8, ord above 255 */
051a06d4
KW
2172 result = CALL_TITLE_CASE(p, ustrp, lenp);
2173
2174 if (flags) {
357aadde 2175 result = check_locale_boundary_crossing(p, result, ustrp, lenp);
051a06d4
KW
2176 }
2177 return result;
2178 }
2179
4a4088c4 2180 /* Here, used locale rules. Convert back to UTF-8 */
051a06d4
KW
2181 if (UTF8_IS_INVARIANT(result)) {
2182 *ustrp = (U8) result;
2183 *lenp = 1;
2184 }
2185 else {
62cb07ea
KW
2186 *ustrp = UTF8_EIGHT_BIT_HI((U8) result);
2187 *(ustrp + 1) = UTF8_EIGHT_BIT_LO((U8) result);
051a06d4 2188 *lenp = 2;
3a4c58c9
KW
2189 }
2190
051a06d4 2191 return result;
a0ed51b3
LW
2192}
2193
d3e79532 2194/*
87cea99e 2195=for apidoc to_utf8_lower
d3e79532 2196
1f607577 2197Instead use L</toLOWER_utf8>.
a1433954 2198
d3e79532
JH
2199=cut */
2200
051a06d4 2201/* Not currently externally documented, and subject to change:
31f05a37
KW
2202 * <flags> is set iff iff the rules from the current underlying locale are to
2203 * be used.
2204 */
051a06d4 2205
2104c8d9 2206UV
31f05a37 2207Perl__to_utf8_lower_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, bool flags)
a0ed51b3 2208{
051a06d4
KW
2209 UV result;
2210
051a06d4 2211 PERL_ARGS_ASSERT__TO_UTF8_LOWER_FLAGS;
7918f24d 2212
780fcc9f
KW
2213 if (flags) {
2214 /* Treat a UTF-8 locale as not being in locale at all */
2215 if (IN_UTF8_CTYPE_LOCALE) {
2216 flags = FALSE;
2217 }
2218 else {
2219 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2220 }
31f05a37
KW
2221 }
2222
968c5e6a 2223 if (UTF8_IS_INVARIANT(*p)) {
051a06d4
KW
2224 if (flags) {
2225 result = toLOWER_LC(*p);
2226 }
2227 else {
81c6c7ce 2228 return to_lower_latin1(*p, ustrp, lenp);
051a06d4 2229 }
968c5e6a
KW
2230 }
2231 else if UTF8_IS_DOWNGRADEABLE_START(*p) {
051a06d4 2232 if (flags) {
a62b247b 2233 U8 c = EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1));
68067e4e 2234 result = toLOWER_LC(c);
051a06d4
KW
2235 }
2236 else {
a62b247b 2237 return to_lower_latin1(EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1)),
81c6c7ce 2238 ustrp, lenp);
051a06d4 2239 }
968c5e6a 2240 }
4a4088c4 2241 else { /* UTF-8, ord above 255 */
051a06d4
KW
2242 result = CALL_LOWER_CASE(p, ustrp, lenp);
2243
2244 if (flags) {
357aadde 2245 result = check_locale_boundary_crossing(p, result, ustrp, lenp);
051a06d4 2246 }
968c5e6a 2247
051a06d4
KW
2248 return result;
2249 }
2250
4a4088c4 2251 /* Here, used locale rules. Convert back to UTF-8 */
051a06d4
KW
2252 if (UTF8_IS_INVARIANT(result)) {
2253 *ustrp = (U8) result;
2254 *lenp = 1;
2255 }
2256 else {
62cb07ea
KW
2257 *ustrp = UTF8_EIGHT_BIT_HI((U8) result);
2258 *(ustrp + 1) = UTF8_EIGHT_BIT_LO((U8) result);
051a06d4
KW
2259 *lenp = 2;
2260 }
2261
051a06d4 2262 return result;
b4e400f9
JH
2263}
2264
d3e79532 2265/*
87cea99e 2266=for apidoc to_utf8_fold
d3e79532 2267
1f607577 2268Instead use L</toFOLD_utf8>.
a1433954 2269
d3e79532
JH
2270=cut */
2271
051a06d4
KW
2272/* Not currently externally documented, and subject to change,
2273 * in <flags>
31f05a37
KW
2274 * bit FOLD_FLAGS_LOCALE is set iff the rules from the current underlying
2275 * locale are to be used.
051a06d4
KW
2276 * bit FOLD_FLAGS_FULL is set iff full case folds are to be used;
2277 * otherwise simple folds
a0270393
KW
2278 * bit FOLD_FLAGS_NOMIX_ASCII is set iff folds of non-ASCII to ASCII are
2279 * prohibited
445bf929 2280 */
36bb2ab6 2281
b4e400f9 2282UV
445bf929 2283Perl__to_utf8_fold_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, U8 flags)
b4e400f9 2284{
051a06d4
KW
2285 UV result;
2286
36bb2ab6 2287 PERL_ARGS_ASSERT__TO_UTF8_FOLD_FLAGS;
7918f24d 2288
a0270393
KW
2289 /* These are mutually exclusive */
2290 assert (! ((flags & FOLD_FLAGS_LOCALE) && (flags & FOLD_FLAGS_NOMIX_ASCII)));
2291
50ba90ff
KW
2292 assert(p != ustrp); /* Otherwise overwrites */
2293
780fcc9f
KW
2294 if (flags & FOLD_FLAGS_LOCALE) {
2295 /* Treat a UTF-8 locale as not being in locale at all */
2296 if (IN_UTF8_CTYPE_LOCALE) {
2297 flags &= ~FOLD_FLAGS_LOCALE;
2298 }
2299 else {
2300 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2301 }
31f05a37
KW
2302 }
2303
a1dde8de 2304 if (UTF8_IS_INVARIANT(*p)) {
051a06d4 2305 if (flags & FOLD_FLAGS_LOCALE) {
d22b930b 2306 result = toFOLD_LC(*p);
051a06d4
KW
2307 }
2308 else {
81c6c7ce 2309 return _to_fold_latin1(*p, ustrp, lenp,
1ca267a5 2310 flags & (FOLD_FLAGS_FULL | FOLD_FLAGS_NOMIX_ASCII));
051a06d4 2311 }
a1dde8de
KW
2312 }
2313 else if UTF8_IS_DOWNGRADEABLE_START(*p) {
051a06d4 2314 if (flags & FOLD_FLAGS_LOCALE) {
a62b247b 2315 U8 c = EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1));
68067e4e 2316 result = toFOLD_LC(c);
051a06d4
KW
2317 }
2318 else {
a62b247b 2319 return _to_fold_latin1(EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1)),
51910141 2320 ustrp, lenp,
1ca267a5 2321 flags & (FOLD_FLAGS_FULL | FOLD_FLAGS_NOMIX_ASCII));
051a06d4 2322 }
a1dde8de 2323 }
4a4088c4 2324 else { /* UTF-8, ord above 255 */
a0270393 2325 result = CALL_FOLD_CASE(p, ustrp, lenp, flags & FOLD_FLAGS_FULL);
a1dde8de 2326
1ca267a5
KW
2327 if (flags & FOLD_FLAGS_LOCALE) {
2328
76f2ffcd 2329# define LONG_S_T LATIN_SMALL_LIGATURE_LONG_S_T_UTF8
0766489e
KW
2330 const unsigned int long_s_t_len = sizeof(LONG_S_T) - 1;
2331
2332# ifdef LATIN_CAPITAL_LETTER_SHARP_S_UTF8
2333# define CAP_SHARP_S LATIN_CAPITAL_LETTER_SHARP_S_UTF8
76f2ffcd
KW
2334
2335 const unsigned int cap_sharp_s_len = sizeof(CAP_SHARP_S) - 1;
76f2ffcd 2336
538e84ed
KW
2337 /* Special case these two characters, as what normally gets
2338 * returned under locale doesn't work */
76f2ffcd
KW
2339 if (UTF8SKIP(p) == cap_sharp_s_len
2340 && memEQ((char *) p, CAP_SHARP_S, cap_sharp_s_len))
1ca267a5 2341 {
ab0b796c
KW
2342 /* diag_listed_as: Can't do %s("%s") on non-UTF-8 locale; resolved to "%s". */
2343 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2344 "Can't do fc(\"\\x{1E9E}\") on non-UTF-8 locale; "
2345 "resolved to \"\\x{17F}\\x{17F}\".");
1ca267a5
KW
2346 goto return_long_s;
2347 }
0766489e
KW
2348 else
2349#endif
2350 if (UTF8SKIP(p) == long_s_t_len
76f2ffcd 2351 && memEQ((char *) p, LONG_S_T, long_s_t_len))
9fc2026f 2352 {
ab0b796c
KW
2353 /* diag_listed_as: Can't do %s("%s") on non-UTF-8 locale; resolved to "%s". */
2354 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2355 "Can't do fc(\"\\x{FB05}\") on non-UTF-8 locale; "
2356 "resolved to \"\\x{FB06}\".");
9fc2026f
KW
2357 goto return_ligature_st;
2358 }
74894415
KW
2359
2360#if UNICODE_MAJOR_VERSION == 3 \
2361 && UNICODE_DOT_VERSION == 0 \
2362 && UNICODE_DOT_DOT_VERSION == 1
2363# define DOTTED_I LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE_UTF8
2364
2365 /* And special case this on this Unicode version only, for the same
2366 * reaons the other two are special cased. They would cross the
2367 * 255/256 boundary which is forbidden under /l, and so the code
2368 * wouldn't catch that they are equivalent (which they are only in
2369 * this release) */
2370 else if (UTF8SKIP(p) == sizeof(DOTTED_I) - 1
2371 && memEQ((char *) p, DOTTED_I, sizeof(DOTTED_I) - 1))
2372 {
2373 /* diag_listed_as: Can't do %s("%s") on non-UTF-8 locale; resolved to "%s". */
2374 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2375 "Can't do fc(\"\\x{0130}\") on non-UTF-8 locale; "
2376 "resolved to \"\\x{0131}\".");
2377 goto return_dotless_i;
2378 }
2379#endif
2380
357aadde 2381 return check_locale_boundary_crossing(p, result, ustrp, lenp);
051a06d4 2382 }
a0270393
KW
2383 else if (! (flags & FOLD_FLAGS_NOMIX_ASCII)) {
2384 return result;
2385 }
2386 else {
4a4088c4 2387 /* This is called when changing the case of a UTF-8-encoded
9fc2026f
KW
2388 * character above the ASCII range, and the result should not
2389 * contain an ASCII character. */
a0270393
KW
2390
2391 UV original; /* To store the first code point of <p> */
2392
2393 /* Look at every character in the result; if any cross the
2394 * boundary, the whole thing is disallowed */
2395 U8* s = ustrp;
2396 U8* e = ustrp + *lenp;
2397 while (s < e) {
2398 if (isASCII(*s)) {
2399 /* Crossed, have to return the original */
2400 original = valid_utf8_to_uvchr(p, lenp);
1ca267a5 2401
9fc2026f 2402 /* But in these instances, there is an alternative we can
1ca267a5 2403 * return that is valid */
0766489e
KW
2404 if (original == LATIN_SMALL_LETTER_SHARP_S
2405#ifdef LATIN_CAPITAL_LETTER_SHARP_S /* not defined in early Unicode releases */
2406 || original == LATIN_CAPITAL_LETTER_SHARP_S
2407#endif
2408 ) {
1ca267a5
KW
2409 goto return_long_s;
2410 }
9fc2026f
KW
2411 else if (original == LATIN_SMALL_LIGATURE_LONG_S_T) {
2412 goto return_ligature_st;
2413 }
74894415
KW
2414#if UNICODE_MAJOR_VERSION == 3 \
2415 && UNICODE_DOT_VERSION == 0 \
2416 && UNICODE_DOT_DOT_VERSION == 1
2417
2418 else if (original == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) {
2419 goto return_dotless_i;
2420 }
2421#endif
a0270393
KW
2422 Copy(p, ustrp, *lenp, char);
2423 return original;
2424 }
2425 s += UTF8SKIP(s);
2426 }
051a06d4 2427
a0270393
KW
2428 /* Here, no characters crossed, result is ok as-is */
2429 return result;
2430 }
051a06d4
KW
2431 }
2432
4a4088c4 2433 /* Here, used locale rules. Convert back to UTF-8 */
051a06d4
KW
2434 if (UTF8_IS_INVARIANT(result)) {
2435 *ustrp = (U8) result;
2436 *lenp = 1;
2437 }
2438 else {
62cb07ea
KW
2439 *ustrp = UTF8_EIGHT_BIT_HI((U8) result);
2440 *(ustrp + 1) = UTF8_EIGHT_BIT_LO((U8) result);
051a06d4
KW
2441 *lenp = 2;
2442 }
2443
051a06d4 2444 return result;
1ca267a5
KW
2445
2446 return_long_s:
2447 /* Certain folds to 'ss' are prohibited by the options, but they do allow
2448 * folds to a string of two of these characters. By returning this
2449 * instead, then, e.g.,
2450 * fc("\x{1E9E}") eq fc("\x{17F}\x{17F}")
2451 * works. */
2452
2453 *lenp = 2 * sizeof(LATIN_SMALL_LETTER_LONG_S_UTF8) - 2;
2454 Copy(LATIN_SMALL_LETTER_LONG_S_UTF8 LATIN_SMALL_LETTER_LONG_S_UTF8,
2455 ustrp, *lenp, U8);
2456 return LATIN_SMALL_LETTER_LONG_S;
9fc2026f
KW
2457
2458 return_ligature_st:
2459 /* Two folds to 'st' are prohibited by the options; instead we pick one and
2460 * have the other one fold to it */
2461
2462 *lenp = sizeof(LATIN_SMALL_LIGATURE_ST_UTF8) - 1;
2463 Copy(LATIN_SMALL_LIGATURE_ST_UTF8, ustrp, *lenp, U8);
2464 return LATIN_SMALL_LIGATURE_ST;
74894415
KW
2465
2466#if UNICODE_MAJOR_VERSION == 3 \
2467 && UNICODE_DOT_VERSION == 0 \
2468 && UNICODE_DOT_DOT_VERSION == 1
2469
2470 return_dotless_i:
2471 *lenp = sizeof(LATIN_SMALL_LETTER_DOTLESS_I_UTF8) - 1;
2472 Copy(LATIN_SMALL_LETTER_DOTLESS_I_UTF8, ustrp, *lenp, U8);
2473 return LATIN_SMALL_LETTER_DOTLESS_I;
2474
2475#endif
2476
a0ed51b3
LW
2477}
2478
711a919c 2479/* Note:
f90a9a02 2480 * Returns a "swash" which is a hash described in utf8.c:Perl_swash_fetch().
711a919c
TS
2481 * C<pkg> is a pointer to a package name for SWASHNEW, should be "utf8".
2482 * For other parameters, see utf8::SWASHNEW in lib/utf8_heavy.pl.
2483 */
c4a5db0c 2484
a0ed51b3 2485SV*
7fc63493 2486Perl_swash_init(pTHX_ const char* pkg, const char* name, SV *listsv, I32 minbits, I32 none)
a0ed51b3 2487{
c4a5db0c
KW
2488 PERL_ARGS_ASSERT_SWASH_INIT;
2489
2490 /* Returns a copy of a swash initiated by the called function. This is the
2491 * public interface, and returning a copy prevents others from doing
2492 * mischief on the original */
2493
5d3d13d1 2494 return newSVsv(_core_swash_init(pkg, name, listsv, minbits, none, NULL, NULL));
c4a5db0c
KW
2495}
2496
2497SV*
5d3d13d1 2498Perl__core_swash_init(pTHX_ const char* pkg, const char* name, SV *listsv, I32 minbits, I32 none, SV* invlist, U8* const flags_p)
c4a5db0c 2499{
2c1f00b9
YO
2500
2501 /*NOTE NOTE NOTE - If you want to use "return" in this routine you MUST
2502 * use the following define */
2503
2504#define CORE_SWASH_INIT_RETURN(x) \
2505 PL_curpm= old_PL_curpm; \
2506 return x
2507
c4a5db0c 2508 /* Initialize and return a swash, creating it if necessary. It does this
87367d5f
KW
2509 * by calling utf8_heavy.pl in the general case. The returned value may be
2510 * the swash's inversion list instead if the input parameters allow it.
2511 * Which is returned should be immaterial to callers, as the only
923b6d4e
KW
2512 * operations permitted on a swash, swash_fetch(), _get_swash_invlist(),
2513 * and swash_to_invlist() handle both these transparently.
c4a5db0c
KW
2514 *
2515 * This interface should only be used by functions that won't destroy or
2516 * adversely change the swash, as doing so affects all other uses of the
2517 * swash in the program; the general public should use 'Perl_swash_init'
2518 * instead.
2519 *
2520 * pkg is the name of the package that <name> should be in.
2521 * name is the name of the swash to find. Typically it is a Unicode
2522 * property name, including user-defined ones
2523 * listsv is a string to initialize the swash with. It must be of the form
2524 * documented as the subroutine return value in
2525 * L<perlunicode/User-Defined Character Properties>
2526 * minbits is the number of bits required to represent each data element.
2527 * It is '1' for binary properties.
2528 * none I (khw) do not understand this one, but it is used only in tr///.
9a53f6cf 2529 * invlist is an inversion list to initialize the swash with (or NULL)
83199d38
KW
2530 * flags_p if non-NULL is the address of various input and output flag bits
2531 * to the routine, as follows: ('I' means is input to the routine;
2532 * 'O' means output from the routine. Only flags marked O are
2533 * meaningful on return.)
2534 * _CORE_SWASH_INIT_USER_DEFINED_PROPERTY indicates if the swash
2535 * came from a user-defined property. (I O)
5d3d13d1
KW
2536 * _CORE_SWASH_INIT_RETURN_IF_UNDEF indicates that instead of croaking
2537 * when the swash cannot be located, to simply return NULL. (I)
87367d5f
KW
2538 * _CORE_SWASH_INIT_ACCEPT_INVLIST indicates that the caller will accept a
2539 * return of an inversion list instead of a swash hash if this routine
2540 * thinks that would result in faster execution of swash_fetch() later
2541 * on. (I)
9a53f6cf
KW
2542 *
2543 * Thus there are three possible inputs to find the swash: <name>,
2544 * <listsv>, and <invlist>. At least one must be specified. The result
2545 * will be the union of the specified ones, although <listsv>'s various
aabbdbda
KW
2546 * actions can intersect, etc. what <name> gives. To avoid going out to
2547 * disk at all, <invlist> should specify completely what the swash should
2548 * have, and <listsv> should be &PL_sv_undef and <name> should be "".
9a53f6cf
KW
2549 *
2550 * <invlist> is only valid for binary properties */
c4a5db0c 2551
2c1f00b9
YO
2552 PMOP *old_PL_curpm= PL_curpm; /* save away the old PL_curpm */
2553
c4a5db0c 2554 SV* retval = &PL_sv_undef;
83199d38 2555 HV* swash_hv = NULL;
87367d5f
KW
2556 const int invlist_swash_boundary =
2557 (flags_p && *flags_p & _CORE_SWASH_INIT_ACCEPT_INVLIST)
2558 ? 512 /* Based on some benchmarking, but not extensive, see commit
2559 message */
2560 : -1; /* Never return just an inversion list */
9a53f6cf
KW
2561
2562 assert(listsv != &PL_sv_undef || strNE(name, "") || invlist);
2563 assert(! invlist || minbits == 1);
2564
2c1f00b9
YO
2565 PL_curpm= NULL; /* reset PL_curpm so that we dont get confused between the regex
2566 that triggered the swash init and the swash init perl logic itself.
2567 See perl #122747 */
2568
9a53f6cf
KW
2569 /* If data was passed in to go out to utf8_heavy to find the swash of, do
2570 * so */
2571 if (listsv != &PL_sv_undef || strNE(name, "")) {
69794297
KW
2572 dSP;
2573 const size_t pkg_len = strlen(pkg);
2574 const size_t name_len = strlen(name);
2575 HV * const stash = gv_stashpvn(pkg, pkg_len, 0);
2576 SV* errsv_save;
2577 GV *method;
2578
2579 PERL_ARGS_ASSERT__CORE_SWASH_INIT;
2580
2581 PUSHSTACKi(PERLSI_MAGIC);
ce3b816e 2582 ENTER;
69794297 2583 SAVEHINTS();
2782061f 2584 save_re_context();
650f067c
JL
2585 /* We might get here via a subroutine signature which uses a utf8
2586 * parameter name, at which point PL_subname will have been set
2587 * but not yet used. */
2588 save_item(PL_subname);
69794297
KW
2589 if (PL_parser && PL_parser->error_count)
2590 SAVEI8(PL_parser->error_count), PL_parser->error_count = 0;
2591 method = gv_fetchmeth(stash, "SWASHNEW", 8, -1);
4a4088c4 2592 if (!method) { /* demand load UTF-8 */
69794297 2593 ENTER;
db2c6cb3
FC
2594 if ((errsv_save = GvSV(PL_errgv))) SAVEFREESV(errsv_save);
2595 GvSV(PL_errgv) = NULL;
1a419e6b 2596#ifndef NO_TAINT_SUPPORT
69794297
KW
2597 /* It is assumed that callers of this routine are not passing in
2598 * any user derived data. */
2782061f
DM
2599 /* Need to do this after save_re_context() as it will set
2600 * PL_tainted to 1 while saving $1 etc (see the code after getrx:
2601 * in Perl_magic_get). Even line to create errsv_save can turn on
2602 * PL_tainted. */
284167a5
S
2603 SAVEBOOL(TAINT_get);
2604 TAINT_NOT;
2605#endif
69794297
KW
2606 Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT, newSVpvn(pkg,pkg_len),
2607 NULL);
eed484f9 2608 {
db2c6cb3
FC
2609 /* Not ERRSV, as there is no need to vivify a scalar we are
2610 about to discard. */
2611 SV * const errsv = GvSV(PL_errgv);
2612 if (!SvTRUE(errsv)) {
2613 GvSV(PL_errgv) = SvREFCNT_inc_simple(errsv_save);
2614 SvREFCNT_dec(errsv);
2615 }
eed484f9 2616 }
69794297
KW
2617 LEAVE;
2618 }
2619 SPAGAIN;
2620 PUSHMARK(SP);
2621 EXTEND(SP,5);
2622 mPUSHp(pkg, pkg_len);
2623 mPUSHp(name, name_len);
2624 PUSHs(listsv);
2625 mPUSHi(minbits);
2626 mPUSHi(none);
2627 PUTBACK;
db2c6cb3
FC
2628 if ((errsv_save = GvSV(PL_errgv))) SAVEFREESV(errsv_save);
2629 GvSV(PL_errgv) = NULL;
69794297
KW
2630 /* If we already have a pointer to the method, no need to use
2631 * call_method() to repeat the lookup. */
c41800a8
KW
2632 if (method
2633 ? call_sv(MUTABLE_SV(method), G_SCALAR)
69794297
KW
2634 : call_sv(newSVpvs_flags("SWASHNEW", SVs_TEMP), G_SCALAR | G_METHOD))
2635 {
2636 retval = *PL_stack_sp--;
2637 SvREFCNT_inc(retval);
2638 }
eed484f9 2639 {
db2c6cb3
FC
2640 /* Not ERRSV. See above. */
2641 SV * const errsv = GvSV(PL_errgv);
2642 if (!SvTRUE(errsv)) {
2643 GvSV(PL_errgv) = SvREFCNT_inc_simple(errsv_save);
2644 SvREFCNT_dec(errsv);
2645 }
eed484f9 2646 }
ce3b816e 2647 LEAVE;
69794297
KW
2648 POPSTACK;
2649 if (IN_PERL_COMPILETIME) {
2650 CopHINTS_set(PL_curcop, PL_hints);
2651 }
2652 if (!SvROK(retval) || SvTYPE(SvRV(retval)) != SVt_PVHV) {
2653 if (SvPOK(retval))
2654
2655 /* If caller wants to handle missing properties, let them */
5d3d13d1 2656 if (flags_p && *flags_p & _CORE_SWASH_INIT_RETURN_IF_UNDEF) {
2c1f00b9 2657 CORE_SWASH_INIT_RETURN(NULL);
69794297
KW
2658 }
2659 Perl_croak(aTHX_
2660 "Can't find Unicode property definition \"%"SVf"\"",
2661 SVfARG(retval));
a25b5927 2662 NOT_REACHED; /* NOTREACHED */
69794297 2663 }
9a53f6cf 2664 } /* End of calling the module to find the swash */
36eb48b4 2665
83199d38
KW
2666 /* If this operation fetched a swash, and we will need it later, get it */
2667 if (retval != &PL_sv_undef
2668 && (minbits == 1 || (flags_p
2669 && ! (*flags_p
2670 & _CORE_SWASH_INIT_USER_DEFINED_PROPERTY))))
2671 {
2672 swash_hv = MUTABLE_HV(SvRV(retval));
2673
2674 /* If we don't already know that there is a user-defined component to
2675 * this swash, and the user has indicated they wish to know if there is
2676 * one (by passing <flags_p>), find out */
2677 if (flags_p && ! (*flags_p & _CORE_SWASH_INIT_USER_DEFINED_PROPERTY)) {
2678 SV** user_defined = hv_fetchs(swash_hv, "USER_DEFINED", FALSE);
2679 if (user_defined && SvUV(*user_defined)) {
2680 *flags_p |= _CORE_SWASH_INIT_USER_DEFINED_PROPERTY;
2681 }
2682 }
2683 }
2684
36eb48b4
KW
2685 /* Make sure there is an inversion list for binary properties */
2686 if (minbits == 1) {
2687 SV** swash_invlistsvp = NULL;
2688 SV* swash_invlist = NULL;
9a53f6cf 2689 bool invlist_in_swash_is_valid = FALSE;
02c85471
FC
2690 bool swash_invlist_unclaimed = FALSE; /* whether swash_invlist has
2691 an unclaimed reference count */
36eb48b4 2692
9a53f6cf 2693 /* If this operation fetched a swash, get its already existing
83199d38 2694 * inversion list, or create one for it */
36eb48b4 2695
83199d38 2696 if (swash_hv) {
5c9f4bd2 2697 swash_invlistsvp = hv_fetchs(swash_hv, "V", FALSE);
9a53f6cf
KW
2698 if (swash_invlistsvp) {
2699 swash_invlist = *swash_invlistsvp;
2700 invlist_in_swash_is_valid = TRUE;
2701 }
2702 else {
36eb48b4 2703 swash_invlist = _swash_to_invlist(retval);
02c85471 2704 swash_invlist_unclaimed = TRUE;
9a53f6cf
KW
2705 }
2706 }
2707
2708 /* If an inversion list was passed in, have to include it */
2709 if (invlist) {
2710
2711 /* Any fetched swash will by now have an inversion list in it;
2712 * otherwise <swash_invlist> will be NULL, indicating that we
2713 * didn't fetch a swash */
2714 if (swash_invlist) {
2715
2716 /* Add the passed-in inversion list, which invalidates the one
2717 * already stored in the swash */
2718 invlist_in_swash_is_valid = FALSE;
2719 _invlist_union(invlist, swash_invlist, &swash_invlist);
2720 }
2721 else {
2722
87367d5f
KW
2723 /* Here, there is no swash already. Set up a minimal one, if
2724 * we are going to return a swash */
2725 if ((int) _invlist_len(invlist) > invlist_swash_boundary) {
971d486f 2726 swash_hv = newHV();
4aca0fe6 2727 retval = newRV_noinc(MUTABLE_SV(swash_hv));
87367d5f 2728 }
9a53f6cf
KW
2729 swash_invlist = invlist;
2730 }
9a53f6cf
KW
2731 }
2732
2733 /* Here, we have computed the union of all the passed-in data. It may
2734 * be that there was an inversion list in the swash which didn't get
538e84ed 2735 * touched; otherwise save the computed one */
87367d5f
KW
2736 if (! invlist_in_swash_is_valid
2737 && (int) _invlist_len(swash_invlist) > invlist_swash_boundary)
2738 {
5c9f4bd2 2739 if (! hv_stores(MUTABLE_HV(SvRV(retval)), "V", swash_invlist))
69794297
KW
2740 {
2741 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
2742 }
cc34d8c5
FC
2743 /* We just stole a reference count. */
2744 if (swash_invlist_unclaimed) swash_invlist_unclaimed = FALSE;
2745 else SvREFCNT_inc_simple_void_NN(swash_invlist);
9a53f6cf 2746 }
87367d5f 2747
dbfdbd26
KW
2748 SvREADONLY_on(swash_invlist);
2749
c41800a8 2750 /* Use the inversion list stand-alone if small enough */
87367d5f
KW
2751 if ((int) _invlist_len(swash_invlist) <= invlist_swash_boundary) {
2752 SvREFCNT_dec(retval);
02c85471
FC
2753 if (!swash_invlist_unclaimed)
2754 SvREFCNT_inc_simple_void_NN(swash_invlist);
2755 retval = newRV_noinc(swash_invlist);
87367d5f 2756 }
36eb48b4
KW
2757 }
2758
2c1f00b9
YO
2759 CORE_SWASH_INIT_RETURN(retval);
2760#undef CORE_SWASH_INIT_RETURN
a0ed51b3
LW
2761}
2762
035d37be
JH
2763
2764/* This API is wrong for special case conversions since we may need to
2765 * return several Unicode characters for a single Unicode character
2766 * (see lib/unicore/SpecCase.txt) The SWASHGET in lib/utf8_heavy.pl is
2767 * the lower-level routine, and it is similarly broken for returning
38684baa
KW
2768 * multiple values. --jhi
2769 * For those, you should use to_utf8_case() instead */
b0e3252e 2770/* Now SWASHGET is recasted into S_swatch_get in this file. */
680c470c
TS
2771
2772/* Note:
2773 * Returns the value of property/mapping C<swash> for the first character
2774 * of the string C<ptr>. If C<do_utf8> is true, the string C<ptr> is
4a4088c4 2775 * assumed to be in well-formed UTF-8. If C<do_utf8> is false, the string C<ptr>
3d0f8846 2776 * is assumed to be in native 8-bit encoding. Caches the swatch in C<swash>.
af2af982
KW
2777 *
2778 * A "swash" is a hash which contains initially the keys/values set up by
2779 * SWASHNEW. The purpose is to be able to completely represent a Unicode
2780 * property for all possible code points. Things are stored in a compact form
2781 * (see utf8_heavy.pl) so that calculation is required to find the actual
2782 * property value for a given code point. As code points are looked up, new
2783 * key/value pairs are added to the hash, so that the calculation doesn't have
2784 * to ever be re-done. Further, each calculation is done, not just for the
2785 * desired one, but for a whole block of code points adjacent to that one.
2786 * For binary properties on ASCII machines, the block is usually for 64 code
2787 * points, starting with a code point evenly divisible by 64. Thus if the
2788 * property value for code point 257 is requested, the code goes out and
2789 * calculates the property values for all 64 code points between 256 and 319,
2790 * and stores these as a single 64-bit long bit vector, called a "swatch",
2791 * under the key for code point 256. The key is the UTF-8 encoding for code
2792 * point 256, minus the final byte. Thus, if the length of the UTF-8 encoding
2793 * for a code point is 13 bytes, the key will be 12 bytes long. If the value
2794 * for code point 258 is then requested, this code realizes that it would be
2795 * stored under the key for 256, and would find that value and extract the
2796 * relevant bit, offset from 256.
2797 *
2798 * Non-binary properties are stored in as many bits as necessary to represent
2799 * their values (32 currently, though the code is more general than that), not
2800 * as single bits, but the principal is the same: the value for each key is a
2801 * vector that encompasses the property values for all code points whose UTF-8
2802 * representations are represented by the key. That is, for all code points
2803 * whose UTF-8 representations are length N bytes, and the key is the first N-1
2804 * bytes of that.
680c470c 2805 */
a0ed51b3 2806UV
680c470c 2807Perl_swash_fetch(pTHX_ SV *swash, const U8 *ptr, bool do_utf8)
a0ed51b3 2808{
ef8f7699 2809 HV *const hv = MUTABLE_HV(SvRV(swash));
3568d838
JH
2810 U32 klen;
2811 U32 off;
9b56a019 2812 STRLEN slen = 0;
7d85a32c 2813 STRLEN needents;
cfd0369c 2814 const U8 *tmps = NULL;
979f2922 2815 SV *swatch;
08fb1ac5 2816 const U8 c = *ptr;
3568d838 2817
7918f24d
NC
2818 PERL_ARGS_ASSERT_SWASH_FETCH;
2819
87367d5f
KW
2820 /* If it really isn't a hash, it isn't really swash; must be an inversion
2821 * list */
2822 if (SvTYPE(hv) != SVt_PVHV) {
2823 return _invlist_contains_cp((SV*)hv,
2824 (do_utf8)
2825 ? valid_utf8_to_uvchr(ptr, NULL)
2826 : c);
2827 }
2828
08fb1ac5
KW
2829 /* We store the values in a "swatch" which is a vec() value in a swash
2830 * hash. Code points 0-255 are a single vec() stored with key length
2831 * (klen) 0. All other code points have a UTF-8 representation
2832 * 0xAA..0xYY,0xZZ. A vec() is constructed containing all of them which
2833 * share 0xAA..0xYY, which is the key in the hash to that vec. So the key
2834 * length for them is the length of the encoded char - 1. ptr[klen] is the
2835 * final byte in the sequence representing the character */
2836 if (!do_utf8 || UTF8_IS_INVARIANT(c)) {
2837 klen = 0;
2838 needents = 256;
2839 off = c;
3568d838 2840 }
08fb1ac5
KW
2841 else if (UTF8_IS_DOWNGRADEABLE_START(c)) {
2842 klen = 0;
2843 needents = 256;
a62b247b 2844 off = EIGHT_BIT_UTF8_TO_NATIVE(c, *(ptr + 1));
979f2922
TS
2845 }
2846 else {
08fb1ac5
KW
2847 klen = UTF8SKIP(ptr) - 1;
2848
2849 /* Each vec() stores 2**UTF_ACCUMULATION_SHIFT values. The offset into
2850 * the vec is the final byte in the sequence. (In EBCDIC this is
2851 * converted to I8 to get consecutive values.) To help you visualize
2852 * all this:
2853 * Straight 1047 After final byte
2854 * UTF-8 UTF-EBCDIC I8 transform
2855 * U+0400: \xD0\x80 \xB8\x41\x41 \xB8\x41\xA0
2856 * U+0401: \xD0\x81 \xB8\x41\x42 \xB8\x41\xA1
2857 * ...
2858 * U+0409: \xD0\x89 \xB8\x41\x4A \xB8\x41\xA9
2859 * U+040A: \xD0\x8A \xB8\x41\x51 \xB8\x41\xAA
2860 * ...
2861 * U+0412: \xD0\x92 \xB8\x41\x59 \xB8\x41\xB2
2862 * U+0413: \xD0\x93 \xB8\x41\x62 \xB8\x41\xB3
2863 * ...
2864 * U+041B: \xD0\x9B \xB8\x41\x6A \xB8\x41\xBB
2865 * U+041C: \xD0\x9C \xB8\x41\x70 \xB8\x41\xBC
2866 * ...
2867 * U+041F: \xD0\x9F \xB8\x41\x73 \xB8\x41\xBF
2868 * U+0420: \xD0\xA0 \xB8\x42\x41 \xB8\x42\x41
2869 *
2870 * (There are no discontinuities in the elided (...) entries.)
2871 * The UTF-8 key for these 33 code points is '\xD0' (which also is the
2872 * key for the next 31, up through U+043F, whose UTF-8 final byte is
2873 * \xBF). Thus in UTF-8, each key is for a vec() for 64 code points.
2874 * The final UTF-8 byte, which ranges between \x80 and \xBF, is an
2875 * index into the vec() swatch (after subtracting 0x80, which we
2876 * actually do with an '&').
2877 * In UTF-EBCDIC, each key is for a 32 code point vec(). The first 32
2878 * code points above have key '\xB8\x41'. The final UTF-EBCDIC byte has
2879 * dicontinuities which go away by transforming it into I8, and we
2880 * effectively subtract 0xA0 to get the index. */
979f2922 2881 needents = (1 << UTF_ACCUMULATION_SHIFT);
bc3632a8 2882 off = NATIVE_UTF8_TO_I8(ptr[klen]) & UTF_CONTINUATION_MASK;
979f2922 2883 }
7d85a32c 2884
a0ed51b3 2885 /*
4a4088c4 2886 * This single-entry cache saves about 1/3 of the UTF-8 overhead in test
a0ed51b3
LW
2887 * suite. (That is, only 7-8% overall over just a hash cache. Still,
2888 * it's nothing to sniff at.) Pity we usually come through at least
2889 * two function calls to get here...
2890 *
2891 * NB: this code assumes that swatches are never modified, once generated!
2892 */
2893
3568d838 2894 if (hv == PL_last_swash_hv &&
a0ed51b3 2895 klen == PL_last_swash_klen &&
27da23d5 2896 (!klen || memEQ((char *)ptr, (char *)PL_last_swash_key, klen)) )
a0ed51b3
LW
2897 {
2898 tmps = PL_last_swash_tmps;
2899 slen = PL_last_swash_slen;
2900 }
2901 else {
2902 /* Try our second-level swatch cache, kept in a hash. */
e1ec3a88 2903 SV** svp = hv_fetch(hv, (const char*)ptr, klen, FALSE);
a0ed51b3 2904
b0e3252e 2905 /* If not cached, generate it via swatch_get */
979f2922 2906 if (!svp || !SvPOK(*svp)
08fb1ac5
KW
2907 || !(tmps = (const U8*)SvPV_const(*svp, slen)))
2908 {
2909 if (klen) {
2910 const UV code_point = valid_utf8_to_uvchr(ptr, NULL);
2911 swatch = swatch_get(swash,
2912 code_point & ~((UV)needents - 1),
2913 needents);
2914 }
2915 else { /* For the first 256 code points, the swatch has a key of
2916 length 0 */
2917 swatch = swatch_get(swash, 0, needents);
2918 }
979f2922 2919
923e4eb5 2920 if (IN_PERL_COMPILETIME)
623e6609 2921 CopHINTS_set(PL_curcop, PL_hints);
a0ed51b3 2922
979f2922 2923 svp = hv_store(hv, (const char *)ptr, klen, swatch, 0);
a0ed51b3 2924
979f2922
TS
2925 if (!svp || !(tmps = (U8*)SvPV(*svp, slen))
2926 || (slen << 3) < needents)
5637ef5b
NC
2927 Perl_croak(aTHX_ "panic: swash_fetch got improper swatch, "
2928 "svp=%p, tmps=%p, slen=%"UVuf", needents=%"UVuf,
2929 svp, tmps, (UV)slen, (UV)needents);
a0ed51b3
LW
2930 }
2931
2932 PL_last_swash_hv = hv;
16d8f38a 2933 assert(klen <= sizeof(PL_last_swash_key));
eac04b2e 2934 PL_last_swash_klen = (U8)klen;
cfd0369c
NC
2935 /* FIXME change interpvar.h? */
2936 PL_last_swash_tmps = (U8 *) tmps;
a0ed51b3
LW
2937 PL_last_swash_slen = slen;
2938 if (klen)
2939 Copy(ptr, PL_last_swash_key, klen, U8);
2940 }
2941
9faf8d75 2942 switch ((int)((slen << 3) / needents)) {
a0ed51b3 2943 case 1:
e7aca353 2944 return ((UV) tmps[off >> 3] & (1 << (off & 7))) != 0;
a0ed51b3 2945 case 8:
e7aca353 2946 return ((UV) tmps[off]);
a0ed51b3
LW
2947 case 16:
2948 off <<= 1;
e7aca353
JH
2949 return
2950 ((UV) tmps[off ] << 8) +
2951 ((UV) tmps[off + 1]);
a0ed51b3
LW
2952 case 32:
2953 off <<= 2;
e7aca353
JH
2954 return
2955 ((UV) tmps[off ] << 24) +
2956 ((UV) tmps[off + 1] << 16) +
2957 ((UV) tmps[off + 2] << 8) +
2958 ((UV) tmps[off + 3]);
a0ed51b3 2959 }
5637ef5b
NC
2960 Perl_croak(aTHX_ "panic: swash_fetch got swatch of unexpected bit width, "
2961 "slen=%"UVuf", needents=%"UVuf, (UV)slen, (UV)needents);
670f1322 2962 NORETURN_FUNCTION_END;
a0ed51b3 2963}
2b9d42f0 2964
319009ee
KW
2965/* Read a single line of the main body of the swash input text. These are of
2966 * the form:
2967 * 0053 0056 0073
2968 * where each number is hex. The first two numbers form the minimum and
2969 * maximum of a range, and the third is the value associated with the range.
2970 * Not all swashes should have a third number
2971 *
2972 * On input: l points to the beginning of the line to be examined; it points
2973 * to somewhere in the string of the whole input text, and is
2974 * terminated by a \n or the null string terminator.
2975 * lend points to the null terminator of that string
2976 * wants_value is non-zero if the swash expects a third number
2977 * typestr is the name of the swash's mapping, like 'ToLower'
2978 * On output: *min, *max, and *val are set to the values read from the line.
2979 * returns a pointer just beyond the line examined. If there was no
2980 * valid min number on the line, returns lend+1
2981 */
2982
2983STATIC U8*
2984S_swash_scan_list_line(pTHX_ U8* l, U8* const lend, UV* min, UV* max, UV* val,
2985 const bool wants_value, const U8* const typestr)
2986{
2987 const int typeto = typestr[0] == 'T' && typestr[1] == 'o';
2988 STRLEN numlen; /* Length of the number */
02470786
KW
2989 I32 flags = PERL_SCAN_SILENT_ILLDIGIT
2990 | PERL_SCAN_DISALLOW_PREFIX
2991 | PERL_SCAN_SILENT_NON_PORTABLE;
319009ee
KW
2992
2993 /* nl points to the next \n in the scan */
2994 U8* const nl = (U8*)memchr(l, '\n', lend - l);
2995
95543e92
KW
2996 PERL_ARGS_ASSERT_SWASH_SCAN_LIST_LINE;
2997
319009ee
KW
2998 /* Get the first number on the line: the range minimum */
2999 numlen = lend - l;
3000 *min = grok_hex((char *)l, &numlen, &flags, NULL);
c88850db 3001 *max = *min; /* So can never return without setting max */
319009ee
KW
3002 if (numlen) /* If found a hex number, position past it */
3003 l += numlen;
3004 else if (nl) { /* Else, go handle next line, if any */
3005 return nl + 1; /* 1 is length of "\n" */
3006 }
3007 else { /* Else, no next line */
3008 return lend + 1; /* to LIST's end at which \n is not found */
3009 }
3010
3011 /* The max range value follows, separated by a BLANK */
3012 if (isBLANK(*l)) {
3013 ++l;
02470786
KW
3014 flags = PERL_SCAN_SILENT_ILLDIGIT
3015 | PERL_SCAN_DISALLOW_PREFIX
3016 | PERL_SCAN_SILENT_NON_PORTABLE;
319009ee
KW
3017 numlen = lend - l;
3018 *max = grok_hex((char *)l, &numlen, &flags, NULL);
3019 if (numlen)
3020 l += numlen;
3021 else /* If no value here, it is a single element range */
3022 *max = *min;
3023
3024 /* Non-binary tables have a third entry: what the first element of the
24303724 3025 * range maps to. The map for those currently read here is in hex */
319009ee
KW
3026 if (wants_value) {
3027 if (isBLANK(*l)) {
3028 ++l;
f2a7d0fc
KW
3029 flags = PERL_SCAN_SILENT_ILLDIGIT
3030 | PERL_SCAN_DISALLOW_PREFIX
3031 | PERL_SCAN_SILENT_NON_PORTABLE;
3032 numlen = lend - l;
3033 *val = grok_hex((char *)l, &numlen, &flags, NULL);
3034 if (numlen)
3035 l += numlen;
3036 else
3037 *val = 0;
319009ee
KW
3038 }
3039 else {
3040 *val = 0;
3041 if (typeto) {
dcbac5bb 3042 /* diag_listed_as: To%s: illegal mapping '%s' */
319009ee
KW
3043 Perl_croak(aTHX_ "%s: illegal mapping '%s'",
3044 typestr, l);
3045 }
3046 }
3047 }
3048 else
3049 *val = 0; /* bits == 1, then any val should be ignored */
3050 }
3051 else { /* Nothing following range min, should be single element with no
3052 mapping expected */
319009ee
KW
3053 if (wants_value) {
3054 *val = 0;
3055 if (typeto) {
dcbac5bb 3056 /* diag_listed_as: To%s: illegal mapping '%s' */
319009ee
KW
3057 Perl_croak(aTHX_ "%s: illegal mapping '%s'", typestr, l);
3058 }
3059 }
3060 else
3061 *val = 0; /* bits == 1, then val should be ignored */
3062 }
3063
3064 /* Position to next line if any, or EOF */
3065 if (nl)
3066 l = nl + 1;
3067 else
3068 l = lend;
3069
3070 return l;
3071}
3072
979f2922
TS
3073/* Note:
3074 * Returns a swatch (a bit vector string) for a code point sequence
3075 * that starts from the value C<start> and comprises the number C<span>.
3076 * A C<swash> must be an object created by SWASHNEW (see lib/utf8_heavy.pl).
3077 * Should be used via swash_fetch, which will cache the swatch in C<swash>.
3078 */
3079STATIC SV*
b0e3252e 3080S_swatch_get(pTHX_ SV* swash, UV start, UV span)
979f2922
TS
3081{
3082 SV *swatch;
77f9f126 3083 U8 *l, *lend, *x, *xend, *s, *send;
979f2922 3084 STRLEN lcur, xcur, scur;
ef8f7699 3085 HV *const hv = MUTABLE_HV(SvRV(swash));
5c9f4bd2 3086 SV** const invlistsvp = hv_fetchs(hv, "V", FALSE);
36eb48b4 3087
88d45d28
KW
3088 SV** listsvp = NULL; /* The string containing the main body of the table */
3089 SV** extssvp = NULL;
3090 SV** invert_it_svp = NULL;
3091 U8* typestr = NULL;
786861f5
KW
3092 STRLEN bits;
3093 STRLEN octets; /* if bits == 1, then octets == 0 */
3094 UV none;
3095 UV end = start + span;
972dd592 3096
36eb48b4 3097 if (invlistsvp == NULL) {
786861f5
KW
3098 SV** const bitssvp = hv_fetchs(hv, "BITS", FALSE);
3099 SV** const nonesvp = hv_fetchs(hv, "NONE", FALSE);
3100 SV** const typesvp = hv_fetchs(hv, "TYPE", FALSE);
3101 extssvp = hv_fetchs(hv, "EXTRAS", FALSE);
3102 listsvp = hv_fetchs(hv, "LIST", FALSE);
3103 invert_it_svp = hv_fetchs(hv, "INVERT_IT", FALSE);
3104
3105 bits = SvUV(*bitssvp);
3106 none = SvUV(*nonesvp);
3107 typestr = (U8*)SvPV_nolen(*typesvp);
3108 }
36eb48b4
KW
3109 else {
3110 bits = 1;
3111 none = 0;
3112 }
786861f5 3113 octets = bits >> 3; /* if bits == 1, then octets == 0 */
979f2922 3114
b0e3252e 3115 PERL_ARGS_ASSERT_SWATCH_GET;
7918f24d 3116
979f2922 3117 if (bits != 1 && bits != 8 && bits != 16 && bits != 32) {
b0e3252e 3118 Perl_croak(aTHX_ "panic: swatch_get doesn't expect bits %"UVuf,
660a4616 3119 (UV)bits);
979f2922
TS
3120 }
3121
84ea5ef6
KW
3122 /* If overflowed, use the max possible */
3123 if (end < start) {
3124 end = UV_MAX;
3125 span = end - start;
3126 }
3127
979f2922 3128 /* create and initialize $swatch */
979f2922 3129 scur = octets ? (span * octets) : (span + 7) / 8;
e524fe40
NC
3130 swatch = newSV(scur);
3131 SvPOK_on(swatch);
979f2922
TS
3132 s = (U8*)SvPVX(swatch);
3133 if (octets && none) {
0bd48802 3134 const U8* const e = s + scur;
979f2922
TS
3135 while (s < e) {
3136 if (bits == 8)
3137 *s++ = (U8)(none & 0xff);
3138 else if (bits == 16) {
3139 *s++ = (U8)((none >> 8) & 0xff);
3140 *s++ = (U8)( none & 0xff);
3141 }
3142 else if (bits == 32) {
3143 *s++ = (U8)((none >> 24) & 0xff);
3144 *s++ = (U8)((none >> 16) & 0xff);
3145 *s++ = (U8)((none >> 8) & 0xff);
3146 *s++ = (U8)( none & 0xff);
3147 }
3148 }
3149 *s = '\0';
3150 }
3151 else {
3152 (void)memzero((U8*)s, scur + 1);
3153 }
3154 SvCUR_set(swatch, scur);
3155 s = (U8*)SvPVX(swatch);
3156
36eb48b4
KW
3157 if (invlistsvp) { /* If has an inversion list set up use that */
3158 _invlist_populate_swatch(*invlistsvp, start, end, s);
3159 return swatch;
3160 }
3161
3162 /* read $swash->{LIST} */
979f2922
TS
3163 l = (U8*)SvPV(*listsvp, lcur);
3164 lend = l + lcur;
3165 while (l < lend) {
8ed25d53 3166 UV min, max, val, upper;
95543e92
KW
3167 l = swash_scan_list_line(l, lend, &min, &max, &val,
3168 cBOOL(octets), typestr);
319009ee 3169 if (l > lend) {
979f2922
TS
3170 break;
3171 }
3172
972dd592 3173 /* If looking for something beyond this range, go try the next one */
979f2922
TS
3174 if (max < start)
3175 continue;
3176
8ed25d53
KW
3177 /* <end> is generally 1 beyond where we want to set things, but at the
3178 * platform's infinity, where we can't go any higher, we want to
3179 * include the code point at <end> */
3180 upper = (max < end)
3181 ? max
3182 : (max != UV_MAX || end != UV_MAX)
3183 ? end - 1
3184 : end;
3185
979f2922 3186 if (octets) {
35da51f7 3187 UV key;
979f2922
TS
3188 if (min < start) {
3189 if (!none || val < none) {
3190 val += start - min;
3191 }
3192 min = start;
3193 }
8ed25d53 3194 for (key = min; key <= upper; key++) {
979f2922 3195 STRLEN offset;
979f2922
TS
3196 /* offset must be non-negative (start <= min <= key < end) */
3197 offset = octets * (key - start);
3198 if (bits == 8)
3199 s[offset] = (U8)(val & 0xff);
3200 else if (bits == 16) {
3201 s[offset ] = (U8)((val >> 8) & 0xff);
3202 s[offset + 1] = (U8)( val & 0xff);
3203 }
3204 else if (bits == 32) {
3205 s[offset ] = (U8)((val >> 24) & 0xff);
3206 s[offset + 1] = (U8)((val >> 16) & 0xff);
3207 s[offset + 2] = (U8)((val >> 8) & 0xff);
3208 s[offset + 3] = (U8)( val & 0xff);
3209 }
3210
3211 if (!none || val < none)
3212 ++val;
3213 }
3214 }
711a919c 3215 else { /* bits == 1, then val should be ignored */
35da51f7 3216 UV key;
979f2922
TS
3217 if (min < start)
3218 min = start;
6cb05c12 3219
8ed25d53 3220 for (key = min; key <= upper; key++) {
0bd48802 3221 const STRLEN offset = (STRLEN)(key - start);
979f2922
TS
3222 s[offset >> 3] |= 1 << (offset & 7);
3223 }
3224 }
3225 } /* while */
979f2922 3226
9479a769 3227 /* Invert if the data says it should be. Assumes that bits == 1 */
77f9f126 3228 if (invert_it_svp && SvUV(*invert_it_svp)) {
0bda3001
KW
3229
3230 /* Unicode properties should come with all bits above PERL_UNICODE_MAX
3231 * be 0, and their inversion should also be 0, as we don't succeed any
3232 * Unicode property matches for non-Unicode code points */
3233 if (start <= PERL_UNICODE_MAX) {
3234
3235 /* The code below assumes that we never cross the
3236 * Unicode/above-Unicode boundary in a range, as otherwise we would
3237 * have to figure out where to stop flipping the bits. Since this
3238 * boundary is divisible by a large power of 2, and swatches comes
3239 * in small powers of 2, this should be a valid assumption */
3240 assert(start + span - 1 <= PERL_UNICODE_MAX);
3241
507a8485
KW
3242 send = s + scur;
3243 while (s < send) {
3244 *s = ~(*s);
3245 s++;
3246 }
0bda3001 3247 }
77f9f126
KW
3248 }
3249
d73c39c5
KW
3250 /* read $swash->{EXTRAS}
3251 * This code also copied to swash_to_invlist() below */
979f2922
TS
3252 x = (U8*)SvPV(*extssvp, xcur);
3253 xend = x + xcur;
3254 while (x < xend) {
3255 STRLEN namelen;
3256 U8 *namestr;
3257 SV** othersvp;
3258 HV* otherhv;
3259 STRLEN otherbits;
3260 SV **otherbitssvp, *other;
711a919c 3261 U8 *s, *o, *nl;
979f2922
TS
3262 STRLEN slen, olen;
3263
35da51f7 3264 const U8 opc = *x++;
979f2922
TS
3265 if (opc == '\n')
3266 continue;
3267
3268 nl = (U8*)memchr(x, '\n', xend - x);
3269
3270 if (opc != '-' && opc != '+' && opc != '!' && opc != '&') {
3271 if (nl) {
3272 x = nl + 1; /* 1 is length of "\n" */
3273 continue;
3274 }
3275 else {
3276 x = xend; /* to EXTRAS' end at which \n is not found */
3277 break;
3278 }
3279 }
3280
3281 namestr = x;
3282 if (nl) {
3283 namelen = nl - namestr;
3284 x = nl + 1;
3285 }
3286 else {
3287 namelen = xend - namestr;
3288 x = xend;
3289 }
3290
3291 othersvp = hv_fetch(hv, (char *)namestr, namelen, FALSE);
ef8f7699 3292 otherhv = MUTABLE_HV(SvRV(*othersvp));
017a3ce5 3293 otherbitssvp = hv_fetchs(otherhv, "BITS", FALSE);
979f2922
TS
3294 otherbits = (STRLEN)SvUV(*otherbitssvp);
3295 if (bits < otherbits)
5637ef5b
NC
3296 Perl_croak(aTHX_ "panic: swatch_get found swatch size mismatch, "
3297 "bits=%"UVuf", otherbits=%"UVuf, (UV)bits, (UV)otherbits);
979f2922
TS
3298
3299 /* The "other" swatch must be destroyed after. */
b0e3252e 3300 other = swatch_get(*othersvp, start, span);
979f2922
TS
3301 o = (U8*)SvPV(other, olen);
3302
3303 if (!olen)
b0e3252e 3304 Perl_croak(aTHX_ "panic: swatch_get got improper swatch");
979f2922
TS
3305
3306 s = (U8*)SvPV(swatch, slen);
3307 if (bits == 1 && otherbits == 1) {
3308 if (slen != olen)
5637ef5b
NC
3309 Perl_croak(aTHX_ "panic: swatch_get found swatch length "
3310 "mismatch, slen=%"UVuf", olen=%"UVuf,
3311 (UV)slen, (UV)olen);
979f2922
TS
3312
3313 switch (opc) {
3314 case '+':
3315 while (slen--)
3316 *s++ |= *o++;
3317 break;
3318 case '!':
3319 while (slen--)
3320 *s++ |= ~*o++;
3321 break;
3322 case '-':
3323 while (slen--)
3324 *s++ &= ~*o++;
3325 break;
3326 case '&':
3327 while (slen--)
3328 *s++ &= *o++;
3329 break;
3330 default:
3331 break;
3332 }
3333 }
711a919c 3334 else {
979f2922
TS
3335 STRLEN otheroctets = otherbits >> 3;
3336 STRLEN offset = 0;
35da51f7 3337 U8* const send = s + slen;
979f2922
TS
3338
3339 while (s < send) {
3340 UV otherval = 0;
3341
3342 if (otherbits == 1) {
3343 otherval = (o[offset >> 3] >> (offset & 7)) & 1;
3344 ++offset;
3345 }
3346 else {
3347 STRLEN vlen = otheroctets;
3348 otherval = *o++;
3349 while (--vlen) {
3350 otherval <<= 8;
3351 otherval |= *o++;
3352 }
3353 }
3354
711a919c 3355 if (opc == '+' && otherval)
6f207bd3 3356 NOOP; /* replace with otherval */
979f2922
TS
3357 else if (opc == '!' && !otherval)
3358 otherval = 1;
3359 else if (opc == '-' && otherval)
3360 otherval = 0;
3361 else if (opc == '&' && !otherval)
3362 otherval = 0;
3363 else {
711a919c 3364 s += octets; /* no replacement */
979f2922
TS
3365 continue;
3366 }
3367
3368 if (bits == 8)
3369 *s++ = (U8)( otherval & 0xff);
3370 else if (bits == 16) {
3371 *s++ = (U8)((otherval >> 8) & 0xff);
3372 *s++ = (U8)( otherval & 0xff);
3373 }
3374 else if (bits == 32) {
3375 *s++ = (U8)((otherval >> 24) & 0xff);
3376 *s++ = (U8)((otherval >> 16) & 0xff);
3377 *s++ = (U8)((otherval >> 8) & 0xff);
3378 *s++ = (U8)( otherval & 0xff);
3379 }
3380 }
3381 }
3382 sv_free(other); /* through with it! */
3383 } /* while */
3384 return swatch;
3385}
3386
064c021d 3387HV*
4c2e1131 3388Perl__swash_inversion_hash(pTHX_ SV* const swash)
064c021d
KW
3389{
3390
79a2a0e8 3391 /* Subject to change or removal. For use only in regcomp.c and regexec.c
5662e334
KW
3392 * Can't be used on a property that is subject to user override, as it
3393 * relies on the value of SPECIALS in the swash which would be set by
3394 * utf8_heavy.pl to the hash in the non-overriden file, and hence is not set
3395 * for overridden properties
064c021d
KW
3396 *
3397 * Returns a hash which is the inversion and closure of a swash mapping.
3398 * For example, consider the input lines:
3399 * 004B 006B
3400 * 004C 006C
3401 * 212A 006B
3402 *
4a4088c4 3403 * The returned hash would have two keys, the UTF-8 for 006B and the UTF-8 for
064c021d 3404 * 006C. The value for each key is an array. For 006C, the array would
4a4088c4
KW
3405 * have two elements, the UTF-8 for itself, and for 004C. For 006B, there
3406 * would be three elements in its array, the UTF-8 for 006B, 004B and 212A.
064c021d 3407 *
538e84ed
KW
3408 * Note that there are no elements in the hash for 004B, 004C, 212A. The
3409 * keys are only code points that are folded-to, so it isn't a full closure.
3410 *
064c021d
KW
3411 * Essentially, for any code point, it gives all the code points that map to
3412 * it, or the list of 'froms' for that point.
3413 *
5662e334
KW
3414 * Currently it ignores any additions or deletions from other swashes,
3415 * looking at just the main body of the swash, and if there are SPECIALS
3416 * in the swash, at that hash
3417 *
3418 * The specials hash can be extra code points, and most likely consists of
3419 * maps from single code points to multiple ones (each expressed as a string
4a4088c4 3420 * of UTF-8 characters). This function currently returns only 1-1 mappings.
5662e334
KW
3421 * However consider this possible input in the specials hash:
3422 * "\xEF\xAC\x85" => "\x{0073}\x{0074}", # U+FB05 => 0073 0074
3423 * "\xEF\xAC\x86" => "\x{0073}\x{0074}", # U+FB06 => 0073 0074
3424 *
3425 * Both FB05 and FB06 map to the same multi-char sequence, which we don't
3426 * currently handle. But it also means that FB05 and FB06 are equivalent in
3427 * a 1-1 mapping which we should handle, and this relationship may not be in
3428 * the main table. Therefore this function examines all the multi-char
74894415
KW
3429 * sequences and adds the 1-1 mappings that come out of that.
3430 *
3431 * XXX This function was originally intended to be multipurpose, but its
3432 * only use is quite likely to remain for constructing the inversion of
3433 * the CaseFolding (//i) property. If it were more general purpose for
3434 * regex patterns, it would have to do the FB05/FB06 game for simple folds,
3435 * because certain folds are prohibited under /iaa and /il. As an example,
3436 * in Unicode 3.0.1 both U+0130 and U+0131 fold to 'i', and hence are both
3437 * equivalent under /i. But under /iaa and /il, the folds to 'i' are
3438 * prohibited, so we would not figure out that they fold to each other.
3439 * Code could be written to automatically figure this out, similar to the
3440 * code that does this for multi-character folds, but this is the only case
3441 * where something like this is ever likely to happen, as all the single
7ee537e6 3442 * char folds to the 0-255 range are now quite settled. Instead there is a
74894415
KW
3443 * little special code that is compiled only for this Unicode version. This
3444 * is smaller and didn't require much coding time to do. But this makes
3445 * this routine strongly tied to being used just for CaseFolding. If ever
3446 * it should be generalized, this would have to be fixed */
064c021d
KW
3447
3448 U8 *l, *lend;
3449 STRLEN lcur;
3450 HV *const hv = MUTABLE_HV(SvRV(swash));
3451
923b6d4e
KW
3452 /* The string containing the main body of the table. This will have its
3453 * assertion fail if the swash has been converted to its inversion list */
064c021d
KW
3454 SV** const listsvp = hv_fetchs(hv, "LIST", FALSE);
3455
3456 SV** const typesvp = hv_fetchs(hv, "TYPE", FALSE);
3457 SV** const bitssvp = hv_fetchs(hv, "BITS", FALSE);
3458 SV** const nonesvp = hv_fetchs(hv, "NONE", FALSE);
3459 /*SV** const extssvp = hv_fetchs(hv, "EXTRAS", FALSE);*/
3460 const U8* const typestr = (U8*)SvPV_nolen(*typesvp);
3461 const STRLEN bits = SvUV(*bitssvp);
3462 const STRLEN octets = bits >> 3; /* if bits == 1, then octets == 0 */
3463 const UV none = SvUV(*nonesvp);
5662e334 3464 SV **specials_p = hv_fetchs(hv, "SPECIALS", 0);
064c021d
KW
3465
3466 HV* ret = newHV();
3467
3468 PERL_ARGS_ASSERT__SWASH_INVERSION_HASH;
3469
3470 /* Must have at least 8 bits to get the mappings */
3471 if (bits != 8 && bits != 16 && bits != 32) {
3472 Perl_croak(aTHX_ "panic: swash_inversion_hash doesn't expect bits %"UVuf,
3473 (UV)bits);
3474 }
3475
5662e334
KW
3476 if (specials_p) { /* It might be "special" (sometimes, but not always, a
3477 mapping to more than one character */
3478
3479 /* Construct an inverse mapping hash for the specials */
3480 HV * const specials_hv = MUTABLE_HV(SvRV(*specials_p));
3481 HV * specials_inverse = newHV();
3482 char *char_from; /* the lhs of the map */
3483 I32 from_len; /* its byte length */
3484 char *char_to; /* the rhs of the map */
3485 I32 to_len; /* its byte length */
3486 SV *sv_to; /* and in a sv */
3487 AV* from_list; /* list of things that map to each 'to' */
3488
3489 hv_iterinit(specials_hv);
3490
4a4088c4
KW
3491 /* The keys are the characters (in UTF-8) that map to the corresponding
3492 * UTF-8 string value. Iterate through the list creating the inverse
5662e334
KW
3493 * list. */
3494 while ((sv_to = hv_iternextsv(specials_hv, &char_from, &from_len))) {
3495 SV** listp;
3496 if (! SvPOK(sv_to)) {
5637ef5b
NC
3497 Perl_croak(aTHX_ "panic: value returned from hv_iternextsv() "
3498 "unexpectedly is not a string, flags=%lu",
3499 (unsigned long)SvFLAGS(sv_to));
5662e334 3500 }
4b88fb76 3501 /*DEBUG_U(PerlIO_printf(Perl_debug_log, "Found mapping from %"UVXf", First char of to is %"UVXf"\n", valid_utf8_to_uvchr((U8*) char_from, 0), valid_utf8_to_uvchr((U8*) SvPVX(sv_to), 0)));*/
5662e334
KW
3502
3503 /* Each key in the inverse list is a mapped-to value, and the key's
4a4088c4 3504 * hash value is a list of the strings (each in UTF-8) that map to
5662e334
KW
3505 * it. Those strings are all one character long */
3506 if ((listp = hv_fetch(specials_inverse,
3507 SvPVX(sv_to),
3508 SvCUR(sv_to), 0)))
3509 {
3510 from_list = (AV*) *listp;
3511 }
3512 else { /* No entry yet for it: create one */
3513 from_list = newAV();
3514 if (! hv_store(specials_inverse,
3515 SvPVX(sv_to),
3516 SvCUR(sv_to),
3517 (SV*) from_list, 0))
3518 {
3519 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
3520 }
3521 }
3522
3523 /* Here have the list associated with this 'to' (perhaps newly
3524 * created and empty). Just add to it. Note that we ASSUME that
3525 * the input is guaranteed to not have duplications, so we don't
3526 * check for that. Duplications just slow down execution time. */
3527 av_push(from_list, newSVpvn_utf8(char_from, from_len, TRUE));
3528 }
3529
3530 /* Here, 'specials_inverse' contains the inverse mapping. Go through
3531 * it looking for cases like the FB05/FB06 examples above. There would
3532 * be an entry in the hash like
3533 * 'st' => [ FB05, FB06 ]
3534 * In this example we will create two lists that get stored in the
3535 * returned hash, 'ret':
3536 * FB05 => [ FB05, FB06 ]
3537 * FB06 => [ FB05, FB06 ]
3538 *
3539 * Note that there is nothing to do if the array only has one element.
3540 * (In the normal 1-1 case handled below, we don't have to worry about
3541 * two lists, as everything gets tied to the single list that is
3542 * generated for the single character 'to'. But here, we are omitting
3543 * that list, ('st' in the example), so must have multiple lists.) */
3544 while ((from_list = (AV *) hv_iternextsv(specials_inverse,
3545 &char_to, &to_len)))
3546 {
b9f2b683 3547 if (av_tindex(from_list) > 0) {
c70927a6 3548 SSize_t i;
5662e334
KW
3549
3550 /* We iterate over all combinations of i,j to place each code
3551 * point on each list */
b9f2b683 3552 for (i = 0; i <= av_tindex(from_list); i++) {
c70927a6 3553 SSize_t j;
5662e334
KW
3554 AV* i_list = newAV();
3555 SV** entryp = av_fetch(from_list, i, FALSE);
3556 if (entryp == NULL) {
3557 Perl_croak(aTHX_ "panic: av_fetch() unexpectedly failed");
3558 }
3559 if (hv_fetch(ret, SvPVX(*entryp), SvCUR(*entryp), FALSE)) {
3560 Perl_croak(aTHX_ "panic: unexpected entry for %s", SvPVX(*entryp));
3561 }
3562 if (! hv_store(ret, SvPVX(*entryp), SvCUR(*entryp),
3563 (SV*) i_list, FALSE))
3564 {
3565 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
3566 }
3567
538e84ed 3568 /* For DEBUG_U: UV u = valid_utf8_to_uvchr((U8*) SvPVX(*entryp), 0);*/
b9f2b683 3569 for (j = 0; j <= av_tindex(from_list); j++) {
5662e334
KW
3570 entryp = av_fetch(from_list, j, FALSE);
3571 if (entryp == NULL) {
3572 Perl_croak(aTHX_ "panic: av_fetch() unexpectedly failed");
3573 }
3574
3575 /* When i==j this adds itself to the list */
4b88fb76
KW
3576 av_push(i_list, newSVuv(utf8_to_uvchr_buf(
3577 (U8*) SvPVX(*entryp),
3578 (U8*) SvPVX(*entryp) + SvCUR(*entryp),
3579 0)));
4637d003 3580 /*DEBUG_U(PerlIO_printf(Perl_debug_log, "%s: %d: Adding %"UVXf" to list for %"UVXf"\n", __FILE__, __LINE__, valid_utf8_to_uvchr((U8*) SvPVX(*entryp), 0), u));*/
5662e334
KW
3581 }
3582 }
3583 }
3584 }
3585 SvREFCNT_dec(specials_inverse); /* done with it */
3586 } /* End of specials */
3587
064c021d 3588 /* read $swash->{LIST} */
74894415
KW
3589
3590#if UNICODE_MAJOR_VERSION == 3 \
3591 && UNICODE_DOT_VERSION == 0 \
3592 && UNICODE_DOT_DOT_VERSION == 1
3593
3594 /* For this version only U+130 and U+131 are equivalent under qr//i. Add a
3595 * rule so that things work under /iaa and /il */
3596
3597 SV * mod_listsv = sv_mortalcopy(*listsvp);
3598 sv_catpv(mod_listsv, "130\t130\t131\n");
3599 l = (U8*)SvPV(mod_listsv, lcur);
3600
3601#else
3602
064c021d 3603 l = (U8*)SvPV(*listsvp, lcur);
74894415
KW
3604
3605#endif
3606
064c021d
KW
3607 lend = l + lcur;
3608
3609 /* Go through each input line */
3610 while (l < lend) {
3611 UV min, max, val;
3612 UV inverse;
95543e92
KW
3613 l = swash_scan_list_line(l, lend, &min, &max, &val,
3614 cBOOL(octets), typestr);
064c021d
KW
3615 if (l > lend) {
3616 break;
3617 }
3618
3619 /* Each element in the range is to be inverted */
3620 for (inverse = min; inverse <= max; inverse++) {
3621 AV* list;
064c021d
KW
3622 SV** listp;
3623 IV i;
3624 bool found_key = FALSE;
5662e334 3625 bool found_inverse = FALSE;
064c021d
KW
3626
3627 /* The key is the inverse mapping */
3628 char key[UTF8_MAXBYTES+1];
c80e42f3 3629 char* key_end = (char *) uvchr_to_utf8((U8*) key, val);
064c021d
KW
3630 STRLEN key_len = key_end - key;
3631
064c021d
KW
3632 /* Get the list for the map */
3633 if ((listp = hv_fetch(ret, key, key_len, FALSE))) {
3634 list = (AV*) *listp;
3635