OSDN Git Service

2012-05-12 Tobias Burnus <burnus@net-b.de>
[pf3gnuchains/gcc-fork.git] / libgo / runtime / go-rune.c
1 /* go-rune.c -- rune functions for Go.
2
3    Copyright 2009, 2010 The Go Authors. All rights reserved.
4    Use of this source code is governed by a BSD-style
5    license that can be found in the LICENSE file.  */
6
7 #include <stddef.h>
8
9 #include "go-string.h"
10
11 /* Get a character from the UTF-8 string STR, of length LEN.  Store
12    the Unicode character, if any, in *RUNE.  Return the number of
13    characters used from STR.  */
14
15 int
16 __go_get_rune (const unsigned char *str, size_t len, int *rune)
17 {
18   int c, c1, c2, c3;
19
20   /* Default to the "replacement character".  */
21   *rune = 0xfffd;
22
23   if (len <= 0)
24     return 1;
25
26   c = *str;
27   if (c <= 0x7f)
28     {
29       *rune = c;
30       return 1;
31     }
32
33   if (len <= 1)
34     return 1;
35
36   c1 = str[1];
37   if ((c & 0xe0) == 0xc0
38       && (c1 & 0xc0) == 0x80)
39     {
40       *rune = (((c & 0x1f) << 6)
41                + (c1 & 0x3f));
42       return 2;
43     }
44
45   if (len <= 2)
46     return 1;
47
48   c2 = str[2];
49   if ((c & 0xf0) == 0xe0
50       && (c1 & 0xc0) == 0x80
51       && (c2 & 0xc0) == 0x80)
52     {
53       *rune = (((c & 0xf) << 12)
54                + ((c1 & 0x3f) << 6)
55                + (c2 & 0x3f));
56       return 3;
57     }
58
59   if (len <= 3)
60     return 1;
61
62   c3 = str[3];
63   if ((c & 0xf8) == 0xf0
64       && (c1 & 0xc0) == 0x80
65       && (c2 & 0xc0) == 0x80
66       && (c3 & 0xc0) == 0x80)
67     {
68       *rune = (((c & 0x7) << 18)
69                + ((c1 & 0x3f) << 12)
70                + ((c2 & 0x3f) << 6)
71                + (c3 & 0x3f));
72       return 4;
73     }
74
75   /* Invalid encoding.  Return 1 so that we advance.  */
76   return 1;
77 }