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.
 
 
 
 

43 lines
881 B

  1. #include "fmt.h"
  2. #include "textcode.h"
  3. #include "str.h"
  4. #include "haveinline.h"
  5. /* src is UTF-8 encoded */
  6. size_t fmt_jsonescape(char* dest,const char* src,size_t len) {
  7. register const unsigned char* s=(const unsigned char*) src;
  8. size_t written=0,i;
  9. for (i=0; i<len; ++i) {
  10. switch (s[i]) {
  11. case '\\':
  12. case '"':
  13. if (dest) {
  14. dest[written]='\\';
  15. dest[written+1]=s[i];
  16. }
  17. written+=2;
  18. break;
  19. default:
  20. if (s[i]<' ') {
  21. if (dest) {
  22. dest[written]='\\';
  23. dest[written+1]='u';
  24. dest[written+2]='0';
  25. dest[written+3]='0';
  26. dest[written+4]=fmt_tohex(s[i]>>4);
  27. dest[written+5]=fmt_tohex(s[i]&0xf);
  28. }
  29. written+=6;
  30. } else {
  31. if (dest) dest[written]=s[i];
  32. ++written;
  33. }
  34. break;
  35. }
  36. /* in case someone gives us malicious input */
  37. if (written>((size_t)-1)/2) return (size_t)-1;
  38. }
  39. return written;
  40. }