path.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c) 2012-2016 Daniele Bartolini and individual contributors.
  3. * License: https://github.com/taylor001/crown/blob/master/LICENSE
  4. */
  5. #include "dynamic_string.h"
  6. #include "path.h"
  7. #include <ctype.h> // isalpha
  8. #include <string.h> // strrchr
  9. namespace crown
  10. {
  11. namespace path
  12. {
  13. bool is_absolute(const char* path)
  14. {
  15. CE_ASSERT_NOT_NULL(path);
  16. #if CROWN_PLATFORM_POSIX
  17. return strlen32(path) > 0
  18. && path[0] == PATH_SEPARATOR
  19. ;
  20. #elif CROWN_PLATFORM_WINDOWS
  21. return strlen32(path) > 2
  22. && isalpha(path[0])
  23. && path[1] == ':'
  24. && path[2] == PATH_SEPARATOR
  25. ;
  26. #endif
  27. }
  28. bool is_relative(const char* path)
  29. {
  30. CE_ASSERT_NOT_NULL(path);
  31. return !is_absolute(path);
  32. }
  33. bool is_root(const char* path)
  34. {
  35. CE_ASSERT_NOT_NULL(path);
  36. #if CROWN_PLATFORM_POSIX
  37. return is_absolute(path) && strlen32(path) == 1;
  38. #elif CROWN_PLATFORM_WINDOWS
  39. return is_absolute(path) && strlen32(path) == 3;
  40. #endif
  41. }
  42. void join(const char* path_a, const char* path_b, DynamicString& path)
  43. {
  44. CE_ASSERT_NOT_NULL(path_a);
  45. CE_ASSERT_NOT_NULL(path_b);
  46. const u32 la = strlen32(path_a);
  47. const u32 lb = strlen32(path_b);
  48. path.reserve(la + lb + 1);
  49. path += path_a;
  50. path += PATH_SEPARATOR;
  51. path += path_b;
  52. }
  53. const char* basename(const char* path)
  54. {
  55. CE_ASSERT_NOT_NULL(path);
  56. const char* ls = strrchr(path, '/');
  57. return ls == NULL ? path : ls + 1;
  58. }
  59. const char* extension(const char* path)
  60. {
  61. CE_ASSERT_NOT_NULL(path);
  62. const char* ld = strrchr(path, '.');
  63. return ld == NULL ? NULL : ld + 1;
  64. }
  65. } // namespace path
  66. } // namespace crown