xs_unicode.h 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /* copyright (c) 2022 - 2023 grunfink / MIT license */
  2. #ifndef _XS_UNICODE_H
  3. #define _XS_UNICODE_H
  4. xs_str *xs_utf8_enc(xs_str *str, unsigned int cpoint);
  5. #ifdef XS_IMPLEMENTATION
  6. /** utf-8 **/
  7. xs_str *xs_utf8_enc(xs_str *str, unsigned int cpoint)
  8. /* encodes an Unicode codepoint to utf8 */
  9. {
  10. unsigned char tmp[4];
  11. int n = 0;
  12. if (cpoint < 0x80)
  13. tmp[n++] = cpoint & 0xff;
  14. else
  15. if (cpoint < 0x800) {
  16. tmp[n++] = 0xc0 | (cpoint >> 6);
  17. tmp[n++] = 0x80 | (cpoint & 0x3f);
  18. }
  19. else
  20. if (cpoint < 0x10000) {
  21. tmp[n++] = 0xe0 | (cpoint >> 12);
  22. tmp[n++] = 0x80 | ((cpoint >> 6) & 0x3f);
  23. tmp[n++] = 0x80 | (cpoint & 0x3f);
  24. }
  25. else
  26. if (cpoint < 0x200000) {
  27. tmp[n++] = 0xf0 | (cpoint >> 18);
  28. tmp[n++] = 0x80 | ((cpoint >> 12) & 0x3f);
  29. tmp[n++] = 0x80 | ((cpoint >> 6) & 0x3f);
  30. tmp[n++] = 0x80 | (cpoint & 0x3f);
  31. }
  32. return xs_append_m(str, (char *)tmp, n);
  33. }
  34. #endif /* XS_IMPLEMENTATION */
  35. #endif /* _XS_UNICODE_H */