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.

87 lines
2.0KB

  1. #pragma once
  2. #include "common.hpp"
  3. #include <algorithm> // for transform
  4. #include <libgen.h> // for dirname and basename
  5. namespace rack {
  6. namespace string {
  7. /** Converts a printf format string and optional arguments into a std::string */
  8. inline std::string stringf(const char *format, ...) {
  9. va_list args;
  10. va_start(args, format);
  11. // Compute size of required buffer
  12. int size = vsnprintf(NULL, 0, format, args);
  13. va_end(args);
  14. if (size < 0)
  15. return "";
  16. // Create buffer
  17. std::string s;
  18. s.resize(size);
  19. va_start(args, format);
  20. vsnprintf(&s[0], size + 1, format, args);
  21. va_end(args);
  22. return s;
  23. }
  24. inline std::string lowercase(std::string s) {
  25. std::transform(s.begin(), s.end(), s.begin(), ::tolower);
  26. return s;
  27. }
  28. inline std::string uppercase(std::string s) {
  29. std::transform(s.begin(), s.end(), s.begin(), ::toupper);
  30. return s;
  31. }
  32. /** Truncates and adds "..." to a string, not exceeding `len` characters */
  33. inline std::string ellipsize(std::string s, size_t len) {
  34. if (s.size() <= len)
  35. return s;
  36. else
  37. return s.substr(0, len - 3) + "...";
  38. }
  39. inline bool startsWith(std::string str, std::string prefix) {
  40. return str.substr(0, prefix.size()) == prefix;
  41. }
  42. inline bool endsWith(std::string str, std::string suffix) {
  43. return str.substr(str.size() - suffix.size(), suffix.size()) == suffix;
  44. }
  45. /** Extracts portions of a path */
  46. inline std::string directory(std::string path) {
  47. char *pathDup = strdup(path.c_str());
  48. std::string directory = dirname(pathDup);
  49. free(pathDup);
  50. return directory;
  51. }
  52. inline std::string filename(std::string path) {
  53. char *pathDup = strdup(path.c_str());
  54. std::string filename = basename(pathDup);
  55. free(pathDup);
  56. return filename;
  57. }
  58. inline std::string extension(std::string path) {
  59. const char *ext = strrchr(filename(path).c_str(), '.');
  60. if (!ext)
  61. return "";
  62. return ext + 1;
  63. }
  64. struct CaseInsensitiveCompare {
  65. bool operator()(const std::string &a, const std::string &b) const {
  66. return lowercase(a) < lowercase(b);
  67. }
  68. };
  69. } // namespace string
  70. } // namespace rack