decode.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <stdio.h>
  2. #include <bfc/platform/types.h>
  3. #include <strsafe.h>
  4. static uint8_t quickhex(char c)
  5. {
  6. int hexvalue = c;
  7. if (hexvalue & 0x10)
  8. hexvalue &= ~0x30;
  9. else
  10. {
  11. hexvalue &= 0xF;
  12. hexvalue += 9;
  13. }
  14. return hexvalue;
  15. }
  16. static uint8_t DecodeEscape(const char *&str)
  17. {
  18. uint8_t a = quickhex(*++str);
  19. uint8_t b = quickhex(*++str);
  20. str++;
  21. return a * 16 + b;
  22. }
  23. static void DecodeEscapedUTF8(char *&output, const char *&input)
  24. {
  25. uint8_t utf8_data[1024] = {0}; // hopefully big enough!!
  26. int num_utf8_words=0;
  27. bool error=false;
  28. while (input && *input && *input == '%' && num_utf8_words < sizeof(utf8_data))
  29. {
  30. if (isxdigit(input[1]) && isxdigit(input[2]))
  31. {
  32. utf8_data[num_utf8_words++]=DecodeEscape(input);
  33. }
  34. else if (input[1] == '%')
  35. {
  36. input+=2;
  37. utf8_data[num_utf8_words++]='%';
  38. }
  39. else
  40. {
  41. error = true;
  42. break;
  43. }
  44. }
  45. memcpy(output, utf8_data, num_utf8_words);
  46. output+=num_utf8_words;
  47. //StringCchCopyExA(output, num_utf8_words, (char *)utf8_data, &output, 0, 0);
  48. if (error)
  49. {
  50. *output++ = *input++;
  51. }
  52. }
  53. // benski> We have the luxury of knowing that decoding will ALWAYS produce smaller strings
  54. // so we can do it in-place
  55. void UrlDecode(char *str)
  56. {
  57. const char *itr = str;
  58. while (itr && *itr)
  59. {
  60. switch (*itr)
  61. {
  62. case '%':
  63. DecodeEscapedUTF8(str, itr);
  64. break;
  65. default:
  66. *str++ = *itr++;
  67. break;
  68. }
  69. }
  70. *str = 0;
  71. }