Debian Codegraph @

generic/tclUtf.c

raw
1 /*
2 * tclUtf.c --
3 *
4 * Routines for manipulating UTF-8 strings.
5 *
6 * Copyright (c) 1997-1998 Sun Microsystems, Inc.
7 *
8 * See the file "license.terms" for information on usage and redistribution of
9 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
10 */
11
12 #include "tclInt.h"
13
14 /*
15 * Include the static character classification tables and macros.
16 */
17
18 #include "tclUniData.c"
19
20 /*
21 * The following macros are used for fast character category tests. The x_BITS
22 * values are shifted right by the category value to determine whether the
23 * given category is included in the set.
24 */
25
26 #define ALPHA_BITS ((1 << UPPERCASE_LETTER) | (1 << LOWERCASE_LETTER) \
27 | (1 << TITLECASE_LETTER) | (1 << MODIFIER_LETTER) | (1<<OTHER_LETTER))
28
29 #define CONTROL_BITS ((1 << CONTROL) | (1 << FORMAT))
30
31 #define DIGIT_BITS (1 << DECIMAL_DIGIT_NUMBER)
32
33 #define SPACE_BITS ((1 << SPACE_SEPARATOR) | (1 << LINE_SEPARATOR) \
34 | (1 << PARAGRAPH_SEPARATOR))
35
36 #define WORD_BITS (ALPHA_BITS | DIGIT_BITS | (1 << CONNECTOR_PUNCTUATION))
37
38 #define PUNCT_BITS ((1 << CONNECTOR_PUNCTUATION) | \
39 (1 << DASH_PUNCTUATION) | (1 << OPEN_PUNCTUATION) | \
40 (1 << CLOSE_PUNCTUATION) | (1 << INITIAL_QUOTE_PUNCTUATION) | \
41 (1 << FINAL_QUOTE_PUNCTUATION) | (1 << OTHER_PUNCTUATION))
42
43 #define GRAPH_BITS (WORD_BITS | PUNCT_BITS | \
44 (1 << NON_SPACING_MARK) | (1 << ENCLOSING_MARK) | \
45 (1 << COMBINING_SPACING_MARK) | (1 << LETTER_NUMBER) | \
46 (1 << OTHER_NUMBER) | \
47 (1 << MATH_SYMBOL) | (1 << CURRENCY_SYMBOL) | \
48 (1 << MODIFIER_SYMBOL) | (1 << OTHER_SYMBOL))
49
50 /*
51 * Unicode characters less than this value are represented by themselves in
52 * UTF-8 strings.
53 */
54
55 #define UNICODE_SELF 0x80
56
57 /*
58 * The following structures are used when mapping between Unicode (UCS-2) and
59 * UTF-8.
60 */
61
62 static const unsigned char totalBytes[256] = {
63 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
64 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
65 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
66 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
67 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
68 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
69 2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
70 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
71 #if TCL_UTF_MAX > 3
72 4,4,4,4,4,
73 #else
74 1,1,1,1,1,
75 #endif
76 1,1,1,1,1,1,1,1,1,1,1
77 };
78
79 static const unsigned char complete[256] = {
80 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
81 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
82 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
83 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
84 /* Tcl_UtfCharComplete() might point to 2nd byte of valid 4-byte sequence */
85 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
86 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
87 /* End of "continuation byte section" */
88 2,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
89 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
90 #if TCL_UTF_MAX > 3
91 4,4,4,4,4,
92 #else
93 /* Tcl_UtfToUniChar() accesses src[1] and src[2] to check whether
94 * the UTF-8 sequence is valid, so we cannot use 1 here. */
95 3,3,3,3,3,
96 #endif
97 1,1,1,1,1,1,1,1,1,1,1
98 };
99
100 /*
101 * Functions used only in this module.
102 */
103
104 static int UtfCount(int ch);
105 static int Invalid(const char *src);
106 static int UCS4ToUpper(int ch);
107 static int UCS4ToTitle(int ch);
108
109 /*
110 *---------------------------------------------------------------------------
111 *
112 * UtfCount --
113 *
114 * Find the number of bytes in the Utf character "ch".
115 *
116 * Results:
117 * The return values is the number of bytes in the Utf character "ch".
118 *
119 * Side effects:
120 * None.
121 *
122 *---------------------------------------------------------------------------
123 */
124
125 static inline int
126 UtfCount(
127 int ch) /* The Unicode character whose size is returned. */
128 {
129 if ((unsigned)(ch - 1) < (UNICODE_SELF - 1)) {
130 return 1;
131 }
132 if (ch <= 0x7FF) {
133 return 2;
134 }
135 #if TCL_UTF_MAX > 3
136 if (((unsigned)(ch - 0x10000) <= 0xFFFFF)) {
137 return 4;
138 }
139 #endif
140 return 3;
141 }
142
143 /*
144 *---------------------------------------------------------------------------
145 *
146 * Invalid --
147 *
148 * Given a pointer to a two-byte prefix of a well-formed UTF-8 byte
149 * sequence (a lead byte followed by a trail byte) this routine
150 * examines those two bytes to determine whether the sequence is
151 * invalid in UTF-8. This might be because it is an overlong
152 * encoding, or because it encodes something out of the proper range.
153 *
154 * Given a pointer to the bytes \xF8 or \xFC , this routine will
155 * try to read beyond the end of the "bounds" table. Callers must
156 * prevent this.
157 *
158 * Given a pointer to something else (an ASCII byte, a trail byte,
159 * or another byte that can never begin a valid byte sequence such
160 * as \xF5) this routine returns false. That makes the routine poorly
161 * named, as it does not detect and report all invalid sequences.
162 *
163 * Callers have to take care that this routine does something useful
164 * for their needs.
165 *
166 * Results:
167 * A boolean.
168 *---------------------------------------------------------------------------
169 */
170
171 static const unsigned char bounds[28] = {
172 0x80, 0x80, /* \xC0 accepts \x80 only */
173 0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF,
174 0x80, 0xBF, /* (\xC4 - \xDC) -- all sequences valid */
175 0xA0, 0xBF, /* \xE0\x80 through \xE0\x9F are invalid prefixes */
176 0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF, /* (\xE4 - \xEC) -- all valid */
177 #if TCL_UTF_MAX > 3
178 0x90, 0xBF, /* \xF0\x80 through \xF0\x8F are invalid prefixes */
179 0x80, 0x8F /* \xF4\x90 and higher are invalid prefixes */
180 #else
181 0xC0, 0xBF, /* Not used, but reject all again for safety. */
182 0xC0, 0xBF /* Not used, but reject all again for safety. */
183 #endif
184 };
185
186 static int
187 Invalid(
188 const char *src) /* Points to lead byte of a UTF-8 byte sequence */
189 {
190 unsigned char byte = UCHAR(*src);
191 int index;
192
193 if ((byte & 0xC3) == 0xC0) {
194 /* Only lead bytes 0xC0, 0xE0, 0xF0, 0xF4 need examination */
195 index = (byte - 0xC0) >> 1;
196 if (UCHAR(src[1]) < bounds[index] || UCHAR(src[1]) > bounds[index+1]) {
197 /* Out of bounds - report invalid. */
198 return 1;
199 }
200 }
201 return 0;
202 }
203
204 /*
205 *---------------------------------------------------------------------------
206 *
207 * Tcl_UniCharToUtf --
208 *
209 * Stores the given Tcl_UniChar as a sequence of UTF-8 bytes in the
210 * provided buffer. Equivalent to Plan 9 runetochar().
211 *
212 * Results:
213 * Returns the number of bytes stored into the buffer.
214 *
215 * Side effects:
216 * None.
217 *
218 *---------------------------------------------------------------------------
219 */
220
221 int
222 Tcl_UniCharToUtf(
223 int ch, /* The Tcl_UniChar to be stored in the
224 * buffer. */
225 char *buf) /* Buffer in which the UTF-8 representation of
226 * the Tcl_UniChar is stored. Buffer must be
227 * large enough to hold the UTF-8 character
228 * (at most TCL_UTF_MAX bytes). */
229 {
230 if ((unsigned)(ch - 1) < (UNICODE_SELF - 1)) {
231 buf[0] = (char) ch;
232 return 1;
233 }
234 if (ch >= 0) {
235 if (ch <= 0x7FF) {
236 buf[1] = (char) (0x80 | (0x3F & ch));
237 buf[0] = (char) (0xC0 | (ch >> 6));
238 return 2;
239 }
240 if (ch <= 0xFFFF) {
241 #if TCL_UTF_MAX > 3
242 if ((ch & 0xF800) == 0xD800) {
243 if (ch & 0x0400) {
244 /* Low surrogate */
245 if ( (0x80 == (0xC0 & buf[0]))
246 && (0 == (0xCF & buf[1]))) {
247 /* Previous Tcl_UniChar was a high surrogate, so combine */
248 buf[2] = (char) (0x80 | (0x3F & ch));
249 buf[1] |= (char) (0x80 | (0x0F & (ch >> 6)));
250 return 3;
251 }
252 /* Previous Tcl_UniChar was not a high surrogate, so just output */
253 } else {
254 /* High surrogate */
255 ch += 0x40;
256 /* Fill buffer with specific 3-byte (invalid) byte combination,
257 so following low surrogate can recognize it and combine */
258 buf[2] = (char) ((ch << 4) & 0x30);
259 buf[1] = (char) (0x80 | (0x3F & (ch >> 2)));
260 buf[0] = (char) (0xF0 | (0x07 & (ch >> 8)));
261 return 1;
262 }
263 }
264 #endif
265 goto three;
266 }
267
268 #if TCL_UTF_MAX > 3
269 if (ch <= 0x10FFFF) {
270 buf[3] = (char) (0x80 | (0x3F & ch));
271 buf[2] = (char) (0x80 | (0x3F & (ch >> 6)));
272 buf[1] = (char) (0x80 | (0x3F & (ch >> 12)));
273 buf[0] = (char) (0xF0 | (ch >> 18));
274 return 4;
275 }
276 } else if (ch == -1) {
277 if ( (0x80 == (0xC0 & buf[0]))
278 && (0 == (0xCF & buf[1]))
279 && (0xF0 == (0xF8 & buf[-1]))) {
280 ch = 0xD7C0
281 + ((0x07 & buf[-1]) << 8)
282 + ((0x3F & buf[0]) << 2)
283 + ((0x30 & buf[1]) >> 4);
284 buf[1] = (char) (0x80 | (0x3F & ch));
285 buf[0] = (char) (0x80 | (0x3F & (ch >> 6)));
286 buf[-1] = (char) (0xE0 | (ch >> 12));
287 return 2;
288 }
289 #endif
290 }
291
292 ch = 0xFFFD;
293 three:
294 buf[2] = (char) (0x80 | (0x3F & ch));
295 buf[1] = (char) (0x80 | (0x3F & (ch >> 6)));
296 buf[0] = (char) (0xE0 | (ch >> 12));
297 return 3;
298 }
299
300 /*
301 *---------------------------------------------------------------------------
302 *
303 * Tcl_UniCharToUtfDString --
304 *
305 * Convert the given Unicode string to UTF-8.
306 *
307 * Results:
308 * The return value is a pointer to the UTF-8 representation of the
309 * Unicode string. Storage for the return value is appended to the end of
310 * dsPtr.
311 *
312 * Side effects:
313 * None.
314 *
315 *---------------------------------------------------------------------------
316 */
317
318 char *
319 Tcl_UniCharToUtfDString(
320 const Tcl_UniChar *uniStr, /* Unicode string to convert to UTF-8. */
321 int uniLength, /* Length of Unicode string in Tcl_UniChars
322 * (must be >= 0). */
323 Tcl_DString *dsPtr) /* UTF-8 representation of string is appended
324 * to this previously initialized DString. */
325 {
326 const Tcl_UniChar *w, *wEnd;
327 char *p, *string;
328 int oldLength;
329
330 /*
331 * UTF-8 string length in bytes will be <= Unicode string length *
332 * TCL_UTF_MAX.
333 */
334
335 oldLength = Tcl_DStringLength(dsPtr);
336 Tcl_DStringSetLength(dsPtr, oldLength + (uniLength + 1) * TCL_UTF_MAX);
337 string = Tcl_DStringValue(dsPtr) + oldLength;
338
339 p = string;
340 wEnd = uniStr + uniLength;
341 for (w = uniStr; w < wEnd; ) {
342 p += Tcl_UniCharToUtf(*w, p);
343 w++;
344 }
345 Tcl_DStringSetLength(dsPtr, oldLength + (p - string));
346
347 return string;
348 }
349
350 /*
351 *---------------------------------------------------------------------------
352 *
353 * Tcl_UtfToUniChar --
354 *
355 * Extract the Tcl_UniChar represented by the UTF-8 string. Bad UTF-8
356 * sequences are converted to valid Tcl_UniChars and processing
357 * continues. Equivalent to Plan 9 chartorune().
358 *
359 * The caller must ensure that the source buffer is long enough that this
360 * routine does not run off the end and dereference non-existent memory
361 * looking for trail bytes. If the source buffer is known to be '\0'
362 * terminated, this cannot happen. Otherwise, the caller should call
363 * Tcl_UtfCharComplete() before calling this routine to ensure that
364 * enough bytes remain in the string.
365 *
366 * If TCL_UTF_MAX <= 4, special handling of Surrogate pairs is done:
367 * For any UTF-8 string containing a character outside of the BMP, the
368 * first call to this function will fill *chPtr with the high surrogate
369 * and generate a return value of 1. Calling Tcl_UtfToUniChar again
370 * will produce the low surrogate and a return value of 3. Because *chPtr
371 * is used to remember whether the high surrogate is already produced, it
372 * is recommended to initialize the variable it points to as 0 before
373 * the first call to Tcl_UtfToUniChar is done.
374 *
375 * Results:
376 * *chPtr is filled with the Tcl_UniChar, and the return value is the
377 * number of bytes from the UTF-8 string that were consumed.
378 *
379 * Side effects:
380 * None.
381 *
382 *---------------------------------------------------------------------------
383 */
384
385 int
386 Tcl_UtfToUniChar(
387 const char *src, /* The UTF-8 string. */
388 Tcl_UniChar *chPtr)/* Filled with the Tcl_UniChar represented by
389 * the UTF-8 string. */
390 {
391 Tcl_UniChar byte;
392
393 /*
394 * Unroll 1 to 3 (or 4) byte UTF-8 sequences.
395 */
396
397 byte = UCHAR(*src);
398 if (byte < 0xC0) {
399 /*
400 * Handles properly formed UTF-8 characters between 0x01 and 0x7F.
401 * Also treats \0 and naked trail bytes 0x80 to 0xBF as valid
402 * characters representing themselves.
403 */
404
405 #if TCL_UTF_MAX <= 4
406 /* If *chPtr contains a high surrogate (produced by a previous
407 * Tcl_UtfToUniChar() call) and the next 3 bytes are UTF-8 continuation
408 * bytes, then we must produce a follow-up low surrogate. We only
409 * do that if the high surrogate matches the bits we encounter.
410 */
411 if (((byte & 0xC0) == 0x80)
412 && ((src[1] & 0xC0) == 0x80) && ((src[2] & 0xC0) == 0x80)
413 && (((((byte - 0x10) << 2) & 0xFC) | 0xD800) == (*chPtr & 0xFCFC))
414 && ((src[1] & 0xF0) == (((*chPtr << 4) & 0x30) | 0x80))) {
415 *chPtr = ((src[1] & 0x0F) << 6) + (src[2] & 0x3F) + 0xDC00;
416 return 3;
417 }
418 #endif
419 *chPtr = byte;
420 return 1;
421 } else if (byte < 0xE0) {
422 if ((byte != 0xC1) && ((src[1] & 0xC0) == 0x80)) {
423 /*
424 * Two-byte-character lead-byte followed by a trail-byte.
425 */
426
427 *chPtr = (((byte & 0x1F) << 6) | (src[1] & 0x3F));
428 if ((unsigned)(*chPtr - 1) >= (UNICODE_SELF - 1)) {
429 return 2;
430 }
431 }
432
433 /*
434 * A two-byte-character lead-byte not followed by trail-byte
435 * represents itself.
436 */
437 } else if (byte < 0xF0) {
438 if (((src[1] & 0xC0) == 0x80) && ((src[2] & 0xC0) == 0x80)) {
439 /*
440 * Three-byte-character lead byte followed by two trail bytes.
441 */
442
443 *chPtr = (((byte & 0x0F) << 12)
444 | ((src[1] & 0x3F) << 6) | (src[2] & 0x3F));
445 if (*chPtr > 0x7FF) {
446 return 3;
447 }
448 }
449
450 /*
451 * A three-byte-character lead-byte not followed by two trail-bytes
452 * represents itself.
453 */
454 } else if (byte < 0xF5) {
455 if (((src[1] & 0xC0) == 0x80) && ((src[2] & 0xC0) == 0x80)) {
456 /*
457 * Four-byte-character lead byte followed by at least two trail bytes.
458 * We don't test the validity of 3th trail byte, see [ed29806ba]
459 */
460 #if TCL_UTF_MAX <= 4
461 Tcl_UniChar high = (((byte & 0x07) << 8) | ((src[1] & 0x3F) << 2)
462 | ((src[2] & 0x3F) >> 4)) - 0x40;
463 if (high < 0x400) {
464 /* produce high surrogate, advance source pointer */
465 *chPtr = 0xD800 + high;
466 return 1;
467 }
468 /* out of range, < 0x10000 or > 0x10FFFF */
469 #else
470 if ((src[3] & 0xC0) == 0x80) {
471 *chPtr = (((byte & 0x07) << 18) | ((src[1] & 0x3F) << 12)
472 | ((src[2] & 0x3F) << 6) | (src[3] & 0x3F));
473 if ((unsigned)(*chPtr - 0x10000) <= 0xFFFFF) {
474 return 4;
475 }
476 }
477 #endif
478 }
479
480 /*
481 * A four-byte-character lead-byte not followed by three trail-bytes
482 * represents itself.
483 */
484 }
485
486 *chPtr = byte;
487 return 1;
488 }
489
490 /*
491 *---------------------------------------------------------------------------
492 *
493 * Tcl_UtfToUniCharDString --
494 *
495 * Convert the UTF-8 string to Unicode.
496 *
497 * Results:
498 * The return value is a pointer to the Unicode representation of the
499 * UTF-8 string. Storage for the return value is appended to the end of
500 * dsPtr. The Unicode string is terminated with a Unicode NULL character.
501 *
502 * Side effects:
503 * None.
504 *
505 *---------------------------------------------------------------------------
506 */
507
508 Tcl_UniChar *
509 Tcl_UtfToUniCharDString(
510 const char *src, /* UTF-8 string to convert to Unicode. */
511 int length, /* Length of UTF-8 string in bytes, or -1 for
512 * strlen(). */
513 Tcl_DString *dsPtr) /* Unicode representation of string is
514 * appended to this previously initialized
515 * DString. */
516 {
517 Tcl_UniChar ch = 0, *w, *wString;
518 const char *p;
519 int oldLength;
520 /* Pointer to the end of string. Never read endPtr[0] */
521 const char *endPtr = src + length;
522 /* Pointer to last byte where optimization still can be used */
523 const char *optPtr = endPtr - TCL_UTF_MAX;
524
525 if (length < 0) {
526 length = strlen(src);
527 }
528
529 /*
530 * Unicode string length in Tcl_UniChars will be <= UTF-8 string length in
531 * bytes.
532 */
533
534 oldLength = Tcl_DStringLength(dsPtr);
535
536 Tcl_DStringSetLength(dsPtr,
537 oldLength + ((length + 1) * sizeof(Tcl_UniChar)));
538 wString = (Tcl_UniChar *) (Tcl_DStringValue(dsPtr) + oldLength);
539
540 w = wString;
541 p = src;
542 endPtr = src + length;
543 optPtr = endPtr - ((TCL_UTF_MAX > 3) ? 4 : 3) ;
544 while (p <= optPtr) {
545 p += TclUtfToUniChar(p, &ch);
546 *w++ = ch;
547 }
548 while (p < endPtr) {
549 if (Tcl_UtfCharComplete(p, endPtr-p)) {
550 p += TclUtfToUniChar(p, &ch);
551 *w++ = ch;
552 } else {
553 *w++ = UCHAR(*p++);
554 }
555 }
556 *w = '\0';
557 Tcl_DStringSetLength(dsPtr,
558 oldLength + ((char *) w - (char *) wString));
559
560 return wString;
561 }
562
563 /*
564 *---------------------------------------------------------------------------
565 *
566 * Tcl_UtfCharComplete --
567 *
568 * Determine if the UTF-8 string of the given length is long enough to be
569 * decoded by Tcl_UtfToUniChar(). This does not ensure that the UTF-8
570 * string is properly formed. Equivalent to Plan 9 fullrune().
571 *
572 * Results:
573 * The return value is 0 if the string is not long enough, non-zero
574 * otherwise.
575 *
576 * Side effects:
577 * None.
578 *
579 *---------------------------------------------------------------------------
580 */
581
582 int
583 Tcl_UtfCharComplete(
584 const char *src, /* String to check if first few bytes contain
585 * a complete UTF-8 character. */
586 int length) /* Length of above string in bytes. */
587 {
588 return length >= complete[UCHAR(*src)];
589 }
590
591 /*
592 *---------------------------------------------------------------------------
593 *
594 * Tcl_NumUtfChars --
595 *
596 * Returns the number of characters (not bytes) in the UTF-8 string, not
597 * including the terminating NULL byte. This is equivalent to Plan 9
598 * utflen() and utfnlen().
599 *
600 * Results:
601 * As above.
602 *
603 * Side effects:
604 * None.
605 *
606 *---------------------------------------------------------------------------
607 */
608
609 int
610 Tcl_NumUtfChars(
611 const char *src, /* The UTF-8 string to measure. */
612 int length) /* The length of the string in bytes, or -1
613 * for strlen(string). */
614 {
615 Tcl_UniChar ch = 0;
616 int i = 0;
617
618 if (length < 0) {
619 /* string is NUL-terminated, so TclUtfToUniChar calls are safe. */
620 while ((*src != '\0') && (i < INT_MAX)) {
621 src += TclUtfToUniChar(src, &ch);
622 i++;
623 }
624 } else {
625 /* Will return value between 0 and length. No overflow checks. */
626
627 /* Pointer to the end of string. Never read endPtr[0] */
628 const char *endPtr = src + length;
629 /* Pointer to last byte where optimization still can be used */
630 const char *optPtr = endPtr - ((TCL_UTF_MAX > 3) ? 4 : 3);
631
632 /*
633 * Optimize away the call in this loop. Justified because...
634 * when (src <= optPtr), (endPtr - src) >= (endPtr - optPtr)
635 * By initialization above (endPtr - optPtr) = TCL_UTF_MAX
636 * So (endPtr - src) >= TCL_UTF_MAX, and passing that to
637 * Tcl_UtfCharComplete we know will cause return of 1.
638 */
639 while (src <= optPtr
640 /* && Tcl_UtfCharComplete(src, endPtr - src) */ ) {
641 src += TclUtfToUniChar(src, &ch);
642 i++;
643 }
644 /* Loop over the remaining string where call must happen */
645 while (src < endPtr) {
646 if (Tcl_UtfCharComplete(src, endPtr - src)) {
647 src += TclUtfToUniChar(src, &ch);
648 } else {
649 /*
650 * src points to incomplete UTF-8 sequence
651 * Treat first byte as character and count it
652 */
653 src++;
654 }
655 i++;
656 }
657 }
658 return i;
659 }
660
661 /*
662 *---------------------------------------------------------------------------
663 *
664 * Tcl_UtfFindFirst --
665 *
666 * Returns a pointer to the first occurrence of the given Unicode character
667 * in the NULL-terminated UTF-8 string. The NULL terminator is considered
668 * part of the UTF-8 string. Equivalent to Plan 9 utfrune().
669 *
670 * Results:
671 * As above. If the Unicode character does not exist in the given string,
672 * the return value is NULL.
673 *
674 * Side effects:
675 * None.
676 *
677 *---------------------------------------------------------------------------
678 */
679
680 const char *
681 Tcl_UtfFindFirst(
682 const char *src, /* The UTF-8 string to be searched. */
683 int ch) /* The Unicode character to search for. */
684 {
685 while (1) {
686 int find, len = TclUtfToUCS4(src, &find);
687
688 if (find == ch) {
689 return src;
690 }
691 if (*src == '\0') {
692 return NULL;
693 }
694 src += len;
695 }
696 }
697
698 /*
699 *---------------------------------------------------------------------------
700 *
701 * Tcl_UtfFindLast --
702 *
703 * Returns a pointer to the last occurrence of the given Unicode character
704 * in the NULL-terminated UTF-8 string. The NULL terminator is considered
705 * part of the UTF-8 string. Equivalent to Plan 9 utfrrune().
706 *
707 * Results:
708 * As above. If the Unicode character does not exist in the given string, the
709 * return value is NULL.
710 *
711 * Side effects:
712 * None.
713 *
714 *---------------------------------------------------------------------------
715 */
716
717 const char *
718 Tcl_UtfFindLast(
719 const char *src, /* The UTF-8 string to be searched. */
720 int ch) /* The Unicode character to search for. */
721 {
722 const char *last = NULL;
723
724 while (1) {
725 int find, len = TclUtfToUCS4(src, &find);
726
727 if (find == ch) {
728 last = src;
729 }
730 if (*src == '\0') {
731 break;
732 }
733 src += len;
734 }
735 return last;
736 }
737
738 /*
739 *---------------------------------------------------------------------------
740 *
741 * Tcl_UtfNext --
742 *
743 * Given a pointer to some location in a UTF-8 string, Tcl_UtfNext
744 * returns a pointer to the next UTF-8 character in the string.
745 * The caller must not ask for the next character after the last
746 * character in the string if the string is not terminated by a null
747 * character.
748 *
749 * Results:
750 * The return value is the pointer to the next character in the UTF-8
751 * string.
752 *
753 * Side effects:
754 * None.
755 *
756 *---------------------------------------------------------------------------
757 */
758
759 const char *
760 Tcl_UtfNext(
761 const char *src) /* The current location in the string. */
762 {
763 int left;
764 const char *next;
765
766 #if TCL_UTF_MAX > 3
767 if (((*src) & 0xC0) == 0x80) {
768 /* Continuation byte, so we start 'inside' a (possible valid) UTF-8
769 * sequence. Since we are not allowed to access src[-1], we cannot
770 * check if the sequence is actually valid, the best we can do is
771 * just assume it is valid and locate the end. */
772 if ((((*++src) & 0xC0) == 0x80) && (((*++src) & 0xC0) == 0x80)) {
773 ++src;
774 }
775 return src;
776 }
777 #endif
778
779 left = totalBytes[UCHAR(*src)];
780 next = src + 1;
781 while (--left) {
782 if ((*next & 0xC0) != 0x80) {
783 /*
784 * src points to non-trail byte; We ran out of trail bytes
785 * before the needs of the lead byte were satisfied.
786 * Let the (malformed) lead byte alone be a character
787 */
788 return src + 1;
789 }
790 next++;
791 }
792 /*
793 * Call Invalid() here only if required conditions are met:
794 * src[0] is known a lead byte.
795 * src[1] is known a trail byte.
796 * Especially important to prevent calls when src[0] == '\xF8' or '\xFC'
797 * See tests utf-6.37 through utf-6.43 through valgrind or similar tool.
798 */
799 if ((next == src + 1) || Invalid(src)) {
800 return src + 1;
801 }
802 return next;
803 }
804
805 /*
806 *---------------------------------------------------------------------------
807 *
808 * Tcl_UtfPrev --
809 *
810 * Given a pointer to some current location in a UTF-8 string, move
811 * backwards one character. This works correctly when the pointer is in
812 * the middle of a UTF-8 character.
813 *
814 * Results:
815 * The return value is a pointer to the previous character in the UTF-8
816 * string. If the current location was already at the beginning of the
817 * string, the return value will also be a pointer to the beginning of
818 * the string.
819 *
820 * Side effects:
821 * None.
822 *
823 *---------------------------------------------------------------------------
824 */
825
826 const char *
827 Tcl_UtfPrev(
828 const char *src, /* A location in a UTF-8 string. */
829 const char *start) /* Pointer to the beginning of the string */
830 {
831 int trailBytesSeen = 0; /* How many trail bytes have been verified? */
832 const char *fallback = src - 1;
833 /* If we cannot find a lead byte that might
834 * start a prefix of a valid UTF byte sequence,
835 * we will fallback to a one-byte back step */
836 const char *look = fallback;
837 /* Start search at the fallback position */
838
839 /* Quick boundary case exit. */
840 if (fallback <= start) {
841 return start;
842 }
843
844 do {
845 unsigned char byte = UCHAR(look[0]);
846
847 if (byte < 0x80) {
848 /*
849 * Single byte character. Either this is a correct previous
850 * character, or it is followed by at least one trail byte
851 * which indicates a malformed sequence. In either case the
852 * correct result is to return the fallback.
853 */
854 return fallback;
855 }
856 if (byte >= 0xC0) {
857 /* Non-trail byte; May be multibyte lead. */
858
859 if ((trailBytesSeen == 0)
860 /*
861 * We've seen no trailing context to use to check
862 * anything. From what we know, this non-trail byte
863 * is a prefix of a previous character, and accepting
864 * it (the fallback) is correct.
865 */
866
867 || (trailBytesSeen >= totalBytes[byte])) {
868 /*
869 * That is, (1 + trailBytesSeen > needed).
870 * We've examined more bytes than needed to complete
871 * this lead byte. No matter about well-formedness or
872 * validity, the sequence starting with this lead byte
873 * will never include the fallback location, so we must
874 * return the fallback location. See test utf-7.17
875 */
876 return fallback;
877 }
878
879 /*
880 * trailBytesSeen > 0, so we can examine look[1] safely.
881 * Use that capability to screen out invalid sequences.
882 */
883
884 if (Invalid(look)) {
885 /* Reject */
886 return fallback;
887 }
888 return (const char *)look;
889 }
890
891 /* We saw a trail byte. */
892 trailBytesSeen++;
893
894 if ((const char *)look == start) {
895 /*
896 * Do not read before the start of the string
897 *
898 * If we get here, we've examined bytes at every location
899 * >= start and < src and all of them are trail bytes,
900 * including (*start). We need to return our fallback
901 * and exit this loop before we run past the start of the string.
902 */
903 return fallback;
904 }
905
906 /* Continue the search backwards... */
907 look--;
908 } while (trailBytesSeen < (TCL_UTF_MAX < 4 ? 3 : 4));
909
910 /*
911 * We've seen 3 trail bytes, so we know there will not be a
912 * properly formed byte sequence to find, and we can stop looking,
913 * accepting the fallback.
914 */
915 return fallback;
916 }
917
918 /*
919 *---------------------------------------------------------------------------
920 *
921 * Tcl_UniCharAtIndex --
922 *
923 * Returns the Tcl_UniChar represented at the specified character
924 * (not byte) position in the UTF-8 string.
925 *
926 * Results:
927 * As above.
928 *
929 * Side effects:
930 * None.
931 *
932 *---------------------------------------------------------------------------
933 */
934
935 Tcl_UniChar
936 Tcl_UniCharAtIndex(
937 const char *src, /* The UTF-8 string to dereference. */
938 int index) /* The position of the desired character. */
939 {
940 Tcl_UniChar ch = 0;
941
942 while (index-- >= 0) {
943 src += TclUtfToUniChar(src, &ch);
944 }
945 return ch;
946 }
947
948 /*
949 *---------------------------------------------------------------------------
950 *
951 * Tcl_UtfAtIndex --
952 *
953 * Returns a pointer to the specified character (not byte) position in
954 * the UTF-8 string.
955 *
956 * Results:
957 * As above.
958 *
959 * Side effects:
960 * None.
961 *
962 *---------------------------------------------------------------------------
963 */
964
965 const char *
966 Tcl_UtfAtIndex(
967 const char *src, /* The UTF-8 string. */
968 int index) /* The position of the desired character. */
969 {
970 Tcl_UniChar ch = 0;
971 int len = 0;
972
973 while (index-- > 0) {
974 len = TclUtfToUniChar(src, &ch);
975 src += len;
976 }
977 #if TCL_UTF_MAX == 4
978 if ((ch >= 0xD800) && (len < 3)) {
979 /* Index points at character following high Surrogate */
980 src += TclUtfToUniChar(src, &ch);
981 }
982 #endif
983 return src;
984 }
985
986 /*
987 *---------------------------------------------------------------------------
988 *
989 * Tcl_UtfBackslash --
990 *
991 * Figure out how to handle a backslash sequence.
992 *
993 * Results:
994 * Stores the bytes represented by the backslash sequence in dst and
995 * returns the number of bytes written to dst. At most TCL_UTF_MAX bytes
996 * are written to dst; dst must have been large enough to accept those
997 * bytes. If readPtr isn't NULL then it is filled in with a count of the
998 * number of bytes in the backslash sequence.
999 *
1000 * Side effects:
1001 * The maximum number of bytes it takes to represent a Unicode character
1002 * in UTF-8 is guaranteed to be less than the number of bytes used to
1003 * express the backslash sequence that represents that Unicode character.
1004 * If the target buffer into which the caller is going to store the bytes
1005 * that represent the Unicode character is at least as large as the
1006 * source buffer from which the backslashed sequence was extracted, no
1007 * buffer overruns should occur.
1008 *
1009 *---------------------------------------------------------------------------
1010 */
1011
1012 int
1013 Tcl_UtfBackslash(
1014 const char *src, /* Points to the backslash character of a
1015 * backslash sequence. */
1016 int *readPtr, /* Fill in with number of characters read from
1017 * src, unless NULL. */
1018 char *dst) /* Filled with the bytes represented by the
1019 * backslash sequence. */
1020 {
1021 #define LINE_LENGTH 128
1022 int numRead;
1023 int result;
1024
1025 result = TclParseBackslash(src, LINE_LENGTH, &numRead, dst);
1026 if (numRead == LINE_LENGTH) {
1027 /*
1028 * We ate a whole line. Pay the price of a strlen()
1029 */
1030
1031 result = TclParseBackslash(src, strlen(src), &numRead, dst);
1032 }
1033 if (readPtr != NULL) {
1034 *readPtr = numRead;
1035 }
1036 return result;
1037 }
1038
1039 /*
1040 *----------------------------------------------------------------------
1041 *
1042 * Tcl_UtfToUpper --
1043 *
1044 * Convert lowercase characters to uppercase characters in a UTF string
1045 * in place. The conversion may shrink the UTF string.
1046 *
1047 * Results:
1048 * Returns the number of bytes in the resulting string excluding the
1049 * trailing null.
1050 *
1051 * Side effects:
1052 * Writes a terminating null after the last converted character.
1053 *
1054 *----------------------------------------------------------------------
1055 */
1056
1057 int
1058 Tcl_UtfToUpper(
1059 char *str) /* String to convert in place. */
1060 {
1061 int ch, upChar;
1062 char *src, *dst;
1063 int len;
1064
1065 /*
1066 * Iterate over the string until we hit the terminating null.
1067 */
1068
1069 src = dst = str;
1070 while (*src) {
1071 len = TclUtfToUCS4(src, &ch);
1072 upChar = UCS4ToUpper(ch);
1073
1074 /*
1075 * To keep badly formed Utf strings from getting inflated by the
1076 * conversion (thereby causing a segfault), only copy the upper case
1077 * char to dst if its size is <= the original char.
1078 */
1079
1080 if (len < UtfCount(upChar)) {
1081 memmove(dst, src, len);
1082 dst += len;
1083 } else {
1084 dst += TclUCS4ToUtf(upChar, dst);
1085 }
1086 src += len;
1087 }
1088 *dst = '\0';
1089 return (dst - str);
1090 }
1091
1092 /*
1093 *----------------------------------------------------------------------
1094 *
1095 * Tcl_UtfToLower --
1096 *
1097 * Convert uppercase characters to lowercase characters in a UTF string
1098 * in place. The conversion may shrink the UTF string.
1099 *
1100 * Results:
1101 * Returns the number of bytes in the resulting string excluding the
1102 * trailing null.
1103 *
1104 * Side effects:
1105 * Writes a terminating null after the last converted character.
1106 *
1107 *----------------------------------------------------------------------
1108 */
1109
1110 int
1111 Tcl_UtfToLower(
1112 char *str) /* String to convert in place. */
1113 {
1114 int ch, lowChar;
1115 char *src, *dst;
1116 int len;
1117
1118 /*
1119 * Iterate over the string until we hit the terminating null.
1120 */
1121
1122 src = dst = str;
1123 while (*src) {
1124 len = TclUtfToUCS4(src, &ch);
1125 lowChar = TclUCS4ToLower(ch);
1126
1127 /*
1128 * To keep badly formed Utf strings from getting inflated by the
1129 * conversion (thereby causing a segfault), only copy the lower case
1130 * char to dst if its size is <= the original char.
1131 */
1132
1133 if (len < UtfCount(lowChar)) {
1134 memmove(dst, src, len);
1135 dst += len;
1136 } else {
1137 dst += TclUCS4ToUtf(lowChar, dst);
1138 }
1139 src += len;
1140 }
1141 *dst = '\0';
1142 return (dst - str);
1143 }
1144
1145 /*
1146 *----------------------------------------------------------------------
1147 *
1148 * Tcl_UtfToTitle --
1149 *
1150 * Changes the first character of a UTF string to title case or uppercase
1151 * and the rest of the string to lowercase. The conversion happens in
1152 * place and may shrink the UTF string.
1153 *
1154 * Results:
1155 * Returns the number of bytes in the resulting string excluding the
1156 * trailing null.
1157 *
1158 * Side effects:
1159 * Writes a terminating null after the last converted character.
1160 *
1161 *----------------------------------------------------------------------
1162 */
1163
1164 int
1165 Tcl_UtfToTitle(
1166 char *str) /* String to convert in place. */
1167 {
1168 int ch, titleChar, lowChar;
1169 char *src, *dst;
1170 int len;
1171
1172 /*
1173 * Capitalize the first character and then lowercase the rest of the
1174 * characters until we get to a null.
1175 */
1176
1177 src = dst = str;
1178
1179 if (*src) {
1180 len = TclUtfToUCS4(src, &ch);
1181 titleChar = UCS4ToTitle(ch);
1182
1183 if (len < UtfCount(titleChar)) {
1184 memmove(dst, src, len);
1185 dst += len;
1186 } else {
1187 dst += TclUCS4ToUtf(titleChar, dst);
1188 }
1189 src += len;
1190 }
1191 while (*src) {
1192 len = TclUtfToUCS4(src, &ch);
1193 lowChar = ch;
1194 /* Special exception for Georgian Asomtavruli chars, no titlecase. */
1195 if ((unsigned)(lowChar - 0x1C90) >= 0x30) {
1196 lowChar = TclUCS4ToLower(lowChar);
1197 }
1198
1199 if (len < UtfCount(lowChar)) {
1200 memmove(dst, src, len);
1201 dst += len;
1202 } else {
1203 dst += TclUCS4ToUtf(lowChar, dst);
1204 }
1205 src += len;
1206 }
1207 *dst = '\0';
1208 return (dst - str);
1209 }
1210
1211 /*
1212 *----------------------------------------------------------------------
1213 *
1214 * TclpUtfNcmp2 --
1215 *
1216 * Compare at most numBytes bytes of utf-8 strings cs and ct. Both cs and
1217 * ct are assumed to be at least numBytes bytes long.
1218 *
1219 * Results:
1220 * Return <0 if cs < ct, 0 if cs == ct, or >0 if cs > ct.
1221 *
1222 * Side effects:
1223 * None.
1224 *
1225 *----------------------------------------------------------------------
1226 */
1227
1228 int
1229 TclpUtfNcmp2(
1230 const char *cs, /* UTF string to compare to ct. */
1231 const char *ct, /* UTF string cs is compared to. */
1232 unsigned long numBytes) /* Number of *bytes* to compare. */
1233 {
1234 return TclUtfNcmp2(cs, ct, numBytes);
1235 }
1236
1237 int
1238 TclUtfNcmp2(
1239 const void *csPtr, /* UTF string to compare to ct. */
1240 const void *ctPtr, /* UTF string cs is compared to. */
1241 size_t numBytes) /* Number of *bytes* to compare. */
1242 {
1243 const char *cs = (const char *)csPtr;
1244 const char *ct = (const char *)ctPtr;
1245 /*
1246 * We can't simply call 'memcmp(cs, ct, numBytes);' because we need to
1247 * check for Tcl's \xC0\x80 non-utf-8 null encoding. Otherwise utf-8 lexes
1248 * fine in the strcmp manner.
1249 */
1250
1251 int result = 0;
1252
1253 for ( ; numBytes != 0; numBytes--, cs++, ct++) {
1254 if (*cs != *ct) {
1255 result = UCHAR(*cs) - UCHAR(*ct);
1256 break;
1257 }
1258 }
1259 if (numBytes && ((UCHAR(*cs) == 0xC0) || (UCHAR(*ct) == 0xC0))) {
1260 unsigned char c1, c2;
1261
1262 c1 = ((UCHAR(*cs) == 0xC0) && (UCHAR(cs[1]) == 0x80)) ? 0 : UCHAR(*cs);
1263 c2 = ((UCHAR(*ct) == 0xC0) && (UCHAR(ct[1]) == 0x80)) ? 0 : UCHAR(*ct);
1264 result = (c1 - c2);
1265 }
1266 return result;
1267 }
1268
1269 /*
1270 *----------------------------------------------------------------------
1271 *
1272 * Tcl_UtfNcmp --
1273 *
1274 * Compare at most numChars UTF chars of string cs to string ct. Both cs
1275 * and ct are assumed to be at least numChars UTF chars long.
1276 *
1277 * Results:
1278 * Return <0 if cs < ct, 0 if cs == ct, or >0 if cs > ct.
1279 *
1280 * Side effects:
1281 * None.
1282 *
1283 *----------------------------------------------------------------------
1284 */
1285
1286 int
1287 Tcl_UtfNcmp(
1288 const char *cs, /* UTF string to compare to ct. */
1289 const char *ct, /* UTF string cs is compared to. */
1290 unsigned long numChars) /* Number of UTF chars to compare. */
1291 {
1292 return TclUtfNcmp(cs, ct, numChars);
1293 }
1294
1295 int
1296 TclUtfNcmp(
1297 const void *csPtr, /* UTF string to compare to ct. */
1298 const void *ctPtr, /* UTF string cs is compared to. */
1299 size_t numChars) /* Number of UTF chars to compare. */
1300 {
1301 const char *cs = (const char *)csPtr;
1302 const char *ct = (const char *)ctPtr;
1303 Tcl_UniChar ch1 = 0, ch2 = 0;
1304
1305 /*
1306 * Cannot use 'memcmp(cs, ct, n);' as byte representation of \u0000 (the
1307 * pair of bytes 0xC0,0x80) is larger than byte representation of \u0001
1308 * (the byte 0x01.)
1309 */
1310
1311 while (numChars-- > 0) {
1312 /*
1313 * n must be interpreted as chars, not bytes. This should be called
1314 * only when both strings are of at least n chars long (no need for \0
1315 * check)
1316 */
1317
1318 cs += TclUtfToUniChar(cs, &ch1);
1319 ct += TclUtfToUniChar(ct, &ch2);
1320 if (ch1 != ch2) {
1321 #if TCL_UTF_MAX == 4
1322 /* Surrogates always report higher than non-surrogates */
1323 if (((ch1 & 0xFC00) == 0xD800)) {
1324 if ((ch2 & 0xFC00) != 0xD800) {
1325 return ch1;
1326 }
1327 } else if ((ch2 & 0xFC00) == 0xD800) {
1328 return -ch2;
1329 }
1330 #endif
1331 return (ch1 - ch2);
1332 }
1333 }
1334 return 0;
1335 }
1336
1337 /*
1338 *----------------------------------------------------------------------
1339 *
1340 * Tcl_UtfNcasecmp --
1341 *
1342 * Compare at most numChars UTF chars of string cs to string ct case
1343 * insensitive. Both cs and ct are assumed to be at least numChars UTF
1344 * chars long.
1345 *
1346 * Results:
1347 * Return <0 if cs < ct, 0 if cs == ct, or >0 if cs > ct.
1348 *
1349 * Side effects:
1350 * None.
1351 *
1352 *----------------------------------------------------------------------
1353 */
1354
1355 int
1356 Tcl_UtfNcasecmp(
1357 const char *cs, /* UTF string to compare to ct. */
1358 const char *ct, /* UTF string cs is compared to. */
1359 unsigned long numChars) /* Number of UTF chars to compare. */
1360 {
1361 return TclUtfNcasecmp(cs, ct, numChars);
1362 }
1363
1364 int
1365 TclUtfNcasecmp(
1366 const void *csPtr, /* UTF string to compare to ct. */
1367 const void *ctPtr, /* UTF string cs is compared to. */
1368 size_t numChars) /* Number of UTF chars to compare. */
1369 {
1370 const char *cs = (const char *)csPtr;
1371 const char *ct = (const char *)ctPtr;
1372 Tcl_UniChar ch1 = 0, ch2 = 0;
1373
1374 while (numChars-- > 0) {
1375 /*
1376 * n must be interpreted as chars, not bytes.
1377 * This should be called only when both strings are of
1378 * at least n chars long (no need for \0 check)
1379 */
1380 cs += TclUtfToUniChar(cs, &ch1);
1381 ct += TclUtfToUniChar(ct, &ch2);
1382 if (ch1 != ch2) {
1383 #if TCL_UTF_MAX == 4
1384 /* Surrogates always report higher than non-surrogates */
1385 if (((ch1 & 0xFC00) == 0xD800)) {
1386 if ((ch2 & 0xFC00) != 0xD800) {
1387 return ch1;
1388 }
1389 } else if ((ch2 & 0xFC00) == 0xD800) {
1390 return -ch2;
1391 }
1392 #endif
1393 ch1 = Tcl_UniCharToLower(ch1);
1394 ch2 = Tcl_UniCharToLower(ch2);
1395 if (ch1 != ch2) {
1396 return (ch1 - ch2);
1397 }
1398 }
1399 }
1400 return 0;
1401 }
1402
1403 /*
1404 *----------------------------------------------------------------------
1405 *
1406 * TclUtfCasecmp --
1407 *
1408 * Compare UTF chars of string cs to string ct case insensitively.
1409 * Replacement for strcasecmp in Tcl core, in places where UTF-8 should
1410 * be handled.
1411 *
1412 * Results:
1413 * Return <0 if cs < ct, 0 if cs == ct, or >0 if cs > ct.
1414 *
1415 * Side effects:
1416 * None.
1417 *
1418 *----------------------------------------------------------------------
1419 */
1420
1421 int
1422 TclUtfCasecmp(
1423 const char *cs, /* UTF string to compare to ct. */
1424 const char *ct) /* UTF string cs is compared to. */
1425 {
1426 Tcl_UniChar ch1 = 0, ch2 = 0;
1427
1428 while (*cs && *ct) {
1429 cs += TclUtfToUniChar(cs, &ch1);
1430 ct += TclUtfToUniChar(ct, &ch2);
1431 if (ch1 != ch2) {
1432 #if TCL_UTF_MAX == 4
1433 /* Surrogates always report higher than non-surrogates */
1434 if (((ch1 & 0xFC00) == 0xD800)) {
1435 if ((ch2 & 0xFC00) != 0xD800) {
1436 return ch1;
1437 }
1438 } else if ((ch2 & 0xFC00) == 0xD800) {
1439 return -ch2;
1440 }
1441 #endif
1442 ch1 = Tcl_UniCharToLower(ch1);
1443 ch2 = Tcl_UniCharToLower(ch2);
1444 if (ch1 != ch2) {
1445 return ch1 - ch2;
1446 }
1447 }
1448 }
1449 return UCHAR(*cs) - UCHAR(*ct);
1450 }
1451
1452
1453 /*
1454 *----------------------------------------------------------------------
1455 *
1456 * Tcl_UniCharToUpper --
1457 *
1458 * Compute the uppercase equivalent of the given Unicode character.
1459 *
1460 * Results:
1461 * Returns the uppercase Unicode character.
1462 *
1463 * Side effects:
1464 * None.
1465 *
1466 *----------------------------------------------------------------------
1467 */
1468
1469 static int
1470 UCS4ToUpper(
1471 int ch) /* Unicode character to convert. */
1472 {
1473 if (!UNICODE_OUT_OF_RANGE(ch)) {
1474 int info = GetUniCharInfo(ch);
1475
1476 if (GetCaseType(info) & 0x04) {
1477 ch -= GetDelta(info);
1478 }
1479 }
1480 /* Clear away extension bits, if any */
1481 return ch & 0x1FFFFF;
1482 }
1483
1484 Tcl_UniChar
1485 Tcl_UniCharToUpper(
1486 int ch) /* Unicode character to convert. */
1487 {
1488 return (Tcl_UniChar) UCS4ToUpper(ch);
1489 }
1490
1491 /*
1492 *----------------------------------------------------------------------
1493 *
1494 * Tcl_UniCharToLower --
1495 *
1496 * Compute the lowercase equivalent of the given Unicode character.
1497 *
1498 * Results:
1499 * Returns the lowercase Unicode character.
1500 *
1501 * Side effects:
1502 * None.
1503 *
1504 *----------------------------------------------------------------------
1505 */
1506
1507 int
1508 TclUCS4ToLower(
1509 int ch) /* Unicode character to convert. */
1510 {
1511 if (!UNICODE_OUT_OF_RANGE(ch)) {
1512 int info = GetUniCharInfo(ch);
1513 int mode = GetCaseType(info);
1514
1515 if ((mode & 0x02) && (mode != 0x7)) {
1516 ch += GetDelta(info);
1517 }
1518 }
1519 /* Clear away extension bits, if any */
1520 return ch & 0x1FFFFF;
1521 }
1522
1523 Tcl_UniChar
1524 Tcl_UniCharToLower(
1525 int ch) /* Unicode character to convert. */
1526 {
1527 return (Tcl_UniChar) TclUCS4ToLower(ch);
1528 }
1529
1530 /*
1531 *----------------------------------------------------------------------
1532 *
1533 * Tcl_UniCharToTitle --
1534 *
1535 * Compute the titlecase equivalent of the given Unicode character.
1536 *
1537 * Results:
1538 * Returns the titlecase Unicode character.
1539 *
1540 * Side effects:
1541 * None.
1542 *
1543 *----------------------------------------------------------------------
1544 */
1545
1546 static int
1547 UCS4ToTitle(
1548 int ch) /* Unicode character to convert. */
1549 {
1550 if (!UNICODE_OUT_OF_RANGE(ch)) {
1551 int info = GetUniCharInfo(ch);
1552 int mode = GetCaseType(info);
1553
1554 if (mode & 0x1) {
1555 /*
1556 * Subtract or add one depending on the original case.
1557 */
1558
1559 if (mode != 0x7) {
1560 ch += ((mode & 0x4) ? -1 : 1);
1561 }
1562 } else if (mode == 0x4) {
1563 ch -= GetDelta(info);
1564 }
1565 }
1566 /* Clear away extension bits, if any */
1567 return ch & 0x1FFFFF;
1568 }
1569
1570 Tcl_UniChar
1571 Tcl_UniCharToTitle(
1572 int ch) /* Unicode character to convert. */
1573 {
1574 return (Tcl_UniChar) UCS4ToTitle(ch);
1575 }
1576
1577 /*
1578 *----------------------------------------------------------------------
1579 *
1580 * Tcl_UniCharLen --
1581 *
1582 * Find the length of a UniChar string. The str input must be null
1583 * terminated.
1584 *
1585 * Results:
1586 * Returns the length of str in UniChars (not bytes).
1587 *
1588 * Side effects:
1589 * None.
1590 *
1591 *----------------------------------------------------------------------
1592 */
1593
1594 int
1595 Tcl_UniCharLen(
1596 const Tcl_UniChar *uniStr) /* Unicode string to find length of. */
1597 {
1598 int len = 0;
1599
1600 while (*uniStr != '\0') {
1601 len++;
1602 uniStr++;
1603 }
1604 return len;
1605 }
1606
1607 /*
1608 *----------------------------------------------------------------------
1609 *
1610 * Tcl_UniCharNcmp --
1611 *
1612 * Compare at most numChars unichars of string ucs to string uct.
1613 * Both ucs and uct are assumed to be at least numChars unichars long.
1614 *
1615 * Results:
1616 * Return <0 if ucs < uct, 0 if ucs == uct, or >0 if ucs > uct.
1617 *
1618 * Side effects:
1619 * None.
1620 *
1621 *----------------------------------------------------------------------
1622 */
1623
1624 #undef TclUniCharNcmp
1625 int
1626 Tcl_UniCharNcmp(
1627 const Tcl_UniChar *ucs, /* Unicode string to compare to uct. */
1628 const Tcl_UniChar *uct, /* Unicode string ucs is compared to. */
1629 unsigned long numChars) /* Number of unichars to compare. */
1630 {
1631 return TclUniCharNcmp(ucs, uct, numChars);
1632 }
1633
1634 int
1635 TclUniCharNcmp(
1636 const void *ucsPtr, /* Unicode string to compare to uct. */
1637 const void *uctPtr, /* Unicode string ucs is compared to. */
1638 size_t numChars) /* Number of unichars to compare. */
1639 {
1640 const Tcl_UniChar *ucs = (const Tcl_UniChar *)ucsPtr;
1641 const Tcl_UniChar *uct = (const Tcl_UniChar *)uctPtr;
1642 #if defined(WORDS_BIGENDIAN) && (TCL_UTF_MAX != 4)
1643 /*
1644 * We are definitely on a big-endian machine; memcmp() is safe
1645 */
1646
1647 return memcmp(ucs, uct, numChars*sizeof(Tcl_UniChar));
1648
1649 #else /* !WORDS_BIGENDIAN */
1650 /*
1651 * We can't simply call memcmp() because that is not lexically correct.
1652 */
1653
1654 for ( ; numChars != 0; ucs++, uct++, numChars--) {
1655 if (*ucs != *uct) {
1656 #if TCL_UTF_MAX == 4
1657 /* special case for handling upper surrogates */
1658 if (((*ucs & 0xFC00) == 0xD800) && ((*uct & 0xFC00) != 0xD800)) {
1659 return 1;
1660 } else if (((*uct & 0xFC00) == 0xD800)) {
1661 return -1;
1662 }
1663 #endif
1664 return (*ucs - *uct);
1665 }
1666 }
1667 return 0;
1668 #endif /* WORDS_BIGENDIAN */
1669 }
1670
1671 /*
1672 *----------------------------------------------------------------------
1673 *
1674 * Tcl_UniCharNcasecmp --
1675 *
1676 * Compare at most numChars unichars of string ucs to string uct case
1677 * insensitive. Both ucs and uct are assumed to be at least numChars
1678 * unichars long.
1679 *
1680 * Results:
1681 * Return <0 if ucs < uct, 0 if ucs == uct, or >0 if ucs > uct.
1682 *
1683 * Side effects:
1684 * None.
1685 *
1686 *----------------------------------------------------------------------
1687 */
1688
1689 int
1690 Tcl_UniCharNcasecmp(
1691 const Tcl_UniChar *ucs, /* Unicode string to compare to uct. */
1692 const Tcl_UniChar *uct, /* Unicode string ucs is compared to. */
1693 unsigned long numChars) /* Number of Unichars to compare. */
1694 {
1695 return TclUniCharNcasecmp(ucs, uct, numChars);
1696 }
1697
1698 int
1699 TclUniCharNcasecmp(
1700 const void *ucsPtr, /* Unicode string to compare to uct. */
1701 const void *uctPtr, /* Unicode string ucs is compared to. */
1702 size_t numChars) /* Number of Unichars to compare. */
1703 {
1704 const Tcl_UniChar *ucs = (const Tcl_UniChar *)ucsPtr;
1705 const Tcl_UniChar *uct = (const Tcl_UniChar *)uctPtr;
1706
1707 for ( ; numChars != 0; numChars--, ucs++, uct++) {
1708 if (*ucs != *uct) {
1709 Tcl_UniChar lcs = Tcl_UniCharToLower(*ucs);
1710 Tcl_UniChar lct = Tcl_UniCharToLower(*uct);
1711
1712 if (lcs != lct) {
1713 #if TCL_UTF_MAX == 4
1714 /* special case for handling upper surrogates */
1715 if (((lcs & 0xFC00) == 0xD800) && ((lct & 0xFC00) != 0xD800)) {
1716 return 1;
1717 } else if (((lct & 0xFC00) == 0xD800)) {
1718 return -1;
1719 }
1720 #endif
1721 return (lcs - lct);
1722 }
1723 }
1724 }
1725 return 0;
1726 }
1727
1728 /*
1729 *----------------------------------------------------------------------
1730 *
1731 * Tcl_UniCharIsAlnum --
1732 *
1733 * Test if a character is an alphanumeric Unicode character.
1734 *
1735 * Results:
1736 * Returns 1 if character is alphanumeric.
1737 *
1738 * Side effects:
1739 * None.
1740 *
1741 *----------------------------------------------------------------------
1742 */
1743
1744 int
1745 Tcl_UniCharIsAlnum(
1746 int ch) /* Unicode character to test. */
1747 {
1748 #if TCL_UTF_MAX > 3
1749 if (UNICODE_OUT_OF_RANGE(ch)) {
1750 return 0;
1751 }
1752 #endif
1753 return (((ALPHA_BITS | DIGIT_BITS) >> GetCategory(ch)) & 1);
1754 }
1755
1756 /*
1757 *----------------------------------------------------------------------
1758 *
1759 * Tcl_UniCharIsAlpha --
1760 *
1761 * Test if a character is an alphabetic Unicode character.
1762 *
1763 * Results:
1764 * Returns 1 if character is alphabetic.
1765 *
1766 * Side effects:
1767 * None.
1768 *
1769 *----------------------------------------------------------------------
1770 */
1771
1772 int
1773 Tcl_UniCharIsAlpha(
1774 int ch) /* Unicode character to test. */
1775 {
1776 #if TCL_UTF_MAX > 3
1777 if (UNICODE_OUT_OF_RANGE(ch)) {
1778 return 0;
1779 }
1780 #endif
1781 return ((ALPHA_BITS >> GetCategory(ch)) & 1);
1782 }
1783
1784 /*
1785 *----------------------------------------------------------------------
1786 *
1787 * Tcl_UniCharIsControl --
1788 *
1789 * Test if a character is a Unicode control character.
1790 *
1791 * Results:
1792 * Returns non-zero if character is a control.
1793 *
1794 * Side effects:
1795 * None.
1796 *
1797 *----------------------------------------------------------------------
1798 */
1799
1800 int
1801 Tcl_UniCharIsControl(
1802 int ch) /* Unicode character to test. */
1803 {
1804 #if TCL_UTF_MAX > 3
1805 if (UNICODE_OUT_OF_RANGE(ch)) {
1806 /* Clear away extension bits, if any */
1807 ch &= 0x1FFFFF;
1808 return ((ch == 0xE0001) || ((unsigned)(ch - 0xE0020) <= 0x5F));
1809 }
1810 #endif
1811 return ((CONTROL_BITS >> GetCategory(ch)) & 1);
1812 }
1813
1814 /*
1815 *----------------------------------------------------------------------
1816 *
1817 * Tcl_UniCharIsDigit --
1818 *
1819 * Test if a character is a numeric Unicode character.
1820 *
1821 * Results:
1822 * Returns non-zero if character is a digit.
1823 *
1824 * Side effects:
1825 * None.
1826 *
1827 *----------------------------------------------------------------------
1828 */
1829
1830 int
1831 Tcl_UniCharIsDigit(
1832 int ch) /* Unicode character to test. */
1833 {
1834 #if TCL_UTF_MAX > 3
1835 if (UNICODE_OUT_OF_RANGE(ch)) {
1836 return 0;
1837 }
1838 #endif
1839 return (GetCategory(ch) == DECIMAL_DIGIT_NUMBER);
1840 }
1841
1842 /*
1843 *----------------------------------------------------------------------
1844 *
1845 * Tcl_UniCharIsGraph --
1846 *
1847 * Test if a character is any Unicode print character except space.
1848 *
1849 * Results:
1850 * Returns non-zero if character is printable, but not space.
1851 *
1852 * Side effects:
1853 * None.
1854 *
1855 *----------------------------------------------------------------------
1856 */
1857
1858 int
1859 Tcl_UniCharIsGraph(
1860 int ch) /* Unicode character to test. */
1861 {
1862 #if TCL_UTF_MAX > 3
1863 if (UNICODE_OUT_OF_RANGE(ch)) {
1864 return ((unsigned)((ch & 0x1FFFFF) - 0xE0100) <= 0xEF);
1865 }
1866 #endif
1867 return ((GRAPH_BITS >> GetCategory(ch)) & 1);
1868 }
1869
1870 /*
1871 *----------------------------------------------------------------------
1872 *
1873 * Tcl_UniCharIsLower --
1874 *
1875 * Test if a character is a lowercase Unicode character.
1876 *
1877 * Results:
1878 * Returns non-zero if character is lowercase.
1879 *
1880 * Side effects:
1881 * None.
1882 *
1883 *----------------------------------------------------------------------
1884 */
1885
1886 int
1887 Tcl_UniCharIsLower(
1888 int ch) /* Unicode character to test. */
1889 {
1890 #if TCL_UTF_MAX > 3
1891 if (UNICODE_OUT_OF_RANGE(ch)) {
1892 return 0;
1893 }
1894 #endif
1895 return (GetCategory(ch) == LOWERCASE_LETTER);
1896 }
1897
1898 /*
1899 *----------------------------------------------------------------------
1900 *
1901 * Tcl_UniCharIsPrint --
1902 *
1903 * Test if a character is a Unicode print character.
1904 *
1905 * Results:
1906 * Returns non-zero if character is printable.
1907 *
1908 * Side effects:
1909 * None.
1910 *
1911 *----------------------------------------------------------------------
1912 */
1913
1914 int
1915 Tcl_UniCharIsPrint(
1916 int ch) /* Unicode character to test. */
1917 {
1918 #if TCL_UTF_MAX > 3
1919 if (UNICODE_OUT_OF_RANGE(ch)) {
1920 return ((unsigned)((ch & 0x1FFFFF) - 0xE0100) <= 0xEF);
1921 }
1922 #endif
1923 return (((GRAPH_BITS|SPACE_BITS) >> GetCategory(ch)) & 1);
1924 }
1925
1926 /*
1927 *----------------------------------------------------------------------
1928 *
1929 * Tcl_UniCharIsPunct --
1930 *
1931 * Test if a character is a Unicode punctuation character.
1932 *
1933 * Results:
1934 * Returns non-zero if character is punct.
1935 *
1936 * Side effects:
1937 * None.
1938 *
1939 *----------------------------------------------------------------------
1940 */
1941
1942 int
1943 Tcl_UniCharIsPunct(
1944 int ch) /* Unicode character to test. */
1945 {
1946 #if TCL_UTF_MAX > 3
1947 if (UNICODE_OUT_OF_RANGE(ch)) {
1948 return 0;
1949 }
1950 #endif
1951 return ((PUNCT_BITS >> GetCategory(ch)) & 1);
1952 }
1953
1954 /*
1955 *----------------------------------------------------------------------
1956 *
1957 * Tcl_UniCharIsSpace --
1958 *
1959 * Test if a character is a whitespace Unicode character.
1960 *
1961 * Results:
1962 * Returns non-zero if character is a space.
1963 *
1964 * Side effects:
1965 * None.
1966 *
1967 *----------------------------------------------------------------------
1968 */
1969
1970 int
1971 Tcl_UniCharIsSpace(
1972 int ch) /* Unicode character to test. */
1973 {
1974 #if TCL_UTF_MAX > 3
1975 /* Ignore upper 11 bits. */
1976 ch &= 0x1FFFFF;
1977 #else
1978 /* Ignore upper 16 bits. */
1979 ch &= 0xFFFF;
1980 #endif
1981
1982 /*
1983 * If the character is within the first 127 characters, just use the
1984 * standard C function, otherwise consult the Unicode table.
1985 */
1986
1987 if (ch < 0x80) {
1988 return TclIsSpaceProcM((char) ch);
1989 #if TCL_UTF_MAX > 3
1990 } else if (UNICODE_OUT_OF_RANGE(ch)) {
1991 return 0;
1992 #endif
1993 } else if (ch == 0x0085 || ch == 0x180E || ch == 0x200B
1994 || ch == 0x202F || ch == 0x2060 || ch == 0xFEFF) {
1995 return 1;
1996 } else {
1997 return ((SPACE_BITS >> GetCategory(ch)) & 1);
1998 }
1999 }
2000
2001 /*
2002 *----------------------------------------------------------------------
2003 *
2004 * Tcl_UniCharIsUpper --
2005 *
2006 * Test if a character is a uppercase Unicode character.
2007 *
2008 * Results:
2009 * Returns non-zero if character is uppercase.
2010 *
2011 * Side effects:
2012 * None.
2013 *
2014 *----------------------------------------------------------------------
2015 */
2016
2017 int
2018 Tcl_UniCharIsUpper(
2019 int ch) /* Unicode character to test. */
2020 {
2021 #if TCL_UTF_MAX > 3
2022 if (UNICODE_OUT_OF_RANGE(ch)) {
2023 return 0;
2024 }
2025 #endif
2026 return (GetCategory(ch) == UPPERCASE_LETTER);
2027 }
2028
2029 /*
2030 *----------------------------------------------------------------------
2031 *
2032 * Tcl_UniCharIsWordChar --
2033 *
2034 * Test if a character is alphanumeric or a connector punctuation mark.
2035 *
2036 * Results:
2037 * Returns 1 if character is a word character.
2038 *
2039 * Side effects:
2040 * None.
2041 *
2042 *----------------------------------------------------------------------
2043 */
2044
2045 int
2046 Tcl_UniCharIsWordChar(
2047 int ch) /* Unicode character to test. */
2048 {
2049 #if TCL_UTF_MAX > 3
2050 if (UNICODE_OUT_OF_RANGE(ch)) {
2051 return 0;
2052 }
2053 #endif
2054 return ((WORD_BITS >> GetCategory(ch)) & 1);
2055 }
2056
2057 /*
2058 *----------------------------------------------------------------------
2059 *
2060 * Tcl_UniCharCaseMatch --
2061 *
2062 * See if a particular Unicode string matches a particular pattern.
2063 * Allows case insensitivity. This is the Unicode equivalent of the char*
2064 * Tcl_StringCaseMatch. The UniChar strings must be NULL-terminated.
2065 * This has no provision for counted UniChar strings, thus should not be
2066 * used where NULLs are expected in the UniChar string. Use
2067 * TclUniCharMatch where possible.
2068 *
2069 * Results:
2070 * The return value is 1 if string matches pattern, and 0 otherwise. The
2071 * matching operation permits the following special characters in the
2072 * pattern: *?\[] (see the manual entry for details on what these mean).
2073 *
2074 * Side effects:
2075 * None.
2076 *
2077 *----------------------------------------------------------------------
2078 */
2079
2080 int
2081 Tcl_UniCharCaseMatch(
2082 const Tcl_UniChar *uniStr, /* Unicode String. */
2083 const Tcl_UniChar *uniPattern,
2084 /* Pattern, which may contain special
2085 * characters. */
2086 int nocase) /* 0 for case sensitive, 1 for insensitive */
2087 {
2088 Tcl_UniChar ch1 = 0, p;
2089
2090 while (1) {
2091 p = *uniPattern;
2092
2093 /*
2094 * See if we're at the end of both the pattern and the string. If so,
2095 * we succeeded. If we're at the end of the pattern but not at the end
2096 * of the string, we failed.
2097 */
2098
2099 if (p == 0) {
2100 return (*uniStr == 0);
2101 }
2102 if ((*uniStr == 0) && (p != '*')) {
2103 return 0;
2104 }
2105
2106 /*
2107 * Check for a "*" as the next pattern character. It matches any
2108 * substring. We handle this by skipping all the characters up to the
2109 * next matching one in the pattern, and then calling ourselves
2110 * recursively for each postfix of string, until either we match or we
2111 * reach the end of the string.
2112 */
2113
2114 if (p == '*') {
2115 /*
2116 * Skip all successive *'s in the pattern
2117 */
2118
2119 while (*(++uniPattern) == '*') {
2120 /* empty body */
2121 }
2122 p = *uniPattern;
2123 if (p == 0) {
2124 return 1;
2125 }
2126 if (nocase) {
2127 p = Tcl_UniCharToLower(p);
2128 }
2129 while (1) {
2130 /*
2131 * Optimization for matching - cruise through the string
2132 * quickly if the next char in the pattern isn't a special
2133 * character
2134 */
2135
2136 if ((p != '[') && (p != '?') && (p != '\\')) {
2137 if (nocase) {
2138 while (*uniStr && (p != *uniStr)
2139 && (p != Tcl_UniCharToLower(*uniStr))) {
2140 uniStr++;
2141 }
2142 } else {
2143 while (*uniStr && (p != *uniStr)) {
2144 uniStr++;
2145 }
2146 }
2147 }
2148 if (Tcl_UniCharCaseMatch(uniStr, uniPattern, nocase)) {
2149 return 1;
2150 }
2151 if (*uniStr == 0) {
2152 return 0;
2153 }
2154 uniStr++;
2155 }
2156 }
2157
2158 /*
2159 * Check for a "?" as the next pattern character. It matches any
2160 * single character.
2161 */
2162
2163 if (p == '?') {
2164 uniPattern++;
2165 uniStr++;
2166 continue;
2167 }
2168
2169 /*
2170 * Check for a "[" as the next pattern character. It is followed by a
2171 * list of characters that are acceptable, or by a range (two
2172 * characters separated by "-").
2173 */
2174
2175 if (p == '[') {
2176 Tcl_UniChar startChar, endChar;
2177
2178 uniPattern++;
2179 ch1 = (nocase ? Tcl_UniCharToLower(*uniStr) : *uniStr);
2180 uniStr++;
2181 while (1) {
2182 if ((*uniPattern == ']') || (*uniPattern == 0)) {
2183 return 0;
2184 }
2185 startChar = (nocase ? Tcl_UniCharToLower(*uniPattern)
2186 : *uniPattern);
2187 uniPattern++;
2188 if (*uniPattern == '-') {
2189 uniPattern++;
2190 if (*uniPattern == 0) {
2191 return 0;
2192 }
2193 endChar = (nocase ? Tcl_UniCharToLower(*uniPattern)
2194 : *uniPattern);
2195 uniPattern++;
2196 if (((startChar <= ch1) && (ch1 <= endChar))
2197 || ((endChar <= ch1) && (ch1 <= startChar))) {
2198 /*
2199 * Matches ranges of form [a-z] or [z-a].
2200 */
2201 break;
2202 }
2203 } else if (startChar == ch1) {
2204 break;
2205 }
2206 }
2207 while (*uniPattern != ']') {
2208 if (*uniPattern == 0) {
2209 uniPattern--;
2210 break;
2211 }
2212 uniPattern++;
2213 }
2214 uniPattern++;
2215 continue;
2216 }
2217
2218 /*
2219 * If the next pattern character is '\', just strip off the '\' so we
2220 * do exact matching on the character that follows.
2221 */
2222
2223 if (p == '\\') {
2224 if (*(++uniPattern) == '\0') {
2225 return 0;
2226 }
2227 }
2228
2229 /*
2230 * There's no special character. Just make sure that the next bytes of
2231 * each string match.
2232 */
2233
2234 if (nocase) {
2235 if (Tcl_UniCharToLower(*uniStr) !=
2236 Tcl_UniCharToLower(*uniPattern)) {
2237 return 0;
2238 }
2239 } else if (*uniStr != *uniPattern) {
2240 return 0;
2241 }
2242 uniStr++;
2243 uniPattern++;
2244 }
2245 }
2246
2247 /*
2248 *----------------------------------------------------------------------
2249 *
2250 * TclUniCharMatch --
2251 *
2252 * See if a particular Unicode string matches a particular pattern.
2253 * Allows case insensitivity. This is the Unicode equivalent of the char*
2254 * Tcl_StringCaseMatch. This variant of Tcl_UniCharCaseMatch uses counted
2255 * Strings, so embedded NULLs are allowed.
2256 *
2257 * Results:
2258 * The return value is 1 if string matches pattern, and 0 otherwise. The
2259 * matching operation permits the following special characters in the
2260 * pattern: *?\[] (see the manual entry for details on what these mean).
2261 *
2262 * Side effects:
2263 * None.
2264 *
2265 *----------------------------------------------------------------------
2266 */
2267
2268 int
2269 TclUniCharMatch(
2270 const Tcl_UniChar *string, /* Unicode String. */
2271 int strLen, /* Length of String */
2272 const Tcl_UniChar *pattern, /* Pattern, which may contain special
2273 * characters. */
2274 int ptnLen, /* Length of Pattern */
2275 int nocase) /* 0 for case sensitive, 1 for insensitive */
2276 {
2277 const Tcl_UniChar *stringEnd, *patternEnd;
2278 Tcl_UniChar p;
2279
2280 stringEnd = string + strLen;
2281 patternEnd = pattern + ptnLen;
2282
2283 while (1) {
2284 /*
2285 * See if we're at the end of both the pattern and the string. If so,
2286 * we succeeded. If we're at the end of the pattern but not at the end
2287 * of the string, we failed.
2288 */
2289
2290 if (pattern == patternEnd) {
2291 return (string == stringEnd);
2292 }
2293 p = *pattern;
2294 if ((string == stringEnd) && (p != '*')) {
2295 return 0;
2296 }
2297
2298 /*
2299 * Check for a "*" as the next pattern character. It matches any
2300 * substring. We handle this by skipping all the characters up to the
2301 * next matching one in the pattern, and then calling ourselves
2302 * recursively for each postfix of string, until either we match or we
2303 * reach the end of the string.
2304 */
2305
2306 if (p == '*') {
2307 /*
2308 * Skip all successive *'s in the pattern.
2309 */
2310
2311 while (*(++pattern) == '*') {
2312 /* empty body */
2313 }
2314 if (pattern == patternEnd) {
2315 return 1;
2316 }
2317 p = *pattern;
2318 if (nocase) {
2319 p = Tcl_UniCharToLower(p);
2320 }
2321 while (1) {
2322 /*
2323 * Optimization for matching - cruise through the string
2324 * quickly if the next char in the pattern isn't a special
2325 * character.
2326 */
2327
2328 if ((p != '[') && (p != '?') && (p != '\\')) {
2329 if (nocase) {
2330 while ((string < stringEnd) && (p != *string)
2331 && (p != Tcl_UniCharToLower(*string))) {
2332 string++;
2333 }
2334 } else {
2335 while ((string < stringEnd) && (p != *string)) {
2336 string++;
2337 }
2338 }
2339 }
2340 if (TclUniCharMatch(string, stringEnd - string,
2341 pattern, patternEnd - pattern, nocase)) {
2342 return 1;
2343 }
2344 if (string == stringEnd) {
2345 return 0;
2346 }
2347 string++;
2348 }
2349 }
2350
2351 /*
2352 * Check for a "?" as the next pattern character. It matches any
2353 * single character.
2354 */
2355
2356 if (p == '?') {
2357 pattern++;
2358 string++;
2359 continue;
2360 }
2361
2362 /*
2363 * Check for a "[" as the next pattern character. It is followed by a
2364 * list of characters that are acceptable, or by a range (two
2365 * characters separated by "-").
2366 */
2367
2368 if (p == '[') {
2369 Tcl_UniChar ch1, startChar, endChar;
2370
2371 pattern++;
2372 ch1 = (nocase ? Tcl_UniCharToLower(*string) : *string);
2373 string++;
2374 while (1) {
2375 if ((*pattern == ']') || (pattern == patternEnd)) {
2376 return 0;
2377 }
2378 startChar = (nocase ? Tcl_UniCharToLower(*pattern) : *pattern);
2379 pattern++;
2380 if (*pattern == '-') {
2381 pattern++;
2382 if (pattern == patternEnd) {
2383 return 0;
2384 }
2385 endChar = (nocase ? Tcl_UniCharToLower(*pattern)
2386 : *pattern);
2387 pattern++;
2388 if (((startChar <= ch1) && (ch1 <= endChar))
2389 || ((endChar <= ch1) && (ch1 <= startChar))) {
2390 /*
2391 * Matches ranges of form [a-z] or [z-a].
2392 */
2393 break;
2394 }
2395 } else if (startChar == ch1) {
2396 break;
2397 }
2398 }
2399 while (*pattern != ']') {
2400 if (pattern == patternEnd) {
2401 pattern--;
2402 break;
2403 }
2404 pattern++;
2405 }
2406 pattern++;
2407 continue;
2408 }
2409
2410 /*
2411 * If the next pattern character is '\', just strip off the '\' so we
2412 * do exact matching on the character that follows.
2413 */
2414
2415 if (p == '\\') {
2416 if (++pattern == patternEnd) {
2417 return 0;
2418 }
2419 }
2420
2421 /*
2422 * There's no special character. Just make sure that the next bytes of
2423 * each string match.
2424 */
2425
2426 if (nocase) {
2427 if (Tcl_UniCharToLower(*string) != Tcl_UniCharToLower(*pattern)) {
2428 return 0;
2429 }
2430 } else if (*string != *pattern) {
2431 return 0;
2432 }
2433 string++;
2434 pattern++;
2435 }
2436 }
2437
2438 /*
2439 *---------------------------------------------------------------------------
2440 *
2441 * TclUtfToUCS4 --
2442 *
2443 * Extracts the 4-byte codepoint from the leading bytes of the
2444 * Modified UTF-8 string "src". This is a utility routine to
2445 * contain the surrogate gymnastics in one place.
2446 *
2447 * The caller must ensure that the source buffer is long enough that this
2448 * routine does not run off the end and dereference non-existent memory
2449 * looking for trail bytes. If the source buffer is known to be '\0'
2450 * terminated, this cannot happen. Otherwise, the caller should call
2451 * TclUCS4Complete() before calling this routine to ensure that
2452 * enough bytes remain in the string.
2453 *
2454 * Results:
2455 * Fills *usc4Ptr with the UCS4 code point and returns the number of bytes
2456 * consumed from the source string.
2457 *
2458 * Side effects:
2459 * None.
2460 *
2461 *---------------------------------------------------------------------------
2462 */
2463
2464 int
2465 TclpUtfToUCS4(
2466 const char *src, /* The UTF-8 string. */
2467 int *ucs4Ptr) /* Filled with the UCS4 codepoint represented
2468 * by the UTF-8 string. */
2469 {
2470 Tcl_UniChar ch = 0;
2471 int len = TclUtfToUniChar(src, &ch);
2472
2473 #if TCL_UTF_MAX <= 4
2474 if ((ch & ~0x3FF) == 0xD800) {
2475 Tcl_UniChar low = ch;
2476 int len2 = TclUtfToUniChar(src+len, &low);
2477 if ((low & ~0x3FF) == 0xDC00) {
2478 *ucs4Ptr = (((ch & 0x3FF) << 10) | (low & 0x3FF)) + 0x10000;
2479 return len + len2;
2480 }
2481 }
2482 #endif
2483 *ucs4Ptr = (int)ch;
2484 return len;
2485 }
2486
2487 #if TCL_UTF_MAX == 4
2488 int
2489 TclUniCharToUCS4(
2490 const Tcl_UniChar *src, /* The Tcl_UniChar string. */
2491 int *ucs4Ptr) /* Filled with the UCS4 codepoint represented
2492 * by the Tcl_UniChar string. */
2493 {
2494 if (((src[0] & 0xFC00) == 0xD800) && ((src[1] & 0xFC00) == 0xDC00)) {
2495 *ucs4Ptr = (((src[0] & 0x3FF) << 10) | (src[01] & 0x3FF)) + 0x10000;
2496 return 2;
2497 }
2498 *ucs4Ptr = src[0];
2499 return 1;
2500 }
2501 #endif
2502
2503 /*
2504 *---------------------------------------------------------------------------
2505 *
2506 * TclUCS4ToUtf --
2507 *
2508 * Store the given Unicode character as a sequence of UTF-8 bytes in the
2509 * provided buffer. Might output 6 bytes, if the code point > 0xFFFF.
2510 *
2511 * Results:
2512 * The return values is the number of bytes in the buffer that were
2513 * consumed. If ch == -1, this function outputs 0 bytes (empty string),
2514 * since TclGetUCS4 returns -1 for out-of-range indices.
2515 *
2516 * Side effects:
2517 * None.
2518 *
2519 *---------------------------------------------------------------------------
2520 */
2521
2522 int
2523 TclUCS4ToUtf(
2524 int ch, /* Unicode character to be stored in the
2525 * buffer. */
2526 char *buf) /* Buffer in which the UTF-8 representation of
2527 * the Unicode character is stored. Buffer must be
2528 * large enough to hold the UTF-8 character(s)
2529 * (at most 6 bytes). */
2530 {
2531 #if TCL_UTF_MAX <= 4
2532 if (((unsigned)(ch - 0x10000) <= 0xFFFFF)) {
2533 /* Spit out a 4-byte UTF-8 character or 2 x 3-byte UTF-8 characters, depending on Tcl
2534 * version and/or TCL_UTF_MAX build value */
2535 int len = Tcl_UniCharToUtf(0xD800 | ((ch - 0x10000) >> 10), buf);
2536 return len + Tcl_UniCharToUtf(0xDC00 | (ch & 0x7FF), buf + len);
2537 }
2538 #endif
2539 if ((ch & ~0x7FF) == 0xD800) {
2540 buf[2] = (char) ((ch | 0x80) & 0xBF);
2541 buf[1] = (char) (((ch >> 6) | 0x80) & 0xBF);
2542 buf[0] = (char) ((ch >> 12) | 0xE0);
2543 return 3;
2544 }
2545 if (ch == -1) {
2546 return 0;
2547 }
2548 return Tcl_UniCharToUtf(ch, buf);
2549 }
2550
2551 /*
2552 * Local Variables:
2553 * mode: c
2554 * c-basic-offset: 4
2555 * fill-column: 78
2556 * End:
2557 */