This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Add new opcodes to Opcode.pm
[perl5.git] / utf8.c
1 /*    utf8.c
2  *
3  *    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
4  *    by Larry Wall and others
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 /*
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  *
16  *     [p.603 of _The Lord of the Rings_, IV/I: "The Taming of Sméagol"]
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,
20  *  as is the custom in the West, if you wish to be answered?'
21  *                           --Gandalf, addressing Théoden's door wardens
22  *
23  *     [p.508 of _The Lord of the Rings_, III/vi: "The King of the Golden Hall"]
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.
27  *
28  *     [p.512 of _The Lord of the Rings_, III/vi: "The King of the Golden Hall"]
29  */
30
31 #include "EXTERN.h"
32 #define PERL_IN_UTF8_C
33 #include "perl.h"
34 #include "inline_invlist.c"
35
36 static const char unees[] =
37     "Malformed UTF-8 character (unexpected end of string)";
38
39 /*
40 =head1 Unicode Support
41
42 This file contains various utility functions for manipulating UTF8-encoded
43 strings. For the uninitiated, this is a method of representing arbitrary
44 Unicode characters as a variable number of bytes, in such a way that
45 characters in the ASCII range are unmodified, and a zero byte never appears
46 within non-zero characters.
47
48 =cut
49 */
50
51 /*
52 =for apidoc is_ascii_string
53
54 Returns true if the first C<len> bytes of the string C<s> are the same whether
55 or not the string is encoded in UTF-8 (or UTF-EBCDIC on EBCDIC machines).  That
56 is, if they are invariant.  On ASCII-ish machines, only ASCII characters
57 fit this definition, hence the function's name.
58
59 If C<len> is 0, it will be calculated using C<strlen(s)>.  
60
61 See also L</is_utf8_string>(), L</is_utf8_string_loclen>(), and L</is_utf8_string_loc>().
62
63 =cut
64 */
65
66 bool
67 Perl_is_ascii_string(const U8 *s, STRLEN len)
68 {
69     const U8* const send = s + (len ? len : strlen((const char *)s));
70     const U8* x = s;
71
72     PERL_ARGS_ASSERT_IS_ASCII_STRING;
73
74     for (; x < send; ++x) {
75         if (!UTF8_IS_INVARIANT(*x))
76             break;
77     }
78
79     return x == send;
80 }
81
82 /*
83 =for apidoc uvoffuni_to_utf8_flags
84
85 THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES.
86 Instead, B<Almost all code should use L</uvchr_to_utf8> or
87 L</uvchr_to_utf8_flags>>.
88
89 This function is like them, but the input is a strict Unicode
90 (as opposed to native) code point.  Only in very rare circumstances should code
91 not be using the native code point.
92
93 For details, see the description for L</uvchr_to_utf8_flags>>.
94
95 =cut
96 */
97
98 U8 *
99 Perl_uvoffuni_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags)
100 {
101     PERL_ARGS_ASSERT_UVOFFUNI_TO_UTF8_FLAGS;
102
103     if (UNI_IS_INVARIANT(uv)) {
104         *d++ = (U8) LATIN1_TO_NATIVE(uv);
105         return d;
106     }
107
108     /* The first problematic code point is the first surrogate */
109     if (uv >= UNICODE_SURROGATE_FIRST
110         && ckWARN4_d(WARN_UTF8, WARN_SURROGATE, WARN_NON_UNICODE, WARN_NONCHAR))
111     {
112         if (UNICODE_IS_SURROGATE(uv)) {
113             if (flags & UNICODE_WARN_SURROGATE) {
114                 Perl_ck_warner_d(aTHX_ packWARN(WARN_SURROGATE),
115                                             "UTF-16 surrogate U+%04"UVXf, uv);
116             }
117             if (flags & UNICODE_DISALLOW_SURROGATE) {
118                 return NULL;
119             }
120         }
121         else if (UNICODE_IS_SUPER(uv)) {
122             if (flags & UNICODE_WARN_SUPER
123                 || (UNICODE_IS_FE_FF(uv) && (flags & UNICODE_WARN_FE_FF)))
124             {
125                 Perl_ck_warner_d(aTHX_ packWARN(WARN_NON_UNICODE),
126                           "Code point 0x%04"UVXf" is not Unicode, may not be portable", uv);
127             }
128             if (flags & UNICODE_DISALLOW_SUPER
129                 || (UNICODE_IS_FE_FF(uv) && (flags & UNICODE_DISALLOW_FE_FF)))
130             {
131                 return NULL;
132             }
133         }
134         else if (UNICODE_IS_NONCHAR(uv)) {
135             if (flags & UNICODE_WARN_NONCHAR) {
136                 Perl_ck_warner_d(aTHX_ packWARN(WARN_NONCHAR),
137                  "Unicode non-character U+%04"UVXf" is illegal for open interchange",
138                  uv);
139             }
140             if (flags & UNICODE_DISALLOW_NONCHAR) {
141                 return NULL;
142             }
143         }
144     }
145
146 #if defined(EBCDIC)
147     {
148         STRLEN len  = OFFUNISKIP(uv);
149         U8 *p = d+len-1;
150         while (p > d) {
151             *p-- = (U8) I8_TO_NATIVE_UTF8((uv & UTF_CONTINUATION_MASK) | UTF_CONTINUATION_MARK);
152             uv >>= UTF_ACCUMULATION_SHIFT;
153         }
154         *p = (U8) I8_TO_NATIVE_UTF8((uv & UTF_START_MASK(len)) | UTF_START_MARK(len));
155         return d+len;
156     }
157 #else /* Non loop style */
158     if (uv < 0x800) {
159         *d++ = (U8)(( uv >>  6)         | 0xc0);
160         *d++ = (U8)(( uv        & 0x3f) | 0x80);
161         return d;
162     }
163     if (uv < 0x10000) {
164         *d++ = (U8)(( uv >> 12)         | 0xe0);
165         *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
166         *d++ = (U8)(( uv        & 0x3f) | 0x80);
167         return d;
168     }
169     if (uv < 0x200000) {
170         *d++ = (U8)(( uv >> 18)         | 0xf0);
171         *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
172         *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
173         *d++ = (U8)(( uv        & 0x3f) | 0x80);
174         return d;
175     }
176     if (uv < 0x4000000) {
177         *d++ = (U8)(( uv >> 24)         | 0xf8);
178         *d++ = (U8)(((uv >> 18) & 0x3f) | 0x80);
179         *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
180         *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
181         *d++ = (U8)(( uv        & 0x3f) | 0x80);
182         return d;
183     }
184     if (uv < 0x80000000) {
185         *d++ = (U8)(( uv >> 30)         | 0xfc);
186         *d++ = (U8)(((uv >> 24) & 0x3f) | 0x80);
187         *d++ = (U8)(((uv >> 18) & 0x3f) | 0x80);
188         *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
189         *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
190         *d++ = (U8)(( uv        & 0x3f) | 0x80);
191         return d;
192     }
193 #ifdef HAS_QUAD
194     if (uv < UTF8_QUAD_MAX)
195 #endif
196     {
197         *d++ =                            0xfe; /* Can't match U+FEFF! */
198         *d++ = (U8)(((uv >> 30) & 0x3f) | 0x80);
199         *d++ = (U8)(((uv >> 24) & 0x3f) | 0x80);
200         *d++ = (U8)(((uv >> 18) & 0x3f) | 0x80);
201         *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
202         *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
203         *d++ = (U8)(( uv        & 0x3f) | 0x80);
204         return d;
205     }
206 #ifdef HAS_QUAD
207     {
208         *d++ =                            0xff;         /* Can't match U+FFFE! */
209         *d++ =                            0x80;         /* 6 Reserved bits */
210         *d++ = (U8)(((uv >> 60) & 0x0f) | 0x80);        /* 2 Reserved bits */
211         *d++ = (U8)(((uv >> 54) & 0x3f) | 0x80);
212         *d++ = (U8)(((uv >> 48) & 0x3f) | 0x80);
213         *d++ = (U8)(((uv >> 42) & 0x3f) | 0x80);
214         *d++ = (U8)(((uv >> 36) & 0x3f) | 0x80);
215         *d++ = (U8)(((uv >> 30) & 0x3f) | 0x80);
216         *d++ = (U8)(((uv >> 24) & 0x3f) | 0x80);
217         *d++ = (U8)(((uv >> 18) & 0x3f) | 0x80);
218         *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
219         *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
220         *d++ = (U8)(( uv        & 0x3f) | 0x80);
221         return d;
222     }
223 #endif
224 #endif /* Non loop style */
225 }
226 /*
227 =for apidoc uvchr_to_utf8
228
229 Adds the UTF-8 representation of the native code point C<uv> to the end
230 of the string C<d>; C<d> should have at least C<UTF8_MAXBYTES+1> free
231 bytes available. The return value is the pointer to the byte after the
232 end of the new character. In other words,
233
234     d = uvchr_to_utf8(d, uv);
235
236 is the recommended wide native character-aware way of saying
237
238     *(d++) = uv;
239
240 This function accepts any UV as input.  To forbid or warn on non-Unicode code
241 points, or those that may be problematic, see L</uvchr_to_utf8_flags>.
242
243 =cut
244 */
245
246 /* This is also a macro */
247 PERL_CALLCONV U8*       Perl_uvchr_to_utf8(pTHX_ U8 *d, UV uv);
248
249 U8 *
250 Perl_uvchr_to_utf8(pTHX_ U8 *d, UV uv)
251 {
252     return uvchr_to_utf8(d, uv);
253 }
254
255 /*
256 =for apidoc uvchr_to_utf8_flags
257
258 Adds the UTF-8 representation of the native code point C<uv> to the end
259 of the string C<d>; C<d> should have at least C<UTF8_MAXBYTES+1> free
260 bytes available. The return value is the pointer to the byte after the
261 end of the new character. In other words,
262
263     d = uvchr_to_utf8_flags(d, uv, flags);
264
265 or, in most cases,
266
267     d = uvchr_to_utf8_flags(d, uv, 0);
268
269 This is the Unicode-aware way of saying
270
271     *(d++) = uv;
272
273 This function will convert to UTF-8 (and not warn) even code points that aren't
274 legal Unicode or are problematic, unless C<flags> contains one or more of the
275 following flags:
276
277 If C<uv> is a Unicode surrogate code point and UNICODE_WARN_SURROGATE is set,
278 the function will raise a warning, provided UTF8 warnings are enabled.  If instead
279 UNICODE_DISALLOW_SURROGATE is set, the function will fail and return NULL.
280 If both flags are set, the function will both warn and return NULL.
281
282 The UNICODE_WARN_NONCHAR and UNICODE_DISALLOW_NONCHAR flags correspondingly
283 affect how the function handles a Unicode non-character.  And likewise, the
284 UNICODE_WARN_SUPER and UNICODE_DISALLOW_SUPER flags, affect the handling of
285 code points that are
286 above the Unicode maximum of 0x10FFFF.  Code points above 0x7FFF_FFFF (which are
287 even less portable) can be warned and/or disallowed even if other above-Unicode
288 code points are accepted, by the UNICODE_WARN_FE_FF and UNICODE_DISALLOW_FE_FF
289 flags.
290
291 And finally, the flag UNICODE_WARN_ILLEGAL_INTERCHANGE selects all four of the
292 above WARN flags; and UNICODE_DISALLOW_ILLEGAL_INTERCHANGE selects all four
293 DISALLOW flags.
294
295 =cut
296 */
297
298 /* This is also a macro */
299 PERL_CALLCONV U8*       Perl_uvchr_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags);
300
301 U8 *
302 Perl_uvchr_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags)
303 {
304     return uvchr_to_utf8_flags(d, uv, flags);
305 }
306
307 /*
308
309 Tests if the first C<len> bytes of string C<s> form a valid UTF-8
310 character.  Note that an INVARIANT (i.e. ASCII on non-EBCDIC) character is a
311 valid UTF-8 character.  The number of bytes in the UTF-8 character
312 will be returned if it is valid, otherwise 0.
313
314 This is the "slow" version as opposed to the "fast" version which is
315 the "unrolled" IS_UTF8_CHAR().  E.g. for t/uni/class.t the speed
316 difference is a factor of 2 to 3.  For lengths (UTF8SKIP(s)) of four
317 or less you should use the IS_UTF8_CHAR(), for lengths of five or more
318 you should use the _slow().  In practice this means that the _slow()
319 will be used very rarely, since the maximum Unicode code point (as of
320 Unicode 4.1) is U+10FFFF, which encodes in UTF-8 to four bytes.  Only
321 the "Perl extended UTF-8" (e.g, the infamous 'v-strings') will encode into
322 five bytes or more.
323
324 =cut */
325 PERL_STATIC_INLINE STRLEN
326 S_is_utf8_char_slow(const U8 *s, const STRLEN len)
327 {
328     dTHX;   /* The function called below requires thread context */
329
330     STRLEN actual_len;
331
332     PERL_ARGS_ASSERT_IS_UTF8_CHAR_SLOW;
333
334     utf8n_to_uvchr(s, len, &actual_len, UTF8_CHECK_ONLY);
335
336     return (actual_len == (STRLEN) -1) ? 0 : actual_len;
337 }
338
339 /*
340 =for apidoc is_utf8_char_buf
341
342 Returns the number of bytes that comprise the first UTF-8 encoded character in
343 buffer C<buf>.  C<buf_end> should point to one position beyond the end of the
344 buffer.  0 is returned if C<buf> does not point to a complete, valid UTF-8
345 encoded character.
346
347 Note that an INVARIANT character (i.e. ASCII on non-EBCDIC
348 machines) is a valid UTF-8 character.
349
350 =cut */
351
352 STRLEN
353 Perl_is_utf8_char_buf(const U8 *buf, const U8* buf_end)
354 {
355
356     STRLEN len;
357
358     PERL_ARGS_ASSERT_IS_UTF8_CHAR_BUF;
359
360     if (buf_end <= buf) {
361         return 0;
362     }
363
364     len = buf_end - buf;
365     if (len > UTF8SKIP(buf)) {
366         len = UTF8SKIP(buf);
367     }
368
369 #ifdef IS_UTF8_CHAR
370     if (IS_UTF8_CHAR_FAST(len))
371         return IS_UTF8_CHAR(buf, len) ? len : 0;
372 #endif /* #ifdef IS_UTF8_CHAR */
373     return is_utf8_char_slow(buf, len);
374 }
375
376 /*
377 =for apidoc is_utf8_char
378
379 Tests if some arbitrary number of bytes begins in a valid UTF-8
380 character.  Note that an INVARIANT (i.e. ASCII on non-EBCDIC machines)
381 character is a valid UTF-8 character.  The actual number of bytes in the UTF-8
382 character will be returned if it is valid, otherwise 0.
383
384 This function is deprecated due to the possibility that malformed input could
385 cause reading beyond the end of the input buffer.  Use L</is_utf8_char_buf>
386 instead.
387
388 =cut */
389
390 STRLEN
391 Perl_is_utf8_char(const U8 *s)
392 {
393     PERL_ARGS_ASSERT_IS_UTF8_CHAR;
394
395     /* Assumes we have enough space, which is why this is deprecated */
396     return is_utf8_char_buf(s, s + UTF8SKIP(s));
397 }
398
399
400 /*
401 =for apidoc is_utf8_string
402
403 Returns true if the first C<len> bytes of string C<s> form a valid
404 UTF-8 string, false otherwise.  If C<len> is 0, it will be calculated
405 using C<strlen(s)> (which means if you use this option, that C<s> has to have a
406 terminating NUL byte).  Note that all characters being ASCII constitute 'a
407 valid UTF-8 string'.
408
409 See also L</is_ascii_string>(), L</is_utf8_string_loclen>(), and L</is_utf8_string_loc>().
410
411 =cut
412 */
413
414 bool
415 Perl_is_utf8_string(const U8 *s, STRLEN len)
416 {
417     const U8* const send = s + (len ? len : strlen((const char *)s));
418     const U8* x = s;
419
420     PERL_ARGS_ASSERT_IS_UTF8_STRING;
421
422     while (x < send) {
423          /* Inline the easy bits of is_utf8_char() here for speed... */
424          if (UTF8_IS_INVARIANT(*x)) {
425             x++;
426          }
427          else {
428               /* ... and call is_utf8_char() only if really needed. */
429              const STRLEN c = UTF8SKIP(x);
430              const U8* const next_char_ptr = x + c;
431
432              if (next_char_ptr > send) {
433                  return FALSE;
434              }
435
436              if (IS_UTF8_CHAR_FAST(c)) {
437                  if (!IS_UTF8_CHAR(x, c))
438                      return FALSE;
439              }
440              else if (! is_utf8_char_slow(x, c)) {
441                  return FALSE;
442              }
443              x = next_char_ptr;
444          }
445     }
446
447     return TRUE;
448 }
449
450 /*
451 Implemented as a macro in utf8.h
452
453 =for apidoc is_utf8_string_loc
454
455 Like L</is_utf8_string> but stores the location of the failure (in the
456 case of "utf8ness failure") or the location C<s>+C<len> (in the case of
457 "utf8ness success") in the C<ep>.
458
459 See also L</is_utf8_string_loclen>() and L</is_utf8_string>().
460
461 =for apidoc is_utf8_string_loclen
462
463 Like L</is_utf8_string>() but stores the location of the failure (in the
464 case of "utf8ness failure") or the location C<s>+C<len> (in the case of
465 "utf8ness success") in the C<ep>, and the number of UTF-8
466 encoded characters in the C<el>.
467
468 See also L</is_utf8_string_loc>() and L</is_utf8_string>().
469
470 =cut
471 */
472
473 bool
474 Perl_is_utf8_string_loclen(const U8 *s, STRLEN len, const U8 **ep, STRLEN *el)
475 {
476     const U8* const send = s + (len ? len : strlen((const char *)s));
477     const U8* x = s;
478     STRLEN c;
479     STRLEN outlen = 0;
480
481     PERL_ARGS_ASSERT_IS_UTF8_STRING_LOCLEN;
482
483     while (x < send) {
484          const U8* next_char_ptr;
485
486          /* Inline the easy bits of is_utf8_char() here for speed... */
487          if (UTF8_IS_INVARIANT(*x))
488              next_char_ptr = x + 1;
489          else {
490              /* ... and call is_utf8_char() only if really needed. */
491              c = UTF8SKIP(x);
492              next_char_ptr = c + x;
493              if (next_char_ptr > send) {
494                  goto out;
495              }
496              if (IS_UTF8_CHAR_FAST(c)) {
497                  if (!IS_UTF8_CHAR(x, c))
498                      c = 0;
499              } else
500                  c = is_utf8_char_slow(x, c);
501              if (!c)
502                  goto out;
503          }
504          x = next_char_ptr;
505          outlen++;
506     }
507
508  out:
509     if (el)
510         *el = outlen;
511
512     if (ep)
513         *ep = x;
514     return (x == send);
515 }
516
517 /*
518
519 =for apidoc utf8n_to_uvchr
520
521 THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES.
522 Most code should use L</utf8_to_uvchr_buf>() rather than call this directly.
523
524 Bottom level UTF-8 decode routine.
525 Returns the native code point value of the first character in the string C<s>,
526 which is assumed to be in UTF-8 (or UTF-EBCDIC) encoding, and no longer than
527 C<curlen> bytes; C<*retlen> (if C<retlen> isn't NULL) will be set to
528 the length, in bytes, of that character.
529
530 The value of C<flags> determines the behavior when C<s> does not point to a
531 well-formed UTF-8 character.  If C<flags> is 0, when a malformation is found,
532 zero is returned and C<*retlen> is set so that (S<C<s> + C<*retlen>>) is the
533 next possible position in C<s> that could begin a non-malformed character.
534 Also, if UTF-8 warnings haven't been lexically disabled, a warning is raised.
535
536 Various ALLOW flags can be set in C<flags> to allow (and not warn on)
537 individual types of malformations, such as the sequence being overlong (that
538 is, when there is a shorter sequence that can express the same code point;
539 overlong sequences are expressly forbidden in the UTF-8 standard due to
540 potential security issues).  Another malformation example is the first byte of
541 a character not being a legal first byte.  See F<utf8.h> for the list of such
542 flags.  For allowed 0 length strings, this function returns 0; for allowed
543 overlong sequences, the computed code point is returned; for all other allowed
544 malformations, the Unicode REPLACEMENT CHARACTER is returned, as these have no
545 determinable reasonable value.
546
547 The UTF8_CHECK_ONLY flag overrides the behavior when a non-allowed (by other
548 flags) malformation is found.  If this flag is set, the routine assumes that
549 the caller will raise a warning, and this function will silently just set
550 C<retlen> to C<-1> (cast to C<STRLEN>) and return zero.
551
552 Note that this API requires disambiguation between successful decoding a NUL
553 character, and an error return (unless the UTF8_CHECK_ONLY flag is set), as
554 in both cases, 0 is returned.  To disambiguate, upon a zero return, see if the
555 first byte of C<s> is 0 as well.  If so, the input was a NUL; if not, the input
556 had an error.
557
558 Certain code points are considered problematic.  These are Unicode surrogates,
559 Unicode non-characters, and code points above the Unicode maximum of 0x10FFFF.
560 By default these are considered regular code points, but certain situations
561 warrant special handling for them.  If C<flags> contains
562 UTF8_DISALLOW_ILLEGAL_INTERCHANGE, all three classes are treated as
563 malformations and handled as such.  The flags UTF8_DISALLOW_SURROGATE,
564 UTF8_DISALLOW_NONCHAR, and UTF8_DISALLOW_SUPER (meaning above the legal Unicode
565 maximum) can be set to disallow these categories individually.
566
567 The flags UTF8_WARN_ILLEGAL_INTERCHANGE, UTF8_WARN_SURROGATE,
568 UTF8_WARN_NONCHAR, and UTF8_WARN_SUPER will cause warning messages to be raised
569 for their respective categories, but otherwise the code points are considered
570 valid (not malformations).  To get a category to both be treated as a
571 malformation and raise a warning, specify both the WARN and DISALLOW flags.
572 (But note that warnings are not raised if lexically disabled nor if
573 UTF8_CHECK_ONLY is also specified.)
574
575 Very large code points (above 0x7FFF_FFFF) are considered more problematic than
576 the others that are above the Unicode legal maximum.  There are several
577 reasons: they requre at least 32 bits to represent them on ASCII platforms, are
578 not representable at all on EBCDIC platforms, and the original UTF-8
579 specification never went above this number (the current 0x10FFFF limit was
580 imposed later).  (The smaller ones, those that fit into 32 bits, are
581 representable by a UV on ASCII platforms, but not by an IV, which means that
582 the number of operations that can be performed on them is quite restricted.)
583 The UTF-8 encoding on ASCII platforms for these large code points begins with a
584 byte containing 0xFE or 0xFF.  The UTF8_DISALLOW_FE_FF flag will cause them to
585 be treated as malformations, while allowing smaller above-Unicode code points.
586 (Of course UTF8_DISALLOW_SUPER will treat all above-Unicode code points,
587 including these, as malformations.) Similarly, UTF8_WARN_FE_FF acts just like
588 the other WARN flags, but applies just to these code points.
589
590 All other code points corresponding to Unicode characters, including private
591 use and those yet to be assigned, are never considered malformed and never
592 warn.
593
594 =cut
595 */
596
597 UV
598 Perl_utf8n_to_uvchr(pTHX_ const U8 *s, STRLEN curlen, STRLEN *retlen, U32 flags)
599 {
600     dVAR;
601     const U8 * const s0 = s;
602     U8 overflow_byte = '\0';    /* Save byte in case of overflow */
603     U8 * send;
604     UV uv = *s;
605     STRLEN expectlen;
606     SV* sv = NULL;
607     UV outlier_ret = 0; /* return value when input is in error or problematic
608                          */
609     UV pack_warn = 0;   /* Save result of packWARN() for later */
610     bool unexpected_non_continuation = FALSE;
611     bool overflowed = FALSE;
612     bool do_overlong_test = TRUE;   /* May have to skip this test */
613
614     const char* const malformed_text = "Malformed UTF-8 character";
615
616     PERL_ARGS_ASSERT_UTF8N_TO_UVCHR;
617
618     /* The order of malformation tests here is important.  We should consume as
619      * few bytes as possible in order to not skip any valid character.  This is
620      * required by the Unicode Standard (section 3.9 of Unicode 6.0); see also
621      * http://unicode.org/reports/tr36 for more discussion as to why.  For
622      * example, once we've done a UTF8SKIP, we can tell the expected number of
623      * bytes, and could fail right off the bat if the input parameters indicate
624      * that there are too few available.  But it could be that just that first
625      * byte is garbled, and the intended character occupies fewer bytes.  If we
626      * blindly assumed that the first byte is correct, and skipped based on
627      * that number, we could skip over a valid input character.  So instead, we
628      * always examine the sequence byte-by-byte.
629      *
630      * We also should not consume too few bytes, otherwise someone could inject
631      * things.  For example, an input could be deliberately designed to
632      * overflow, and if this code bailed out immediately upon discovering that,
633      * returning to the caller *retlen pointing to the very next byte (one
634      * which is actually part of of the overflowing sequence), that could look
635      * legitimate to the caller, which could discard the initial partial
636      * sequence and process the rest, inappropriately */
637
638     /* Zero length strings, if allowed, of necessity are zero */
639     if (UNLIKELY(curlen == 0)) {
640         if (retlen) {
641             *retlen = 0;
642         }
643
644         if (flags & UTF8_ALLOW_EMPTY) {
645             return 0;
646         }
647         if (! (flags & UTF8_CHECK_ONLY)) {
648             sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (empty string)", malformed_text));
649         }
650         goto malformed;
651     }
652
653     expectlen = UTF8SKIP(s);
654
655     /* A well-formed UTF-8 character, as the vast majority of calls to this
656      * function will be for, has this expected length.  For efficiency, set
657      * things up here to return it.  It will be overriden only in those rare
658      * cases where a malformation is found */
659     if (retlen) {
660         *retlen = expectlen;
661     }
662
663     /* An invariant is trivially well-formed */
664     if (UTF8_IS_INVARIANT(uv)) {
665         return uv;
666     }
667
668     /* A continuation character can't start a valid sequence */
669     if (UNLIKELY(UTF8_IS_CONTINUATION(uv))) {
670         if (flags & UTF8_ALLOW_CONTINUATION) {
671             if (retlen) {
672                 *retlen = 1;
673             }
674             return UNICODE_REPLACEMENT;
675         }
676
677         if (! (flags & UTF8_CHECK_ONLY)) {
678             sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (unexpected continuation byte 0x%02x, with no preceding start byte)", malformed_text, *s0));
679         }
680         curlen = 1;
681         goto malformed;
682     }
683
684     /* Here is not a continuation byte, nor an invariant.  The only thing left
685      * is a start byte (possibly for an overlong) */
686
687 #ifdef EBCDIC
688     uv = NATIVE_UTF8_TO_I8(uv);
689 #endif
690
691     /* Remove the leading bits that indicate the number of bytes in the
692      * character's whole UTF-8 sequence, leaving just the bits that are part of
693      * the value */
694     uv &= UTF_START_MASK(expectlen);
695
696     /* Now, loop through the remaining bytes in the character's sequence,
697      * accumulating each into the working value as we go.  Be sure to not look
698      * past the end of the input string */
699     send =  (U8*) s0 + ((expectlen <= curlen) ? expectlen : curlen);
700
701     for (s = s0 + 1; s < send; s++) {
702         if (LIKELY(UTF8_IS_CONTINUATION(*s))) {
703 #ifndef EBCDIC  /* Can't overflow in EBCDIC */
704             if (uv & UTF_ACCUMULATION_OVERFLOW_MASK) {
705
706                 /* The original implementors viewed this malformation as more
707                  * serious than the others (though I, khw, don't understand
708                  * why, since other malformations also give very very wrong
709                  * results), so there is no way to turn off checking for it.
710                  * Set a flag, but keep going in the loop, so that we absorb
711                  * the rest of the bytes that comprise the character. */
712                 overflowed = TRUE;
713                 overflow_byte = *s; /* Save for warning message's use */
714             }
715 #endif
716             uv = UTF8_ACCUMULATE(uv, *s);
717         }
718         else {
719             /* Here, found a non-continuation before processing all expected
720              * bytes.  This byte begins a new character, so quit, even if
721              * allowing this malformation. */
722             unexpected_non_continuation = TRUE;
723             break;
724         }
725     } /* End of loop through the character's bytes */
726
727     /* Save how many bytes were actually in the character */
728     curlen = s - s0;
729
730     /* The loop above finds two types of malformations: non-continuation and/or
731      * overflow.  The non-continuation malformation is really a too-short
732      * malformation, as it means that the current character ended before it was
733      * expected to (being terminated prematurely by the beginning of the next
734      * character, whereas in the too-short malformation there just are too few
735      * bytes available to hold the character.  In both cases, the check below
736      * that we have found the expected number of bytes would fail if executed.)
737      * Thus the non-continuation malformation is really unnecessary, being a
738      * subset of the too-short malformation.  But there may be existing
739      * applications that are expecting the non-continuation type, so we retain
740      * it, and return it in preference to the too-short malformation.  (If this
741      * code were being written from scratch, the two types might be collapsed
742      * into one.)  I, khw, am also giving priority to returning the
743      * non-continuation and too-short malformations over overflow when multiple
744      * ones are present.  I don't know of any real reason to prefer one over
745      * the other, except that it seems to me that multiple-byte errors trumps
746      * errors from a single byte */
747     if (UNLIKELY(unexpected_non_continuation)) {
748         if (!(flags & UTF8_ALLOW_NON_CONTINUATION)) {
749             if (! (flags & UTF8_CHECK_ONLY)) {
750                 if (curlen == 1) {
751                     sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (unexpected non-continuation byte 0x%02x, immediately after start byte 0x%02x)", malformed_text, *s, *s0));
752                 }
753                 else {
754                     sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (unexpected non-continuation byte 0x%02x, %d bytes after start byte 0x%02x, expected %d bytes)", malformed_text, *s, (int) curlen, *s0, (int)expectlen));
755                 }
756             }
757             goto malformed;
758         }
759         uv = UNICODE_REPLACEMENT;
760
761         /* Skip testing for overlongs, as the REPLACEMENT may not be the same
762          * as what the original expectations were. */
763         do_overlong_test = FALSE;
764         if (retlen) {
765             *retlen = curlen;
766         }
767     }
768     else if (UNLIKELY(curlen < expectlen)) {
769         if (! (flags & UTF8_ALLOW_SHORT)) {
770             if (! (flags & UTF8_CHECK_ONLY)) {
771                 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (%d byte%s, need %d, after start byte 0x%02x)", malformed_text, (int)curlen, curlen == 1 ? "" : "s", (int)expectlen, *s0));
772             }
773             goto malformed;
774         }
775         uv = UNICODE_REPLACEMENT;
776         do_overlong_test = FALSE;
777         if (retlen) {
778             *retlen = curlen;
779         }
780     }
781
782 #ifndef EBCDIC  /* EBCDIC allows FE, FF, can't overflow */
783     if ((*s0 & 0xFE) == 0xFE    /* matches both FE, FF */
784         && (flags & (UTF8_WARN_FE_FF|UTF8_DISALLOW_FE_FF)))
785     {
786         /* By adding UTF8_CHECK_ONLY to the test, we avoid unnecessary
787          * generation of the sv, since no warnings are raised under CHECK */
788         if ((flags & (UTF8_WARN_FE_FF|UTF8_CHECK_ONLY)) == UTF8_WARN_FE_FF
789             && ckWARN_d(WARN_UTF8))
790         {
791             /* This message is deliberately not of the same syntax as the other
792              * messages for malformations, for backwards compatibility in the
793              * unlikely event that code is relying on its precise earlier text
794              */
795             sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s Code point beginning with byte 0x%02X is not Unicode, and not portable", malformed_text, *s0));
796             pack_warn = packWARN(WARN_UTF8);
797         }
798         if (flags & UTF8_DISALLOW_FE_FF) {
799             goto malformed;
800         }
801     }
802     if (UNLIKELY(overflowed)) {
803
804         /* If the first byte is FF, it will overflow a 32-bit word.  If the
805          * first byte is FE, it will overflow a signed 32-bit word.  The
806          * above preserves backward compatibility, since its message was used
807          * in earlier versions of this code in preference to overflow */
808         sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (overflow at byte 0x%02x, after start byte 0x%02x)", malformed_text, overflow_byte, *s0));
809         goto malformed;
810     }
811 #endif
812
813     if (do_overlong_test
814         && expectlen > (STRLEN) OFFUNISKIP(uv)
815         && ! (flags & UTF8_ALLOW_LONG))
816     {
817         /* The overlong malformation has lower precedence than the others.
818          * Note that if this malformation is allowed, we return the actual
819          * value, instead of the replacement character.  This is because this
820          * value is actually well-defined. */
821         if (! (flags & UTF8_CHECK_ONLY)) {
822             sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (%d byte%s, need %d, after start byte 0x%02x)", malformed_text, (int)expectlen, expectlen == 1 ? "": "s", OFFUNISKIP(uv), *s0));
823         }
824         goto malformed;
825     }
826
827     /* Here, the input is considered to be well-formed , but could be a
828      * problematic code point that is not allowed by the input parameters. */
829     if (uv >= UNICODE_SURROGATE_FIRST /* isn't problematic if < this */
830         && (flags & (UTF8_DISALLOW_ILLEGAL_INTERCHANGE
831                      |UTF8_WARN_ILLEGAL_INTERCHANGE)))
832     {
833         if (UNICODE_IS_SURROGATE(uv)) {
834             if ((flags & (UTF8_WARN_SURROGATE|UTF8_CHECK_ONLY)) == UTF8_WARN_SURROGATE
835                 && ckWARN2_d(WARN_UTF8, WARN_SURROGATE))
836             {
837                 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "UTF-16 surrogate U+%04"UVXf"", uv));
838                 pack_warn = packWARN2(WARN_UTF8, WARN_SURROGATE);
839             }
840             if (flags & UTF8_DISALLOW_SURROGATE) {
841                 goto disallowed;
842             }
843         }
844         else if ((uv > PERL_UNICODE_MAX)) {
845             if ((flags & (UTF8_WARN_SUPER|UTF8_CHECK_ONLY)) == UTF8_WARN_SUPER
846                 && ckWARN2_d(WARN_UTF8, WARN_NON_UNICODE))
847             {
848                 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "Code point 0x%04"UVXf" is not Unicode, may not be portable", uv));
849                 pack_warn = packWARN2(WARN_UTF8, WARN_NON_UNICODE);
850             }
851             if (flags & UTF8_DISALLOW_SUPER) {
852                 goto disallowed;
853             }
854         }
855         else if (UNICODE_IS_NONCHAR(uv)) {
856             if ((flags & (UTF8_WARN_NONCHAR|UTF8_CHECK_ONLY)) == UTF8_WARN_NONCHAR
857                 && ckWARN2_d(WARN_UTF8, WARN_NONCHAR))
858             {
859                 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "Unicode non-character U+%04"UVXf" is illegal for open interchange", uv));
860                 pack_warn = packWARN2(WARN_UTF8, WARN_NONCHAR);
861             }
862             if (flags & UTF8_DISALLOW_NONCHAR) {
863                 goto disallowed;
864             }
865         }
866
867         if (sv) {
868             outlier_ret = uv;   /* Note we don't bother to convert to native,
869                                    as all the outlier code points are the same
870                                    in both ASCII and EBCDIC */
871             goto do_warn;
872         }
873
874         /* Here, this is not considered a malformed character, so drop through
875          * to return it */
876     }
877
878     return UNI_TO_NATIVE(uv);
879
880     /* There are three cases which get to beyond this point.  In all 3 cases:
881      * <sv>         if not null points to a string to print as a warning.
882      * <curlen>     is what <*retlen> should be set to if UTF8_CHECK_ONLY isn't
883      *              set.
884      * <outlier_ret> is what return value to use if UTF8_CHECK_ONLY isn't set.
885      *              This is done by initializing it to 0, and changing it only
886      *              for case 1).
887      * The 3 cases are:
888      * 1)   The input is valid but problematic, and to be warned about.  The
889      *      return value is the resultant code point; <*retlen> is set to
890      *      <curlen>, the number of bytes that comprise the code point.
891      *      <pack_warn> contains the result of packWARN() for the warning
892      *      types.  The entry point for this case is the label <do_warn>;
893      * 2)   The input is a valid code point but disallowed by the parameters to
894      *      this function.  The return value is 0.  If UTF8_CHECK_ONLY is set,
895      *      <*relen> is -1; otherwise it is <curlen>, the number of bytes that
896      *      comprise the code point.  <pack_warn> contains the result of
897      *      packWARN() for the warning types.  The entry point for this case is
898      *      the label <disallowed>.
899      * 3)   The input is malformed.  The return value is 0.  If UTF8_CHECK_ONLY
900      *      is set, <*relen> is -1; otherwise it is <curlen>, the number of
901      *      bytes that comprise the malformation.  All such malformations are
902      *      assumed to be warning type <utf8>.  The entry point for this case
903      *      is the label <malformed>.
904      */
905
906 malformed:
907
908     if (sv && ckWARN_d(WARN_UTF8)) {
909         pack_warn = packWARN(WARN_UTF8);
910     }
911
912 disallowed:
913
914     if (flags & UTF8_CHECK_ONLY) {
915         if (retlen)
916             *retlen = ((STRLEN) -1);
917         return 0;
918     }
919
920 do_warn:
921
922     if (pack_warn) {    /* <pack_warn> was initialized to 0, and changed only
923                            if warnings are to be raised. */
924         const char * const string = SvPVX_const(sv);
925
926         if (PL_op)
927             Perl_warner(aTHX_ pack_warn, "%s in %s", string,  OP_DESC(PL_op));
928         else
929             Perl_warner(aTHX_ pack_warn, "%s", string);
930     }
931
932     if (retlen) {
933         *retlen = curlen;
934     }
935
936     return outlier_ret;
937 }
938
939 /*
940 =for apidoc utf8_to_uvchr_buf
941
942 Returns the native code point of the first character in the string C<s> which
943 is assumed to be in UTF-8 encoding; C<send> points to 1 beyond the end of C<s>.
944 C<*retlen> will be set to the length, in bytes, of that character.
945
946 If C<s> does not point to a well-formed UTF-8 character and UTF8 warnings are
947 enabled, zero is returned and C<*retlen> is set (if C<retlen> isn't
948 NULL) to -1.  If those warnings are off, the computed value, if well-defined
949 (or the Unicode REPLACEMENT CHARACTER if not), is silently returned, and
950 C<*retlen> is set (if C<retlen> isn't NULL) so that (S<C<s> + C<*retlen>>) is
951 the next possible position in C<s> that could begin a non-malformed character.
952 See L</utf8n_to_uvchr> for details on when the REPLACEMENT CHARACTER is
953 returned.
954
955 =cut
956 */
957
958
959 UV
960 Perl_utf8_to_uvchr_buf(pTHX_ const U8 *s, const U8 *send, STRLEN *retlen)
961 {
962     assert(s < send);
963
964     return utf8n_to_uvchr(s, send - s, retlen,
965                           ckWARN_d(WARN_UTF8) ? 0 : UTF8_ALLOW_ANY);
966 }
967
968 /* Like L</utf8_to_uvchr_buf>(), but should only be called when it is known that
969  * there are no malformations in the input UTF-8 string C<s>.  surrogates,
970  * non-character code points, and non-Unicode code points are allowed. */
971
972 UV
973 Perl_valid_utf8_to_uvchr(pTHX_ const U8 *s, STRLEN *retlen)
974 {
975     UV expectlen = UTF8SKIP(s);
976     const U8* send = s + expectlen;
977     UV uv = *s;
978
979     PERL_ARGS_ASSERT_VALID_UTF8_TO_UVCHR;
980
981     if (retlen) {
982         *retlen = expectlen;
983     }
984
985     /* An invariant is trivially returned */
986     if (expectlen == 1) {
987         return uv;
988     }
989
990 #ifdef EBCDIC
991     uv = NATIVE_UTF8_TO_I8(uv);
992 #endif
993
994     /* Remove the leading bits that indicate the number of bytes, leaving just
995      * the bits that are part of the value */
996     uv &= UTF_START_MASK(expectlen);
997
998     /* Now, loop through the remaining bytes, accumulating each into the
999      * working total as we go.  (I khw tried unrolling the loop for up to 4
1000      * bytes, but there was no performance improvement) */
1001     for (++s; s < send; s++) {
1002         uv = UTF8_ACCUMULATE(uv, *s);
1003     }
1004
1005     return UNI_TO_NATIVE(uv);
1006
1007 }
1008
1009 /*
1010 =for apidoc utf8_to_uvchr
1011
1012 Returns the native code point of the first character in the string C<s>
1013 which is assumed to be in UTF-8 encoding; C<retlen> will be set to the
1014 length, in bytes, of that character.
1015
1016 Some, but not all, UTF-8 malformations are detected, and in fact, some
1017 malformed input could cause reading beyond the end of the input buffer, which
1018 is why this function is deprecated.  Use L</utf8_to_uvchr_buf> instead.
1019
1020 If C<s> points to one of the detected malformations, and UTF8 warnings are
1021 enabled, zero is returned and C<*retlen> is set (if C<retlen> isn't
1022 NULL) to -1.  If those warnings are off, the computed value if well-defined (or
1023 the Unicode REPLACEMENT CHARACTER, if not) is silently returned, and C<*retlen>
1024 is set (if C<retlen> isn't NULL) so that (S<C<s> + C<*retlen>>) is the
1025 next possible position in C<s> that could begin a non-malformed character.
1026 See L</utf8n_to_uvchr> for details on when the REPLACEMENT CHARACTER is returned.
1027
1028 =cut
1029 */
1030
1031 UV
1032 Perl_utf8_to_uvchr(pTHX_ const U8 *s, STRLEN *retlen)
1033 {
1034     PERL_ARGS_ASSERT_UTF8_TO_UVCHR;
1035
1036     return utf8_to_uvchr_buf(s, s + UTF8_MAXBYTES, retlen);
1037 }
1038
1039 /*
1040 =for apidoc utf8_to_uvuni_buf
1041
1042 Only in very rare circumstances should code need to be dealing in Unicode
1043 (as opposed to native) code points.  In those few cases, use
1044 C<L<NATIVE_TO_UNI(utf8_to_uvchr_buf(...))|/utf8_to_uvchr_buf>> instead.
1045
1046 Returns the Unicode (not-native) code point of the first character in the
1047 string C<s> which
1048 is assumed to be in UTF-8 encoding; C<send> points to 1 beyond the end of C<s>.
1049 C<retlen> will be set to the length, in bytes, of that character.
1050
1051 If C<s> does not point to a well-formed UTF-8 character and UTF8 warnings are
1052 enabled, zero is returned and C<*retlen> is set (if C<retlen> isn't
1053 NULL) to -1.  If those warnings are off, the computed value if well-defined (or
1054 the Unicode REPLACEMENT CHARACTER, if not) is silently returned, and C<*retlen>
1055 is set (if C<retlen> isn't NULL) so that (S<C<s> + C<*retlen>>) is the
1056 next possible position in C<s> that could begin a non-malformed character.
1057 See L</utf8n_to_uvchr> for details on when the REPLACEMENT CHARACTER is returned.
1058
1059 =cut
1060 */
1061
1062 UV
1063 Perl_utf8_to_uvuni_buf(pTHX_ const U8 *s, const U8 *send, STRLEN *retlen)
1064 {
1065     PERL_ARGS_ASSERT_UTF8_TO_UVUNI_BUF;
1066
1067     assert(send > s);
1068
1069     /* Call the low level routine asking for checks */
1070     return NATIVE_TO_UNI(Perl_utf8n_to_uvchr(aTHX_ s, send -s, retlen,
1071                                ckWARN_d(WARN_UTF8) ? 0 : UTF8_ALLOW_ANY));
1072 }
1073
1074 /* DEPRECATED!
1075  * Like L</utf8_to_uvuni_buf>(), but should only be called when it is known that
1076  * there are no malformations in the input UTF-8 string C<s>.  Surrogates,
1077  * non-character code points, and non-Unicode code points are allowed */
1078
1079 UV
1080 Perl_valid_utf8_to_uvuni(pTHX_ const U8 *s, STRLEN *retlen)
1081 {
1082     PERL_ARGS_ASSERT_VALID_UTF8_TO_UVUNI;
1083
1084     return NATIVE_TO_UNI(valid_utf8_to_uvchr(s, retlen));
1085 }
1086
1087 /*
1088 =for apidoc utf8_to_uvuni
1089
1090 Returns the Unicode code point of the first character in the string C<s>
1091 which is assumed to be in UTF-8 encoding; C<retlen> will be set to the
1092 length, in bytes, of that character.
1093
1094 Some, but not all, UTF-8 malformations are detected, and in fact, some
1095 malformed input could cause reading beyond the end of the input buffer, which
1096 is one reason why this function is deprecated.  The other is that only in
1097 extremely limited circumstances should the Unicode versus native code point be
1098 of any interest to you.  See L</utf8_to_uvuni_buf> for alternatives.
1099
1100 If C<s> points to one of the detected malformations, and UTF8 warnings are
1101 enabled, zero is returned and C<*retlen> is set (if C<retlen> doesn't point to
1102 NULL) to -1.  If those warnings are off, the computed value if well-defined (or
1103 the Unicode REPLACEMENT CHARACTER, if not) is silently returned, and C<*retlen>
1104 is set (if C<retlen> isn't NULL) so that (S<C<s> + C<*retlen>>) is the
1105 next possible position in C<s> that could begin a non-malformed character.
1106 See L</utf8n_to_uvchr> for details on when the REPLACEMENT CHARACTER is returned.
1107
1108 =cut
1109 */
1110
1111 UV
1112 Perl_utf8_to_uvuni(pTHX_ const U8 *s, STRLEN *retlen)
1113 {
1114     PERL_ARGS_ASSERT_UTF8_TO_UVUNI;
1115
1116     return NATIVE_TO_UNI(valid_utf8_to_uvchr(s, retlen));
1117 }
1118
1119 /*
1120 =for apidoc utf8_length
1121
1122 Return the length of the UTF-8 char encoded string C<s> in characters.
1123 Stops at C<e> (inclusive).  If C<e E<lt> s> or if the scan would end
1124 up past C<e>, croaks.
1125
1126 =cut
1127 */
1128
1129 STRLEN
1130 Perl_utf8_length(pTHX_ const U8 *s, const U8 *e)
1131 {
1132     dVAR;
1133     STRLEN len = 0;
1134
1135     PERL_ARGS_ASSERT_UTF8_LENGTH;
1136
1137     /* Note: cannot use UTF8_IS_...() too eagerly here since e.g.
1138      * the bitops (especially ~) can create illegal UTF-8.
1139      * In other words: in Perl UTF-8 is not just for Unicode. */
1140
1141     if (e < s)
1142         goto warn_and_return;
1143     while (s < e) {
1144         s += UTF8SKIP(s);
1145         len++;
1146     }
1147
1148     if (e != s) {
1149         len--;
1150         warn_and_return:
1151         if (PL_op)
1152             Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
1153                              "%s in %s", unees, OP_DESC(PL_op));
1154         else
1155             Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8), "%s", unees);
1156     }
1157
1158     return len;
1159 }
1160
1161 /*
1162 =for apidoc utf8_distance
1163
1164 Returns the number of UTF-8 characters between the UTF-8 pointers C<a>
1165 and C<b>.
1166
1167 WARNING: use only if you *know* that the pointers point inside the
1168 same UTF-8 buffer.
1169
1170 =cut
1171 */
1172
1173 IV
1174 Perl_utf8_distance(pTHX_ const U8 *a, const U8 *b)
1175 {
1176     PERL_ARGS_ASSERT_UTF8_DISTANCE;
1177
1178     return (a < b) ? -1 * (IV) utf8_length(a, b) : (IV) utf8_length(b, a);
1179 }
1180
1181 /*
1182 =for apidoc utf8_hop
1183
1184 Return the UTF-8 pointer C<s> displaced by C<off> characters, either
1185 forward or backward.
1186
1187 WARNING: do not use the following unless you *know* C<off> is within
1188 the UTF-8 data pointed to by C<s> *and* that on entry C<s> is aligned
1189 on the first byte of character or just after the last byte of a character.
1190
1191 =cut
1192 */
1193
1194 U8 *
1195 Perl_utf8_hop(pTHX_ const U8 *s, I32 off)
1196 {
1197     PERL_ARGS_ASSERT_UTF8_HOP;
1198
1199     PERL_UNUSED_CONTEXT;
1200     /* Note: cannot use UTF8_IS_...() too eagerly here since e.g
1201      * the bitops (especially ~) can create illegal UTF-8.
1202      * In other words: in Perl UTF-8 is not just for Unicode. */
1203
1204     if (off >= 0) {
1205         while (off--)
1206             s += UTF8SKIP(s);
1207     }
1208     else {
1209         while (off++) {
1210             s--;
1211             while (UTF8_IS_CONTINUATION(*s))
1212                 s--;
1213         }
1214     }
1215     return (U8 *)s;
1216 }
1217
1218 /*
1219 =for apidoc bytes_cmp_utf8
1220
1221 Compares the sequence of characters (stored as octets) in C<b>, C<blen> with the
1222 sequence of characters (stored as UTF-8) in C<u>, C<ulen>. Returns 0 if they are
1223 equal, -1 or -2 if the first string is less than the second string, +1 or +2
1224 if the first string is greater than the second string.
1225
1226 -1 or +1 is returned if the shorter string was identical to the start of the
1227 longer string. -2 or +2 is returned if the was a difference between characters
1228 within the strings.
1229
1230 =cut
1231 */
1232
1233 int
1234 Perl_bytes_cmp_utf8(pTHX_ const U8 *b, STRLEN blen, const U8 *u, STRLEN ulen)
1235 {
1236     const U8 *const bend = b + blen;
1237     const U8 *const uend = u + ulen;
1238
1239     PERL_ARGS_ASSERT_BYTES_CMP_UTF8;
1240
1241     PERL_UNUSED_CONTEXT;
1242
1243     while (b < bend && u < uend) {
1244         U8 c = *u++;
1245         if (!UTF8_IS_INVARIANT(c)) {
1246             if (UTF8_IS_DOWNGRADEABLE_START(c)) {
1247                 if (u < uend) {
1248                     U8 c1 = *u++;
1249                     if (UTF8_IS_CONTINUATION(c1)) {
1250                         c = TWO_BYTE_UTF8_TO_NATIVE(c, c1);
1251                     } else {
1252                         Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
1253                                          "Malformed UTF-8 character "
1254                                          "(unexpected non-continuation byte 0x%02x"
1255                                          ", immediately after start byte 0x%02x)"
1256                                          /* Dear diag.t, it's in the pod.  */
1257                                          "%s%s", c1, c,
1258                                          PL_op ? " in " : "",
1259                                          PL_op ? OP_DESC(PL_op) : "");
1260                         return -2;
1261                     }
1262                 } else {
1263                     if (PL_op)
1264                         Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
1265                                          "%s in %s", unees, OP_DESC(PL_op));
1266                     else
1267                         Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8), "%s", unees);
1268                     return -2; /* Really want to return undef :-)  */
1269                 }
1270             } else {
1271                 return -2;
1272             }
1273         }
1274         if (*b != c) {
1275             return *b < c ? -2 : +2;
1276         }
1277         ++b;
1278     }
1279
1280     if (b == bend && u == uend)
1281         return 0;
1282
1283     return b < bend ? +1 : -1;
1284 }
1285
1286 /*
1287 =for apidoc utf8_to_bytes
1288
1289 Converts a string C<s> of length C<len> from UTF-8 into native byte encoding.
1290 Unlike L</bytes_to_utf8>, this over-writes the original string, and
1291 updates C<len> to contain the new length.
1292 Returns zero on failure, setting C<len> to -1.
1293
1294 If you need a copy of the string, see L</bytes_from_utf8>.
1295
1296 =cut
1297 */
1298
1299 U8 *
1300 Perl_utf8_to_bytes(pTHX_ U8 *s, STRLEN *len)
1301 {
1302     U8 * const save = s;
1303     U8 * const send = s + *len;
1304     U8 *d;
1305
1306     PERL_ARGS_ASSERT_UTF8_TO_BYTES;
1307
1308     /* ensure valid UTF-8 and chars < 256 before updating string */
1309     while (s < send) {
1310         if (! UTF8_IS_INVARIANT(*s)) {
1311             if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(s, send)) {
1312                 *len = ((STRLEN) -1);
1313                 return 0;
1314             }
1315             s++;
1316         }
1317         s++;
1318     }
1319
1320     d = s = save;
1321     while (s < send) {
1322         U8 c = *s++;
1323         if (! UTF8_IS_INVARIANT(c)) {
1324             /* Then it is two-byte encoded */
1325             c = TWO_BYTE_UTF8_TO_NATIVE(c, *s);
1326             s++;
1327         }
1328         *d++ = c;
1329     }
1330     *d = '\0';
1331     *len = d - save;
1332     return save;
1333 }
1334
1335 /*
1336 =for apidoc bytes_from_utf8
1337
1338 Converts a string C<s> of length C<len> from UTF-8 into native byte encoding.
1339 Unlike L</utf8_to_bytes> but like L</bytes_to_utf8>, returns a pointer to
1340 the newly-created string, and updates C<len> to contain the new
1341 length.  Returns the original string if no conversion occurs, C<len>
1342 is unchanged. Do nothing if C<is_utf8> points to 0. Sets C<is_utf8> to
1343 0 if C<s> is converted or consisted entirely of characters that are invariant
1344 in utf8 (i.e., US-ASCII on non-EBCDIC machines).
1345
1346 =cut
1347 */
1348
1349 U8 *
1350 Perl_bytes_from_utf8(pTHX_ const U8 *s, STRLEN *len, bool *is_utf8)
1351 {
1352     U8 *d;
1353     const U8 *start = s;
1354     const U8 *send;
1355     I32 count = 0;
1356
1357     PERL_ARGS_ASSERT_BYTES_FROM_UTF8;
1358
1359     PERL_UNUSED_CONTEXT;
1360     if (!*is_utf8)
1361         return (U8 *)start;
1362
1363     /* ensure valid UTF-8 and chars < 256 before converting string */
1364     for (send = s + *len; s < send;) {
1365         if (! UTF8_IS_INVARIANT(*s)) {
1366             if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(s, send)) {
1367                 return (U8 *)start;
1368             }
1369             count++;
1370             s++;
1371         }
1372         s++;
1373     }
1374
1375     *is_utf8 = FALSE;
1376
1377     Newx(d, (*len) - count + 1, U8);
1378     s = start; start = d;
1379     while (s < send) {
1380         U8 c = *s++;
1381         if (! UTF8_IS_INVARIANT(c)) {
1382             /* Then it is two-byte encoded */
1383             c = TWO_BYTE_UTF8_TO_NATIVE(c, *s);
1384             s++;
1385         }
1386         *d++ = c;
1387     }
1388     *d = '\0';
1389     *len = d - start;
1390     return (U8 *)start;
1391 }
1392
1393 /*
1394 =for apidoc bytes_to_utf8
1395
1396 Converts a string C<s> of length C<len> bytes from the native encoding into
1397 UTF-8.
1398 Returns a pointer to the newly-created string, and sets C<len> to
1399 reflect the new length in bytes.
1400
1401 A NUL character will be written after the end of the string.
1402
1403 If you want to convert to UTF-8 from encodings other than
1404 the native (Latin1 or EBCDIC),
1405 see L</sv_recode_to_utf8>().
1406
1407 =cut
1408 */
1409
1410 /* This logic is duplicated in sv_catpvn_flags, so any bug fixes will
1411    likewise need duplication. */
1412
1413 U8*
1414 Perl_bytes_to_utf8(pTHX_ const U8 *s, STRLEN *len)
1415 {
1416     const U8 * const send = s + (*len);
1417     U8 *d;
1418     U8 *dst;
1419
1420     PERL_ARGS_ASSERT_BYTES_TO_UTF8;
1421     PERL_UNUSED_CONTEXT;
1422
1423     Newx(d, (*len) * 2 + 1, U8);
1424     dst = d;
1425
1426     while (s < send) {
1427         append_utf8_from_native_byte(*s, &d);
1428         s++;
1429     }
1430     *d = '\0';
1431     *len = d-dst;
1432     return dst;
1433 }
1434
1435 /*
1436  * Convert native (big-endian) or reversed (little-endian) UTF-16 to UTF-8.
1437  *
1438  * Destination must be pre-extended to 3/2 source.  Do not use in-place.
1439  * We optimize for native, for obvious reasons. */
1440
1441 U8*
1442 Perl_utf16_to_utf8(pTHX_ U8* p, U8* d, I32 bytelen, I32 *newlen)
1443 {
1444     U8* pend;
1445     U8* dstart = d;
1446
1447     PERL_ARGS_ASSERT_UTF16_TO_UTF8;
1448
1449     if (bytelen & 1)
1450         Perl_croak(aTHX_ "panic: utf16_to_utf8: odd bytelen %"UVuf, (UV)bytelen);
1451
1452     pend = p + bytelen;
1453
1454     while (p < pend) {
1455         UV uv = (p[0] << 8) + p[1]; /* UTF-16BE */
1456         p += 2;
1457         if (UNI_IS_INVARIANT(uv)) {
1458             *d++ = LATIN1_TO_NATIVE((U8) uv);
1459             continue;
1460         }
1461         if (uv <= MAX_UTF8_TWO_BYTE) {
1462             *d++ = UTF8_TWO_BYTE_HI(UNI_TO_NATIVE(uv));
1463             *d++ = UTF8_TWO_BYTE_LO(UNI_TO_NATIVE(uv));
1464             continue;
1465         }
1466 #define FIRST_HIGH_SURROGATE UNICODE_SURROGATE_FIRST
1467 #define LAST_HIGH_SURROGATE  0xDBFF
1468 #define FIRST_LOW_SURROGATE  0xDC00
1469 #define LAST_LOW_SURROGATE   UNICODE_SURROGATE_LAST
1470         if (uv >= FIRST_HIGH_SURROGATE && uv <= LAST_HIGH_SURROGATE) {
1471             if (p >= pend) {
1472                 Perl_croak(aTHX_ "Malformed UTF-16 surrogate");
1473             } else {
1474                 UV low = (p[0] << 8) + p[1];
1475                 p += 2;
1476                 if (low < FIRST_LOW_SURROGATE || low > LAST_LOW_SURROGATE)
1477                     Perl_croak(aTHX_ "Malformed UTF-16 surrogate");
1478                 uv = ((uv - FIRST_HIGH_SURROGATE) << 10)
1479                                        + (low - FIRST_LOW_SURROGATE) + 0x10000;
1480             }
1481         } else if (uv >= FIRST_LOW_SURROGATE && uv <= LAST_LOW_SURROGATE) {
1482             Perl_croak(aTHX_ "Malformed UTF-16 surrogate");
1483         }
1484 #ifdef EBCDIC
1485         d = uvoffuni_to_utf8_flags(d, uv, 0);
1486 #else
1487         if (uv < 0x10000) {
1488             *d++ = (U8)(( uv >> 12)         | 0xe0);
1489             *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
1490             *d++ = (U8)(( uv        & 0x3f) | 0x80);
1491             continue;
1492         }
1493         else {
1494             *d++ = (U8)(( uv >> 18)         | 0xf0);
1495             *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
1496             *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
1497             *d++ = (U8)(( uv        & 0x3f) | 0x80);
1498             continue;
1499         }
1500 #endif
1501     }
1502     *newlen = d - dstart;
1503     return d;
1504 }
1505
1506 /* Note: this one is slightly destructive of the source. */
1507
1508 U8*
1509 Perl_utf16_to_utf8_reversed(pTHX_ U8* p, U8* d, I32 bytelen, I32 *newlen)
1510 {
1511     U8* s = (U8*)p;
1512     U8* const send = s + bytelen;
1513
1514     PERL_ARGS_ASSERT_UTF16_TO_UTF8_REVERSED;
1515
1516     if (bytelen & 1)
1517         Perl_croak(aTHX_ "panic: utf16_to_utf8_reversed: odd bytelen %"UVuf,
1518                    (UV)bytelen);
1519
1520     while (s < send) {
1521         const U8 tmp = s[0];
1522         s[0] = s[1];
1523         s[1] = tmp;
1524         s += 2;
1525     }
1526     return utf16_to_utf8(p, d, bytelen, newlen);
1527 }
1528
1529 bool
1530 Perl__is_uni_FOO(pTHX_ const U8 classnum, const UV c)
1531 {
1532     U8 tmpbuf[UTF8_MAXBYTES+1];
1533     uvchr_to_utf8(tmpbuf, c);
1534     return _is_utf8_FOO(classnum, tmpbuf);
1535 }
1536
1537 /* for now these are all defined (inefficiently) in terms of the utf8 versions.
1538  * Note that the macros in handy.h that call these short-circuit calling them
1539  * for Latin-1 range inputs */
1540
1541 bool
1542 Perl_is_uni_alnum(pTHX_ UV c)
1543 {
1544     U8 tmpbuf[UTF8_MAXBYTES+1];
1545     uvchr_to_utf8(tmpbuf, c);
1546     return _is_utf8_FOO(_CC_WORDCHAR, tmpbuf);
1547 }
1548
1549 bool
1550 Perl_is_uni_alnumc(pTHX_ UV c)
1551 {
1552     U8 tmpbuf[UTF8_MAXBYTES+1];
1553     uvchr_to_utf8(tmpbuf, c);
1554     return _is_utf8_FOO(_CC_ALPHANUMERIC, tmpbuf);
1555 }
1556
1557 /* Internal function so we can deprecate the external one, and call
1558    this one from other deprecated functions in this file */
1559
1560 PERL_STATIC_INLINE bool
1561 S_is_utf8_idfirst(pTHX_ const U8 *p)
1562 {
1563     dVAR;
1564
1565     if (*p == '_')
1566         return TRUE;
1567     /* is_utf8_idstart would be more logical. */
1568     return is_utf8_common(p, &PL_utf8_idstart, "IdStart");
1569 }
1570
1571 bool
1572 Perl_is_uni_idfirst(pTHX_ UV c)
1573 {
1574     U8 tmpbuf[UTF8_MAXBYTES+1];
1575     uvchr_to_utf8(tmpbuf, c);
1576     return S_is_utf8_idfirst(aTHX_ tmpbuf);
1577 }
1578
1579 bool
1580 Perl__is_uni_perl_idcont(pTHX_ UV c)
1581 {
1582     U8 tmpbuf[UTF8_MAXBYTES+1];
1583     uvchr_to_utf8(tmpbuf, c);
1584     return _is_utf8_perl_idcont(tmpbuf);
1585 }
1586
1587 bool
1588 Perl__is_uni_perl_idstart(pTHX_ UV c)
1589 {
1590     U8 tmpbuf[UTF8_MAXBYTES+1];
1591     uvchr_to_utf8(tmpbuf, c);
1592     return _is_utf8_perl_idstart(tmpbuf);
1593 }
1594
1595 bool
1596 Perl_is_uni_alpha(pTHX_ UV c)
1597 {
1598     U8 tmpbuf[UTF8_MAXBYTES+1];
1599     uvchr_to_utf8(tmpbuf, c);
1600     return _is_utf8_FOO(_CC_ALPHA, tmpbuf);
1601 }
1602
1603 bool
1604 Perl_is_uni_ascii(pTHX_ UV c)
1605 {
1606     return isASCII(c);
1607 }
1608
1609 bool
1610 Perl_is_uni_blank(pTHX_ UV c)
1611 {
1612     return isBLANK_uni(c);
1613 }
1614
1615 bool
1616 Perl_is_uni_space(pTHX_ UV c)
1617 {
1618     return isSPACE_uni(c);
1619 }
1620
1621 bool
1622 Perl_is_uni_digit(pTHX_ UV c)
1623 {
1624     U8 tmpbuf[UTF8_MAXBYTES+1];
1625     uvchr_to_utf8(tmpbuf, c);
1626     return _is_utf8_FOO(_CC_DIGIT, tmpbuf);
1627 }
1628
1629 bool
1630 Perl_is_uni_upper(pTHX_ UV c)
1631 {
1632     U8 tmpbuf[UTF8_MAXBYTES+1];
1633     uvchr_to_utf8(tmpbuf, c);
1634     return _is_utf8_FOO(_CC_UPPER, tmpbuf);
1635 }
1636
1637 bool
1638 Perl_is_uni_lower(pTHX_ UV c)
1639 {
1640     U8 tmpbuf[UTF8_MAXBYTES+1];
1641     uvchr_to_utf8(tmpbuf, c);
1642     return _is_utf8_FOO(_CC_LOWER, tmpbuf);
1643 }
1644
1645 bool
1646 Perl_is_uni_cntrl(pTHX_ UV c)
1647 {
1648     return isCNTRL_L1(c);
1649 }
1650
1651 bool
1652 Perl_is_uni_graph(pTHX_ UV c)
1653 {
1654     U8 tmpbuf[UTF8_MAXBYTES+1];
1655     uvchr_to_utf8(tmpbuf, c);
1656     return _is_utf8_FOO(_CC_GRAPH, tmpbuf);
1657 }
1658
1659 bool
1660 Perl_is_uni_print(pTHX_ UV c)
1661 {
1662     U8 tmpbuf[UTF8_MAXBYTES+1];
1663     uvchr_to_utf8(tmpbuf, c);
1664     return _is_utf8_FOO(_CC_PRINT, tmpbuf);
1665 }
1666
1667 bool
1668 Perl_is_uni_punct(pTHX_ UV c)
1669 {
1670     U8 tmpbuf[UTF8_MAXBYTES+1];
1671     uvchr_to_utf8(tmpbuf, c);
1672     return _is_utf8_FOO(_CC_PUNCT, tmpbuf);
1673 }
1674
1675 bool
1676 Perl_is_uni_xdigit(pTHX_ UV c)
1677 {
1678     return isXDIGIT_uni(c);
1679 }
1680
1681 UV
1682 Perl__to_upper_title_latin1(pTHX_ const U8 c, U8* p, STRLEN *lenp, const char S_or_s)
1683 {
1684     /* We have the latin1-range values compiled into the core, so just use
1685      * those, converting the result to utf8.  The only difference between upper
1686      * and title case in this range is that LATIN_SMALL_LETTER_SHARP_S is
1687      * either "SS" or "Ss".  Which one to use is passed into the routine in
1688      * 'S_or_s' to avoid a test */
1689
1690     UV converted = toUPPER_LATIN1_MOD(c);
1691
1692     PERL_ARGS_ASSERT__TO_UPPER_TITLE_LATIN1;
1693
1694     assert(S_or_s == 'S' || S_or_s == 's');
1695
1696     if (UVCHR_IS_INVARIANT(converted)) { /* No difference between the two for
1697                                              characters in this range */
1698         *p = (U8) converted;
1699         *lenp = 1;
1700         return converted;
1701     }
1702
1703     /* toUPPER_LATIN1_MOD gives the correct results except for three outliers,
1704      * which it maps to one of them, so as to only have to have one check for
1705      * it in the main case */
1706     if (UNLIKELY(converted == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
1707         switch (c) {
1708             case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
1709                 converted = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
1710                 break;
1711             case MICRO_SIGN:
1712                 converted = GREEK_CAPITAL_LETTER_MU;
1713                 break;
1714             case LATIN_SMALL_LETTER_SHARP_S:
1715                 *(p)++ = 'S';
1716                 *p = S_or_s;
1717                 *lenp = 2;
1718                 return 'S';
1719             default:
1720                 Perl_croak(aTHX_ "panic: to_upper_title_latin1 did not expect '%c' to map to '%c'", c, LATIN_SMALL_LETTER_Y_WITH_DIAERESIS);
1721                 assert(0); /* NOTREACHED */
1722         }
1723     }
1724
1725     *(p)++ = UTF8_TWO_BYTE_HI(converted);
1726     *p = UTF8_TWO_BYTE_LO(converted);
1727     *lenp = 2;
1728
1729     return converted;
1730 }
1731
1732 /* Call the function to convert a UTF-8 encoded character to the specified case.
1733  * Note that there may be more than one character in the result.
1734  * INP is a pointer to the first byte of the input character
1735  * OUTP will be set to the first byte of the string of changed characters.  It
1736  *      needs to have space for UTF8_MAXBYTES_CASE+1 bytes
1737  * LENP will be set to the length in bytes of the string of changed characters
1738  *
1739  * The functions return the ordinal of the first character in the string of OUTP */
1740 #define CALL_UPPER_CASE(INP, OUTP, LENP) Perl_to_utf8_case(aTHX_ INP, OUTP, LENP, &PL_utf8_toupper, "ToUc", "utf8::ToSpecUc")
1741 #define CALL_TITLE_CASE(INP, OUTP, LENP) Perl_to_utf8_case(aTHX_ INP, OUTP, LENP, &PL_utf8_totitle, "ToTc", "utf8::ToSpecTc")
1742 #define CALL_LOWER_CASE(INP, OUTP, LENP) Perl_to_utf8_case(aTHX_ INP, OUTP, LENP, &PL_utf8_tolower, "ToLc", "utf8::ToSpecLc")
1743
1744 /* This additionally has the input parameter SPECIALS, which if non-zero will
1745  * cause this to use the SPECIALS hash for folding (meaning get full case
1746  * folding); otherwise, when zero, this implies a simple case fold */
1747 #define CALL_FOLD_CASE(INP, OUTP, LENP, SPECIALS) Perl_to_utf8_case(aTHX_ INP, OUTP, LENP, &PL_utf8_tofold, "ToCf", (SPECIALS) ? "utf8::ToSpecCf" : NULL)
1748
1749 UV
1750 Perl_to_uni_upper(pTHX_ UV c, U8* p, STRLEN *lenp)
1751 {
1752     dVAR;
1753
1754     /* Convert the Unicode character whose ordinal is <c> to its uppercase
1755      * version and store that in UTF-8 in <p> and its length in bytes in <lenp>.
1756      * Note that the <p> needs to be at least UTF8_MAXBYTES_CASE+1 bytes since
1757      * the changed version may be longer than the original character.
1758      *
1759      * The ordinal of the first character of the changed version is returned
1760      * (but note, as explained above, that there may be more.) */
1761
1762     PERL_ARGS_ASSERT_TO_UNI_UPPER;
1763
1764     if (c < 256) {
1765         return _to_upper_title_latin1((U8) c, p, lenp, 'S');
1766     }
1767
1768     uvchr_to_utf8(p, c);
1769     return CALL_UPPER_CASE(p, p, lenp);
1770 }
1771
1772 UV
1773 Perl_to_uni_title(pTHX_ UV c, U8* p, STRLEN *lenp)
1774 {
1775     dVAR;
1776
1777     PERL_ARGS_ASSERT_TO_UNI_TITLE;
1778
1779     if (c < 256) {
1780         return _to_upper_title_latin1((U8) c, p, lenp, 's');
1781     }
1782
1783     uvchr_to_utf8(p, c);
1784     return CALL_TITLE_CASE(p, p, lenp);
1785 }
1786
1787 STATIC U8
1788 S_to_lower_latin1(pTHX_ const U8 c, U8* p, STRLEN *lenp)
1789 {
1790     /* We have the latin1-range values compiled into the core, so just use
1791      * those, converting the result to utf8.  Since the result is always just
1792      * one character, we allow <p> to be NULL */
1793
1794     U8 converted = toLOWER_LATIN1(c);
1795
1796     if (p != NULL) {
1797         if (NATIVE_BYTE_IS_INVARIANT(converted)) {
1798             *p = converted;
1799             *lenp = 1;
1800         }
1801         else {
1802             *p = UTF8_TWO_BYTE_HI(converted);
1803             *(p+1) = UTF8_TWO_BYTE_LO(converted);
1804             *lenp = 2;
1805         }
1806     }
1807     return converted;
1808 }
1809
1810 UV
1811 Perl_to_uni_lower(pTHX_ UV c, U8* p, STRLEN *lenp)
1812 {
1813     dVAR;
1814
1815     PERL_ARGS_ASSERT_TO_UNI_LOWER;
1816
1817     if (c < 256) {
1818         return to_lower_latin1((U8) c, p, lenp);
1819     }
1820
1821     uvchr_to_utf8(p, c);
1822     return CALL_LOWER_CASE(p, p, lenp);
1823 }
1824
1825 UV
1826 Perl__to_fold_latin1(pTHX_ const U8 c, U8* p, STRLEN *lenp, const unsigned int flags)
1827 {
1828     /* Corresponds to to_lower_latin1(); <flags> bits meanings:
1829      *      FOLD_FLAGS_NOMIX_ASCII iff non-ASCII to ASCII folds are prohibited
1830      *      FOLD_FLAGS_FULL  iff full folding is to be used;
1831      *
1832      *  Not to be used for locale folds
1833      */
1834
1835     UV converted;
1836
1837     PERL_ARGS_ASSERT__TO_FOLD_LATIN1;
1838
1839     assert (! (flags & FOLD_FLAGS_LOCALE));
1840
1841     if (c == MICRO_SIGN) {
1842         converted = GREEK_SMALL_LETTER_MU;
1843     }
1844     else if ((flags & FOLD_FLAGS_FULL) && c == LATIN_SMALL_LETTER_SHARP_S) {
1845
1846         /* If can't cross 127/128 boundary, can't return "ss"; instead return
1847          * two U+017F characters, as fc("\df") should eq fc("\x{17f}\x{17f}")
1848          * under those circumstances. */
1849         if (flags & FOLD_FLAGS_NOMIX_ASCII) {
1850             *lenp = 2 * sizeof(LATIN_SMALL_LETTER_LONG_S_UTF8) - 2;
1851             Copy(LATIN_SMALL_LETTER_LONG_S_UTF8 LATIN_SMALL_LETTER_LONG_S_UTF8,
1852                  p, *lenp, U8);
1853             return LATIN_SMALL_LETTER_LONG_S;
1854         }
1855         else {
1856             *(p)++ = 's';
1857             *p = 's';
1858             *lenp = 2;
1859             return 's';
1860         }
1861     }
1862     else { /* In this range the fold of all other characters is their lower
1863               case */
1864         converted = toLOWER_LATIN1(c);
1865     }
1866
1867     if (UVCHR_IS_INVARIANT(converted)) {
1868         *p = (U8) converted;
1869         *lenp = 1;
1870     }
1871     else {
1872         *(p)++ = UTF8_TWO_BYTE_HI(converted);
1873         *p = UTF8_TWO_BYTE_LO(converted);
1874         *lenp = 2;
1875     }
1876
1877     return converted;
1878 }
1879
1880 UV
1881 Perl__to_uni_fold_flags(pTHX_ UV c, U8* p, STRLEN *lenp, const U8 flags)
1882 {
1883
1884     /* Not currently externally documented, and subject to change
1885      *  <flags> bits meanings:
1886      *      FOLD_FLAGS_FULL  iff full folding is to be used;
1887      *      FOLD_FLAGS_LOCALE iff in locale
1888      *      FOLD_FLAGS_NOMIX_ASCII iff non-ASCII to ASCII folds are prohibited
1889      */
1890
1891     PERL_ARGS_ASSERT__TO_UNI_FOLD_FLAGS;
1892
1893     if (c < 256) {
1894         UV result = _to_fold_latin1((U8) c, p, lenp,
1895                               flags & (FOLD_FLAGS_FULL | FOLD_FLAGS_NOMIX_ASCII));
1896         /* It is illegal for the fold to cross the 255/256 boundary under
1897          * locale; in this case return the original */
1898         return (result > 256 && flags & FOLD_FLAGS_LOCALE)
1899                ? c
1900                : result;
1901     }
1902
1903     /* If no special needs, just use the macro */
1904     if ( ! (flags & (FOLD_FLAGS_LOCALE|FOLD_FLAGS_NOMIX_ASCII))) {
1905         uvchr_to_utf8(p, c);
1906         return CALL_FOLD_CASE(p, p, lenp, flags & FOLD_FLAGS_FULL);
1907     }
1908     else {  /* Otherwise, _to_utf8_fold_flags has the intelligence to deal with
1909                the special flags. */
1910         U8 utf8_c[UTF8_MAXBYTES + 1];
1911         uvchr_to_utf8(utf8_c, c);
1912         return _to_utf8_fold_flags(utf8_c, p, lenp, flags, NULL);
1913     }
1914 }
1915
1916 bool
1917 Perl_is_uni_alnum_lc(pTHX_ UV c)
1918 {
1919     if (c < 256) {
1920         return isALNUM_LC(c);
1921     }
1922     return _is_uni_FOO(_CC_WORDCHAR, c);
1923 }
1924
1925 bool
1926 Perl_is_uni_alnumc_lc(pTHX_ UV c)
1927 {
1928     if (c < 256) {
1929         return isALPHANUMERIC_LC(c);
1930     }
1931     return _is_uni_FOO(_CC_ALPHANUMERIC, c);
1932 }
1933
1934 bool
1935 Perl_is_uni_idfirst_lc(pTHX_ UV c)
1936 {
1937     if (c < 256) {
1938         return isIDFIRST_LC(c);
1939     }
1940     return _is_uni_perl_idstart(c);
1941 }
1942
1943 bool
1944 Perl_is_uni_alpha_lc(pTHX_ UV c)
1945 {
1946     if (c < 256) {
1947         return isALPHA_LC(c);
1948     }
1949     return _is_uni_FOO(_CC_ALPHA, c);
1950 }
1951
1952 bool
1953 Perl_is_uni_ascii_lc(pTHX_ UV c)
1954 {
1955     if (c < 256) {
1956         return isASCII_LC(c);
1957     }
1958     return 0;
1959 }
1960
1961 bool
1962 Perl_is_uni_blank_lc(pTHX_ UV c)
1963 {
1964     if (c < 256) {
1965         return isBLANK_LC(c);
1966     }
1967     return isBLANK_uni(c);
1968 }
1969
1970 bool
1971 Perl_is_uni_space_lc(pTHX_ UV c)
1972 {
1973     if (c < 256) {
1974         return isSPACE_LC(c);
1975     }
1976     return isSPACE_uni(c);
1977 }
1978
1979 bool
1980 Perl_is_uni_digit_lc(pTHX_ UV c)
1981 {
1982     if (c < 256) {
1983         return isDIGIT_LC(c);
1984     }
1985     return _is_uni_FOO(_CC_DIGIT, c);
1986 }
1987
1988 bool
1989 Perl_is_uni_upper_lc(pTHX_ UV c)
1990 {
1991     if (c < 256) {
1992         return isUPPER_LC(c);
1993     }
1994     return _is_uni_FOO(_CC_UPPER, c);
1995 }
1996
1997 bool
1998 Perl_is_uni_lower_lc(pTHX_ UV c)
1999 {
2000     if (c < 256) {
2001         return isLOWER_LC(c);
2002     }
2003     return _is_uni_FOO(_CC_LOWER, c);
2004 }
2005
2006 bool
2007 Perl_is_uni_cntrl_lc(pTHX_ UV c)
2008 {
2009     if (c < 256) {
2010         return isCNTRL_LC(c);
2011     }
2012     return 0;
2013 }
2014
2015 bool
2016 Perl_is_uni_graph_lc(pTHX_ UV c)
2017 {
2018     if (c < 256) {
2019         return isGRAPH_LC(c);
2020     }
2021     return _is_uni_FOO(_CC_GRAPH, c);
2022 }
2023
2024 bool
2025 Perl_is_uni_print_lc(pTHX_ UV c)
2026 {
2027     if (c < 256) {
2028         return isPRINT_LC(c);
2029     }
2030     return _is_uni_FOO(_CC_PRINT, c);
2031 }
2032
2033 bool
2034 Perl_is_uni_punct_lc(pTHX_ UV c)
2035 {
2036     if (c < 256) {
2037         return isPUNCT_LC(c);
2038     }
2039     return _is_uni_FOO(_CC_PUNCT, c);
2040 }
2041
2042 bool
2043 Perl_is_uni_xdigit_lc(pTHX_ UV c)
2044 {
2045     if (c < 256) {
2046        return isXDIGIT_LC(c);
2047     }
2048     return isXDIGIT_uni(c);
2049 }
2050
2051 U32
2052 Perl_to_uni_upper_lc(pTHX_ U32 c)
2053 {
2054     /* XXX returns only the first character -- do not use XXX */
2055     /* XXX no locale support yet */
2056     STRLEN len;
2057     U8 tmpbuf[UTF8_MAXBYTES_CASE+1];
2058     return (U32)to_uni_upper(c, tmpbuf, &len);
2059 }
2060
2061 U32
2062 Perl_to_uni_title_lc(pTHX_ U32 c)
2063 {
2064     /* XXX returns only the first character XXX -- do not use XXX */
2065     /* XXX no locale support yet */
2066     STRLEN len;
2067     U8 tmpbuf[UTF8_MAXBYTES_CASE+1];
2068     return (U32)to_uni_title(c, tmpbuf, &len);
2069 }
2070
2071 U32
2072 Perl_to_uni_lower_lc(pTHX_ U32 c)
2073 {
2074     /* XXX returns only the first character -- do not use XXX */
2075     /* XXX no locale support yet */
2076     STRLEN len;
2077     U8 tmpbuf[UTF8_MAXBYTES_CASE+1];
2078     return (U32)to_uni_lower(c, tmpbuf, &len);
2079 }
2080
2081 PERL_STATIC_INLINE bool
2082 S_is_utf8_common(pTHX_ const U8 *const p, SV **swash,
2083                  const char *const swashname)
2084 {
2085     /* returns a boolean giving whether or not the UTF8-encoded character that
2086      * starts at <p> is in the swash indicated by <swashname>.  <swash>
2087      * contains a pointer to where the swash indicated by <swashname>
2088      * is to be stored; which this routine will do, so that future calls will
2089      * look at <*swash> and only generate a swash if it is not null
2090      *
2091      * Note that it is assumed that the buffer length of <p> is enough to
2092      * contain all the bytes that comprise the character.  Thus, <*p> should
2093      * have been checked before this call for mal-formedness enough to assure
2094      * that. */
2095
2096     dVAR;
2097
2098     PERL_ARGS_ASSERT_IS_UTF8_COMMON;
2099
2100     /* The API should have included a length for the UTF-8 character in <p>,
2101      * but it doesn't.  We therefore assume that p has been validated at least
2102      * as far as there being enough bytes available in it to accommodate the
2103      * character without reading beyond the end, and pass that number on to the
2104      * validating routine */
2105     if (! is_utf8_char_buf(p, p + UTF8SKIP(p))) {
2106         if (ckWARN_d(WARN_UTF8)) {
2107             Perl_warner(aTHX_ packWARN2(WARN_DEPRECATED,WARN_UTF8),
2108                     "Passing malformed UTF-8 to \"%s\" is deprecated", swashname);
2109             if (ckWARN(WARN_UTF8)) {    /* This will output details as to the
2110                                            what the malformation is */
2111                 utf8_to_uvchr_buf(p, p + UTF8SKIP(p), NULL);
2112             }
2113         }
2114         return FALSE;
2115     }
2116     if (!*swash) {
2117         U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2118         *swash = _core_swash_init("utf8", swashname, &PL_sv_undef, 1, 0, NULL, &flags);
2119     }
2120
2121     return swash_fetch(*swash, p, TRUE) != 0;
2122 }
2123
2124 bool
2125 Perl__is_utf8_FOO(pTHX_ const U8 classnum, const U8 *p)
2126 {
2127     dVAR;
2128
2129     PERL_ARGS_ASSERT__IS_UTF8_FOO;
2130
2131     assert(classnum < _FIRST_NON_SWASH_CC);
2132
2133     return is_utf8_common(p, &PL_utf8_swash_ptrs[classnum], swash_property_names[classnum]);
2134 }
2135
2136 bool
2137 Perl_is_utf8_alnum(pTHX_ const U8 *p)
2138 {
2139     dVAR;
2140
2141     PERL_ARGS_ASSERT_IS_UTF8_ALNUM;
2142
2143     /* NOTE: "IsWord", not "IsAlnum", since Alnum is a true
2144      * descendant of isalnum(3), in other words, it doesn't
2145      * contain the '_'. --jhi */
2146     return is_utf8_common(p, &PL_utf8_swash_ptrs[_CC_WORDCHAR], "IsWord");
2147 }
2148
2149 bool
2150 Perl_is_utf8_alnumc(pTHX_ const U8 *p)
2151 {
2152     dVAR;
2153
2154     PERL_ARGS_ASSERT_IS_UTF8_ALNUMC;
2155
2156     return is_utf8_common(p, &PL_utf8_swash_ptrs[_CC_ALPHANUMERIC], "IsAlnum");
2157 }
2158
2159 bool
2160 Perl_is_utf8_idfirst(pTHX_ const U8 *p) /* The naming is historical. */
2161 {
2162     dVAR;
2163
2164     PERL_ARGS_ASSERT_IS_UTF8_IDFIRST;
2165
2166     return S_is_utf8_idfirst(aTHX_ p);
2167 }
2168
2169 bool
2170 Perl_is_utf8_xidfirst(pTHX_ const U8 *p) /* The naming is historical. */
2171 {
2172     dVAR;
2173
2174     PERL_ARGS_ASSERT_IS_UTF8_XIDFIRST;
2175
2176     if (*p == '_')
2177         return TRUE;
2178     /* is_utf8_idstart would be more logical. */
2179     return is_utf8_common(p, &PL_utf8_xidstart, "XIdStart");
2180 }
2181
2182 bool
2183 Perl__is_utf8_perl_idstart(pTHX_ const U8 *p)
2184 {
2185     dVAR;
2186
2187     PERL_ARGS_ASSERT__IS_UTF8_PERL_IDSTART;
2188
2189     return is_utf8_common(p, &PL_utf8_perl_idstart, "_Perl_IDStart");
2190 }
2191
2192 bool
2193 Perl__is_utf8_perl_idcont(pTHX_ const U8 *p)
2194 {
2195     dVAR;
2196
2197     PERL_ARGS_ASSERT__IS_UTF8_PERL_IDCONT;
2198
2199     return is_utf8_common(p, &PL_utf8_perl_idcont, "_Perl_IDCont");
2200 }
2201
2202
2203 bool
2204 Perl_is_utf8_idcont(pTHX_ const U8 *p)
2205 {
2206     dVAR;
2207
2208     PERL_ARGS_ASSERT_IS_UTF8_IDCONT;
2209
2210     return is_utf8_common(p, &PL_utf8_idcont, "IdContinue");
2211 }
2212
2213 bool
2214 Perl_is_utf8_xidcont(pTHX_ const U8 *p)
2215 {
2216     dVAR;
2217
2218     PERL_ARGS_ASSERT_IS_UTF8_XIDCONT;
2219
2220     return is_utf8_common(p, &PL_utf8_idcont, "XIdContinue");
2221 }
2222
2223 bool
2224 Perl_is_utf8_alpha(pTHX_ const U8 *p)
2225 {
2226     dVAR;
2227
2228     PERL_ARGS_ASSERT_IS_UTF8_ALPHA;
2229
2230     return is_utf8_common(p, &PL_utf8_swash_ptrs[_CC_ALPHA], "IsAlpha");
2231 }
2232
2233 bool
2234 Perl_is_utf8_ascii(pTHX_ const U8 *p)
2235 {
2236     dVAR;
2237
2238     PERL_ARGS_ASSERT_IS_UTF8_ASCII;
2239
2240     /* ASCII characters are the same whether in utf8 or not.  So the macro
2241      * works on both utf8 and non-utf8 representations. */
2242     return isASCII(*p);
2243 }
2244
2245 bool
2246 Perl_is_utf8_blank(pTHX_ const U8 *p)
2247 {
2248     dVAR;
2249
2250     PERL_ARGS_ASSERT_IS_UTF8_BLANK;
2251
2252     return isBLANK_utf8(p);
2253 }
2254
2255 bool
2256 Perl_is_utf8_space(pTHX_ const U8 *p)
2257 {
2258     dVAR;
2259
2260     PERL_ARGS_ASSERT_IS_UTF8_SPACE;
2261
2262     return isSPACE_utf8(p);
2263 }
2264
2265 bool
2266 Perl_is_utf8_perl_space(pTHX_ const U8 *p)
2267 {
2268     dVAR;
2269
2270     PERL_ARGS_ASSERT_IS_UTF8_PERL_SPACE;
2271
2272     /* Only true if is an ASCII space-like character, and ASCII is invariant
2273      * under utf8, so can just use the macro */
2274     return isSPACE_A(*p);
2275 }
2276
2277 bool
2278 Perl_is_utf8_perl_word(pTHX_ const U8 *p)
2279 {
2280     dVAR;
2281
2282     PERL_ARGS_ASSERT_IS_UTF8_PERL_WORD;
2283
2284     /* Only true if is an ASCII word character, and ASCII is invariant
2285      * under utf8, so can just use the macro */
2286     return isWORDCHAR_A(*p);
2287 }
2288
2289 bool
2290 Perl_is_utf8_digit(pTHX_ const U8 *p)
2291 {
2292     dVAR;
2293
2294     PERL_ARGS_ASSERT_IS_UTF8_DIGIT;
2295
2296     return is_utf8_common(p, &PL_utf8_swash_ptrs[_CC_DIGIT], "IsDigit");
2297 }
2298
2299 bool
2300 Perl_is_utf8_posix_digit(pTHX_ const U8 *p)
2301 {
2302     dVAR;
2303
2304     PERL_ARGS_ASSERT_IS_UTF8_POSIX_DIGIT;
2305
2306     /* Only true if is an ASCII digit character, and ASCII is invariant
2307      * under utf8, so can just use the macro */
2308     return isDIGIT_A(*p);
2309 }
2310
2311 bool
2312 Perl_is_utf8_upper(pTHX_ const U8 *p)
2313 {
2314     dVAR;
2315
2316     PERL_ARGS_ASSERT_IS_UTF8_UPPER;
2317
2318     return is_utf8_common(p, &PL_utf8_swash_ptrs[_CC_UPPER], "IsUppercase");
2319 }
2320
2321 bool
2322 Perl_is_utf8_lower(pTHX_ const U8 *p)
2323 {
2324     dVAR;
2325
2326     PERL_ARGS_ASSERT_IS_UTF8_LOWER;
2327
2328     return is_utf8_common(p, &PL_utf8_swash_ptrs[_CC_LOWER], "IsLowercase");
2329 }
2330
2331 bool
2332 Perl_is_utf8_cntrl(pTHX_ const U8 *p)
2333 {
2334     dVAR;
2335
2336     PERL_ARGS_ASSERT_IS_UTF8_CNTRL;
2337
2338     return isCNTRL_utf8(p);
2339 }
2340
2341 bool
2342 Perl_is_utf8_graph(pTHX_ const U8 *p)
2343 {
2344     dVAR;
2345
2346     PERL_ARGS_ASSERT_IS_UTF8_GRAPH;
2347
2348     return is_utf8_common(p, &PL_utf8_swash_ptrs[_CC_GRAPH], "IsGraph");
2349 }
2350
2351 bool
2352 Perl_is_utf8_print(pTHX_ const U8 *p)
2353 {
2354     dVAR;
2355
2356     PERL_ARGS_ASSERT_IS_UTF8_PRINT;
2357
2358     return is_utf8_common(p, &PL_utf8_swash_ptrs[_CC_PRINT], "IsPrint");
2359 }
2360
2361 bool
2362 Perl_is_utf8_punct(pTHX_ const U8 *p)
2363 {
2364     dVAR;
2365
2366     PERL_ARGS_ASSERT_IS_UTF8_PUNCT;
2367
2368     return is_utf8_common(p, &PL_utf8_swash_ptrs[_CC_PUNCT], "IsPunct");
2369 }
2370
2371 bool
2372 Perl_is_utf8_xdigit(pTHX_ const U8 *p)
2373 {
2374     dVAR;
2375
2376     PERL_ARGS_ASSERT_IS_UTF8_XDIGIT;
2377
2378     return is_XDIGIT_utf8(p);
2379 }
2380
2381 bool
2382 Perl__is_utf8_mark(pTHX_ const U8 *p)
2383 {
2384     dVAR;
2385
2386     PERL_ARGS_ASSERT__IS_UTF8_MARK;
2387
2388     return is_utf8_common(p, &PL_utf8_mark, "IsM");
2389 }
2390
2391
2392 bool
2393 Perl_is_utf8_mark(pTHX_ const U8 *p)
2394 {
2395     dVAR;
2396
2397     PERL_ARGS_ASSERT_IS_UTF8_MARK;
2398
2399     return _is_utf8_mark(p);
2400 }
2401
2402 /*
2403 =for apidoc to_utf8_case
2404
2405 The C<p> contains the pointer to the UTF-8 string encoding
2406 the character that is being converted.  This routine assumes that the character
2407 at C<p> is well-formed.
2408
2409 The C<ustrp> is a pointer to the character buffer to put the
2410 conversion result to.  The C<lenp> is a pointer to the length
2411 of the result.
2412
2413 The C<swashp> is a pointer to the swash to use.
2414
2415 Both the special and normal mappings are stored in F<lib/unicore/To/Foo.pl>,
2416 and loaded by SWASHNEW, using F<lib/utf8_heavy.pl>.  The C<special> (usually,
2417 but not always, a multicharacter mapping), is tried first.
2418
2419 The C<special> is a string like "utf8::ToSpecLower", which means the
2420 hash %utf8::ToSpecLower.  The access to the hash is through
2421 Perl_to_utf8_case().
2422
2423 The C<normal> is a string like "ToLower" which means the swash
2424 %utf8::ToLower.
2425
2426 =cut */
2427
2428 UV
2429 Perl_to_utf8_case(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp,
2430                         SV **swashp, const char *normal, const char *special)
2431 {
2432     dVAR;
2433     STRLEN len = 0;
2434     const UV uv1 = valid_utf8_to_uvchr(p, NULL);
2435
2436     PERL_ARGS_ASSERT_TO_UTF8_CASE;
2437
2438     /* Note that swash_fetch() doesn't output warnings for these because it
2439      * assumes we will */
2440     if (uv1 >= UNICODE_SURROGATE_FIRST) {
2441         if (uv1 <= UNICODE_SURROGATE_LAST) {
2442             if (ckWARN_d(WARN_SURROGATE)) {
2443                 const char* desc = (PL_op) ? OP_DESC(PL_op) : normal;
2444                 Perl_warner(aTHX_ packWARN(WARN_SURROGATE),
2445                     "Operation \"%s\" returns its argument for UTF-16 surrogate U+%04"UVXf"", desc, uv1);
2446             }
2447         }
2448         else if (UNICODE_IS_SUPER(uv1)) {
2449             if (ckWARN_d(WARN_NON_UNICODE)) {
2450                 const char* desc = (PL_op) ? OP_DESC(PL_op) : normal;
2451                 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
2452                     "Operation \"%s\" returns its argument for non-Unicode code point 0x%04"UVXf"", desc, uv1);
2453             }
2454         }
2455
2456         /* Note that non-characters are perfectly legal, so no warning should
2457          * be given */
2458     }
2459
2460     if (!*swashp) /* load on-demand */
2461          *swashp = _core_swash_init("utf8", normal, &PL_sv_undef, 4, 0, NULL, NULL);
2462
2463     if (special) {
2464          /* It might be "special" (sometimes, but not always,
2465           * a multicharacter mapping) */
2466          HV * const hv = get_hv(special, 0);
2467          SV **svp;
2468
2469          if (hv &&
2470              (svp = hv_fetch(hv, (const char*)p, UNISKIP(uv1), FALSE)) &&
2471              (*svp)) {
2472              const char *s;
2473
2474               s = SvPV_const(*svp, len);
2475               if (len == 1)
2476                   /* EIGHTBIT */
2477                    len = uvchr_to_utf8(ustrp, *(U8*)s) - ustrp;
2478               else {
2479                    Copy(s, ustrp, len, U8);
2480               }
2481          }
2482     }
2483
2484     if (!len && *swashp) {
2485         const UV uv2 = swash_fetch(*swashp, p, TRUE /* => is utf8 */);
2486
2487          if (uv2) {
2488               /* It was "normal" (a single character mapping). */
2489               len = uvchr_to_utf8(ustrp, uv2) - ustrp;
2490          }
2491     }
2492
2493     if (len) {
2494         if (lenp) {
2495             *lenp = len;
2496         }
2497         return valid_utf8_to_uvchr(ustrp, 0);
2498     }
2499
2500     /* Here, there was no mapping defined, which means that the code point maps
2501      * to itself.  Return the inputs */
2502     len = UTF8SKIP(p);
2503     if (p != ustrp) {   /* Don't copy onto itself */
2504         Copy(p, ustrp, len, U8);
2505     }
2506
2507     if (lenp)
2508          *lenp = len;
2509
2510     return uv1;
2511
2512 }
2513
2514 STATIC UV
2515 S_check_locale_boundary_crossing(pTHX_ const U8* const p, const UV result, U8* const ustrp, STRLEN *lenp)
2516 {
2517     /* This is called when changing the case of a utf8-encoded character above
2518      * the Latin1 range, and the operation is in locale.  If the result
2519      * contains a character that crosses the 255/256 boundary, disallow the
2520      * change, and return the original code point.  See L<perlfunc/lc> for why;
2521      *
2522      * p        points to the original string whose case was changed; assumed
2523      *          by this routine to be well-formed
2524      * result   the code point of the first character in the changed-case string
2525      * ustrp    points to the changed-case string (<result> represents its first char)
2526      * lenp     points to the length of <ustrp> */
2527
2528     UV original;    /* To store the first code point of <p> */
2529
2530     PERL_ARGS_ASSERT_CHECK_LOCALE_BOUNDARY_CROSSING;
2531
2532     assert(UTF8_IS_ABOVE_LATIN1(*p));
2533
2534     /* We know immediately if the first character in the string crosses the
2535      * boundary, so can skip */
2536     if (result > 255) {
2537
2538         /* Look at every character in the result; if any cross the
2539         * boundary, the whole thing is disallowed */
2540         U8* s = ustrp + UTF8SKIP(ustrp);
2541         U8* e = ustrp + *lenp;
2542         while (s < e) {
2543             if (! UTF8_IS_ABOVE_LATIN1(*s)) {
2544                 goto bad_crossing;
2545             }
2546             s += UTF8SKIP(s);
2547         }
2548
2549         /* Here, no characters crossed, result is ok as-is */
2550         return result;
2551     }
2552
2553 bad_crossing:
2554
2555     /* Failed, have to return the original */
2556     original = valid_utf8_to_uvchr(p, lenp);
2557     Copy(p, ustrp, *lenp, char);
2558     return original;
2559 }
2560
2561 /*
2562 =for apidoc to_utf8_upper
2563
2564 Instead use L</toUPPER_utf8>.
2565
2566 =cut */
2567
2568 /* Not currently externally documented, and subject to change:
2569  * <flags> is set iff locale semantics are to be used for code points < 256
2570  * <tainted_ptr> if non-null, *tainted_ptr will be set TRUE iff locale rules
2571  *               were used in the calculation; otherwise unchanged. */
2572
2573 UV
2574 Perl__to_utf8_upper_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, const bool flags, bool* tainted_ptr)
2575 {
2576     dVAR;
2577
2578     UV result;
2579
2580     PERL_ARGS_ASSERT__TO_UTF8_UPPER_FLAGS;
2581
2582     if (UTF8_IS_INVARIANT(*p)) {
2583         if (flags) {
2584             result = toUPPER_LC(*p);
2585         }
2586         else {
2587             return _to_upper_title_latin1(*p, ustrp, lenp, 'S');
2588         }
2589     }
2590     else if UTF8_IS_DOWNGRADEABLE_START(*p) {
2591         if (flags) {
2592             result = toUPPER_LC(TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1)));
2593         }
2594         else {
2595             return _to_upper_title_latin1(TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1)),
2596                                           ustrp, lenp, 'S');
2597         }
2598     }
2599     else {  /* utf8, ord above 255 */
2600         result = CALL_UPPER_CASE(p, ustrp, lenp);
2601
2602         if (flags) {
2603             result = check_locale_boundary_crossing(p, result, ustrp, lenp);
2604         }
2605         return result;
2606     }
2607
2608     /* Here, used locale rules.  Convert back to utf8 */
2609     if (UTF8_IS_INVARIANT(result)) {
2610         *ustrp = (U8) result;
2611         *lenp = 1;
2612     }
2613     else {
2614         *ustrp = UTF8_EIGHT_BIT_HI(result);
2615         *(ustrp + 1) = UTF8_EIGHT_BIT_LO(result);
2616         *lenp = 2;
2617     }
2618
2619     if (tainted_ptr) {
2620         *tainted_ptr = TRUE;
2621     }
2622     return result;
2623 }
2624
2625 /*
2626 =for apidoc to_utf8_title
2627
2628 Instead use L</toTITLE_utf8>.
2629
2630 =cut */
2631
2632 /* Not currently externally documented, and subject to change:
2633  * <flags> is set iff locale semantics are to be used for code points < 256
2634  *         Since titlecase is not defined in POSIX, uppercase is used instead
2635  *         for these/
2636  * <tainted_ptr> if non-null, *tainted_ptr will be set TRUE iff locale rules
2637  *               were used in the calculation; otherwise unchanged. */
2638
2639 UV
2640 Perl__to_utf8_title_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, const bool flags, bool* tainted_ptr)
2641 {
2642     dVAR;
2643
2644     UV result;
2645
2646     PERL_ARGS_ASSERT__TO_UTF8_TITLE_FLAGS;
2647
2648     if (UTF8_IS_INVARIANT(*p)) {
2649         if (flags) {
2650             result = toUPPER_LC(*p);
2651         }
2652         else {
2653             return _to_upper_title_latin1(*p, ustrp, lenp, 's');
2654         }
2655     }
2656     else if UTF8_IS_DOWNGRADEABLE_START(*p) {
2657         if (flags) {
2658             result = toUPPER_LC(TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1)));
2659         }
2660         else {
2661             return _to_upper_title_latin1(TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1)),
2662                                           ustrp, lenp, 's');
2663         }
2664     }
2665     else {  /* utf8, ord above 255 */
2666         result = CALL_TITLE_CASE(p, ustrp, lenp);
2667
2668         if (flags) {
2669             result = check_locale_boundary_crossing(p, result, ustrp, lenp);
2670         }
2671         return result;
2672     }
2673
2674     /* Here, used locale rules.  Convert back to utf8 */
2675     if (UTF8_IS_INVARIANT(result)) {
2676         *ustrp = (U8) result;
2677         *lenp = 1;
2678     }
2679     else {
2680         *ustrp = UTF8_EIGHT_BIT_HI(result);
2681         *(ustrp + 1) = UTF8_EIGHT_BIT_LO(result);
2682         *lenp = 2;
2683     }
2684
2685     if (tainted_ptr) {
2686         *tainted_ptr = TRUE;
2687     }
2688     return result;
2689 }
2690
2691 /*
2692 =for apidoc to_utf8_lower
2693
2694 Instead use L</toLOWER_utf8>.
2695
2696 =cut */
2697
2698 /* Not currently externally documented, and subject to change:
2699  * <flags> is set iff locale semantics are to be used for code points < 256
2700  * <tainted_ptr> if non-null, *tainted_ptr will be set TRUE iff locale rules
2701  *               were used in the calculation; otherwise unchanged. */
2702
2703 UV
2704 Perl__to_utf8_lower_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, const bool flags, bool* tainted_ptr)
2705 {
2706     UV result;
2707
2708     dVAR;
2709
2710     PERL_ARGS_ASSERT__TO_UTF8_LOWER_FLAGS;
2711
2712     if (UTF8_IS_INVARIANT(*p)) {
2713         if (flags) {
2714             result = toLOWER_LC(*p);
2715         }
2716         else {
2717             return to_lower_latin1(*p, ustrp, lenp);
2718         }
2719     }
2720     else if UTF8_IS_DOWNGRADEABLE_START(*p) {
2721         if (flags) {
2722             result = toLOWER_LC(TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1)));
2723         }
2724         else {
2725             return to_lower_latin1(TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1)),
2726                                    ustrp, lenp);
2727         }
2728     }
2729     else {  /* utf8, ord above 255 */
2730         result = CALL_LOWER_CASE(p, ustrp, lenp);
2731
2732         if (flags) {
2733             result = check_locale_boundary_crossing(p, result, ustrp, lenp);
2734         }
2735
2736         return result;
2737     }
2738
2739     /* Here, used locale rules.  Convert back to utf8 */
2740     if (UTF8_IS_INVARIANT(result)) {
2741         *ustrp = (U8) result;
2742         *lenp = 1;
2743     }
2744     else {
2745         *ustrp = UTF8_EIGHT_BIT_HI(result);
2746         *(ustrp + 1) = UTF8_EIGHT_BIT_LO(result);
2747         *lenp = 2;
2748     }
2749
2750     if (tainted_ptr) {
2751         *tainted_ptr = TRUE;
2752     }
2753     return result;
2754 }
2755
2756 /*
2757 =for apidoc to_utf8_fold
2758
2759 Instead use L</toFOLD_utf8>.
2760
2761 =cut */
2762
2763 /* Not currently externally documented, and subject to change,
2764  * in <flags>
2765  *      bit FOLD_FLAGS_LOCALE is set iff locale semantics are to be used for code
2766  *                            points < 256.  Since foldcase is not defined in
2767  *                            POSIX, lowercase is used instead
2768  *      bit FOLD_FLAGS_FULL   is set iff full case folds are to be used;
2769  *                            otherwise simple folds
2770  *      bit FOLD_FLAGS_NOMIX_ASCII is set iff folds of non-ASCII to ASCII are
2771  *                            prohibited
2772  * <tainted_ptr> if non-null, *tainted_ptr will be set TRUE iff locale rules
2773  *               were used in the calculation; otherwise unchanged. */
2774
2775 UV
2776 Perl__to_utf8_fold_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, U8 flags, bool* tainted_ptr)
2777 {
2778     dVAR;
2779
2780     UV result;
2781
2782     PERL_ARGS_ASSERT__TO_UTF8_FOLD_FLAGS;
2783
2784     /* These are mutually exclusive */
2785     assert (! ((flags & FOLD_FLAGS_LOCALE) && (flags & FOLD_FLAGS_NOMIX_ASCII)));
2786
2787     assert(p != ustrp); /* Otherwise overwrites */
2788
2789     if (UTF8_IS_INVARIANT(*p)) {
2790         if (flags & FOLD_FLAGS_LOCALE) {
2791             result = toFOLD_LC(*p);
2792         }
2793         else {
2794             return _to_fold_latin1(*p, ustrp, lenp,
2795                             flags & (FOLD_FLAGS_FULL | FOLD_FLAGS_NOMIX_ASCII));
2796         }
2797     }
2798     else if UTF8_IS_DOWNGRADEABLE_START(*p) {
2799         if (flags & FOLD_FLAGS_LOCALE) {
2800             result = toFOLD_LC(TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1)));
2801         }
2802         else {
2803             return _to_fold_latin1(TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1)),
2804                             ustrp, lenp,
2805                             flags & (FOLD_FLAGS_FULL | FOLD_FLAGS_NOMIX_ASCII));
2806         }
2807     }
2808     else {  /* utf8, ord above 255 */
2809         result = CALL_FOLD_CASE(p, ustrp, lenp, flags & FOLD_FLAGS_FULL);
2810
2811         if (flags & FOLD_FLAGS_LOCALE) {
2812
2813             /* Special case these characters, as what normally gets returned
2814              * under locale doesn't work */
2815             if (UTF8SKIP(p) == sizeof(LATIN_CAPITAL_LETTER_SHARP_S_UTF8) - 1
2816                 && memEQ((char *) p, LATIN_CAPITAL_LETTER_SHARP_S_UTF8,
2817                           sizeof(LATIN_CAPITAL_LETTER_SHARP_S_UTF8) - 1))
2818             {
2819                 goto return_long_s;
2820             }
2821             else if (UTF8SKIP(p) == sizeof(LATIN_SMALL_LIGATURE_LONG_S_T) - 1
2822                 && memEQ((char *) p, LATIN_SMALL_LIGATURE_LONG_S_T_UTF8,
2823                           sizeof(LATIN_SMALL_LIGATURE_LONG_S_T_UTF8) - 1))
2824             {
2825                 goto return_ligature_st;
2826             }
2827             return check_locale_boundary_crossing(p, result, ustrp, lenp);
2828         }
2829         else if (! (flags & FOLD_FLAGS_NOMIX_ASCII)) {
2830             return result;
2831         }
2832         else {
2833             /* This is called when changing the case of a utf8-encoded
2834              * character above the ASCII range, and the result should not
2835              * contain an ASCII character. */
2836
2837             UV original;    /* To store the first code point of <p> */
2838
2839             /* Look at every character in the result; if any cross the
2840             * boundary, the whole thing is disallowed */
2841             U8* s = ustrp;
2842             U8* e = ustrp + *lenp;
2843             while (s < e) {
2844                 if (isASCII(*s)) {
2845                     /* Crossed, have to return the original */
2846                     original = valid_utf8_to_uvchr(p, lenp);
2847
2848                     /* But in these instances, there is an alternative we can
2849                      * return that is valid */
2850                     if (original == LATIN_CAPITAL_LETTER_SHARP_S
2851                         || original == LATIN_SMALL_LETTER_SHARP_S)
2852                     {
2853                         goto return_long_s;
2854                     }
2855                     else if (original == LATIN_SMALL_LIGATURE_LONG_S_T) {
2856                         goto return_ligature_st;
2857                     }
2858                     Copy(p, ustrp, *lenp, char);
2859                     return original;
2860                 }
2861                 s += UTF8SKIP(s);
2862             }
2863
2864             /* Here, no characters crossed, result is ok as-is */
2865             return result;
2866         }
2867     }
2868
2869     /* Here, used locale rules.  Convert back to utf8 */
2870     if (UTF8_IS_INVARIANT(result)) {
2871         *ustrp = (U8) result;
2872         *lenp = 1;
2873     }
2874     else {
2875         *ustrp = UTF8_EIGHT_BIT_HI(result);
2876         *(ustrp + 1) = UTF8_EIGHT_BIT_LO(result);
2877         *lenp = 2;
2878     }
2879
2880     if (tainted_ptr) {
2881         *tainted_ptr = TRUE;
2882     }
2883     return result;
2884
2885   return_long_s:
2886     /* Certain folds to 'ss' are prohibited by the options, but they do allow
2887      * folds to a string of two of these characters.  By returning this
2888      * instead, then, e.g.,
2889      *      fc("\x{1E9E}") eq fc("\x{17F}\x{17F}")
2890      * works. */
2891
2892     *lenp = 2 * sizeof(LATIN_SMALL_LETTER_LONG_S_UTF8) - 2;
2893     Copy(LATIN_SMALL_LETTER_LONG_S_UTF8 LATIN_SMALL_LETTER_LONG_S_UTF8,
2894         ustrp, *lenp, U8);
2895     return LATIN_SMALL_LETTER_LONG_S;
2896
2897   return_ligature_st:
2898     /* Two folds to 'st' are prohibited by the options; instead we pick one and
2899      * have the other one fold to it */
2900
2901     *lenp = sizeof(LATIN_SMALL_LIGATURE_ST_UTF8) - 1;
2902     Copy(LATIN_SMALL_LIGATURE_ST_UTF8, ustrp, *lenp, U8);
2903     return LATIN_SMALL_LIGATURE_ST;
2904 }
2905
2906 /* Note:
2907  * Returns a "swash" which is a hash described in utf8.c:Perl_swash_fetch().
2908  * C<pkg> is a pointer to a package name for SWASHNEW, should be "utf8".
2909  * For other parameters, see utf8::SWASHNEW in lib/utf8_heavy.pl.
2910  */
2911
2912 SV*
2913 Perl_swash_init(pTHX_ const char* pkg, const char* name, SV *listsv, I32 minbits, I32 none)
2914 {
2915     PERL_ARGS_ASSERT_SWASH_INIT;
2916
2917     /* Returns a copy of a swash initiated by the called function.  This is the
2918      * public interface, and returning a copy prevents others from doing
2919      * mischief on the original */
2920
2921     return newSVsv(_core_swash_init(pkg, name, listsv, minbits, none, NULL, NULL));
2922 }
2923
2924 SV*
2925 Perl__core_swash_init(pTHX_ const char* pkg, const char* name, SV *listsv, I32 minbits, I32 none, SV* invlist, U8* const flags_p)
2926 {
2927     /* Initialize and return a swash, creating it if necessary.  It does this
2928      * by calling utf8_heavy.pl in the general case.  The returned value may be
2929      * the swash's inversion list instead if the input parameters allow it.
2930      * Which is returned should be immaterial to callers, as the only
2931      * operations permitted on a swash, swash_fetch(), _get_swash_invlist(),
2932      * and swash_to_invlist() handle both these transparently.
2933      *
2934      * This interface should only be used by functions that won't destroy or
2935      * adversely change the swash, as doing so affects all other uses of the
2936      * swash in the program; the general public should use 'Perl_swash_init'
2937      * instead.
2938      *
2939      * pkg  is the name of the package that <name> should be in.
2940      * name is the name of the swash to find.  Typically it is a Unicode
2941      *      property name, including user-defined ones
2942      * listsv is a string to initialize the swash with.  It must be of the form
2943      *      documented as the subroutine return value in
2944      *      L<perlunicode/User-Defined Character Properties>
2945      * minbits is the number of bits required to represent each data element.
2946      *      It is '1' for binary properties.
2947      * none I (khw) do not understand this one, but it is used only in tr///.
2948      * invlist is an inversion list to initialize the swash with (or NULL)
2949      * flags_p if non-NULL is the address of various input and output flag bits
2950      *      to the routine, as follows:  ('I' means is input to the routine;
2951      *      'O' means output from the routine.  Only flags marked O are
2952      *      meaningful on return.)
2953      *  _CORE_SWASH_INIT_USER_DEFINED_PROPERTY indicates if the swash
2954      *      came from a user-defined property.  (I O)
2955      *  _CORE_SWASH_INIT_RETURN_IF_UNDEF indicates that instead of croaking
2956      *      when the swash cannot be located, to simply return NULL. (I)
2957      *  _CORE_SWASH_INIT_ACCEPT_INVLIST indicates that the caller will accept a
2958      *      return of an inversion list instead of a swash hash if this routine
2959      *      thinks that would result in faster execution of swash_fetch() later
2960      *      on. (I)
2961      *
2962      * Thus there are three possible inputs to find the swash: <name>,
2963      * <listsv>, and <invlist>.  At least one must be specified.  The result
2964      * will be the union of the specified ones, although <listsv>'s various
2965      * actions can intersect, etc. what <name> gives.
2966      *
2967      * <invlist> is only valid for binary properties */
2968
2969     dVAR;
2970     SV* retval = &PL_sv_undef;
2971     HV* swash_hv = NULL;
2972     const int invlist_swash_boundary =
2973         (flags_p && *flags_p & _CORE_SWASH_INIT_ACCEPT_INVLIST)
2974         ? 512    /* Based on some benchmarking, but not extensive, see commit
2975                     message */
2976         : -1;   /* Never return just an inversion list */
2977
2978     assert(listsv != &PL_sv_undef || strNE(name, "") || invlist);
2979     assert(! invlist || minbits == 1);
2980
2981     /* If data was passed in to go out to utf8_heavy to find the swash of, do
2982      * so */
2983     if (listsv != &PL_sv_undef || strNE(name, "")) {
2984         dSP;
2985         const size_t pkg_len = strlen(pkg);
2986         const size_t name_len = strlen(name);
2987         HV * const stash = gv_stashpvn(pkg, pkg_len, 0);
2988         SV* errsv_save;
2989         GV *method;
2990
2991         PERL_ARGS_ASSERT__CORE_SWASH_INIT;
2992
2993         PUSHSTACKi(PERLSI_MAGIC);
2994         ENTER;
2995         SAVEHINTS();
2996         save_re_context();
2997         /* We might get here via a subroutine signature which uses a utf8
2998          * parameter name, at which point PL_subname will have been set
2999          * but not yet used. */
3000         save_item(PL_subname);
3001         if (PL_parser && PL_parser->error_count)
3002             SAVEI8(PL_parser->error_count), PL_parser->error_count = 0;
3003         method = gv_fetchmeth(stash, "SWASHNEW", 8, -1);
3004         if (!method) {  /* demand load utf8 */
3005             ENTER;
3006             if ((errsv_save = GvSV(PL_errgv))) SAVEFREESV(errsv_save);
3007             GvSV(PL_errgv) = NULL;
3008             /* It is assumed that callers of this routine are not passing in
3009              * any user derived data.  */
3010             /* Need to do this after save_re_context() as it will set
3011              * PL_tainted to 1 while saving $1 etc (see the code after getrx:
3012              * in Perl_magic_get).  Even line to create errsv_save can turn on
3013              * PL_tainted.  */
3014 #ifndef NO_TAINT_SUPPORT
3015             SAVEBOOL(TAINT_get);
3016             TAINT_NOT;
3017 #endif
3018             Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT, newSVpvn(pkg,pkg_len),
3019                              NULL);
3020             {
3021                 /* Not ERRSV, as there is no need to vivify a scalar we are
3022                    about to discard. */
3023                 SV * const errsv = GvSV(PL_errgv);
3024                 if (!SvTRUE(errsv)) {
3025                     GvSV(PL_errgv) = SvREFCNT_inc_simple(errsv_save);
3026                     SvREFCNT_dec(errsv);
3027                 }
3028             }
3029             LEAVE;
3030         }
3031         SPAGAIN;
3032         PUSHMARK(SP);
3033         EXTEND(SP,5);
3034         mPUSHp(pkg, pkg_len);
3035         mPUSHp(name, name_len);
3036         PUSHs(listsv);
3037         mPUSHi(minbits);
3038         mPUSHi(none);
3039         PUTBACK;
3040         if ((errsv_save = GvSV(PL_errgv))) SAVEFREESV(errsv_save);
3041         GvSV(PL_errgv) = NULL;
3042         /* If we already have a pointer to the method, no need to use
3043          * call_method() to repeat the lookup.  */
3044         if (method
3045             ? call_sv(MUTABLE_SV(method), G_SCALAR)
3046             : call_sv(newSVpvs_flags("SWASHNEW", SVs_TEMP), G_SCALAR | G_METHOD))
3047         {
3048             retval = *PL_stack_sp--;
3049             SvREFCNT_inc(retval);
3050         }
3051         {
3052             /* Not ERRSV.  See above. */
3053             SV * const errsv = GvSV(PL_errgv);
3054             if (!SvTRUE(errsv)) {
3055                 GvSV(PL_errgv) = SvREFCNT_inc_simple(errsv_save);
3056                 SvREFCNT_dec(errsv);
3057             }
3058         }
3059         LEAVE;
3060         POPSTACK;
3061         if (IN_PERL_COMPILETIME) {
3062             CopHINTS_set(PL_curcop, PL_hints);
3063         }
3064         if (!SvROK(retval) || SvTYPE(SvRV(retval)) != SVt_PVHV) {
3065             if (SvPOK(retval))
3066
3067                 /* If caller wants to handle missing properties, let them */
3068                 if (flags_p && *flags_p & _CORE_SWASH_INIT_RETURN_IF_UNDEF) {
3069                     return NULL;
3070                 }
3071                 Perl_croak(aTHX_
3072                            "Can't find Unicode property definition \"%"SVf"\"",
3073                            SVfARG(retval));
3074             Perl_croak(aTHX_ "SWASHNEW didn't return an HV ref");
3075         }
3076     } /* End of calling the module to find the swash */
3077
3078     /* If this operation fetched a swash, and we will need it later, get it */
3079     if (retval != &PL_sv_undef
3080         && (minbits == 1 || (flags_p
3081                             && ! (*flags_p
3082                                   & _CORE_SWASH_INIT_USER_DEFINED_PROPERTY))))
3083     {
3084         swash_hv = MUTABLE_HV(SvRV(retval));
3085
3086         /* If we don't already know that there is a user-defined component to
3087          * this swash, and the user has indicated they wish to know if there is
3088          * one (by passing <flags_p>), find out */
3089         if (flags_p && ! (*flags_p & _CORE_SWASH_INIT_USER_DEFINED_PROPERTY)) {
3090             SV** user_defined = hv_fetchs(swash_hv, "USER_DEFINED", FALSE);
3091             if (user_defined && SvUV(*user_defined)) {
3092                 *flags_p |= _CORE_SWASH_INIT_USER_DEFINED_PROPERTY;
3093             }
3094         }
3095     }
3096
3097     /* Make sure there is an inversion list for binary properties */
3098     if (minbits == 1) {
3099         SV** swash_invlistsvp = NULL;
3100         SV* swash_invlist = NULL;
3101         bool invlist_in_swash_is_valid = FALSE;
3102         bool swash_invlist_unclaimed = FALSE; /* whether swash_invlist has
3103                                             an unclaimed reference count */
3104
3105         /* If this operation fetched a swash, get its already existing
3106          * inversion list, or create one for it */
3107
3108         if (swash_hv) {
3109             swash_invlistsvp = hv_fetchs(swash_hv, "V", FALSE);
3110             if (swash_invlistsvp) {
3111                 swash_invlist = *swash_invlistsvp;
3112                 invlist_in_swash_is_valid = TRUE;
3113             }
3114             else {
3115                 swash_invlist = _swash_to_invlist(retval);
3116                 swash_invlist_unclaimed = TRUE;
3117             }
3118         }
3119
3120         /* If an inversion list was passed in, have to include it */
3121         if (invlist) {
3122
3123             /* Any fetched swash will by now have an inversion list in it;
3124              * otherwise <swash_invlist>  will be NULL, indicating that we
3125              * didn't fetch a swash */
3126             if (swash_invlist) {
3127
3128                 /* Add the passed-in inversion list, which invalidates the one
3129                  * already stored in the swash */
3130                 invlist_in_swash_is_valid = FALSE;
3131                 _invlist_union(invlist, swash_invlist, &swash_invlist);
3132             }
3133             else {
3134
3135                 /* Here, there is no swash already.  Set up a minimal one, if
3136                  * we are going to return a swash */
3137                 if ((int) _invlist_len(invlist) > invlist_swash_boundary) {
3138                     swash_hv = newHV();
3139                     retval = newRV_noinc(MUTABLE_SV(swash_hv));
3140                 }
3141                 swash_invlist = invlist;
3142             }
3143         }
3144
3145         /* Here, we have computed the union of all the passed-in data.  It may
3146          * be that there was an inversion list in the swash which didn't get
3147          * touched; otherwise save the one computed one */
3148         if (! invlist_in_swash_is_valid
3149             && (int) _invlist_len(swash_invlist) > invlist_swash_boundary)
3150         {
3151             if (! hv_stores(MUTABLE_HV(SvRV(retval)), "V", swash_invlist))
3152             {
3153                 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
3154             }
3155             /* We just stole a reference count. */
3156             if (swash_invlist_unclaimed) swash_invlist_unclaimed = FALSE;
3157             else SvREFCNT_inc_simple_void_NN(swash_invlist);
3158         }
3159
3160         /* Use the inversion list stand-alone if small enough */
3161         if ((int) _invlist_len(swash_invlist) <= invlist_swash_boundary) {
3162             SvREFCNT_dec(retval);
3163             if (!swash_invlist_unclaimed)
3164                 SvREFCNT_inc_simple_void_NN(swash_invlist);
3165             retval = newRV_noinc(swash_invlist);
3166         }
3167     }
3168
3169     return retval;
3170 }
3171
3172
3173 /* This API is wrong for special case conversions since we may need to
3174  * return several Unicode characters for a single Unicode character
3175  * (see lib/unicore/SpecCase.txt) The SWASHGET in lib/utf8_heavy.pl is
3176  * the lower-level routine, and it is similarly broken for returning
3177  * multiple values.  --jhi
3178  * For those, you should use to_utf8_case() instead */
3179 /* Now SWASHGET is recasted into S_swatch_get in this file. */
3180
3181 /* Note:
3182  * Returns the value of property/mapping C<swash> for the first character
3183  * of the string C<ptr>. If C<do_utf8> is true, the string C<ptr> is
3184  * assumed to be in well-formed utf8. If C<do_utf8> is false, the string C<ptr>
3185  * is assumed to be in native 8-bit encoding. Caches the swatch in C<swash>.
3186  *
3187  * A "swash" is a hash which contains initially the keys/values set up by
3188  * SWASHNEW.  The purpose is to be able to completely represent a Unicode
3189  * property for all possible code points.  Things are stored in a compact form
3190  * (see utf8_heavy.pl) so that calculation is required to find the actual
3191  * property value for a given code point.  As code points are looked up, new
3192  * key/value pairs are added to the hash, so that the calculation doesn't have
3193  * to ever be re-done.  Further, each calculation is done, not just for the
3194  * desired one, but for a whole block of code points adjacent to that one.
3195  * For binary properties on ASCII machines, the block is usually for 64 code
3196  * points, starting with a code point evenly divisible by 64.  Thus if the
3197  * property value for code point 257 is requested, the code goes out and
3198  * calculates the property values for all 64 code points between 256 and 319,
3199  * and stores these as a single 64-bit long bit vector, called a "swatch",
3200  * under the key for code point 256.  The key is the UTF-8 encoding for code
3201  * point 256, minus the final byte.  Thus, if the length of the UTF-8 encoding
3202  * for a code point is 13 bytes, the key will be 12 bytes long.  If the value
3203  * for code point 258 is then requested, this code realizes that it would be
3204  * stored under the key for 256, and would find that value and extract the
3205  * relevant bit, offset from 256.
3206  *
3207  * Non-binary properties are stored in as many bits as necessary to represent
3208  * their values (32 currently, though the code is more general than that), not
3209  * as single bits, but the principal is the same: the value for each key is a
3210  * vector that encompasses the property values for all code points whose UTF-8
3211  * representations are represented by the key.  That is, for all code points
3212  * whose UTF-8 representations are length N bytes, and the key is the first N-1
3213  * bytes of that.
3214  */
3215 UV
3216 Perl_swash_fetch(pTHX_ SV *swash, const U8 *ptr, bool do_utf8)
3217 {
3218     dVAR;
3219     HV *const hv = MUTABLE_HV(SvRV(swash));
3220     U32 klen;
3221     U32 off;
3222     STRLEN slen;
3223     STRLEN needents;
3224     const U8 *tmps = NULL;
3225     U32 bit;
3226     SV *swatch;
3227     const U8 c = *ptr;
3228
3229     PERL_ARGS_ASSERT_SWASH_FETCH;
3230
3231     /* If it really isn't a hash, it isn't really swash; must be an inversion
3232      * list */
3233     if (SvTYPE(hv) != SVt_PVHV) {
3234         return _invlist_contains_cp((SV*)hv,
3235                                     (do_utf8)
3236                                      ? valid_utf8_to_uvchr(ptr, NULL)
3237                                      : c);
3238     }
3239
3240     /* We store the values in a "swatch" which is a vec() value in a swash
3241      * hash.  Code points 0-255 are a single vec() stored with key length
3242      * (klen) 0.  All other code points have a UTF-8 representation
3243      * 0xAA..0xYY,0xZZ.  A vec() is constructed containing all of them which
3244      * share 0xAA..0xYY, which is the key in the hash to that vec.  So the key
3245      * length for them is the length of the encoded char - 1.  ptr[klen] is the
3246      * final byte in the sequence representing the character */
3247     if (!do_utf8 || UTF8_IS_INVARIANT(c)) {
3248         klen = 0;
3249         needents = 256;
3250         off = c;
3251     }
3252     else if (UTF8_IS_DOWNGRADEABLE_START(c)) {
3253         klen = 0;
3254         needents = 256;
3255         off = TWO_BYTE_UTF8_TO_NATIVE(c, *(ptr + 1));
3256     }
3257     else {
3258         klen = UTF8SKIP(ptr) - 1;
3259
3260         /* Each vec() stores 2**UTF_ACCUMULATION_SHIFT values.  The offset into
3261          * the vec is the final byte in the sequence.  (In EBCDIC this is
3262          * converted to I8 to get consecutive values.)  To help you visualize
3263          * all this:
3264          *                       Straight 1047   After final byte
3265          *             UTF-8      UTF-EBCDIC     I8 transform
3266          *  U+0400:  \xD0\x80    \xB8\x41\x41    \xB8\x41\xA0
3267          *  U+0401:  \xD0\x81    \xB8\x41\x42    \xB8\x41\xA1
3268          *    ...
3269          *  U+0409:  \xD0\x89    \xB8\x41\x4A    \xB8\x41\xA9
3270          *  U+040A:  \xD0\x8A    \xB8\x41\x51    \xB8\x41\xAA
3271          *    ...
3272          *  U+0412:  \xD0\x92    \xB8\x41\x59    \xB8\x41\xB2
3273          *  U+0413:  \xD0\x93    \xB8\x41\x62    \xB8\x41\xB3
3274          *    ...
3275          *  U+041B:  \xD0\x9B    \xB8\x41\x6A    \xB8\x41\xBB
3276          *  U+041C:  \xD0\x9C    \xB8\x41\x70    \xB8\x41\xBC
3277          *    ...
3278          *  U+041F:  \xD0\x9F    \xB8\x41\x73    \xB8\x41\xBF
3279          *  U+0420:  \xD0\xA0    \xB8\x42\x41    \xB8\x42\x41
3280          *
3281          * (There are no discontinuities in the elided (...) entries.)
3282          * The UTF-8 key for these 33 code points is '\xD0' (which also is the
3283          * key for the next 31, up through U+043F, whose UTF-8 final byte is
3284          * \xBF).  Thus in UTF-8, each key is for a vec() for 64 code points.
3285          * The final UTF-8 byte, which ranges between \x80 and \xBF, is an
3286          * index into the vec() swatch (after subtracting 0x80, which we
3287          * actually do with an '&').
3288          * In UTF-EBCDIC, each key is for a 32 code point vec().  The first 32
3289          * code points above have key '\xB8\x41'. The final UTF-EBCDIC byte has
3290          * dicontinuities which go away by transforming it into I8, and we
3291          * effectively subtract 0xA0 to get the index. */
3292         needents = (1 << UTF_ACCUMULATION_SHIFT);
3293         off      = NATIVE_UTF8_TO_I8(ptr[klen]) & UTF_CONTINUATION_MASK;
3294     }
3295
3296     /*
3297      * This single-entry cache saves about 1/3 of the utf8 overhead in test
3298      * suite.  (That is, only 7-8% overall over just a hash cache.  Still,
3299      * it's nothing to sniff at.)  Pity we usually come through at least
3300      * two function calls to get here...
3301      *
3302      * NB: this code assumes that swatches are never modified, once generated!
3303      */
3304
3305     if (hv   == PL_last_swash_hv &&
3306         klen == PL_last_swash_klen &&
3307         (!klen || memEQ((char *)ptr, (char *)PL_last_swash_key, klen)) )
3308     {
3309         tmps = PL_last_swash_tmps;
3310         slen = PL_last_swash_slen;
3311     }
3312     else {
3313         /* Try our second-level swatch cache, kept in a hash. */
3314         SV** svp = hv_fetch(hv, (const char*)ptr, klen, FALSE);
3315
3316         /* If not cached, generate it via swatch_get */
3317         if (!svp || !SvPOK(*svp)
3318                  || !(tmps = (const U8*)SvPV_const(*svp, slen)))
3319         {
3320             if (klen) {
3321                 const UV code_point = valid_utf8_to_uvchr(ptr, NULL);
3322                 swatch = swatch_get(swash,
3323                                     code_point & ~((UV)needents - 1),
3324                                     needents);
3325             }
3326             else {  /* For the first 256 code points, the swatch has a key of
3327                        length 0 */
3328                 swatch = swatch_get(swash, 0, needents);
3329             }
3330
3331             if (IN_PERL_COMPILETIME)
3332                 CopHINTS_set(PL_curcop, PL_hints);
3333
3334             svp = hv_store(hv, (const char *)ptr, klen, swatch, 0);
3335
3336             if (!svp || !(tmps = (U8*)SvPV(*svp, slen))
3337                      || (slen << 3) < needents)
3338                 Perl_croak(aTHX_ "panic: swash_fetch got improper swatch, "
3339                            "svp=%p, tmps=%p, slen=%"UVuf", needents=%"UVuf,
3340                            svp, tmps, (UV)slen, (UV)needents);
3341         }
3342
3343         PL_last_swash_hv = hv;
3344         assert(klen <= sizeof(PL_last_swash_key));
3345         PL_last_swash_klen = (U8)klen;
3346         /* FIXME change interpvar.h?  */
3347         PL_last_swash_tmps = (U8 *) tmps;
3348         PL_last_swash_slen = slen;
3349         if (klen)
3350             Copy(ptr, PL_last_swash_key, klen, U8);
3351     }
3352
3353     switch ((int)((slen << 3) / needents)) {
3354     case 1:
3355         bit = 1 << (off & 7);
3356         off >>= 3;
3357         return (tmps[off] & bit) != 0;
3358     case 8:
3359         return tmps[off];
3360     case 16:
3361         off <<= 1;
3362         return (tmps[off] << 8) + tmps[off + 1] ;
3363     case 32:
3364         off <<= 2;
3365         return (tmps[off] << 24) + (tmps[off+1] << 16) + (tmps[off+2] << 8) + tmps[off + 3] ;
3366     }
3367     Perl_croak(aTHX_ "panic: swash_fetch got swatch of unexpected bit width, "
3368                "slen=%"UVuf", needents=%"UVuf, (UV)slen, (UV)needents);
3369     NORETURN_FUNCTION_END;
3370 }
3371
3372 /* Read a single line of the main body of the swash input text.  These are of
3373  * the form:
3374  * 0053 0056    0073
3375  * where each number is hex.  The first two numbers form the minimum and
3376  * maximum of a range, and the third is the value associated with the range.
3377  * Not all swashes should have a third number
3378  *
3379  * On input: l    points to the beginning of the line to be examined; it points
3380  *                to somewhere in the string of the whole input text, and is
3381  *                terminated by a \n or the null string terminator.
3382  *           lend   points to the null terminator of that string
3383  *           wants_value    is non-zero if the swash expects a third number
3384  *           typestr is the name of the swash's mapping, like 'ToLower'
3385  * On output: *min, *max, and *val are set to the values read from the line.
3386  *            returns a pointer just beyond the line examined.  If there was no
3387  *            valid min number on the line, returns lend+1
3388  */
3389
3390 STATIC U8*
3391 S_swash_scan_list_line(pTHX_ U8* l, U8* const lend, UV* min, UV* max, UV* val,
3392                              const bool wants_value, const U8* const typestr)
3393 {
3394     const int  typeto  = typestr[0] == 'T' && typestr[1] == 'o';
3395     STRLEN numlen;          /* Length of the number */
3396     I32 flags = PERL_SCAN_SILENT_ILLDIGIT
3397                 | PERL_SCAN_DISALLOW_PREFIX
3398                 | PERL_SCAN_SILENT_NON_PORTABLE;
3399
3400     /* nl points to the next \n in the scan */
3401     U8* const nl = (U8*)memchr(l, '\n', lend - l);
3402
3403     /* Get the first number on the line: the range minimum */
3404     numlen = lend - l;
3405     *min = grok_hex((char *)l, &numlen, &flags, NULL);
3406     if (numlen)     /* If found a hex number, position past it */
3407         l += numlen;
3408     else if (nl) {          /* Else, go handle next line, if any */
3409         return nl + 1;  /* 1 is length of "\n" */
3410     }
3411     else {              /* Else, no next line */
3412         return lend + 1;        /* to LIST's end at which \n is not found */
3413     }
3414
3415     /* The max range value follows, separated by a BLANK */
3416     if (isBLANK(*l)) {
3417         ++l;
3418         flags = PERL_SCAN_SILENT_ILLDIGIT
3419                 | PERL_SCAN_DISALLOW_PREFIX
3420                 | PERL_SCAN_SILENT_NON_PORTABLE;
3421         numlen = lend - l;
3422         *max = grok_hex((char *)l, &numlen, &flags, NULL);
3423         if (numlen)
3424             l += numlen;
3425         else    /* If no value here, it is a single element range */
3426             *max = *min;
3427
3428         /* Non-binary tables have a third entry: what the first element of the
3429          * range maps to */
3430         if (wants_value) {
3431             if (isBLANK(*l)) {
3432                 ++l;
3433
3434                 /* The ToLc, etc table mappings are not in hex, and must be
3435                  * corrected by adding the code point to them */
3436                 if (typeto) {
3437                     char *after_strtol = (char *) lend;
3438                     *val = Strtol((char *)l, &after_strtol, 10);
3439                     l = (U8 *) after_strtol;
3440                 }
3441                 else { /* Other tables are in hex, and are the correct result
3442                           without tweaking */
3443                     flags = PERL_SCAN_SILENT_ILLDIGIT
3444                         | PERL_SCAN_DISALLOW_PREFIX
3445                         | PERL_SCAN_SILENT_NON_PORTABLE;
3446                     numlen = lend - l;
3447                     *val = grok_hex((char *)l, &numlen, &flags, NULL);
3448                     if (numlen)
3449                         l += numlen;
3450                     else
3451                         *val = 0;
3452                 }
3453             }
3454             else {
3455                 *val = 0;
3456                 if (typeto) {
3457                     /* diag_listed_as: To%s: illegal mapping '%s' */
3458                     Perl_croak(aTHX_ "%s: illegal mapping '%s'",
3459                                      typestr, l);
3460                 }
3461             }
3462         }
3463         else
3464             *val = 0; /* bits == 1, then any val should be ignored */
3465     }
3466     else { /* Nothing following range min, should be single element with no
3467               mapping expected */
3468         *max = *min;
3469         if (wants_value) {
3470             *val = 0;
3471             if (typeto) {
3472                 /* diag_listed_as: To%s: illegal mapping '%s' */
3473                 Perl_croak(aTHX_ "%s: illegal mapping '%s'", typestr, l);
3474             }
3475         }
3476         else
3477             *val = 0; /* bits == 1, then val should be ignored */
3478     }
3479
3480     /* Position to next line if any, or EOF */
3481     if (nl)
3482         l = nl + 1;
3483     else
3484         l = lend;
3485
3486     return l;
3487 }
3488
3489 /* Note:
3490  * Returns a swatch (a bit vector string) for a code point sequence
3491  * that starts from the value C<start> and comprises the number C<span>.
3492  * A C<swash> must be an object created by SWASHNEW (see lib/utf8_heavy.pl).
3493  * Should be used via swash_fetch, which will cache the swatch in C<swash>.
3494  */
3495 STATIC SV*
3496 S_swatch_get(pTHX_ SV* swash, UV start, UV span)
3497 {
3498     SV *swatch;
3499     U8 *l, *lend, *x, *xend, *s, *send;
3500     STRLEN lcur, xcur, scur;
3501     HV *const hv = MUTABLE_HV(SvRV(swash));
3502     SV** const invlistsvp = hv_fetchs(hv, "V", FALSE);
3503
3504     SV** listsvp = NULL; /* The string containing the main body of the table */
3505     SV** extssvp = NULL;
3506     SV** invert_it_svp = NULL;
3507     U8* typestr = NULL;
3508     STRLEN bits;
3509     STRLEN octets; /* if bits == 1, then octets == 0 */
3510     UV  none;
3511     UV  end = start + span;
3512
3513     if (invlistsvp == NULL) {
3514         SV** const bitssvp = hv_fetchs(hv, "BITS", FALSE);
3515         SV** const nonesvp = hv_fetchs(hv, "NONE", FALSE);
3516         SV** const typesvp = hv_fetchs(hv, "TYPE", FALSE);
3517         extssvp = hv_fetchs(hv, "EXTRAS", FALSE);
3518         listsvp = hv_fetchs(hv, "LIST", FALSE);
3519         invert_it_svp = hv_fetchs(hv, "INVERT_IT", FALSE);
3520
3521         bits  = SvUV(*bitssvp);
3522         none  = SvUV(*nonesvp);
3523         typestr = (U8*)SvPV_nolen(*typesvp);
3524     }
3525     else {
3526         bits = 1;
3527         none = 0;
3528     }
3529     octets = bits >> 3; /* if bits == 1, then octets == 0 */
3530
3531     PERL_ARGS_ASSERT_SWATCH_GET;
3532
3533     if (bits != 1 && bits != 8 && bits != 16 && bits != 32) {
3534         Perl_croak(aTHX_ "panic: swatch_get doesn't expect bits %"UVuf,
3535                                                  (UV)bits);
3536     }
3537
3538     /* If overflowed, use the max possible */
3539     if (end < start) {
3540         end = UV_MAX;
3541         span = end - start;
3542     }
3543
3544     /* create and initialize $swatch */
3545     scur   = octets ? (span * octets) : (span + 7) / 8;
3546     swatch = newSV(scur);
3547     SvPOK_on(swatch);
3548     s = (U8*)SvPVX(swatch);
3549     if (octets && none) {
3550         const U8* const e = s + scur;
3551         while (s < e) {
3552             if (bits == 8)
3553                 *s++ = (U8)(none & 0xff);
3554             else if (bits == 16) {
3555                 *s++ = (U8)((none >>  8) & 0xff);
3556                 *s++ = (U8)( none        & 0xff);
3557             }
3558             else if (bits == 32) {
3559                 *s++ = (U8)((none >> 24) & 0xff);
3560                 *s++ = (U8)((none >> 16) & 0xff);
3561                 *s++ = (U8)((none >>  8) & 0xff);
3562                 *s++ = (U8)( none        & 0xff);
3563             }
3564         }
3565         *s = '\0';
3566     }
3567     else {
3568         (void)memzero((U8*)s, scur + 1);
3569     }
3570     SvCUR_set(swatch, scur);
3571     s = (U8*)SvPVX(swatch);
3572
3573     if (invlistsvp) {   /* If has an inversion list set up use that */
3574         _invlist_populate_swatch(*invlistsvp, start, end, s);
3575         return swatch;
3576     }
3577
3578     /* read $swash->{LIST} */
3579     l = (U8*)SvPV(*listsvp, lcur);
3580     lend = l + lcur;
3581     while (l < lend) {
3582         UV min, max, val, upper;
3583         l = S_swash_scan_list_line(aTHX_ l, lend, &min, &max, &val,
3584                                          cBOOL(octets), typestr);
3585         if (l > lend) {
3586             break;
3587         }
3588
3589         /* If looking for something beyond this range, go try the next one */
3590         if (max < start)
3591             continue;
3592
3593         /* <end> is generally 1 beyond where we want to set things, but at the
3594          * platform's infinity, where we can't go any higher, we want to
3595          * include the code point at <end> */
3596         upper = (max < end)
3597                 ? max
3598                 : (max != UV_MAX || end != UV_MAX)
3599                   ? end - 1
3600                   : end;
3601
3602         if (octets) {
3603             UV key;
3604             if (min < start) {
3605                 if (!none || val < none) {
3606                     val += start - min;
3607                 }
3608                 min = start;
3609             }
3610             for (key = min; key <= upper; key++) {
3611                 STRLEN offset;
3612                 /* offset must be non-negative (start <= min <= key < end) */
3613                 offset = octets * (key - start);
3614                 if (bits == 8)
3615                     s[offset] = (U8)(val & 0xff);
3616                 else if (bits == 16) {
3617                     s[offset    ] = (U8)((val >>  8) & 0xff);
3618                     s[offset + 1] = (U8)( val        & 0xff);
3619                 }
3620                 else if (bits == 32) {
3621                     s[offset    ] = (U8)((val >> 24) & 0xff);
3622                     s[offset + 1] = (U8)((val >> 16) & 0xff);
3623                     s[offset + 2] = (U8)((val >>  8) & 0xff);
3624                     s[offset + 3] = (U8)( val        & 0xff);
3625                 }
3626
3627                 if (!none || val < none)
3628                     ++val;
3629             }
3630         }
3631         else { /* bits == 1, then val should be ignored */
3632             UV key;
3633             if (min < start)
3634                 min = start;
3635
3636             for (key = min; key <= upper; key++) {
3637                 const STRLEN offset = (STRLEN)(key - start);
3638                 s[offset >> 3] |= 1 << (offset & 7);
3639             }
3640         }
3641     } /* while */
3642
3643     /* Invert if the data says it should be.  Assumes that bits == 1 */
3644     if (invert_it_svp && SvUV(*invert_it_svp)) {
3645
3646         /* Unicode properties should come with all bits above PERL_UNICODE_MAX
3647          * be 0, and their inversion should also be 0, as we don't succeed any
3648          * Unicode property matches for non-Unicode code points */
3649         if (start <= PERL_UNICODE_MAX) {
3650
3651             /* The code below assumes that we never cross the
3652              * Unicode/above-Unicode boundary in a range, as otherwise we would
3653              * have to figure out where to stop flipping the bits.  Since this
3654              * boundary is divisible by a large power of 2, and swatches comes
3655              * in small powers of 2, this should be a valid assumption */
3656             assert(start + span - 1 <= PERL_UNICODE_MAX);
3657
3658             send = s + scur;
3659             while (s < send) {
3660                 *s = ~(*s);
3661                 s++;
3662             }
3663         }
3664     }
3665
3666     /* read $swash->{EXTRAS}
3667      * This code also copied to swash_to_invlist() below */
3668     x = (U8*)SvPV(*extssvp, xcur);
3669     xend = x + xcur;
3670     while (x < xend) {
3671         STRLEN namelen;
3672         U8 *namestr;
3673         SV** othersvp;
3674         HV* otherhv;
3675         STRLEN otherbits;
3676         SV **otherbitssvp, *other;
3677         U8 *s, *o, *nl;
3678         STRLEN slen, olen;
3679
3680         const U8 opc = *x++;
3681         if (opc == '\n')
3682             continue;
3683
3684         nl = (U8*)memchr(x, '\n', xend - x);
3685
3686         if (opc != '-' && opc != '+' && opc != '!' && opc != '&') {
3687             if (nl) {
3688                 x = nl + 1; /* 1 is length of "\n" */
3689                 continue;
3690             }
3691             else {
3692                 x = xend; /* to EXTRAS' end at which \n is not found */
3693                 break;
3694             }
3695         }
3696
3697         namestr = x;
3698         if (nl) {
3699             namelen = nl - namestr;
3700             x = nl + 1;
3701         }
3702         else {
3703             namelen = xend - namestr;
3704             x = xend;
3705         }
3706
3707         othersvp = hv_fetch(hv, (char *)namestr, namelen, FALSE);
3708         otherhv = MUTABLE_HV(SvRV(*othersvp));
3709         otherbitssvp = hv_fetchs(otherhv, "BITS", FALSE);
3710         otherbits = (STRLEN)SvUV(*otherbitssvp);
3711         if (bits < otherbits)
3712             Perl_croak(aTHX_ "panic: swatch_get found swatch size mismatch, "
3713                        "bits=%"UVuf", otherbits=%"UVuf, (UV)bits, (UV)otherbits);
3714
3715         /* The "other" swatch must be destroyed after. */
3716         other = swatch_get(*othersvp, start, span);
3717         o = (U8*)SvPV(other, olen);
3718
3719         if (!olen)
3720             Perl_croak(aTHX_ "panic: swatch_get got improper swatch");
3721
3722         s = (U8*)SvPV(swatch, slen);
3723         if (bits == 1 && otherbits == 1) {
3724             if (slen != olen)
3725                 Perl_croak(aTHX_ "panic: swatch_get found swatch length "
3726                            "mismatch, slen=%"UVuf", olen=%"UVuf,
3727                            (UV)slen, (UV)olen);
3728
3729             switch (opc) {
3730             case '+':
3731                 while (slen--)
3732                     *s++ |= *o++;
3733                 break;
3734             case '!':
3735                 while (slen--)
3736                     *s++ |= ~*o++;
3737                 break;
3738             case '-':
3739                 while (slen--)
3740                     *s++ &= ~*o++;
3741                 break;
3742             case '&':
3743                 while (slen--)
3744                     *s++ &= *o++;
3745                 break;
3746             default:
3747                 break;
3748             }
3749         }
3750         else {
3751             STRLEN otheroctets = otherbits >> 3;
3752             STRLEN offset = 0;
3753             U8* const send = s + slen;
3754
3755             while (s < send) {
3756                 UV otherval = 0;
3757
3758                 if (otherbits == 1) {
3759                     otherval = (o[offset >> 3] >> (offset & 7)) & 1;
3760                     ++offset;
3761                 }
3762                 else {
3763                     STRLEN vlen = otheroctets;
3764                     otherval = *o++;
3765                     while (--vlen) {
3766                         otherval <<= 8;
3767                         otherval |= *o++;
3768                     }
3769                 }
3770
3771                 if (opc == '+' && otherval)
3772                     NOOP;   /* replace with otherval */
3773                 else if (opc == '!' && !otherval)
3774                     otherval = 1;
3775                 else if (opc == '-' && otherval)
3776                     otherval = 0;
3777                 else if (opc == '&' && !otherval)
3778                     otherval = 0;
3779                 else {
3780                     s += octets; /* no replacement */
3781                     continue;
3782                 }
3783
3784                 if (bits == 8)
3785                     *s++ = (U8)( otherval & 0xff);
3786                 else if (bits == 16) {
3787                     *s++ = (U8)((otherval >>  8) & 0xff);
3788                     *s++ = (U8)( otherval        & 0xff);
3789                 }
3790                 else if (bits == 32) {
3791                     *s++ = (U8)((otherval >> 24) & 0xff);
3792                     *s++ = (U8)((otherval >> 16) & 0xff);
3793                     *s++ = (U8)((otherval >>  8) & 0xff);
3794                     *s++ = (U8)( otherval        & 0xff);
3795                 }
3796             }
3797         }
3798         sv_free(other); /* through with it! */
3799     } /* while */
3800     return swatch;
3801 }
3802
3803 HV*
3804 Perl__swash_inversion_hash(pTHX_ SV* const swash)
3805 {
3806
3807    /* Subject to change or removal.  For use only in regcomp.c and regexec.c
3808     * Can't be used on a property that is subject to user override, as it
3809     * relies on the value of SPECIALS in the swash which would be set by
3810     * utf8_heavy.pl to the hash in the non-overriden file, and hence is not set
3811     * for overridden properties
3812     *
3813     * Returns a hash which is the inversion and closure of a swash mapping.
3814     * For example, consider the input lines:
3815     * 004B              006B
3816     * 004C              006C
3817     * 212A              006B
3818     *
3819     * The returned hash would have two keys, the utf8 for 006B and the utf8 for
3820     * 006C.  The value for each key is an array.  For 006C, the array would
3821     * have two elements, the utf8 for itself, and for 004C.  For 006B, there
3822     * would be three elements in its array, the utf8 for 006B, 004B and 212A.
3823     *
3824     * Essentially, for any code point, it gives all the code points that map to
3825     * it, or the list of 'froms' for that point.
3826     *
3827     * Currently it ignores any additions or deletions from other swashes,
3828     * looking at just the main body of the swash, and if there are SPECIALS
3829     * in the swash, at that hash
3830     *
3831     * The specials hash can be extra code points, and most likely consists of
3832     * maps from single code points to multiple ones (each expressed as a string
3833     * of utf8 characters).   This function currently returns only 1-1 mappings.
3834     * However consider this possible input in the specials hash:
3835     * "\xEF\xAC\x85" => "\x{0073}\x{0074}",         # U+FB05 => 0073 0074
3836     * "\xEF\xAC\x86" => "\x{0073}\x{0074}",         # U+FB06 => 0073 0074
3837     *
3838     * Both FB05 and FB06 map to the same multi-char sequence, which we don't
3839     * currently handle.  But it also means that FB05 and FB06 are equivalent in
3840     * a 1-1 mapping which we should handle, and this relationship may not be in
3841     * the main table.  Therefore this function examines all the multi-char
3842     * sequences and adds the 1-1 mappings that come out of that.  */
3843
3844     U8 *l, *lend;
3845     STRLEN lcur;
3846     HV *const hv = MUTABLE_HV(SvRV(swash));
3847
3848     /* The string containing the main body of the table.  This will have its
3849      * assertion fail if the swash has been converted to its inversion list */
3850     SV** const listsvp = hv_fetchs(hv, "LIST", FALSE);
3851
3852     SV** const typesvp = hv_fetchs(hv, "TYPE", FALSE);
3853     SV** const bitssvp = hv_fetchs(hv, "BITS", FALSE);
3854     SV** const nonesvp = hv_fetchs(hv, "NONE", FALSE);
3855     /*SV** const extssvp = hv_fetchs(hv, "EXTRAS", FALSE);*/
3856     const U8* const typestr = (U8*)SvPV_nolen(*typesvp);
3857     const STRLEN bits  = SvUV(*bitssvp);
3858     const STRLEN octets = bits >> 3; /* if bits == 1, then octets == 0 */
3859     const UV     none  = SvUV(*nonesvp);
3860     SV **specials_p = hv_fetchs(hv, "SPECIALS", 0);
3861
3862     HV* ret = newHV();
3863
3864     PERL_ARGS_ASSERT__SWASH_INVERSION_HASH;
3865
3866     /* Must have at least 8 bits to get the mappings */
3867     if (bits != 8 && bits != 16 && bits != 32) {
3868         Perl_croak(aTHX_ "panic: swash_inversion_hash doesn't expect bits %"UVuf,
3869                                                  (UV)bits);
3870     }
3871
3872     if (specials_p) { /* It might be "special" (sometimes, but not always, a
3873                         mapping to more than one character */
3874
3875         /* Construct an inverse mapping hash for the specials */
3876         HV * const specials_hv = MUTABLE_HV(SvRV(*specials_p));
3877         HV * specials_inverse = newHV();
3878         char *char_from; /* the lhs of the map */
3879         I32 from_len;   /* its byte length */
3880         char *char_to;  /* the rhs of the map */
3881         I32 to_len;     /* its byte length */
3882         SV *sv_to;      /* and in a sv */
3883         AV* from_list;  /* list of things that map to each 'to' */
3884
3885         hv_iterinit(specials_hv);
3886
3887         /* The keys are the characters (in utf8) that map to the corresponding
3888          * utf8 string value.  Iterate through the list creating the inverse
3889          * list. */
3890         while ((sv_to = hv_iternextsv(specials_hv, &char_from, &from_len))) {
3891             SV** listp;
3892             if (! SvPOK(sv_to)) {
3893                 Perl_croak(aTHX_ "panic: value returned from hv_iternextsv() "
3894                            "unexpectedly is not a string, flags=%lu",
3895                            (unsigned long)SvFLAGS(sv_to));
3896             }
3897             /*DEBUG_U(PerlIO_printf(Perl_debug_log, "Found mapping from %"UVXf", First char of to is %"UVXf"\n", valid_utf8_to_uvchr((U8*) char_from, 0), valid_utf8_to_uvchr((U8*) SvPVX(sv_to), 0)));*/
3898
3899             /* Each key in the inverse list is a mapped-to value, and the key's
3900              * hash value is a list of the strings (each in utf8) that map to
3901              * it.  Those strings are all one character long */
3902             if ((listp = hv_fetch(specials_inverse,
3903                                     SvPVX(sv_to),
3904                                     SvCUR(sv_to), 0)))
3905             {
3906                 from_list = (AV*) *listp;
3907             }
3908             else { /* No entry yet for it: create one */
3909                 from_list = newAV();
3910                 if (! hv_store(specials_inverse,
3911                                 SvPVX(sv_to),
3912                                 SvCUR(sv_to),
3913                                 (SV*) from_list, 0))
3914                 {
3915                     Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
3916                 }
3917             }
3918
3919             /* Here have the list associated with this 'to' (perhaps newly
3920              * created and empty).  Just add to it.  Note that we ASSUME that
3921              * the input is guaranteed to not have duplications, so we don't
3922              * check for that.  Duplications just slow down execution time. */
3923             av_push(from_list, newSVpvn_utf8(char_from, from_len, TRUE));
3924         }
3925
3926         /* Here, 'specials_inverse' contains the inverse mapping.  Go through
3927          * it looking for cases like the FB05/FB06 examples above.  There would
3928          * be an entry in the hash like
3929         *       'st' => [ FB05, FB06 ]
3930         * In this example we will create two lists that get stored in the
3931         * returned hash, 'ret':
3932         *       FB05 => [ FB05, FB06 ]
3933         *       FB06 => [ FB05, FB06 ]
3934         *
3935         * Note that there is nothing to do if the array only has one element.
3936         * (In the normal 1-1 case handled below, we don't have to worry about
3937         * two lists, as everything gets tied to the single list that is
3938         * generated for the single character 'to'.  But here, we are omitting
3939         * that list, ('st' in the example), so must have multiple lists.) */
3940         while ((from_list = (AV *) hv_iternextsv(specials_inverse,
3941                                                  &char_to, &to_len)))
3942         {
3943             if (av_len(from_list) > 0) {
3944                 SSize_t i;
3945
3946                 /* We iterate over all combinations of i,j to place each code
3947                  * point on each list */
3948                 for (i = 0; i <= av_len(from_list); i++) {
3949                     SSize_t j;
3950                     AV* i_list = newAV();
3951                     SV** entryp = av_fetch(from_list, i, FALSE);
3952                     if (entryp == NULL) {
3953                         Perl_croak(aTHX_ "panic: av_fetch() unexpectedly failed");
3954                     }
3955                     if (hv_fetch(ret, SvPVX(*entryp), SvCUR(*entryp), FALSE)) {
3956                         Perl_croak(aTHX_ "panic: unexpected entry for %s", SvPVX(*entryp));
3957                     }
3958                     if (! hv_store(ret, SvPVX(*entryp), SvCUR(*entryp),
3959                                    (SV*) i_list, FALSE))
3960                     {
3961                         Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
3962                     }
3963
3964                     /* For debugging: UV u = valid_utf8_to_uvchr((U8*) SvPVX(*entryp), 0);*/
3965                     for (j = 0; j <= av_len(from_list); j++) {
3966                         entryp = av_fetch(from_list, j, FALSE);
3967                         if (entryp == NULL) {
3968                             Perl_croak(aTHX_ "panic: av_fetch() unexpectedly failed");
3969                         }
3970
3971                         /* When i==j this adds itself to the list */
3972                         av_push(i_list, newSVuv(utf8_to_uvchr_buf(
3973                                         (U8*) SvPVX(*entryp),
3974                                         (U8*) SvPVX(*entryp) + SvCUR(*entryp),
3975                                         0)));
3976                         /*DEBUG_U(PerlIO_printf(Perl_debug_log, "%s: %d: Adding %"UVXf" to list for %"UVXf"\n", __FILE__, __LINE__, valid_utf8_to_uvchr((U8*) SvPVX(*entryp), 0), u));*/
3977                     }
3978                 }
3979             }
3980         }
3981         SvREFCNT_dec(specials_inverse); /* done with it */
3982     } /* End of specials */
3983
3984     /* read $swash->{LIST} */
3985     l = (U8*)SvPV(*listsvp, lcur);
3986     lend = l + lcur;
3987
3988     /* Go through each input line */
3989     while (l < lend) {
3990         UV min, max, val;
3991         UV inverse;
3992         l = S_swash_scan_list_line(aTHX_ l, lend, &min, &max, &val,
3993                                          cBOOL(octets), typestr);
3994         if (l > lend) {
3995             break;
3996         }
3997
3998         /* Each element in the range is to be inverted */
3999         for (inverse = min; inverse <= max; inverse++) {
4000             AV* list;
4001             SV** listp;
4002             IV i;
4003             bool found_key = FALSE;
4004             bool found_inverse = FALSE;
4005
4006             /* The key is the inverse mapping */
4007             char key[UTF8_MAXBYTES+1];
4008             char* key_end = (char *) uvchr_to_utf8((U8*) key, val);
4009             STRLEN key_len = key_end - key;
4010
4011             /* Get the list for the map */
4012             if ((listp = hv_fetch(ret, key, key_len, FALSE))) {
4013                 list = (AV*) *listp;
4014             }
4015             else { /* No entry yet for it: create one */
4016                 list = newAV();
4017                 if (! hv_store(ret, key, key_len, (SV*) list, FALSE)) {
4018                     Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
4019                 }
4020             }
4021
4022             /* Look through list to see if this inverse mapping already is
4023              * listed, or if there is a mapping to itself already */
4024             for (i = 0; i <= av_len(list); i++) {
4025                 SV** entryp = av_fetch(list, i, FALSE);
4026                 SV* entry;
4027                 if (entryp == NULL) {
4028                     Perl_croak(aTHX_ "panic: av_fetch() unexpectedly failed");
4029                 }
4030                 entry = *entryp;
4031                 /*DEBUG_U(PerlIO_printf(Perl_debug_log, "list for %"UVXf" contains %"UVXf"\n", val, SvUV(entry)));*/
4032                 if (SvUV(entry) == val) {
4033                     found_key = TRUE;
4034                 }
4035                 if (SvUV(entry) == inverse) {
4036                     found_inverse = TRUE;
4037                 }
4038
4039                 /* No need to continue searching if found everything we are
4040                  * looking for */
4041                 if (found_key && found_inverse) {
4042                     break;
4043                 }
4044             }
4045
4046             /* Make sure there is a mapping to itself on the list */
4047             if (! found_key) {
4048                 av_push(list, newSVuv(val));
4049                 /*DEBUG_U(PerlIO_printf(Perl_debug_log, "%s: %d: Adding %"UVXf" to list for %"UVXf"\n", __FILE__, __LINE__, val, val));*/
4050             }
4051
4052
4053             /* Simply add the value to the list */
4054             if (! found_inverse) {
4055                 av_push(list, newSVuv(inverse));
4056                 /*DEBUG_U(PerlIO_printf(Perl_debug_log, "%s: %d: Adding %"UVXf" to list for %"UVXf"\n", __FILE__, __LINE__, inverse, val));*/
4057             }
4058
4059             /* swatch_get() increments the value of val for each element in the
4060              * range.  That makes more compact tables possible.  You can
4061              * express the capitalization, for example, of all consecutive
4062              * letters with a single line: 0061\t007A\t0041 This maps 0061 to
4063              * 0041, 0062 to 0042, etc.  I (khw) have never understood 'none',
4064              * and it's not documented; it appears to be used only in
4065              * implementing tr//; I copied the semantics from swatch_get(), just
4066              * in case */
4067             if (!none || val < none) {
4068                 ++val;
4069             }
4070         }
4071     }
4072
4073     return ret;
4074 }
4075
4076 SV*
4077 Perl__swash_to_invlist(pTHX_ SV* const swash)
4078 {
4079
4080    /* Subject to change or removal.  For use only in one place in regcomp.c.
4081     * Ownership is given to one reference count in the returned SV* */
4082
4083     U8 *l, *lend;
4084     char *loc;
4085     STRLEN lcur;
4086     HV *const hv = MUTABLE_HV(SvRV(swash));
4087     UV elements = 0;    /* Number of elements in the inversion list */
4088     U8 empty[] = "";
4089     SV** listsvp;
4090     SV** typesvp;
4091     SV** bitssvp;
4092     SV** extssvp;
4093     SV** invert_it_svp;
4094
4095     U8* typestr;
4096     STRLEN bits;
4097     STRLEN octets; /* if bits == 1, then octets == 0 */
4098     U8 *x, *xend;
4099     STRLEN xcur;
4100
4101     SV* invlist;
4102
4103     PERL_ARGS_ASSERT__SWASH_TO_INVLIST;
4104
4105     /* If not a hash, it must be the swash's inversion list instead */
4106     if (SvTYPE(hv) != SVt_PVHV) {
4107         return SvREFCNT_inc_simple_NN((SV*) hv);
4108     }
4109
4110     /* The string containing the main body of the table */
4111     listsvp = hv_fetchs(hv, "LIST", FALSE);
4112     typesvp = hv_fetchs(hv, "TYPE", FALSE);
4113     bitssvp = hv_fetchs(hv, "BITS", FALSE);
4114     extssvp = hv_fetchs(hv, "EXTRAS", FALSE);
4115     invert_it_svp = hv_fetchs(hv, "INVERT_IT", FALSE);
4116
4117     typestr = (U8*)SvPV_nolen(*typesvp);
4118     bits  = SvUV(*bitssvp);
4119     octets = bits >> 3; /* if bits == 1, then octets == 0 */
4120
4121     /* read $swash->{LIST} */
4122     if (SvPOK(*listsvp)) {
4123         l = (U8*)SvPV(*listsvp, lcur);
4124     }
4125     else {
4126         /* LIST legitimately doesn't contain a string during compilation phases
4127          * of Perl itself, before the Unicode tables are generated.  In this
4128          * case, just fake things up by creating an empty list */
4129         l = empty;
4130         lcur = 0;
4131     }
4132     loc = (char *) l;
4133     lend = l + lcur;
4134
4135     /* Scan the input to count the number of lines to preallocate array size
4136      * based on worst possible case, which is each line in the input creates 2
4137      * elements in the inversion list: 1) the beginning of a range in the list;
4138      * 2) the beginning of a range not in the list.  */
4139     while ((loc = (strchr(loc, '\n'))) != NULL) {
4140         elements += 2;
4141         loc++;
4142     }
4143
4144     /* If the ending is somehow corrupt and isn't a new line, add another
4145      * element for the final range that isn't in the inversion list */
4146     if (! (*lend == '\n'
4147         || (*lend == '\0' && (lcur == 0 || *(lend - 1) == '\n'))))
4148     {
4149         elements++;
4150     }
4151
4152     invlist = _new_invlist(elements);
4153
4154     /* Now go through the input again, adding each range to the list */
4155     while (l < lend) {
4156         UV start, end;
4157         UV val;         /* Not used by this function */
4158
4159         l = S_swash_scan_list_line(aTHX_ l, lend, &start, &end, &val,
4160                                          cBOOL(octets), typestr);
4161
4162         if (l > lend) {
4163             break;
4164         }
4165
4166         invlist = _add_range_to_invlist(invlist, start, end);
4167     }
4168
4169     /* Invert if the data says it should be */
4170     if (invert_it_svp && SvUV(*invert_it_svp)) {
4171         _invlist_invert_prop(invlist);
4172     }
4173
4174     /* This code is copied from swatch_get()
4175      * read $swash->{EXTRAS} */
4176     x = (U8*)SvPV(*extssvp, xcur);
4177     xend = x + xcur;
4178     while (x < xend) {
4179         STRLEN namelen;
4180         U8 *namestr;
4181         SV** othersvp;
4182         HV* otherhv;
4183         STRLEN otherbits;
4184         SV **otherbitssvp, *other;
4185         U8 *nl;
4186
4187         const U8 opc = *x++;
4188         if (opc == '\n')
4189             continue;
4190
4191         nl = (U8*)memchr(x, '\n', xend - x);
4192
4193         if (opc != '-' && opc != '+' && opc != '!' && opc != '&') {
4194             if (nl) {
4195                 x = nl + 1; /* 1 is length of "\n" */
4196                 continue;
4197             }
4198             else {
4199                 x = xend; /* to EXTRAS' end at which \n is not found */
4200                 break;
4201             }
4202         }
4203
4204         namestr = x;
4205         if (nl) {
4206             namelen = nl - namestr;
4207             x = nl + 1;
4208         }
4209         else {
4210             namelen = xend - namestr;
4211             x = xend;
4212         }
4213
4214         othersvp = hv_fetch(hv, (char *)namestr, namelen, FALSE);
4215         otherhv = MUTABLE_HV(SvRV(*othersvp));
4216         otherbitssvp = hv_fetchs(otherhv, "BITS", FALSE);
4217         otherbits = (STRLEN)SvUV(*otherbitssvp);
4218
4219         if (bits != otherbits || bits != 1) {
4220             Perl_croak(aTHX_ "panic: _swash_to_invlist only operates on boolean "
4221                        "properties, bits=%"UVuf", otherbits=%"UVuf,
4222                        (UV)bits, (UV)otherbits);
4223         }
4224
4225         /* The "other" swatch must be destroyed after. */
4226         other = _swash_to_invlist((SV *)*othersvp);
4227
4228         /* End of code copied from swatch_get() */
4229         switch (opc) {
4230         case '+':
4231             _invlist_union(invlist, other, &invlist);
4232             break;
4233         case '!':
4234             _invlist_union_maybe_complement_2nd(invlist, other, TRUE, &invlist);
4235             break;
4236         case '-':
4237             _invlist_subtract(invlist, other, &invlist);
4238             break;
4239         case '&':
4240             _invlist_intersection(invlist, other, &invlist);
4241             break;
4242         default:
4243             break;
4244         }
4245         sv_free(other); /* through with it! */
4246     }
4247
4248     return invlist;
4249 }
4250
4251 SV*
4252 Perl__get_swash_invlist(pTHX_ SV* const swash)
4253 {
4254     SV** ptr;
4255
4256     PERL_ARGS_ASSERT__GET_SWASH_INVLIST;
4257
4258     if (! SvROK(swash)) {
4259         return NULL;
4260     }
4261
4262     /* If it really isn't a hash, it isn't really swash; must be an inversion
4263      * list */
4264     if (SvTYPE(SvRV(swash)) != SVt_PVHV) {
4265         return SvRV(swash);
4266     }
4267
4268     ptr = hv_fetchs(MUTABLE_HV(SvRV(swash)), "V", FALSE);
4269     if (! ptr) {
4270         return NULL;
4271     }
4272
4273     return *ptr;
4274 }
4275
4276 bool
4277 Perl_check_utf8_print(pTHX_ const U8* s, const STRLEN len)
4278 {
4279     /* May change: warns if surrogates, non-character code points, or
4280      * non-Unicode code points are in s which has length len bytes.  Returns
4281      * TRUE if none found; FALSE otherwise.  The only other validity check is
4282      * to make sure that this won't exceed the string's length */
4283
4284     const U8* const e = s + len;
4285     bool ok = TRUE;
4286
4287     PERL_ARGS_ASSERT_CHECK_UTF8_PRINT;
4288
4289     while (s < e) {
4290         if (UTF8SKIP(s) > len) {
4291             Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
4292                            "%s in %s", unees, PL_op ? OP_DESC(PL_op) : "print");
4293             return FALSE;
4294         }
4295         if (UNLIKELY(*s >= UTF8_FIRST_PROBLEMATIC_CODE_POINT_FIRST_BYTE)) {
4296             STRLEN char_len;
4297             if (UTF8_IS_SUPER(s)) {
4298                 if (ckWARN_d(WARN_NON_UNICODE)) {
4299                     UV uv = utf8_to_uvchr_buf(s, e, &char_len);
4300                     Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
4301                         "Code point 0x%04"UVXf" is not Unicode, may not be portable", uv);
4302                     ok = FALSE;
4303                 }
4304             }
4305             else if (UTF8_IS_SURROGATE(s)) {
4306                 if (ckWARN_d(WARN_SURROGATE)) {
4307                     UV uv = utf8_to_uvchr_buf(s, e, &char_len);
4308                     Perl_warner(aTHX_ packWARN(WARN_SURROGATE),
4309                         "Unicode surrogate U+%04"UVXf" is illegal in UTF-8", uv);
4310                     ok = FALSE;
4311                 }
4312             }
4313             else if
4314                 ((UTF8_IS_NONCHAR_GIVEN_THAT_NON_SUPER_AND_GE_PROBLEMATIC(s))
4315                  && (ckWARN_d(WARN_NONCHAR)))
4316             {
4317                 UV uv = utf8_to_uvchr_buf(s, e, &char_len);
4318                 Perl_warner(aTHX_ packWARN(WARN_NONCHAR),
4319                     "Unicode non-character U+%04"UVXf" is illegal for open interchange", uv);
4320                 ok = FALSE;
4321             }
4322         }
4323         s += UTF8SKIP(s);
4324     }
4325
4326     return ok;
4327 }
4328
4329 /*
4330 =for apidoc pv_uni_display
4331
4332 Build to the scalar C<dsv> a displayable version of the string C<spv>,
4333 length C<len>, the displayable version being at most C<pvlim> bytes long
4334 (if longer, the rest is truncated and "..." will be appended).
4335
4336 The C<flags> argument can have UNI_DISPLAY_ISPRINT set to display
4337 isPRINT()able characters as themselves, UNI_DISPLAY_BACKSLASH
4338 to display the \\[nrfta\\] as the backslashed versions (like '\n')
4339 (UNI_DISPLAY_BACKSLASH is preferred over UNI_DISPLAY_ISPRINT for \\).
4340 UNI_DISPLAY_QQ (and its alias UNI_DISPLAY_REGEX) have both
4341 UNI_DISPLAY_BACKSLASH and UNI_DISPLAY_ISPRINT turned on.
4342
4343 The pointer to the PV of the C<dsv> is returned.
4344
4345 =cut */
4346 char *
4347 Perl_pv_uni_display(pTHX_ SV *dsv, const U8 *spv, STRLEN len, STRLEN pvlim, UV flags)
4348 {
4349     int truncated = 0;
4350     const char *s, *e;
4351
4352     PERL_ARGS_ASSERT_PV_UNI_DISPLAY;
4353
4354     sv_setpvs(dsv, "");
4355     SvUTF8_off(dsv);
4356     for (s = (const char *)spv, e = s + len; s < e; s += UTF8SKIP(s)) {
4357          UV u;
4358           /* This serves double duty as a flag and a character to print after
4359              a \ when flags & UNI_DISPLAY_BACKSLASH is true.
4360           */
4361          char ok = 0;
4362
4363          if (pvlim && SvCUR(dsv) >= pvlim) {
4364               truncated++;
4365               break;
4366          }
4367          u = utf8_to_uvchr_buf((U8*)s, (U8*)e, 0);
4368          if (u < 256) {
4369              const unsigned char c = (unsigned char)u & 0xFF;
4370              if (flags & UNI_DISPLAY_BACKSLASH) {
4371                  switch (c) {
4372                  case '\n':
4373                      ok = 'n'; break;
4374                  case '\r':
4375                      ok = 'r'; break;
4376                  case '\t':
4377                      ok = 't'; break;
4378                  case '\f':
4379                      ok = 'f'; break;
4380                  case '\a':
4381                      ok = 'a'; break;
4382                  case '\\':
4383                      ok = '\\'; break;
4384                  default: break;
4385                  }
4386                  if (ok) {
4387                      const char string = ok;
4388                      sv_catpvs(dsv, "\\");
4389                      sv_catpvn(dsv, &string, 1);
4390                  }
4391              }
4392              /* isPRINT() is the locale-blind version. */
4393              if (!ok && (flags & UNI_DISPLAY_ISPRINT) && isPRINT(c)) {
4394                  const char string = c;
4395                  sv_catpvn(dsv, &string, 1);
4396                  ok = 1;
4397              }
4398          }
4399          if (!ok)
4400              Perl_sv_catpvf(aTHX_ dsv, "\\x{%"UVxf"}", u);
4401     }
4402     if (truncated)
4403          sv_catpvs(dsv, "...");
4404
4405     return SvPVX(dsv);
4406 }
4407
4408 /*
4409 =for apidoc sv_uni_display
4410
4411 Build to the scalar C<dsv> a displayable version of the scalar C<sv>,
4412 the displayable version being at most C<pvlim> bytes long
4413 (if longer, the rest is truncated and "..." will be appended).
4414
4415 The C<flags> argument is as in L</pv_uni_display>().
4416
4417 The pointer to the PV of the C<dsv> is returned.
4418
4419 =cut
4420 */
4421 char *
4422 Perl_sv_uni_display(pTHX_ SV *dsv, SV *ssv, STRLEN pvlim, UV flags)
4423 {
4424     const char * const ptr =
4425         isREGEXP(ssv) ? RX_WRAPPED((REGEXP*)ssv) : SvPVX_const(ssv);
4426
4427     PERL_ARGS_ASSERT_SV_UNI_DISPLAY;
4428
4429     return Perl_pv_uni_display(aTHX_ dsv, (const U8*)ptr,
4430                                 SvCUR(ssv), pvlim, flags);
4431 }
4432
4433 /*
4434 =for apidoc foldEQ_utf8
4435
4436 Returns true if the leading portions of the strings C<s1> and C<s2> (either or both
4437 of which may be in UTF-8) are the same case-insensitively; false otherwise.
4438 How far into the strings to compare is determined by other input parameters.
4439
4440 If C<u1> is true, the string C<s1> is assumed to be in UTF-8-encoded Unicode;
4441 otherwise it is assumed to be in native 8-bit encoding.  Correspondingly for C<u2>
4442 with respect to C<s2>.
4443
4444 If the byte length C<l1> is non-zero, it says how far into C<s1> to check for fold
4445 equality.  In other words, C<s1>+C<l1> will be used as a goal to reach.  The
4446 scan will not be considered to be a match unless the goal is reached, and
4447 scanning won't continue past that goal.  Correspondingly for C<l2> with respect to
4448 C<s2>.
4449
4450 If C<pe1> is non-NULL and the pointer it points to is not NULL, that pointer is
4451 considered an end pointer to the position 1 byte past the maximum point
4452 in C<s1> beyond which scanning will not continue under any circumstances.
4453 (This routine assumes that UTF-8 encoded input strings are not malformed;
4454 malformed input can cause it to read past C<pe1>).
4455 This means that if both C<l1> and C<pe1> are specified, and C<pe1>
4456 is less than C<s1>+C<l1>, the match will never be successful because it can
4457 never
4458 get as far as its goal (and in fact is asserted against).  Correspondingly for
4459 C<pe2> with respect to C<s2>.
4460
4461 At least one of C<s1> and C<s2> must have a goal (at least one of C<l1> and
4462 C<l2> must be non-zero), and if both do, both have to be
4463 reached for a successful match.   Also, if the fold of a character is multiple
4464 characters, all of them must be matched (see tr21 reference below for
4465 'folding').
4466
4467 Upon a successful match, if C<pe1> is non-NULL,
4468 it will be set to point to the beginning of the I<next> character of C<s1>
4469 beyond what was matched.  Correspondingly for C<pe2> and C<s2>.
4470
4471 For case-insensitiveness, the "casefolding" of Unicode is used
4472 instead of upper/lowercasing both the characters, see
4473 L<http://www.unicode.org/unicode/reports/tr21/> (Case Mappings).
4474
4475 =cut */
4476
4477 /* A flags parameter has been added which may change, and hence isn't
4478  * externally documented.  Currently it is:
4479  *  0 for as-documented above
4480  *  FOLDEQ_UTF8_NOMIX_ASCII meaning that if a non-ASCII character folds to an
4481                             ASCII one, to not match
4482  *  FOLDEQ_UTF8_LOCALE      meaning that locale rules are to be used for code
4483  *                          points below 256; unicode rules for above 255; and
4484  *                          folds that cross those boundaries are disallowed,
4485  *                          like the NOMIX_ASCII option
4486  *  FOLDEQ_S1_ALREADY_FOLDED s1 has already been folded before calling this
4487  *                           routine.  This allows that step to be skipped.
4488  *  FOLDEQ_S2_ALREADY_FOLDED   Similarly.
4489  */
4490 I32
4491 Perl_foldEQ_utf8_flags(pTHX_ const char *s1, char **pe1, UV l1, bool u1, const char *s2, char **pe2, UV l2, bool u2, U32 flags)
4492 {
4493     dVAR;
4494     const U8 *p1  = (const U8*)s1; /* Point to current char */
4495     const U8 *p2  = (const U8*)s2;
4496     const U8 *g1 = NULL;       /* goal for s1 */
4497     const U8 *g2 = NULL;
4498     const U8 *e1 = NULL;       /* Don't scan s1 past this */
4499     U8 *f1 = NULL;             /* Point to current folded */
4500     const U8 *e2 = NULL;
4501     U8 *f2 = NULL;
4502     STRLEN n1 = 0, n2 = 0;              /* Number of bytes in current char */
4503     U8 foldbuf1[UTF8_MAXBYTES_CASE+1];
4504     U8 foldbuf2[UTF8_MAXBYTES_CASE+1];
4505
4506     PERL_ARGS_ASSERT_FOLDEQ_UTF8_FLAGS;
4507
4508     assert( ! ((flags & (FOLDEQ_UTF8_NOMIX_ASCII | FOLDEQ_UTF8_LOCALE))
4509            && (flags & (FOLDEQ_S1_ALREADY_FOLDED | FOLDEQ_S2_ALREADY_FOLDED))));
4510     /* The algorithm is to trial the folds without regard to the flags on
4511      * the first line of the above assert(), and then see if the result
4512      * violates them.  This means that the inputs can't be pre-folded to a
4513      * violating result, hence the assert.  This could be changed, with the
4514      * addition of extra tests here for the already-folded case, which would
4515      * slow it down.  That cost is more than any possible gain for when these
4516      * flags are specified, as the flags indicate /il or /iaa matching which
4517      * is less common than /iu, and I (khw) also believe that real-world /il
4518      * and /iaa matches are most likely to involve code points 0-255, and this
4519      * function only under rare conditions gets called for 0-255. */
4520
4521     if (pe1) {
4522         e1 = *(U8**)pe1;
4523     }
4524
4525     if (l1) {
4526         g1 = (const U8*)s1 + l1;
4527     }
4528
4529     if (pe2) {
4530         e2 = *(U8**)pe2;
4531     }
4532
4533     if (l2) {
4534         g2 = (const U8*)s2 + l2;
4535     }
4536
4537     /* Must have at least one goal */
4538     assert(g1 || g2);
4539
4540     if (g1) {
4541
4542         /* Will never match if goal is out-of-bounds */
4543         assert(! e1  || e1 >= g1);
4544
4545         /* Here, there isn't an end pointer, or it is beyond the goal.  We
4546         * only go as far as the goal */
4547         e1 = g1;
4548     }
4549     else {
4550         assert(e1);    /* Must have an end for looking at s1 */
4551     }
4552
4553     /* Same for goal for s2 */
4554     if (g2) {
4555         assert(! e2  || e2 >= g2);
4556         e2 = g2;
4557     }
4558     else {
4559         assert(e2);
4560     }
4561
4562     /* If both operands are already folded, we could just do a memEQ on the
4563      * whole strings at once, but it would be better if the caller realized
4564      * this and didn't even call us */
4565
4566     /* Look through both strings, a character at a time */
4567     while (p1 < e1 && p2 < e2) {
4568
4569         /* If at the beginning of a new character in s1, get its fold to use
4570          * and the length of the fold.  (exception: locale rules just get the
4571          * character to a single byte) */
4572         if (n1 == 0) {
4573             if (flags & FOLDEQ_S1_ALREADY_FOLDED) {
4574                 f1 = (U8 *) p1;
4575                 n1 = UTF8SKIP(f1);
4576             }
4577             else {
4578                 /* If in locale matching, we use two sets of rules, depending
4579                  * on if the code point is above or below 255.  Here, we test
4580                  * for and handle locale rules */
4581                 if ((flags & FOLDEQ_UTF8_LOCALE)
4582                     && (! u1 || ! UTF8_IS_ABOVE_LATIN1(*p1)))
4583                 {
4584                     /* There is no mixing of code points above and below 255. */
4585                     if (u2 && UTF8_IS_ABOVE_LATIN1(*p2)) {
4586                         return 0;
4587                     }
4588
4589                     /* We handle locale rules by converting, if necessary, the
4590                      * code point to a single byte. */
4591                     if (! u1 || UTF8_IS_INVARIANT(*p1)) {
4592                         *foldbuf1 = *p1;
4593                     }
4594                     else {
4595                         *foldbuf1 = TWO_BYTE_UTF8_TO_NATIVE(*p1, *(p1 + 1));
4596                     }
4597                     n1 = 1;
4598                 }
4599                 else if (isASCII(*p1)) {    /* Note, that here won't be both
4600                                                ASCII and using locale rules */
4601
4602                     /* If trying to mix non- with ASCII, and not supposed to,
4603                      * fail */
4604                     if ((flags & FOLDEQ_UTF8_NOMIX_ASCII) && ! isASCII(*p2)) {
4605                         return 0;
4606                     }
4607                     n1 = 1;
4608                     *foldbuf1 = toFOLD(*p1);
4609                 }
4610                 else if (u1) {
4611                     to_utf8_fold(p1, foldbuf1, &n1);
4612                 }
4613                 else {  /* Not utf8, get utf8 fold */
4614                     to_uni_fold(*p1, foldbuf1, &n1);
4615                 }
4616                 f1 = foldbuf1;
4617             }
4618         }
4619
4620         if (n2 == 0) {    /* Same for s2 */
4621             if (flags & FOLDEQ_S2_ALREADY_FOLDED) {
4622                 f2 = (U8 *) p2;
4623                 n2 = UTF8SKIP(f2);
4624             }
4625             else {
4626                 if ((flags & FOLDEQ_UTF8_LOCALE)
4627                     && (! u2 || ! UTF8_IS_ABOVE_LATIN1(*p2)))
4628                 {
4629                     /* Here, the next char in s2 is < 256.  We've already
4630                      * worked on s1, and if it isn't also < 256, can't match */
4631                     if (u1 && UTF8_IS_ABOVE_LATIN1(*p1)) {
4632                         return 0;
4633                     }
4634                     if (! u2 || UTF8_IS_INVARIANT(*p2)) {
4635                         *foldbuf2 = *p2;
4636                     }
4637                     else {
4638                         *foldbuf2 = TWO_BYTE_UTF8_TO_NATIVE(*p2, *(p2 + 1));
4639                     }
4640
4641                     /* Use another function to handle locale rules.  We've made
4642                      * sure that both characters to compare are single bytes */
4643                     if (! foldEQ_locale((char *) f1, (char *) foldbuf2, 1)) {
4644                         return 0;
4645                     }
4646                     n1 = n2 = 0;
4647                 }
4648                 else if (isASCII(*p2)) {
4649                     if ((flags & FOLDEQ_UTF8_NOMIX_ASCII) && ! isASCII(*p1)) {
4650                         return 0;
4651                     }
4652                     n2 = 1;
4653                     *foldbuf2 = toFOLD(*p2);
4654                 }
4655                 else if (u2) {
4656                     to_utf8_fold(p2, foldbuf2, &n2);
4657                 }
4658                 else {
4659                     to_uni_fold(*p2, foldbuf2, &n2);
4660                 }
4661                 f2 = foldbuf2;
4662             }
4663         }
4664
4665         /* Here f1 and f2 point to the beginning of the strings to compare.
4666          * These strings are the folds of the next character from each input
4667          * string, stored in utf8. */
4668
4669         /* While there is more to look for in both folds, see if they
4670         * continue to match */
4671         while (n1 && n2) {
4672             U8 fold_length = UTF8SKIP(f1);
4673             if (fold_length != UTF8SKIP(f2)
4674                 || (fold_length == 1 && *f1 != *f2) /* Short circuit memNE
4675                                                        function call for single
4676                                                        byte */
4677                 || memNE((char*)f1, (char*)f2, fold_length))
4678             {
4679                 return 0; /* mismatch */
4680             }
4681
4682             /* Here, they matched, advance past them */
4683             n1 -= fold_length;
4684             f1 += fold_length;
4685             n2 -= fold_length;
4686             f2 += fold_length;
4687         }
4688
4689         /* When reach the end of any fold, advance the input past it */
4690         if (n1 == 0) {
4691             p1 += u1 ? UTF8SKIP(p1) : 1;
4692         }
4693         if (n2 == 0) {
4694             p2 += u2 ? UTF8SKIP(p2) : 1;
4695         }
4696     } /* End of loop through both strings */
4697
4698     /* A match is defined by each scan that specified an explicit length
4699     * reaching its final goal, and the other not having matched a partial
4700     * character (which can happen when the fold of a character is more than one
4701     * character). */
4702     if (! ((g1 == 0 || p1 == g1) && (g2 == 0 || p2 == g2)) || n1 || n2) {
4703         return 0;
4704     }
4705
4706     /* Successful match.  Set output pointers */
4707     if (pe1) {
4708         *pe1 = (char*)p1;
4709     }
4710     if (pe2) {
4711         *pe2 = (char*)p2;
4712     }
4713     return 1;
4714 }
4715
4716 /* XXX The next four functions should likely be moved to mathoms.c once all
4717  * occurrences of them are removed from the core; some cpan-upstream modules
4718  * still use them */
4719
4720 U8 *
4721 Perl_uvuni_to_utf8(pTHX_ U8 *d, UV uv)
4722 {
4723     PERL_ARGS_ASSERT_UVUNI_TO_UTF8;
4724
4725     return Perl_uvoffuni_to_utf8_flags(aTHX_ d, uv, 0);
4726 }
4727
4728 UV
4729 Perl_utf8n_to_uvuni(pTHX_ const U8 *s, STRLEN curlen, STRLEN *retlen, U32 flags)
4730 {
4731     PERL_ARGS_ASSERT_UTF8N_TO_UVUNI;
4732
4733     return NATIVE_TO_UNI(utf8n_to_uvchr(s, curlen, retlen, flags));
4734 }
4735
4736 /*
4737 =for apidoc uvuni_to_utf8_flags
4738
4739 Instead you almost certainly want to use L</uvchr_to_utf8> or
4740 L</uvchr_to_utf8_flags>>.
4741
4742 This function is a deprecated synonym for L</uvoffuni_to_utf8_flags>,
4743 which itself, while not deprecated, should be used only in isolated
4744 circumstances.  These functions were useful for code that wanted to handle
4745 both EBCDIC and ASCII platforms with Unicode properties, but starting in Perl
4746 v5.20, the distinctions between the platforms have mostly been made invisible
4747 to most code, so this function is quite unlikely to be what you want.
4748
4749 =cut
4750 */
4751
4752 U8 *
4753 Perl_uvuni_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags)
4754 {
4755     PERL_ARGS_ASSERT_UVUNI_TO_UTF8_FLAGS;
4756
4757     return uvoffuni_to_utf8_flags(d, uv, flags);
4758 }
4759
4760 /*
4761 =for apidoc utf8n_to_uvuni
4762
4763 Instead use L</utf8_to_uvchr_buf>, or rarely, L</utf8n_to_uvchr>.
4764
4765 This function was usefulfor code that wanted to handle both EBCDIC and
4766 ASCII platforms with Unicode properties, but starting in Perl v5.20, the
4767 distinctions between the platforms have mostly been made invisible to most
4768 code, so this function is quite unlikely to be what you want.
4769 C<L<NATIVE_TO_UNI(utf8_to_uvchr_buf(...))|/utf8_to_uvchr_buf>> instead.
4770
4771 =cut
4772 */
4773
4774 /*
4775  * Local variables:
4776  * c-indentation-style: bsd
4777  * c-basic-offset: 4
4778  * indent-tabs-mode: nil
4779  * End:
4780  *
4781  * ex: set ts=8 sts=4 sw=4 et:
4782  */