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