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