unicode.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #pragma once
  2. #include <cstdint>
  3. #include <string>
  4. #include <vector>
  5. // TODO: prefix all symbols with "llama_"
  6. struct codepoint_flags {
  7. enum {
  8. UNDEFINED = 0x0001,
  9. NUMBER = 0x0002, // regex: \p{N}
  10. LETTER = 0x0004, // regex: \p{L}
  11. SEPARATOR = 0x0008, // regex: \p{Z}
  12. ACCENT_MARK = 0x0010, // regex: \p{M}
  13. PUNCTUATION = 0x0020, // regex: \p{P}
  14. SYMBOL = 0x0040, // regex: \p{S}
  15. CONTROL = 0x0080, // regex: \p{C}
  16. MASK_CATEGORIES = 0x00FF,
  17. };
  18. // codepoint type
  19. uint16_t is_undefined : 1;
  20. uint16_t is_number : 1; // regex: \p{N}
  21. uint16_t is_letter : 1; // regex: \p{L}
  22. uint16_t is_separator : 1; // regex: \p{Z}
  23. uint16_t is_accent_mark : 1; // regex: \p{M}
  24. uint16_t is_punctuation : 1; // regex: \p{P}
  25. uint16_t is_symbol : 1; // regex: \p{S}
  26. uint16_t is_control : 1; // regex: \p{C}
  27. // helper flags
  28. uint16_t is_whitespace : 1; // regex: \s
  29. uint16_t is_lowercase : 1;
  30. uint16_t is_uppercase : 1;
  31. uint16_t is_nfd : 1;
  32. // decode from uint16
  33. inline codepoint_flags(const uint16_t flags=0) {
  34. *reinterpret_cast<uint16_t*>(this) = flags;
  35. }
  36. inline uint16_t as_uint() const {
  37. return *reinterpret_cast<const uint16_t*>(this);
  38. }
  39. inline uint16_t category_flag() const {
  40. return this->as_uint() & MASK_CATEGORIES;
  41. }
  42. };
  43. size_t unicode_len_utf8(char src);
  44. std::string unicode_cpt_to_utf8(uint32_t cp);
  45. uint32_t unicode_cpt_from_utf8(const std::string & utf8, size_t & offset);
  46. std::vector<uint32_t> unicode_cpts_from_utf8(const std::string & utf8);
  47. std::vector<uint32_t> unicode_cpts_normalize_nfd(const std::vector<uint32_t> & cpts);
  48. codepoint_flags unicode_cpt_flags(const uint32_t cp);
  49. codepoint_flags unicode_cpt_flags(const std::string & utf8);
  50. std::string unicode_byte_to_utf8(uint8_t byte);
  51. uint8_t unicode_utf8_to_byte(const std::string & utf8);
  52. uint32_t unicode_tolower(uint32_t cp);
  53. std::vector<std::string> unicode_regex_split(const std::string & text, const std::vector<std::string> & regex_exprs);