You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.8 KiB

  1. /* Copyright 2021 QMK
  2. *
  3. * This program is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include "utf8.h"
  17. // Borrowed from https://nullprogram.com/blog/2017/10/06/
  18. const char *decode_utf8(const char *str, int32_t *code_point) {
  19. const char *next;
  20. if (str[0] < 0x80) { // U+0000-007F
  21. *code_point = str[0];
  22. next = str + 1;
  23. } else if ((str[0] & 0xE0) == 0xC0) { // U+0080-07FF
  24. *code_point = ((int32_t)(str[0] & 0x1F) << 6) | ((int32_t)(str[1] & 0x3F) << 0);
  25. next = str + 2;
  26. } else if ((str[0] & 0xF0) == 0xE0) { // U+0800-FFFF
  27. *code_point = ((int32_t)(str[0] & 0x0F) << 12) | ((int32_t)(str[1] & 0x3F) << 6) | ((int32_t)(str[2] & 0x3F) << 0);
  28. next = str + 3;
  29. } else if ((str[0] & 0xF8) == 0xF0 && (str[0] <= 0xF4)) { // U+10000-10FFFF
  30. *code_point = ((int32_t)(str[0] & 0x07) << 18) | ((int32_t)(str[1] & 0x3F) << 12) | ((int32_t)(str[2] & 0x3F) << 6) | ((int32_t)(str[3] & 0x3F) << 0);
  31. next = str + 4;
  32. } else {
  33. *code_point = -1;
  34. next = str + 1;
  35. }
  36. // part of a UTF-16 surrogate pair - invalid
  37. if (*code_point >= 0xD800 && *code_point <= 0xDFFF) {
  38. *code_point = -1;
  39. }
  40. return next;
  41. }