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.

326 lines
7.1KB

  1. #include <ctime>
  2. #include <cctype> // for tolower and toupper
  3. #include <algorithm> // for transform and equal
  4. #include <libgen.h> // for dirname and basename
  5. #include <stdarg.h>
  6. #if defined ARCH_WIN
  7. #include <windows.h> // for MultiByteToWideChar
  8. #endif
  9. #include <string.hpp>
  10. namespace rack {
  11. namespace string {
  12. std::string f(const char* format, ...) {
  13. va_list args;
  14. va_start(args, format);
  15. std::string s = fV(format, args);
  16. va_end(args);
  17. return s;
  18. }
  19. std::string fV(const char* format, va_list args) {
  20. // va_lists cannot be reused but we need it twice, so clone args.
  21. va_list args2;
  22. va_copy(args2, args);
  23. DEFER({va_end(args2);});
  24. // Compute size of required buffer
  25. int size = vsnprintf(NULL, 0, format, args);
  26. if (size < 0)
  27. return "";
  28. // Create buffer
  29. std::string s;
  30. s.resize(size);
  31. vsnprintf(&s[0], size + 1, format, args2);
  32. return s;
  33. }
  34. std::string lowercase(const std::string& s) {
  35. std::string r = s;
  36. std::transform(r.begin(), r.end(), r.begin(), [](unsigned char c) {
  37. return std::tolower(c);
  38. });
  39. return r;
  40. }
  41. std::string uppercase(const std::string& s) {
  42. std::string r = s;
  43. std::transform(r.begin(), r.end(), r.begin(), [](unsigned char c) {
  44. return std::toupper(c);
  45. });
  46. return r;
  47. }
  48. std::string trim(const std::string& s) {
  49. const std::string whitespace = " \n\r\t";
  50. size_t first = s.find_first_not_of(whitespace);
  51. if (first == std::string::npos)
  52. return "";
  53. size_t last = s.find_last_not_of(whitespace);
  54. if (last == std::string::npos)
  55. return "";
  56. return s.substr(first, last - first + 1);
  57. }
  58. std::string ellipsize(const std::string& s, size_t len) {
  59. if (s.size() <= len)
  60. return s;
  61. else
  62. return s.substr(0, len - 3) + "...";
  63. }
  64. std::string ellipsizePrefix(const std::string& s, size_t len) {
  65. if (s.size() <= len)
  66. return s;
  67. else
  68. return "..." + s.substr(s.size() - (len - 3));
  69. }
  70. bool startsWith(const std::string& str, const std::string& prefix) {
  71. if (str.size() < prefix.size())
  72. return false;
  73. return std::equal(prefix.begin(), prefix.end(), str.begin());
  74. }
  75. bool endsWith(const std::string& str, const std::string& suffix) {
  76. if (str.size() < suffix.size())
  77. return false;
  78. return std::equal(suffix.begin(), suffix.end(), str.end() - suffix.size());
  79. }
  80. std::string toBase64(const uint8_t* data, size_t dataLen) {
  81. static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  82. size_t numBlocks = (dataLen + 2) / 3;
  83. size_t strLen = numBlocks * 4;
  84. std::string str;
  85. str.reserve(strLen);
  86. for (size_t b = 0; b < numBlocks; b++) {
  87. // Encode block
  88. uint32_t block = 0;
  89. int i;
  90. for (i = 0; i < 3 && 3 * b + i < dataLen; i++) {
  91. block |= uint32_t(data[3 * b + i]) << (8 * (2 - i));
  92. }
  93. // Decode block
  94. str += alphabet[(block >> 18) & 0x3f];
  95. str += alphabet[(block >> 12) & 0x3f];
  96. str += (i > 1) ? alphabet[(block >> 6) & 0x3f] : '=';
  97. str += (i > 2) ? alphabet[(block >> 0) & 0x3f] : '=';
  98. }
  99. return str;
  100. }
  101. std::string toBase64(const std::vector<uint8_t>& data) {
  102. return toBase64(data.data(), data.size());
  103. }
  104. std::vector<uint8_t> fromBase64(const std::string& str) {
  105. std::vector<uint8_t> data;
  106. uint32_t block = 0;
  107. int i = 0;
  108. int padding = 0;
  109. for (char c : str) {
  110. uint8_t d = 0;
  111. if ('A' <= c && c <= 'Z') {
  112. d = c - 'A';
  113. }
  114. else if ('a' <= c && c <= 'z') {
  115. d = c - 'a' + 26;
  116. }
  117. else if ('0' <= c && c <= '9') {
  118. d = c - '0' + 52;
  119. }
  120. else if (c == '+') {
  121. d = 62;
  122. }
  123. else if (c == '/') {
  124. d = 63;
  125. }
  126. else if (c == '=') {
  127. padding++;
  128. }
  129. else {
  130. // Ignore whitespace and non-base64 characters
  131. continue;
  132. }
  133. block |= uint32_t(d) << (6 * (3 - i));
  134. i++;
  135. if (i >= 4) {
  136. // Decode block
  137. data.push_back((block >> (8 * (2 - 0))) & 0xff);
  138. if (padding < 2)
  139. data.push_back((block >> (8 * (2 - 1))) & 0xff);
  140. if (padding < 1)
  141. data.push_back((block >> (8 * (2 - 2))) & 0xff);
  142. // Reset block
  143. block = 0;
  144. i = 0;
  145. padding = 0;
  146. }
  147. }
  148. return data;
  149. }
  150. bool CaseInsensitiveCompare::operator()(const std::string& a, const std::string& b) const {
  151. for (size_t i = 0;; i++) {
  152. char ai = std::tolower(a[i]);
  153. char bi = std::tolower(b[i]);
  154. if (ai < bi)
  155. return true;
  156. if (ai > bi)
  157. return false;
  158. if (!ai || !bi)
  159. return false;
  160. }
  161. }
  162. std::vector<std::string> split(const std::string& s, const std::string& separator, size_t maxTokens) {
  163. if (separator.empty())
  164. throw Exception("split(): separator cannot be empty string");
  165. // Special case of empty string
  166. if (s == "")
  167. return {};
  168. if (maxTokens == 1)
  169. return {s};
  170. std::vector<std::string> v;
  171. size_t sepLen = separator.size();
  172. size_t start = 0;
  173. size_t end;
  174. while ((end = s.find(separator, start)) != std::string::npos) {
  175. // Add token to vector
  176. std::string token = s.substr(start, end - start);
  177. v.push_back(token);
  178. // Don't include delimiter
  179. start = end + sepLen;
  180. // Stop searching for tokens if we're at the token limit
  181. if (maxTokens == v.size() + 1)
  182. break;
  183. }
  184. v.push_back(s.substr(start));
  185. return v;
  186. }
  187. std::string formatTime(const char* format, double timestamp) {
  188. time_t t = timestamp;
  189. char str[1024];
  190. size_t s = std::strftime(str, sizeof(str), format, std::localtime(&t));
  191. return std::string(str, s);
  192. }
  193. std::string formatTimeISO(double timestamp) {
  194. // Windows doesn't support %F or %T, and %z gives the full timezone name instead of offset
  195. return formatTime("%Y-%m-%d %H:%M:%S %z", timestamp);
  196. }
  197. #if defined ARCH_WIN
  198. std::string UTF16toUTF8(const std::wstring& w) {
  199. if (w.empty())
  200. return "";
  201. // Compute length of output buffer
  202. int len = WideCharToMultiByte(CP_UTF8, 0, &w[0], w.size(), NULL, 0, NULL, NULL);
  203. assert(len > 0);
  204. std::string s;
  205. // Allocate enough space for null character
  206. s.resize(len);
  207. len = WideCharToMultiByte(CP_UTF8, 0, &w[0], w.size(), &s[0], len, 0, 0);
  208. assert(len > 0);
  209. return s;
  210. }
  211. std::wstring UTF8toUTF16(const std::string& s) {
  212. if (s.empty())
  213. return L"";
  214. // Compute length of output buffer
  215. int len = MultiByteToWideChar(CP_UTF8, 0, &s[0], s.size(), NULL, 0);
  216. assert(len > 0);
  217. std::wstring w;
  218. // Allocate enough space for null character
  219. w.resize(len);
  220. len = MultiByteToWideChar(CP_UTF8, 0, &s[0], s.size(), &w[0], len);
  221. assert(len > 0);
  222. return w;
  223. }
  224. #endif
  225. /** Parses `s` as a positive base-10 number. Returns -1 if invalid. */
  226. static int stringToInt(const std::string& s) {
  227. if (s.empty())
  228. return -1;
  229. int i = 0;
  230. for (char c : s) {
  231. if (!std::isdigit((unsigned char) c))
  232. return -1;
  233. i *= 10;
  234. i += (c - '0');
  235. }
  236. return i;
  237. }
  238. /** Returns whether version part p1 is earlier than p2. */
  239. static bool compareVersionPart(const std::string& p1, const std::string& p2) {
  240. int i1 = stringToInt(p1);
  241. int i2 = stringToInt(p2);
  242. if (i1 >= 0 && i2 >= 0) {
  243. // Compare integers.
  244. return i1 < i2;
  245. }
  246. else if (i1 < 0 && i2 < 0) {
  247. // Compare strings.
  248. return p1 < p2;
  249. }
  250. else {
  251. // Types are different. String is always less than int.
  252. return i1 < 0;
  253. }
  254. }
  255. Version::Version(const std::string& s) {
  256. parts = split(s, ".");
  257. }
  258. Version::operator std::string() const {
  259. return join(parts, ".");
  260. }
  261. bool Version::operator<(const Version& other) {
  262. return std::lexicographical_compare(parts.begin(), parts.end(), other.parts.begin(), other.parts.end(), compareVersionPart);
  263. }
  264. } // namespace string
  265. } // namespace rack