aboutsummaryrefslogtreecommitdiffstats
path: root/src/gdisp/mcufont/mf_encoding.c
blob: 4e3975ae25c27909a2842249ee5581e48eb1d0ab (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
#include "mf_encoding.h"

#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)--;
}

#endif