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.

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