2 * Copyright (c) 2009 Petri Lehtinen <petri@digip.org>
4 * Jansson is free software; you can redistribute it and/or modify
5 * it under the terms of the MIT license. See LICENSE for details.
10 int utf8_encode(int codepoint, char *buffer, int *size)
14 else if(codepoint < 0x80)
16 buffer[0] = (char)codepoint;
19 else if(codepoint < 0x800)
21 buffer[0] = 0xC0 + ((codepoint & 0x7C0) >> 6);
22 buffer[1] = 0x80 + ((codepoint & 0x03F));
25 else if(codepoint < 0x10000)
27 buffer[0] = 0xE0 + ((codepoint & 0xF000) >> 12);
28 buffer[1] = 0x80 + ((codepoint & 0x0FC0) >> 6);
29 buffer[2] = 0x80 + ((codepoint & 0x003F));
32 else if(codepoint <= 0x10FFFF)
34 buffer[0] = 0xF0 + ((codepoint & 0x1C0000) >> 18);
35 buffer[1] = 0x80 + ((codepoint & 0x03F000) >> 12);
36 buffer[2] = 0x80 + ((codepoint & 0x000FC0) >> 6);
37 buffer[3] = 0x80 + ((codepoint & 0x00003F));
46 int utf8_check_first(char byte)
48 unsigned char u = (unsigned char)byte;
53 if(0x80 <= u && u <= 0xBF) {
54 /* second, third or fourth byte of a multi-byte
55 sequence, i.e. a "continuation byte" */
58 else if(u == 0xC0 || u == 0xC1) {
59 /* overlong encoding of an ASCII byte */
62 else if(0xC2 <= u && u <= 0xDF) {
67 else if(0xE0 <= u && u <= 0xEF) {
71 else if(0xF0 <= u && u <= 0xF4) {
75 else { /* u >= 0xF5 */
76 /* Restricted (start of 4-, 5- or 6-byte sequence) or invalid
82 int utf8_check_full(const char *buffer, int size)
85 unsigned char u = (unsigned char)buffer[0];
102 for(i = 1; i < size; i++)
104 u = (unsigned char)buffer[i];
106 if(u < 0x80 || u > 0xBF) {
107 /* not a continuation byte */
111 value = (value << 6) + (u & 0x3F);
114 if(value > 0x10FFFF) {
115 /* not in Unicode range */
119 else if(0xD800 <= value && value <= 0xDFFF) {
120 /* invalid code point (UTF-16 surrogate halves) */
124 else if((size == 2 && value < 0x80) ||
125 (size == 3 && value < 0x800) ||
126 (size == 4 && value < 0x10000)) {
127 /* overlong encoding */
134 int utf8_check_string(const char *string, int length)
139 length = strlen(string);
141 for(i = 0; i < length; i++)
143 int count = utf8_check_first(string[i]);
148 if(i + count > length)
151 if(!utf8_check_full(&string[i], count))