version 2.8
mf_encoding.c
1 /*
2  * This file is subject to the terms of the GFX License. If a copy of
3  * the license was not distributed with this file, you can obtain one at:
4  *
5  * http://ugfx.org/license.html
6  */
7 
8 #include "mf_encoding.h"
9 
10 #ifndef MF_NO_COMPILE
11 
12 #if MF_ENCODING == MF_ENCODING_UTF8
13 
14 mf_char mf_getchar(mf_str *str)
15 {
16  uint8_t c;
17  uint8_t tmp, seqlen;
18  uint16_t result;
19 
20  c = **str;
21  if (!c)
22  return 0;
23 
24  (*str)++;
25 
26  if ((c & 0x80) == 0)
27  {
28  /* Just normal ASCII character. */
29  return c;
30  }
31  else if ((c & 0xC0) == 0x80)
32  {
33  /* Dangling piece of corrupted multibyte sequence.
34  * Did you cut the string in the wrong place?
35  */
36  return c;
37  }
38  else if ((**str & 0xC0) == 0xC0)
39  {
40  /* Start of multibyte sequence without any following bytes.
41  * Silly. Maybe you are using the wrong encoding.
42  */
43  return c;
44  }
45  else
46  {
47  /* Beginning of a multi-byte sequence.
48  * Find out how many characters and combine them.
49  */
50  seqlen = 2;
51  tmp = 0x20;
52  result = 0;
53  while ((c & tmp) && (seqlen < 5))
54  {
55  seqlen++;
56  tmp >>= 1;
57 
58  result = (result << 6) | (**str & 0x3F);
59  (*str)++;
60  }
61 
62  result = (result << 6) | (**str & 0x3F);
63  (*str)++;
64 
65  result |= (c & (tmp - 1)) << ((seqlen - 1) * 6);
66  return result;
67  }
68 }
69 
70 void mf_rewind(mf_str *str)
71 {
72  (*str)--;
73 
74  while ((**str & 0x80) != 0x00 && (**str & 0xC0) != 0xC0)
75  (*str)--;
76 }
77 
78 #else
79 
80 mf_char mf_getchar(mf_str *str)
81 {
82  if (!(**str))
83  return 0;
84  else
85  return *(*str)++;
86 }
87 
88 void mf_rewind(mf_str *str)
89 {
90  (*str)--;
91 }
92 
93 #endif
94 
95 #endif //MF_NO_COMPILE
96