Mirror of :pserver:cvs@cvs.fefe.de:/cvs libowfat https://www.fefe.de/libowfat/
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.

47 lines
921 B

  1. #include "fmt.h"
  2. static void fmt_hex4(char* dest,uint16_t w) {
  3. dest[3]=fmt_tohex(w&0xf); w>>=4;
  4. dest[2]=fmt_tohex(w&0xf); w>>=4;
  5. dest[1]=fmt_tohex(w&0xf); w>>=4;
  6. dest[0]=fmt_tohex(w&0xf);
  7. }
  8. size_t fmt_escapecharjson(char* dest,uint32_t ch) {
  9. size_t n;
  10. switch (ch) {
  11. case '\b':
  12. ch='b'; goto simple;
  13. case '\n':
  14. ch='n'; goto simple;
  15. case '\r':
  16. ch='r'; goto simple;
  17. case '"':
  18. case '\\':
  19. case '/':
  20. simple:
  21. if (dest) {
  22. dest[0]='\\';
  23. dest[1]=(char)ch;
  24. }
  25. return 2;
  26. }
  27. if (ch>0xffff) {
  28. if (ch>0x10ffff) return 0; // highest representable unicode codepoint
  29. if (dest) {
  30. dest[0]='\\';
  31. dest[1]='u';
  32. fmt_hex4(dest+2,(uint16_t)(0xd800 | (((ch-0x10000)>>10)&0x3ff)));
  33. dest+=6;
  34. }
  35. ch=(ch&0x3ff)|0xdc00;
  36. n=6;
  37. } else
  38. n=0;
  39. if (dest) {
  40. dest[0]='\\';
  41. dest[1]='u';
  42. fmt_hex4(dest+2,(uint16_t)ch);
  43. }
  44. return n+6;
  45. }