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