normalize_path.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #include "api.h"
  2. #include "pal_debug.h"
  3. #include "pal_defs.h"
  4. #include "pal_error.h"
  5. static int strcmp(const char* a, const char* b) {
  6. for (; *a && *b && *a == *b; a++, b++);
  7. return *a - *b;
  8. }
  9. static const char* get_norm_path_cases[][2] = {
  10. { "/", "/" },
  11. { "/a/b/c", "/a/b/c" },
  12. { "/a/../b", "/b" },
  13. { "/../a", "/a" },
  14. { "/../../../../../a", "/a" },
  15. { "/../a/../../b", "/b" },
  16. { "/../..a/b", "/..a/b" },
  17. {" /a/..", "/" },
  18. { "/a/.", "/a" },
  19. { "/.//a//./b", "/a/b" },
  20. { "///////.////////////./", "/" },
  21. { "/...././a/../././.../b/.....", "/..../.../b/....." },
  22. { "a/b/c", "a/b/c" },
  23. { "a/../b", "b" },
  24. { "../a", "../a" },
  25. { "../../../../../a", "../../../../../a" },
  26. { "../a/../../b", "../../b" },
  27. { "../..a/b", "../..a/b" },
  28. { "a/..", "" },
  29. { "a/." "a" },
  30. };
  31. static const char* get_base_name_cases[][2] = {
  32. { "/", "" },
  33. { "/a", "a" },
  34. { "/a/b/c", "c" },
  35. { "/..a/b", "b" },
  36. { "", "" },
  37. { "../a", "a" },
  38. { "../../../../../a", "a" },
  39. { "..a/b", "b" },
  40. { "a/b/c", "c" },
  41. };
  42. #define ARR_LEN(x) (sizeof(x) / sizeof(x[0]) / sizeof(x[0][0]))
  43. #define print_err(name, i, ...) \
  44. do { \
  45. pal_printf("%s: case %lu (%s) ", name, i, cases[i][0]); \
  46. pal_printf(__VA_ARGS__); \
  47. } while (0)
  48. static const char* (*cases)[2];
  49. static size_t cases_len;
  50. static int (*func_to_test)(const char*, char*, size_t*);
  51. static const char* func_name;
  52. static int run_test(void) {
  53. char buf[URI_MAX] = { 0 };
  54. for (size_t i = 0; i < cases_len; i++) {
  55. size_t size = sizeof(buf);
  56. int ret = func_to_test(cases[i][0], buf, &size);
  57. if (ret < 0) {
  58. print_err(func_name, i, "failed with error: %s\n", PAL_STRERROR(ret));
  59. return 1;
  60. }
  61. if (strlen(buf) != size) {
  62. print_err(func_name, i, "returned wrong size: %zu\n", size);
  63. return 1;
  64. }
  65. if (strcmp(cases[i][1], buf) != 0) {
  66. print_err(func_name, i, "returned: \"%s\", instead of: %s\n", buf, cases[i][1]);
  67. return 1;
  68. }
  69. }
  70. return 0;
  71. }
  72. int main(void) {
  73. cases = get_norm_path_cases;
  74. cases_len = ARR_LEN(get_norm_path_cases);
  75. func_to_test = get_norm_path;
  76. if (run_test()) {
  77. return 1;
  78. }
  79. cases = get_base_name_cases;
  80. cases_len = ARR_LEN(get_base_name_cases);
  81. func_to_test = get_base_name;
  82. if (run_test()) {
  83. return 1;
  84. }
  85. pal_printf("Success!\n");
  86. return 0;
  87. }