2 * Copyright © 2012 Intel Corporation
3 * Copyright © 2014 Ran Benita <ran234@gmail.com>
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice (including the next
13 * paragraph) shall be included in all copies or substantial portions of the
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
24 * Author: Rob Bradford <rob@linux.intel.com>
34 utf32_to_utf8(uint32_t unichar, char *buffer)
36 int count, shift, length;
39 if (unichar <= 0x007f) {
44 else if (unichar <= 0x07FF) {
48 else if (unichar <= 0xffff) {
52 else if (unichar <= 0x1fffff) {
56 else if (unichar <= 0x3ffffff) {
65 for (count = length - 1, shift = 0; count > 0; count--, shift += 6)
66 buffer[count] = 0x80 | ((unichar >> shift) & 0x3f);
68 buffer[0] = head | ((unichar >> shift) & 0x3f);
69 buffer[length] = '\0';
75 is_valid_utf8(const char *ss, size_t len)
78 size_t tail_bytes = 0;
79 const uint8_t *s = (const uint8_t *) ss;
81 /* This beauty is from:
82 * The Unicode Standard Version 6.2 - Core Specification, Table 3.7
83 * http://www.unicode.org/versions/Unicode6.2.0/ch03.pdf#G7404
84 * We can optimize if needed. */
90 else if (s[i] >= 0xC2 && s[i] <= 0xDF) {
93 else if (s[i] == 0xE0) {
95 if (i >= len || !(s[i] >= 0xA0 && s[i] <= 0xBF))
99 else if (s[i] >= 0xE1 && s[i] <= 0xEC) {
102 else if (s[i] == 0xED) {
104 if (i >= len || !(s[i] >= 0x80 && s[i] <= 0x9F))
108 else if (s[i] >= 0xEE && s[i] <= 0xEF) {
111 else if (s[i] == 0xF0) {
113 if (i >= len || !(s[i] >= 0x90 && s[i] <= 0xBF))
117 else if (s[i] >= 0xF1 && s[i] <= 0xF3) {
120 else if (s[i] == 0xF4) {
122 if (i >= len || !(s[i] >= 0x80 && s[i] <= 0x8F))
132 while (i < len && tail_bytes > 0 && s[i] >= 0x80 && s[i] <= 0xBF) {