aboutsummaryrefslogtreecommitdiff
path: root/sys/libunicode/runetobyte.c
blob: 27f252b6a6622fc6b8004cbba8f3719d95564efe (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
#include "internal.h"

int
utf8ยทrunetobyte(byte* s, rune* r)
{
    int i, j;
    rune c;

    c = *r;
    if(c <= Rune1) {
        s[0] = c;
        return 1;
    }

    for(i = 2; i < UTFmax + 1; i++){
        if(i == 3){
            if(c > RuneMax)
                c = RuneErr;
            if(SurrogateMin <= c && c <= SurrogateMax)
                c = RuneErr;
        }
        if(c <= RuneX(i) || i == UTFmax) {
            s[0] = Tbyte(i) |  (c >> (i - 1)*Bitx);
            for(j = 1; j < i; j++)
                s[j] = Tx | ((c >> (i - j - 1)*Bitx) & Maskx);
            return i;
        }
    }

    return UTFmax;
}