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>
36 utf32_to_utf8(uint32_t unichar, char *buffer)
38 int count, shift, length;
41 if (unichar <= 0x007f) {
46 else if (unichar <= 0x07FF) {
50 else if (unichar <= 0xffff) {
54 else if (unichar <= 0x10ffff) {
63 for (count = length - 1, shift = 0; count > 0; count--, shift += 6)
64 buffer[count] = 0x80 | ((unichar >> shift) & 0x3f);
66 buffer[0] = head | ((unichar >> shift) & 0x3f);
67 buffer[length] = '\0';
73 is_valid_utf8(const char *ss, size_t len)
76 size_t tail_bytes = 0;
77 const uint8_t *s = (const uint8_t *) ss;
79 /* This beauty is from:
80 * The Unicode Standard Version 6.2 - Core Specification, Table 3.7
81 * https://www.unicode.org/versions/Unicode6.2.0/ch03.pdf#G7404
82 * We can optimize if needed. */
88 else if (s[i] >= 0xC2 && s[i] <= 0xDF) {
91 else if (s[i] == 0xE0) {
93 if (i >= len || !(s[i] >= 0xA0 && s[i] <= 0xBF))
97 else if (s[i] >= 0xE1 && s[i] <= 0xEC) {
100 else if (s[i] == 0xED) {
102 if (i >= len || !(s[i] >= 0x80 && s[i] <= 0x9F))
106 else if (s[i] >= 0xEE && s[i] <= 0xEF) {
109 else if (s[i] == 0xF0) {
111 if (i >= len || !(s[i] >= 0x90 && s[i] <= 0xBF))
115 else if (s[i] >= 0xF1 && s[i] <= 0xF3) {
118 else if (s[i] == 0xF4) {
120 if (i >= len || !(s[i] >= 0x80 && s[i] <= 0x8F))
130 while (i < len && tail_bytes > 0 && s[i] >= 0x80 && s[i] <= 0xBF) {