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