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