I loved this table, so I stole it: */ * Copyright (c) 2017 Christian Hansen * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this
| 57 | * S = Surrogates |
| 58 | */ |
| 59 | bool utf8_decode(struct utf8_state *utf8_state, char c) |
| 60 | { |
| 61 | if (utf8_state->used_len == utf8_state->total_len) { |
| 62 | utf8_state->used_len = 1; |
| 63 | /* First character in sequence. */ |
| 64 | if (((unsigned char)c & 0x80) == 0) { |
| 65 | /* ASCII, easy. */ |
| 66 | if (c == 0) |
| 67 | goto bad_encoding; |
| 68 | utf8_state->total_len = 1; |
| 69 | utf8_state->c = c; |
| 70 | goto finished_decoding; |
| 71 | } else if (((unsigned char)c & 0xE0) == 0xC0) { |
| 72 | utf8_state->total_len = 2; |
| 73 | utf8_state->c = ((unsigned char)c & 0x1F); |
| 74 | return false; |
| 75 | } else if (((unsigned char)c & 0xF0) == 0xE0) { |
| 76 | utf8_state->total_len = 3; |
| 77 | utf8_state->c = ((unsigned char)c & 0x0F); |
| 78 | return false; |
| 79 | } else if (((unsigned char)c & 0xF8) == 0xF0) { |
| 80 | utf8_state->total_len = 4; |
| 81 | utf8_state->c = ((unsigned char)c & 0x07); |
| 82 | return false; |
| 83 | } |
| 84 | goto bad_encoding; |
| 85 | } |
| 86 | |
| 87 | if (((unsigned char)c & 0xC0) != 0x80) |
| 88 | goto bad_encoding; |
| 89 | |
| 90 | utf8_state->c <<= 6; |
| 91 | utf8_state->c |= ((unsigned char)c & 0x3F); |
| 92 | |
| 93 | utf8_state->used_len++; |
| 94 | if (utf8_state->used_len == utf8_state->total_len) |
| 95 | goto finished_decoding; |
| 96 | return false; |
| 97 | |
| 98 | finished_decoding: |
| 99 | if (utf8_state->c == 0 || utf8_state->c > 0x10FFFF) |
| 100 | errno = ERANGE; |
| 101 | /* The UTF-16 "surrogate range": illegal in UTF-8 */ |
| 102 | else if (utf8_state->total_len == 3 |
| 103 | && (utf8_state->c & 0xFFFFF800) == 0x0000D800) |
| 104 | errno = ERANGE; |
| 105 | else { |
| 106 | int min_bits; |
| 107 | switch (utf8_state->total_len) { |
| 108 | case 1: |
| 109 | min_bits = 0; |
| 110 | break; |
| 111 | case 2: |
| 112 | min_bits = 7; |
| 113 | break; |
| 114 | case 3: |
| 115 | min_bits = 11; |
| 116 | break; |