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