UnicodeUtils.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * Copyright (c) 2021, Max Wipfli <mail@maxwipfli.ch>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Forward.h>
  8. namespace AK::UnicodeUtils {
  9. constexpr bool is_unicode_control_code_point(u32 code_point)
  10. {
  11. return code_point < 0x20 || (code_point >= 0x80 && code_point < 0xa0);
  12. }
  13. Optional<StringView> get_unicode_control_code_point_alias(u32);
  14. template<typename Callback>
  15. [[nodiscard]] constexpr int code_point_to_utf8(u32 code_point, Callback callback)
  16. {
  17. if (code_point <= 0x7f) {
  18. callback((char)code_point);
  19. return 1;
  20. } else if (code_point <= 0x07ff) {
  21. callback((char)(((code_point >> 6) & 0x1f) | 0xc0));
  22. callback((char)(((code_point >> 0) & 0x3f) | 0x80));
  23. return 2;
  24. } else if (code_point <= 0xffff) {
  25. callback((char)(((code_point >> 12) & 0x0f) | 0xe0));
  26. callback((char)(((code_point >> 6) & 0x3f) | 0x80));
  27. callback((char)(((code_point >> 0) & 0x3f) | 0x80));
  28. return 3;
  29. } else if (code_point <= 0x10ffff) {
  30. callback((char)(((code_point >> 18) & 0x07) | 0xf0));
  31. callback((char)(((code_point >> 12) & 0x3f) | 0x80));
  32. callback((char)(((code_point >> 6) & 0x3f) | 0x80));
  33. callback((char)(((code_point >> 0) & 0x3f) | 0x80));
  34. return 4;
  35. }
  36. return -1;
  37. }
  38. }