Path.hpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #pragma once
  2. #include <string>
  3. namespace QuickMedia {
  4. class Path {
  5. public:
  6. Path() = default;
  7. Path(const char *path) : data(path) {}
  8. Path(const std::string &path) : data(path) {}
  9. // TODO: Return a copy instead? makes it easier to use. Do the same for append
  10. Path& join(const Path &other) {
  11. data += "/";
  12. data += other.data;
  13. return *this;
  14. }
  15. Path& append(const std::string &str) {
  16. data += str;
  17. return *this;
  18. }
  19. Path& append(const char *str) {
  20. data += str;
  21. return *this;
  22. }
  23. // Includes extension
  24. const char* filename() const {
  25. size_t index = data.rfind('/');
  26. if(index == std::string::npos)
  27. return data.c_str();
  28. return data.c_str() + index + 1;
  29. }
  30. std::string filename_no_ext() const {
  31. const char *name = filename();
  32. const char *extension = ext();
  33. if(extension[0] == '\0')
  34. return name;
  35. else
  36. return data.substr(name - data.data(), extension - name);
  37. }
  38. // Returns extension with the dot. Returns empty string if no extension
  39. const char* ext() const {
  40. size_t slash_index = data.rfind('/');
  41. size_t index = data.rfind('.');
  42. if(index != std::string::npos && (slash_index == std::string::npos || index > slash_index))
  43. return data.c_str() + index;
  44. return "";
  45. }
  46. Path parent() const {
  47. size_t slash_index = data.rfind('/');
  48. if(slash_index != std::string::npos && slash_index > 0)
  49. return Path(data.substr(0, slash_index));
  50. if(!data.empty() && data[0] == '/')
  51. return Path("/");
  52. else
  53. return Path("");
  54. }
  55. std::string data;
  56. };
  57. }