File: njs_utf16.c

package info (click to toggle)
libnginx-mod-js 0.9.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,300 kB
  • sloc: ansic: 124,113; perl: 9,084; javascript: 2,717; exp: 487; sh: 322; xml: 312; python: 181; makefile: 18
file content (113 lines) | stat: -rw-r--r-- 1,974 bytes parent folder | download | duplicates (3)
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113

/*
 * Copyright (C) Alexander Borisov
 * Copyright (C) NGINX, Inc.
 */


#include <njs_main.h>


njs_inline void
njs_utf16_encode_write(uint32_t cp, u_char **start)
{
#ifdef NJS_HAVE_BIG_ENDIAN
        *(*start)++ = cp >> 8;
        *(*start)++ = cp & 0x00FF;
#else
        *(*start)++ = cp & 0x00FF;
        *(*start)++ = cp >> 8;
#endif
}


ssize_t
njs_utf16_encode(uint32_t cp, u_char **start, const u_char *end)
{
    if ((*start + 2) > end) {
        return NJS_ERROR;
    }

    if (cp < 0x10000) {
        njs_utf16_encode_write(cp, start);

        return 2;
    }

    if ((*start + 4) > end) {
        return NJS_ERROR;
    }

    cp -= 0x10000;

    njs_utf16_encode_write((0xD800 | (cp >> 0x0A)), start);
    njs_utf16_encode_write((0xDC00 | (cp & 0x03FF)), start);

    return 4;
}


uint32_t
njs_utf16_decode(njs_unicode_decode_t *ctx, const u_char **start,
    const u_char *end)
{
    uint32_t  unit;
    unsigned  lead;

    if (ctx->upper != 0x00) {
        lead = ctx->upper - 0x01;
        ctx->upper = 0x00;

        goto lead_state;
    }

pair_state:

    lead = *(*start)++;

    if (*start >= end) {
        ctx->upper = lead + 0x01;
        return NJS_UNICODE_CONTINUE;
    }

lead_state:

#ifdef NJS_HAVE_BIG_ENDIAN
        unit = (lead << 8) + *(*start)++;
#else
        unit = (*(*start)++ << 8) + lead;
#endif

    if (ctx->codepoint != 0x00) {
        if (njs_surrogate_trailing(unit)) {
            unit = njs_surrogate_pair(ctx->codepoint, unit);

            ctx->codepoint = 0x00;

            return unit;
        }

        (*start)--;

        ctx->upper = lead + 0x01;
        ctx->codepoint = 0x00;

        return NJS_UNICODE_ERROR;
    }

    if (njs_surrogate_any(unit)) {
        if (njs_surrogate_trailing(unit)) {
            return NJS_UNICODE_ERROR;
        }

        ctx->codepoint = unit;

        if (*start >= end) {
            return NJS_UNICODE_CONTINUE;
        }

        goto pair_state;
    }

    return unit;
}