Debian Codegraph @

terps/tads/tads3/utf8.h

raw symbols SCIP
1 /* $Header: d:/cvsroot/tads/tads3/utf8.h,v 1.2 1999/05/17 02:52:29 MJRoberts Exp $ */
2
3 /*
4 * Copyright (c) 1998, 2002 Michael J. Roberts. All Rights Reserved.
5 *
6 * Please see the accompanying license file, LICENSE.TXT, for information
7 * on using and copying this software.
8 */
9 /*
10 Name
11 utf8.h - UTF-8 character string manipulation
12 Function
13
14 Notes
15
16 Modified
17 10/16/98 MJRoberts - Creation
18 */
19
20 #ifndef UTF8_H
21 #define UTF8_H
22
23 #include <stdlib.h>
24 #include "vmuni.h"
25
26 /* ------------------------------------------------------------------------ */
27 /*
28 * UTF-8 character string pointer.
29 *
30 * Note that this class deviates from the normal naming convention where
31 * each class begins with a capital 'C'. Since this class is so
32 * low-level, and is used so much like the (char *) type, it seems more
33 * proper to give it a name as though it were a typedef for a native type.
34 *
35 * If ever there was a time when operator overloading is indicated, this
36 * would be it. We could overload increment and decrement operators, for
37 * example, to step through the string. However, I just plain don't like
38 * operator overloading, so I do not use it here. Instead, we use
39 * explicit method names to avoid obfuscating the code as overloaded
40 * operators would. It's a trade-off: it's less concise this way, but
41 * less obscure.
42 *
43 * Note the important distinction between "byte" and "character": a byte
44 * is the basic multi-bit unit of native storage, and a character
45 * represents the basic lexical unit; a character may be composed of more
46 * than one byte.
47 */
48
49 class utf8_ptr
50 {
51 public:
52 /* create a UTF-8 string pointer, with no initial underlying string */
53 utf8_ptr() { p_ = 0; }
54
55 /*
56 * Create a UTF-8 string pointer with an underlying string. The
57 * pointer must point to the first byte of a valid character.
58 */
59 utf8_ptr(char *str) { set(str); }
60
61 /* create from another utf8 pointer */
62 utf8_ptr(const utf8_ptr *p) { set(p->p_); }
63
64 /*
65 * Set the pointer to a new underlying buffer. The pointer must
66 * point to the first byte of a valid character if there are already
67 * characters in the buffer.
68 */
69 void set(char *str) { p_ = str; }
70 void set(const utf8_ptr *p) { p_ = p->p_; }
71
72 /*
73 * Get the character at the current position
74 */
75 wchar_t getch() const { return s_getch(p_); }
76
77 /*
78 * Get the character at a given character offset from the current
79 * position. The offset must be positive.
80 */
81 wchar_t getch_at(size_t ofs) const { return s_getch_at(p_, ofs); }
82
83 /*
84 * Get the character preceding the current character by the given
85 * amount. The offset must be positive. getch_before(1) returns
86 * the character preceding the current character, (2) returns the
87 * character two positions before the current character, and so on.
88 */
89 wchar_t getch_before(size_t ofs) const { return s_getch_before(p_, ofs); }
90
91 /*
92 * Encode a character into the buffer at the current position, and
93 * increment the pointer past the character.
94 */
95 void setch(wchar_t ch)
96 {
97 /* store the character and advance the buffer pointer */
98 p_ += s_putch(p_, ch);
99 }
100
101 /*
102 * encode a character into the buffer, incrementing the pointer and
103 * decrementing a remaining length count
104 */
105 void setch(wchar_t ch, size_t *rem)
106 {
107 size_t len = s_putch(p_, ch);
108 p_ += len;
109 *rem -= len;
110 }
111
112 /* call setch() for each character in a null-terminated string */
113 void setch_str(const char *str)
114 {
115 for ( ; *str != '\0' ; ++str)
116 p_ += s_putch(p_, *str);
117 }
118
119 /*
120 * Encode a string of wide characters into the buffer. We'll
121 * increment our pointer so that it points to the next available
122 * character when we're done. Returns the number of bytes used for
123 * the encoding.
124 *
125 * 'src_count' is the number of wide characters in the source string.
126 *
127 * 'bufsiz' gives the size remaining in the underlying buffer. If
128 * we run out of space, we won't encode any more characters, but we
129 * will still return the total number of bytes required to encode
130 * the string.
131 */
132 size_t setwchars(const wchar_t *src, size_t src_count, size_t bufsiz);
133
134 /*
135 * Encode a null-terminated string of wide-characters into our buffer.
136 * Works like setwchars(), but stops at the null terminator in the
137 * source rather than taking a character count.
138 *
139 * This routine doesn't store a trailing null in the result string. My
140 * string pointer is left at the next character after the last copied
141 * character.
142 */
143 size_t setwcharsz(const wchar_t *src, size_t bufsiz);
144
145 /* increment the pointer by one character */
146 void inc() { p_ = s_inc(p_); }
147
148 /*
149 * increment the pointer by one character, and decrement a remaining
150 * length counter accordingly
151 */
152 void inc(size_t *rem)
153 {
154 /* calculate the increment amount */
155 char *p = s_inc(p_);
156
157 /* decrement the length counter by the change */
158 *rem -= (p - p_);
159
160 /* save the new pointer value */
161 p_ = p;
162 }
163
164 /* increment by a give number of characters */
165 void inc_by(size_t cnt)
166 { for ( ; cnt > 0 ; inc(), --cnt) ; }
167
168 /* decrement the pointer by one character */
169 void dec() { p_ = s_dec(p_); }
170
171 /* decrement poniter and increment the remaining size to compensate */
172 void dec(size_t *rem)
173 {
174 /* calculate the decrement amount */
175 char *p = s_dec(p_);
176
177 /* decrement the length counter by the change */
178 *rem += (p_ - p);
179
180 /* save the new pointer value */
181 p_ = p;
182 }
183
184 /* increment/decrement by a byte count */
185 void inc_bytes(size_t cnt) { p_ += cnt; }
186 void dec_bytes(size_t cnt) { p_ -= cnt; }
187
188 /*
189 * Determine if the current character is a continuation character.
190 * Returns 1 if so, 0 if not.
191 */
192 int is_continuation() const { return s_is_continuation(p_); }
193
194 /*
195 * count the number of characters in the given number of bytes,
196 * starting at the current byte
197 */
198 size_t len(size_t bytecnt) const { return s_len(p_, bytecnt); }
199
200 /* get the byte size of the current character */
201 size_t charsize() const { return s_charsize(*p_); }
202
203 /*
204 * Get the number of bytes in the given number of characters
205 * starting at the current position.
206 */
207 size_t bytelen(size_t charcnt) const { return s_bytelen(p_, charcnt); }
208
209 /*
210 * count the number of characters to the null terminator
211 */
212 size_t lenz() const
213 {
214 char *p;
215 size_t cnt;
216
217 /* increment until we find a null byte */
218 for (cnt = 0, p = p_ ; *p != 0 ; p = s_inc(p), ++cnt) ;
219
220 /* return the result */
221 return cnt;
222 }
223
224 /* get the current pointer position */
225 char *getptr() const { return p_; }
226
227 /* -------------------------------------------------------------------- */
228 /*
229 * Static methods
230 */
231
232 /*
233 * Compare two UTF-8 strings. Returns a value less than zero if the
234 * first string is lexically less than the second string (i.e., the
235 * first string sorts ahead of the second string), zero if the two
236 * strings are identical, or a value greater than zero if the first
237 * string is lexically greater than the second string.
238 */
239 static int s_compare_to(const char *p1, size_t bytelen1,
240 const char *p2, size_t bytelen2);
241
242 /* get the character at the given byte pointer */
243 static wchar_t s_getch(const char *p)
244 {
245 /*
246 * If the high bit is 0, it's a one-byte sequence encoding the
247 * value in the low seven bits.
248 */
249 if ((*p & 0x80) == 0)
250 return (((unsigned char)*p) & 0x7f);
251
252 /*
253 * If the high two bytes are 110, it's a two-byte sequence, with
254 * the high-order 5 bits in the low 5 bits of the first byte, and
255 * the low-order six bits in the low 6 bits of the second byte.
256 */
257 if ((*p & 0xE0) == 0xC0)
258 return (((((unsigned char)*p) & 0x1F) << 6)
259 + (((unsigned char)*(p + 1)) & 0x3F));
260
261 /*
262 * Otherwise, we have a three-byte sequence: the high-order 4 bits
263 * are in the low-order 5 bits of the first byte, the next 6 bits
264 * are in the low-order 6 bits of the second byte, and the
265 * low-order 6 bits are in the low-order 6 bits of the third byte.
266 */
267 return (((((unsigned char)*p) & 0x0F) << 12)
268 + ((((unsigned char)*(p + 1)) & 0x3F) << 6)
269 + (((unsigned char)*(p + 2)) & 0x3F));
270 }
271
272 /*
273 * get the character at a given positive character offset from a
274 * byte pointer
275 */
276 static wchar_t s_getch_at(const char *p, size_t ofs)
277 {
278 /* skip the given number of characters */
279 for ( ; ofs != 0 ; --ofs, p += s_charsize(*p)) ;
280
281 /* return the character at the current position */
282 return s_getch(p);
283 }
284
285 /*
286 * get the character preceding the current character by the given
287 * number of positions; the offset value must be positive
288 */
289 static wchar_t s_getch_before(const char *p, size_t ofs)
290 {
291 /* skip backwards the given number of characters */
292 for ( ; ofs != 0 ; --ofs)
293 {
294 /*
295 * back up by one to three bytes, until we find no more
296 * continuation flags
297 */
298 --p;
299 p -= s_is_continuation(p);
300 p -= s_is_continuation(p);
301 }
302
303 /* return the character at the current position */
304 return s_getch(p);
305 }
306
307 /*
308 * Write a given wchar_t value to the given byte pointer. The
309 * caller must already have checked (via s_wchar_size) that there's
310 * enough room in the buffer for this character's UTF-8
311 * representation.
312 *
313 * Returns the number of bytes stored.
314 */
315 static size_t s_putch(char *p, wchar_t ch)
316 {
317 /* check the range to determine how to encode it */
318 if (ch <= 0x7f)
319 {
320 /*
321 * it's in the range 0x0000 to 0x007f - encode the low-order
322 * 7 bits in one byte
323 */
324 *p = (char)(ch & 0x7f);
325 return 1;
326 }
327 else if (ch <= 0x07ff)
328 {
329 /*
330 * It's in the range 0x0080 to 0x07ff - encode it in two
331 * bytes. The high-order 5 bits go in the first byte after
332 * the two-byte prefix of 110, and the low-order 6 bits go in
333 * the second byte after the continuation prefix of 10.
334 */
335 *p++ = (char)(0xC0 | ((ch >> 6) & 0x1F));
336 *p = (char)(0x80 | (ch & 0x3F));
337 return 2;
338 }
339 else
340 {
341 /*
342 * It's in the range 0x0800 to 0xffff - encode it in three
343 * bytes. The high-order 4 bits go in the first byte after
344 * the 1110 prefix, the next 6 bits go in the second byte
345 * after the 10 continuation prefix, and the low-order 6 bits
346 * go in the third byte after another 10 continuation prefix.
347 */
348 *p++ = (char)(0xE0 | ((ch >> 12) & 0x0F));
349 *p++ = (char)(0x80 | ((ch >> 6) & 0x3F));
350 *p = (char)(0x80 | (ch & 0x3F));
351 return 3;
352 }
353 }
354
355 /* increment a pointer to a buffer, returning the result */
356 static char *s_inc(const char *p)
357 {
358 /*
359 * increment the pointer by the size of the current character
360 * and return the result
361 */
362 return (char *)p + s_charsize(*p);
363 }
364
365 /* get the size of the character at the given byte pointer */
366 static size_t s_charsize(char c)
367 {
368 unsigned int ch;
369
370 /*
371 * Check the top three bits. If the pattern is 111xxxxx, we're
372 * pointing to a three-byte sequence. If the pattern is
373 * 110xxxxx, we're pointing to a two-byte sequence. If it's
374 * 0xxxxxxx, it's a one-byte sequence.
375 *
376 * We're being somewhat clever (tricky, anyway) here at the
377 * expense of clarity. To avoid conditionals, we're doing some
378 * tricky bit masking and shifting, since these operations are
379 * extremely fast on most machines. We figure out our increment
380 * using the bit patterns above to generate masks, then shift
381 * these around to produce 1's or 0's, then add up all of the
382 * mask calculations to get our final increment.
383 *
384 * The size is always at least 1 byte, so we start out with an
385 * increment of 1.
386 *
387 * Next, we note that character sizes other than 1 always
388 * require the high bit to be set. So, the rest is all ANDed
389 * with (byte & 80) shifted right by seven OR'ed to the same
390 * thing shifted right by six, which will give us a bit mask of
391 * 0 when the high bit is clear and 3 when it's set.
392 *
393 * Next, we'll pick out that third bit (xx1xxxxx or xx0xxxxx) by
394 * AND'ing with 0x20. We'll shift this right by 5, to give us 1
395 * if we have a three-byte sequence.
396 *
397 * We'll then add 1 to this, so we'll have a result of 1 for a
398 * two-byte sequence, 2 for a three-byte sequence.
399 */
400 ch = (unsigned int)(unsigned char)c;
401 return (1 +
402 ((((ch & 0x80) >> 7) | ((ch & 0x80) >> 6))
403 & (1 + ((ch & 0x20) >> 5))));
404 }
405
406 /* count the number of characters in the given number of bytes */
407 static size_t s_len(const char *p, size_t bytecnt)
408 {
409 /* get the ending pointer */
410 const char *end = p + bytecnt;
411
412 /* increment until we run out of bytes */
413 size_t cnt;
414 for (cnt = 0 ; p < end ; p = s_inc(p), ++cnt) ;
415
416 /* return the result */
417 return cnt;
418 }
419
420 /* count the number of bytes in the given number of characters */
421 static size_t s_bytelen(const char *str, size_t charcnt)
422 {
423 /* skip the given number of characters */
424 const char *p;
425 for (p = str ; charcnt != 0 ; p = s_inc(p), --charcnt) ;
426
427 /* return the number of bytes we skipped */
428 return (p - str);
429 }
430
431 /*
432 * get the number of bytes required to encode a given wchar_t in
433 * UTF-8 format
434 */
435 static size_t s_wchar_size(wchar_t ch)
436 {
437 /*
438 * characters 0-0x7f take up one byte; characters 0x80-0x7ff
439 * take up two bytes; all others take up three bytes
440 */
441 return (ch < 0x80 ? 1 : (ch < 0x800 ? 2 : 3));
442 }
443
444 /*
445 * get the number of bytes needed for the utf-8 mapping of a
446 * null-terminated wchar_t string
447 */
448 static size_t s_wstr_size(const wchar_t *str)
449 {
450 /* add up the byte lengths of the characters in 'str' */
451 size_t bytes = 0;
452 for ( ; *str != 0 ; bytes += s_wchar_size(*str++)) ;
453
454 /* return the total */
455 return bytes;
456 }
457
458 /* decrement a pointer by one character, returning the result */
459 static char *s_dec(char *p)
460 {
461 /*
462 * Going backwards, we can't tell that we're on a start byte
463 * until we get there - there's no context to tell us which byte
464 * of a multi-byte sequence we're on, except that we can tell
465 * whether or not we're on the first byte or an extra byte. So,
466 * decrement the pointer by a byte; if we're not on a start
467 * byte, decrement by another byte; if we're still not on a
468 * start byte, decrement it again.
469 *
470 * Since the longest possible sequence is three bytes, we'll
471 * unroll the loop and simply check twice to see if we're done
472 * yet.
473 */
474 --p;
475 p -= s_is_continuation(p);
476 p -= s_is_continuation(p);
477
478 /* return the result */
479 return p;
480 }
481
482 /*
483 * Determine if the current byte is a continuation byte. Returns 1
484 * if this is a continuation byte, 0 if not.
485 */
486 static int s_is_continuation(const char *p)
487 {
488 /*
489 * Continuation bytes have the pattern 10xxxxxx. Initial bytes
490 * never have this pattern. So, if a byte ANDed with 0xC0 is
491 * 0x80 (i.e., the high two bits have the exact pattern '10'),
492 * we're on a continuation byte.
493 *
494 * To avoid conditionals, which can be expensive because they
495 * require branching, we'll play more bit mask tricks: we'll
496 * compute a value that's 1 when the high two bits are '10', and
497 * is zero otherwise, and then subtract that from the current
498 * pointer. To figure this value, we'll mask the byte with 0x80
499 * to pick out the high bit, and shift this right seven bits.
500 * This will give us 1 for 1xxxxxxx. Then, we'll mask the byte
501 * with 0x40, which will pick out the second bit, invert the
502 * resulting bit pattern, AND it again with 0x40, and shift it
503 * right six bits. This will give us 1 for x0xxxxxx. We'll AND
504 * this with the previous calculation, which will give us 1 for
505 * 10xxxxxx and 0 for anything else.
506 */
507 unsigned int ch = (unsigned int)(unsigned char)*p;
508 return (((ch & 0x80) >> 7)
509 & (((~(ch & 0x40)) & 0x40) >> 6));
510 }
511
512 /*
513 * Truncate a string to the given byte length, ensuring that only
514 * whole characters are included in the result. Takes the proposed
515 * truncated length, and returns the actual length to use. The
516 * returned length will be less than or equal to the proposed
517 * length; if the returned length is less than the proposed length,
518 * it means that the proposed length would have cut off a multi-byte
519 * character, so the actual length had to be shorter to ensure that
520 * no bytes of the final character were included.
521 */
522 static size_t s_trunc(const char *p, size_t len)
523 {
524 /*
525 * if the length is zero, no adjustment is needed - you
526 * obviously can't divide zero bytes
527 */
528 if (len == 0)
529 return 0;
530
531 /*
532 * Get a pointer to the start of the last byte within the
533 * proposed truncated byte region. Note that the last byte in
534 * the buffer is at index (len-1), since the byte at index (len)
535 * is the next byte after the truncated region.
536 */
537 const char *last_ch = p + len - 1;
538
539 /*
540 * Decrement this byte pointer until we get to the start of the
541 * character that contains the final byte. Since a character
542 * can never be more than three bytes long, we need decrement
543 * our pointer a maximum of two times.
544 */
545 last_ch -= s_is_continuation(last_ch);
546 last_ch -= s_is_continuation(last_ch);
547
548 /*
549 * figure the number of bytes of the last character that are
550 * actually in the truncated region - this is simply the number
551 * of bytes from where we are now to the end of the region
552 */
553 size_t last_ch_len = len - (last_ch - p);
554
555 /*
556 * Now compute the actual size of this last character. If the
557 * last character's actual size is the same as the truncated
558 * size, then the last character fits exactly and we can return
559 * the proposed length unchanged. If the last character's
560 * required length is more than the truncated length, it means
561 * that the truncation has cut off the last character so that
562 * not all of its bytes fit, and hence we cannot include ANY of
563 * the last character's bytes in the result.
564 */
565 if (last_ch_len >= s_charsize(*last_ch))
566 {
567 /* the last character fits in the truncation - we're fine */
568 return len;
569 }
570 else
571 {
572 /*
573 * the last character doesn't fit - truncate so that none of
574 * the last character's bytes are included
575 */
576 return (last_ch - p);
577 }
578 }
579
580 /*
581 * Convert a utf8 string to a wchar_t string, with null termination.
582 * Returns the number of wchar_t characters in the string. If the
583 * given buffer isn't sufficient, we'll only convert as many characters
584 * as will fit, but we'll still return the full length of the string.
585 */
586 static size_t to_wcharz(wchar_t *buf, size_t bufcnt, const char *str,
587 size_t len)
588 {
589 /* we need at least one character for null termination */
590 if (bufcnt > 0)
591 {
592 /* convert the string, reserving space for a null */
593 size_t cnt = to_wchar(buf, bufcnt - 1, str, len);
594
595 /* add the null termination */
596 buf[bufcnt-1] = 0;
597
598 /* return the character count */
599 return cnt;
600 }
601 else
602 {
603 /*
604 * the output buffer is zero length, so we can't convert
605 * anything and can't null terminate; just calculate the length
606 */
607 return to_wchar(buf, bufcnt, str, len);
608 }
609 }
610
611 /*
612 * Convert a utf8 string to a wchar_t string, without null termination.
613 */
614 static size_t to_wchar(wchar_t *buf, size_t bufcnt, const char *str,
615 size_t len)
616 {
617 /* scan the string */
618 int cnt = 0;
619 for (utf8_ptr p((char *)str) ; len != 0 ; p.inc(&len), ++cnt)
620 {
621 /* if there's room, add this character to the output buffer */
622 if (bufcnt > 0)
623 {
624 *buf++ = p.getch();
625 --bufcnt;
626 }
627 }
628
629 /* return the character count */
630 return cnt;
631 }
632
633 private:
634 /* the buffer pointer */
635 char *p_;
636 };
637
638
639 /* ------------------------------------------------------------------------ */
640 /*
641 * Case folding utf8 string reader
642 */
643 class Utf8FoldStr
644 {
645 public:
646 Utf8FoldStr(const char *p, size_t bytelen)
647 {
648 /* set up at the start of the string */
649 this->p.set((char *)p);
650 this->rem = bytelen;
651
652 /* null-terminate our special one-byte identity conversion buffer */
653 ie[1] = 0;
654
655 /* start without anything loaded */
656 fpbase = ie;
657 fp = &ie[1];
658 }
659
660 /* get the current byte offset */
661 const char *getptr() const { return p.getptr(); }
662
663 /* is a character available? */
664 int more() const { return rem != 0 || *fp != 0 || fp == ie; }
665
666 /* are we at a character boundary in the original string? */
667 int at_boundary() const { return fp != fpbase && *fp == 0; }
668
669 /* get the next character */
670 wchar_t getch()
671 {
672 /* if the expansion is exhausted, expand the next source character */
673 if (fp != ie && *fp == 0)
674 {
675 /* if there's nothing left in the source string, we're done */
676 if (rem == 0)
677 return 0;
678
679 /* get the next source character */
680 wchar_t ch = p.getch();
681 p.inc(&rem);
682
683 /* get its case-folded expansion */
684 if ((fp = t3_to_fold(ch)) == 0)
685 {
686 ie[0] = ch;
687 fpbase = fp = ie;
688 }
689 }
690
691 /* return the next expansion character */
692 return *fp++;
693 }
694
695 private:
696 /* current position in case folding expansion of current 's' character */
697 const wchar_t *fp;
698
699 /* start of current expansion */
700 const wchar_t *fpbase;
701
702 /* buffer for identity expansions */
703 wchar_t ie[2];
704
705 /* pointer into original string source, and remaining length in bytes */
706 utf8_ptr p;
707 size_t rem;
708 };
709
710 #endif /* UTF8_H */
711