url_encoder.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #pragma once
  2. #ifndef URL_ENCODER_H
  3. #define URL_ENCODER_H
  4. #include <string>
  5. #include <sstream>
  6. #include <iomanip>
  7. const char kUnreservedChar[] = {
  8. //0 1 2 3 4 5 6 7 8 9 A B C D E F
  9. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0
  10. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1
  11. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, // 2
  12. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 3
  13. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4
  14. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 5
  15. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6
  16. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, // 7
  17. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8
  18. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9
  19. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A
  20. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B
  21. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C
  22. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D
  23. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E
  24. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // F
  25. };
  26. class UrlEncoder {
  27. public:
  28. static inline void Encode(const std::string& in, std::string* out, bool uppercase = false) {
  29. std::stringstream ss;
  30. for (std::string::const_iterator it = in.begin(); it != in.end(); ++it) {
  31. if (kUnreservedChar[*it]) {
  32. ss << *it;
  33. }
  34. else {
  35. ss << '%' << std::setfill('0') << std::hex;
  36. if (uppercase) ss << std::uppercase;
  37. ss << (int)*it;
  38. }
  39. }
  40. out->assign(ss.str());
  41. }
  42. static inline std::string Encode(const std::string& in, bool uppercase = false) {
  43. std::string out;
  44. Encode(in, &out, uppercase);
  45. return out;
  46. }
  47. private:
  48. };
  49. #endif // URL_ENCODER_H