normalize_path.c 2.6 KB

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