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.

utilstrencodings.h 5.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. // Copyright (c) 2009-2010 Satoshi Nakamoto
  2. // Copyright (c) 2009-2016 The Starwels developers
  3. // Distributed under the MIT software license, see the accompanying
  4. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. /**
  6. * Utilities for converting data from/to strings.
  7. */
  8. #ifndef STARWELS_UTILSTRENCODINGS_H
  9. #define STARWELS_UTILSTRENCODINGS_H
  10. #include <stdint.h>
  11. #include <string>
  12. #include <vector>
  13. #define BEGIN(a) ((char*)&(a))
  14. #define END(a) ((char*)&((&(a))[1]))
  15. #define UBEGIN(a) ((unsigned char*)&(a))
  16. #define UEND(a) ((unsigned char*)&((&(a))[1]))
  17. #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0]))
  18. /** Used by SanitizeString() */
  19. enum SafeChars
  20. {
  21. SAFE_CHARS_DEFAULT, //!< The full set of allowed chars
  22. SAFE_CHARS_UA_COMMENT, //!< BIP-0014 subset
  23. SAFE_CHARS_FILENAME, //!< Chars allowed in filenames
  24. };
  25. /**
  26. * Remove unsafe chars. Safe chars chosen to allow simple messages/URLs/email
  27. * addresses, but avoid anything even possibly remotely dangerous like & or >
  28. * @param[in] str The string to sanitize
  29. * @param[in] rule The set of safe chars to choose (default: least restrictive)
  30. * @return A new string without unsafe chars
  31. */
  32. std::string SanitizeString(const std::string& str, int rule = SAFE_CHARS_DEFAULT);
  33. std::vector<unsigned char> ParseHex(const char* psz);
  34. std::vector<unsigned char> ParseHex(const std::string& str);
  35. signed char HexDigit(char c);
  36. /* Returns true if each character in str is a hex character, and has an even
  37. * number of hex digits.*/
  38. bool IsHex(const std::string& str);
  39. /**
  40. * Return true if the string is a hex number, optionally prefixed with "0x"
  41. */
  42. bool IsHexNumber(const std::string& str);
  43. std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = nullptr);
  44. std::string DecodeBase64(const std::string& str);
  45. std::string EncodeBase64(const unsigned char* pch, size_t len);
  46. std::string EncodeBase64(const std::string& str);
  47. std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid = nullptr);
  48. std::string DecodeBase32(const std::string& str);
  49. std::string EncodeBase32(const unsigned char* pch, size_t len);
  50. std::string EncodeBase32(const std::string& str);
  51. void SplitHostPort(std::string in, int &portOut, std::string &hostOut);
  52. std::string i64tostr(int64_t n);
  53. std::string itostr(int n);
  54. int64_t atoi64(const char* psz);
  55. int64_t atoi64(const std::string& str);
  56. int atoi(const std::string& str);
  57. /**
  58. * Convert string to signed 32-bit integer with strict parse error feedback.
  59. * @returns true if the entire string could be parsed as valid integer,
  60. * false if not the entire string could be parsed or when overflow or underflow occurred.
  61. */
  62. bool ParseInt32(const std::string& str, int32_t *out);
  63. /**
  64. * Convert string to signed 64-bit integer with strict parse error feedback.
  65. * @returns true if the entire string could be parsed as valid integer,
  66. * false if not the entire string could be parsed or when overflow or underflow occurred.
  67. */
  68. bool ParseInt64(const std::string& str, int64_t *out);
  69. /**
  70. * Convert decimal string to unsigned 32-bit integer with strict parse error feedback.
  71. * @returns true if the entire string could be parsed as valid integer,
  72. * false if not the entire string could be parsed or when overflow or underflow occurred.
  73. */
  74. bool ParseUInt32(const std::string& str, uint32_t *out);
  75. /**
  76. * Convert decimal string to unsigned 64-bit integer with strict parse error feedback.
  77. * @returns true if the entire string could be parsed as valid integer,
  78. * false if not the entire string could be parsed or when overflow or underflow occurred.
  79. */
  80. bool ParseUInt64(const std::string& str, uint64_t *out);
  81. /**
  82. * Convert string to double with strict parse error feedback.
  83. * @returns true if the entire string could be parsed as valid double,
  84. * false if not the entire string could be parsed or when overflow or underflow occurred.
  85. */
  86. bool ParseDouble(const std::string& str, double *out);
  87. template<typename T>
  88. std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
  89. {
  90. std::string rv;
  91. static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7',
  92. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  93. rv.reserve((itend-itbegin)*3);
  94. for(T it = itbegin; it < itend; ++it)
  95. {
  96. unsigned char val = (unsigned char)(*it);
  97. if(fSpaces && it != itbegin)
  98. rv.push_back(' ');
  99. rv.push_back(hexmap[val>>4]);
  100. rv.push_back(hexmap[val&15]);
  101. }
  102. return rv;
  103. }
  104. template<typename T>
  105. inline std::string HexStr(const T& vch, bool fSpaces=false)
  106. {
  107. return HexStr(vch.begin(), vch.end(), fSpaces);
  108. }
  109. /**
  110. * Format a paragraph of text to a fixed width, adding spaces for
  111. * indentation to any added line.
  112. */
  113. std::string FormatParagraph(const std::string& in, size_t width = 79, size_t indent = 0);
  114. /**
  115. * Timing-attack-resistant comparison.
  116. * Takes time proportional to length
  117. * of first argument.
  118. */
  119. template <typename T>
  120. bool TimingResistantEqual(const T& a, const T& b)
  121. {
  122. if (b.size() == 0) return a.size() == 0;
  123. size_t accumulator = a.size() ^ b.size();
  124. for (size_t i = 0; i < a.size(); i++)
  125. accumulator |= a[i] ^ b[i%b.size()];
  126. return accumulator == 0;
  127. }
  128. /** Parse number as fixed point according to JSON number syntax.
  129. * See http://json.org/number.gif
  130. * @returns true on success, false on error.
  131. * @note The result must be in the range (-10^18,10^18), otherwise an overflow error will trigger.
  132. */
  133. bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out);
  134. #endif // STARWELS_UTILSTRENCODINGS_H