root/utf.c

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
#include "utf.h"
size_t writeUtf8(char* buffer, uint32_t code) {
    if (code <= 0x7f) {
        *(buffer+0) = (char) (code);
        return 1;
    } else if (code <= 0x7ff) {
        *(buffer+0) = (char) (0xc0 | ((code >> 6) & 0x1f));
        *(buffer+1) = (char) (0x80 | (code & 0x3f));
        return 2;
    } else if (code <= 0xffff) {
        *(buffer+0) = (char) (0xe0 | ((code >> 12) & 0x0f));
        *(buffer+1) = (char) (0x80 | ((code >> 6) & 0x3f));
        *(buffer+2) = (char) (0x80 | (code & 0x3f));
        return 3;
    } else {
        *(buffer+0) = (char) (0xf0 | ((code >> 18) & 0x07));
        *(buffer+1) = (char) (0x80 | ((code >> 12) & 0x3f));
        *(buffer+2) = (char) (0x80 | ((code >> 6) & 0x3f));
        *(buffer+3) = (char) (0x80 | (code & 0x3f));
        return 4;
    }
}

char* utf32_to_utf8(const uint32_t* src, size_t size) {
    char* buffer = malloc((size*4)+1);
    char* writeP = buffer;
    const uint32_t* readP = src;
    while (readP < src + size) {
        uint32_t uchar = *readP;
        size_t written = writeUtf8(writeP, uchar);
        writeP = writeP + written;
        readP = readP+1;
    }
    *writeP = '\0';
    return buffer;
}