aboutsummaryrefslogtreecommitdiffstats
path: root/src/gdisp/mcufont/mf_encoding.c
blob: afa16b1815f231286e9acafda6d2a6bcf6d89832 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
 * This file is subject to the terms of the GFX License. If a copy of
 * the license was not distributed with this file, you can obtain one at:
 *
 *              http://ugfx.io/license.html
 */

#include "mf_encoding.h"

#ifndef MF_NO_COMPILE

#if MF_ENCODING == MF_ENCODING_UTF8

mf_char mf_getchar(mf_str *str)
{
    uint8_t c;
    uint8_t tmp, seqlen;
    uint16_t result;
    
    c = **str;
    if (!c)
        return 0;
    
    (*str)++;
    
    if ((c & 0x80) == 0)
    {
        /* Just normal ASCII character. */
        return c;
    }
    else if ((c & 0xC0) == 0x80)
    {
        /* Dangling piece of corrupted multibyte sequence.
         * Did you cut the string in the wrong place?
         */
        return c;
    }
    else if ((**str & 0xC0) == 0xC0)
    {
        /* Start of multibyte sequence without any following bytes.
         * Silly. Maybe you are using the wrong encoding.
         */
        return c;
    }
    else
    {
        /* Beginning of a multi-byte sequence.
         * Find out how many characters and combine them.
         */
        seqlen = 2;
        tmp = 0x20;
        result = 0;
        while ((c & tmp) && (seqlen < 5))
        {
            seqlen++;
            tmp >>= 1;
            
            result = (result << 6) | (**str & 0x3F);
            (*str)++;
        }
        
        result = (result << 6) | (**str & 0x3F);
        (*str)++;
        
        result |= (c & (tmp - 1)) << ((seqlen - 1) * 6);
        return result;
    }
}

void mf_rewind(mf_str *str)
{
    (*str)--;
    
    while ((**str & 0x80) != 0x00 && (**str & 0xC0) != 0xC0)
        (*str)--;
}

#else

mf_char mf_getchar(mf_str *str)
{
    if (!(**str))
        return 0;
    else
        return *(*str)++;
}

void mf_rewind(mf_str *str)
{
	(*str)--;
}

#endif

#endif //MF_NO_COMPILE