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