Fix PR47707
[official-gcc.git] / libgo / runtime / go-rune.c
blob7e31eb8d6229a371436a9aaffd3afb7e3b22ddf1
1 /* go-rune.c -- rune functions for Go.
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. */
7 #include <stddef.h>
9 #include "go-string.h"
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. */
15 int
16 __go_get_rune (const unsigned char *str, size_t len, int *rune)
18 int c, c1, c2, c3;
20 /* Default to the "replacement character". */
21 *rune = 0xfffd;
23 if (len <= 0)
24 return 1;
26 c = *str;
27 if (c <= 0x7f)
29 *rune = c;
30 return 1;
33 if (len <= 1)
34 return 1;
36 c1 = str[1];
37 if ((c & 0xe0) == 0xc0
38 && (c1 & 0xc0) == 0x80)
40 *rune = (((c & 0x1f) << 6)
41 + (c1 & 0x3f));
42 return 2;
45 if (len <= 2)
46 return 1;
48 c2 = str[2];
49 if ((c & 0xf0) == 0xe0
50 && (c1 & 0xc0) == 0x80
51 && (c2 & 0xc0) == 0x80)
53 *rune = (((c & 0xf) << 12)
54 + ((c1 & 0x3f) << 6)
55 + (c2 & 0x3f));
56 return 3;
59 if (len <= 3)
60 return 1;
62 c3 = str[3];
63 if ((c & 0xf8) == 0xf0
64 && (c1 & 0xc0) == 0x80
65 && (c2 & 0xc0) == 0x80
66 && (c3 & 0xc0) == 0x80)
68 *rune = (((c & 0x7) << 18)
69 + ((c1 & 0x3f) << 12)
70 + ((c2 & 0x3f) << 6)
71 + (c3 & 0x3f));
72 return 4;
75 /* Invalid encoding. Return 1 so that we advance. */
76 return 1;