aboutsummaryrefslogtreecommitdiff
path: root/src/libjin/Graphics/Utf8.cpp
blob: 1a79d436feb41d6fc21c4e081af2989622d45fe2 (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
#include <stdlib.h>
#include <string.h>
#include "Utf8.h"

namespace jin
{
namespace graphics
{

    /* utf8 byte string to unicode codepoint */
    static const char *utf8toCodepoint(const char *p, unsigned *res) {
        unsigned x, mask, shift;
        switch (*p & 0xf0) {
        case 0xf0:  mask = 0x07;  shift = 18;   break;
        case 0xe0:  mask = 0x0f;  shift = 12;   break;
        case 0xc0:
        case 0xd0:  mask = 0x1f;  shift = 6;   break;
        default:
            *res = *p;
            return p + 1;
        }
        x = (*p & mask) << shift;
        do {
            if (*(++p) == '\0') {
                *res = x;
                return p;
            }
            shift -= 6;
            x |= (*p & 0x3f) << shift;
        } while (shift);
        *res = x;
        return p + 1;
    }

    Utf8::Utf8(const char* raw, unsigned int length)
    {
        _length = length;
        _raw = (char*)calloc(1, length);
        memcpy(_raw, raw, length);
    }

    Utf8::Iterator Utf8::getIterator()
    {
        return Iterator(*this);
    }

    Utf8::~Utf8()
    {
        free(_raw);
        _raw = nullptr;
        _length = 0;
    }

    Utf8::Iterator::Iterator(const Utf8& utf8)
        : _utf8(utf8)
    {
        _p = utf8._raw;
    }

    Codepoint Utf8::Iterator::get()
    {
        Codepoint c; 
        _p = utf8toCodepoint(_p, &c);
        return c;
    }

}
}