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