AutoHeader.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #ifndef NULLSOFT_AUTOHEADERH
  2. #define NULLSOFT_AUTOHEADERH
  3. #include <windows.h>
  4. #include "AutoChar.h"
  5. /* encodes a UTF-8 string into a buffer, returns a pointer to the end of the string */
  6. inline char *AutoHeader_Encode(const char *in, char *out, size_t len)
  7. {
  8. if (!len)
  9. return 0;
  10. char *dest=out;
  11. const unsigned char *src = (const unsigned char *)in;
  12. while (*src && --len)
  13. {
  14. if ((*src >= 'A' && *src <= 'Z') ||
  15. (*src >= 'a' && *src <= 'z') ||
  16. (*src >= '0' && *src <= '9') || *src == '.' || *src == '-' || *src == '~')
  17. {
  18. *dest++=*src++;
  19. }
  20. else if (len > 2)
  21. {
  22. int i = *src++;
  23. *dest++ = '=';
  24. int b = (i >> 4) & 15;
  25. if (b < 10) *dest++ = '0' + b;
  26. else *dest++ = 'A' + b - 10;
  27. b = i & 15;
  28. if (b < 10) *dest++ = '0' + b;
  29. else *dest++ = 'A' + b - 10;
  30. }
  31. else
  32. break;
  33. }
  34. *dest=0;
  35. return dest;
  36. }
  37. inline char *AutoHeaderDup(const wchar_t *convert)
  38. {
  39. if (!convert)
  40. return 0;
  41. BOOL failed=FALSE;
  42. int n = WideCharToMultiByte(28591, WC_NO_BEST_FIT_CHARS, convert, -1, 0, 0, 0, &failed);
  43. if (n && !failed)
  44. {
  45. char *url = (char *)malloc(n + 1);
  46. WideCharToMultiByte(28591, WC_NO_BEST_FIT_CHARS, convert, -1, url, n+1, 0, 0);
  47. return url;
  48. }
  49. AutoChar utf8(convert, CP_UTF8);
  50. size_t size = strlen(utf8)*3+1; // one byte might get encoded to 3 bytes, so we'll malloc for worst-case
  51. char *url= (char *)malloc((9 /*?utf-8?q?*/+ size + 2 /*?=*/)*sizeof(char));
  52. memcpy(url, "?utf-8?q?", 9);
  53. char *end = AutoHeader_Encode(utf8, url+9, size);
  54. strcpy(end, "?=");
  55. return url;
  56. }
  57. class AutoHeader
  58. {
  59. public:
  60. AutoHeader(const wchar_t *convert) : narrow(0)
  61. {
  62. narrow = AutoHeaderDup(convert);
  63. }
  64. AutoHeader(const AutoHeader &convert) : narrow(0)
  65. {
  66. if (convert.narrow)
  67. narrow = _strdup(convert.narrow);
  68. }
  69. ~AutoHeader()
  70. {
  71. free(narrow);
  72. narrow=0;
  73. }
  74. operator const char *()
  75. {
  76. return narrow;
  77. }
  78. operator char *()
  79. {
  80. return narrow;
  81. }
  82. private:
  83. char *narrow;
  84. };
  85. #endif