Some changes in interface.
[gedcom-parse.git] / utf8 / utf8.c
1 /* Utility functions for UTF-8
2    Copyright (C) 2001, 2002 Peter Verthez
3
4    Permission granted to do anything with this file that you want, as long
5    as the above copyright is retained in all copies.
6    THERE IS NO WARRANTY - USE AT YOUR OWN RISK
7 */
8
9 /* $Id$ */
10 /* $Name$ */
11
12 #include "utf8.h"
13
14 int is_utf8_string(const char* str)
15 {
16   int expect_bytes = 0;
17
18   if (!str) return 0;
19   
20   while (*str) {
21     if ((*str & 0x80) == 0) {
22       /* Looks like an ASCII character */
23       if (expect_bytes)
24         /* byte of UTF-8 character expected */
25         return 0;
26       else {
27         /* OK, ASCII character expected */
28         str++;
29       }
30     }
31     else {
32       /* Looks like byte of an UTF-8 character */
33       if (expect_bytes) {
34         /* expect_bytes already set: first byte of UTF-8 char already seen */
35         if ((*str & 0xC0) == 0x80) {
36           /* OK, next byte of UTF-8 character */
37           /* Decrement number of expected bytes */
38           expect_bytes--;
39           str++;
40         }
41         else {
42           /* again first byte ?!?! */
43           return 0;
44         }
45       }
46       else {
47         /* First byte of the UTF-8 character */
48         /* count initial one bits and set expect_bytes to 1 less */
49         char ch = *str;
50         while (ch & 0x80) {
51           expect_bytes++;
52           ch = (ch & 0x7f) << 1;
53         }
54         expect_bytes--;
55         str++;
56       }
57     }
58   }
59
60   return (expect_bytes == 0);
61 }
62
63 int utf8_strlen(const char* str)
64 {
65   int num_char = 0;
66   
67   if (!str) return 0;
68   
69   while (*str) {
70     if ((*str & 0x80) == 0 || (*str & 0xC0) == 0xC0)
71       num_char++;
72     str++;
73   }
74   
75   return num_char;
76 }
77