1#include "include/pw.h"
2#include "include/pwlib/path.h"
3
4[[nodiscard]] bool pw_path_as_array(PwValuePtr path, PwValuePtr result)
5{
6 if (pw_is_string(path)) {
7 return pw_path_split(path, result);
8 } else {
9 pw_assert(pw_is_array(path));
10 pw_clone2(result, path);
11 return true;
12 }
13}
14
15[[nodiscard]] bool pw_path_split(PwValuePtr path, PwValuePtr result)
16{
17 pw_assert(pw_is_string(path));
18
19 if (!pw_string_rsplit_chr(path, '/', 0, result)) {
20 return false;
21 }
22 // add root element if path is absolute
23 if (pw_char_at(path, 0) == '/') {
24 PwValue root = PW_STRING("/");
25 if (!pw_array_insert(result, 0, &root)) {
26 return false;
27 }
28 }
29 // delete empty elements caused by multiple slashes
30 unsigned n = pw_array_length(result);
31 for (unsigned i = 0; i < n; i++) {
32 PwValue item = PW_NULL;
33 if (!pw_array_item(result, i, &item)) {
34 return false;
35 }
36 if (pw_strlen(&item) == 0) {
37 if (!pw_array_del(result, i, i + 1)) {
38 return false;
39 }
40 i--;
41 n--;
42 }
43 }
44 return true;
45}