diff options
author | default <nobody@localhost> | 2023-05-09 14:18:15 +0200 |
---|---|---|
committer | default <nobody@localhost> | 2023-05-09 14:18:15 +0200 |
commit | d562c3cfed3080013ee4fc68c7956c874f1323b8 (patch) | |
tree | c547b250935c38beb42aa27358f6cd30f186f313 /xs_unicode.h | |
parent | 510477cf39fd884e6a2e2a654700912c9ca54527 (diff) |
Backport from xs.
Diffstat (limited to 'xs_unicode.h')
-rw-r--r-- | xs_unicode.h | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/xs_unicode.h b/xs_unicode.h new file mode 100644 index 0000000..6f78d58 --- /dev/null +++ b/xs_unicode.h @@ -0,0 +1,46 @@ +/* copyright (c) 2022 - 2023 grunfink / MIT license */ + +#ifndef _XS_UNICODE_H + +#define _XS_UNICODE_H + + xs_str *xs_utf8_enc(xs_str *str, unsigned int cpoint); + + +#ifdef XS_IMPLEMENTATION + +/** utf-8 **/ + +xs_str *xs_utf8_enc(xs_str *str, unsigned int cpoint) +/* encodes an Unicode codepoint to utf8 */ +{ + unsigned char tmp[4]; + int n = 0; + + if (cpoint < 0x80) + tmp[n++] = cpoint & 0xff; + else + if (cpoint < 0x800) { + tmp[n++] = 0xc0 | (cpoint >> 6); + tmp[n++] = 0x80 | (cpoint & 0x3f); + } + else + if (cpoint < 0x10000) { + tmp[n++] = 0xe0 | (cpoint >> 12); + tmp[n++] = 0x80 | ((cpoint >> 6) & 0x3f); + tmp[n++] = 0x80 | (cpoint & 0x3f); + } + else + if (cpoint < 0x200000) { + tmp[n++] = 0xf0 | (cpoint >> 18); + tmp[n++] = 0x80 | ((cpoint >> 12) & 0x3f); + tmp[n++] = 0x80 | ((cpoint >> 6) & 0x3f); + tmp[n++] = 0x80 | (cpoint & 0x3f); + } + + return xs_append_m(str, (char *)tmp, n); +} + +#endif /* XS_IMPLEMENTATION */ + +#endif /* _XS_UNICODE_H */ |