summaryrefslogtreecommitdiff
path: root/src/shared/path.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/shared/path.c')
-rw-r--r--src/shared/path.c30
1 files changed, 12 insertions, 18 deletions
diff --git a/src/shared/path.c b/src/shared/path.c
index 175796f..4e3077b 100644
--- a/src/shared/path.c
+++ b/src/shared/path.c
@@ -3,13 +3,13 @@
#include <shared/mem.h>
#include <stdbool.h>
-int path_simplify(const char *in, char *out, size_t len) {
- if (len == 0) return -1; // empty paths are invalid
- if (in[0] != '/') return -1; // so are relative paths
+size_t path_simplify(const char *in, char *out, size_t len) {
+ if (len == 0) return 0; /* empty paths are invalid */
+ if (in[0] != '/') return 0; /* so are relative paths */
- int seg_len; // the length of the current path segment
+ int seg_len;
int out_pos = 0;
- bool directory = 0;
+ bool directory = false;
for (size_t i = 0; i < len; i += seg_len + 1) {
assert(in[i] == '/');
@@ -24,14 +24,11 @@ int path_simplify(const char *in, char *out, size_t len) {
seg_len++;
}
- /* example iteration, illustrated with terrible ASCII art
- *
- * |i=5 |next i = i + seg_len + 1 = 10
- * v v
- * /some/path/asdf
- * |--|
- * seg_len = 4
- * (segment starts at i+1) */
+ /* |i=5 |next i = i + seg_len + 1 = 10
+ * v v
+ * /some/path/asdf
+ * |--|
+ * seg_len = 4, segment starts at i+1 */
if (seg_len == 0 || (seg_len == 1 && in[i + 1] == '.')) {
/* // or /./ */
@@ -39,21 +36,18 @@ int path_simplify(const char *in, char *out, size_t len) {
} else if (seg_len == 2 && in[i + 1] == '.' && in[i + 2] == '.') {
/* /../ */
directory = true;
-
/* try to backtrack to the last slash */
while (--out_pos >= 0 && out[out_pos] != '/');
- if (out_pos < 0) return -1;
+ if (out_pos < 0) return 0;
} else {
/* a normal segment, e.g. /asdf/ */
out[out_pos] = '/';
memcpy(&out[out_pos + 1], &in[i + 1], seg_len);
out_pos += seg_len + 1;
}
-
}
- /* paths to directories should have a trailing slash */
if (directory) out[out_pos++] = '/';
-
+ assert(0 < out_pos && (size_t)out_pos <= len);
return out_pos;
}