commit 71f475126bf329d0335f2fb2b1f60f64f52c7b24
parent d0d5d7a453b7285b4e5f1b244acb0e4ed51a8c5c
Author: Chris Bracken <chris@bracken.jp>
Date: Fri, 13 Feb 2026 12:25:38 +0900
Improve relpath_from_dir implementation
Diffstat:
1 file changed, 11 insertions(+), 13 deletions(-)
diff --git a/src/utils.c b/src/utils.c
@@ -141,26 +141,24 @@ bool is_safe_mailto(const char* email) {
}
char* relpath_from_dir(const char* dir) {
- size_t slashes = 0;
- for (const char* p = dir; *p != '\0'; p++) {
- if (*p == '/') {
- slashes++;
+ size_t num_components = 1;
+ if (strcmp(dir, ".") != 0) {
+ for (const char* p = dir; *p != '\0'; p++) {
+ if (*p == '/') {
+ num_components++;
+ }
}
}
- size_t num_components = slashes + 1;
- if (strcmp(dir, ".") == 0) {
- num_components = 1;
- }
-
- size_t relpath_chars = num_components * (sizeof("../") - 1);
- size_t relpath_size = relpath_chars + 1;
+ const char segment[] = "../";
+ const size_t segment_len = sizeof(segment) - 1;
+ size_t relpath_size = (num_components * segment_len) + 1;
char* relpath = ecalloc(relpath_size, 1);
char* ptr = relpath;
for (size_t i = 0; i < num_components; i++) {
- memcpy(ptr, "../", sizeof("../") - 1);
- ptr += (sizeof("../") - 1);
+ memcpy(ptr, segment, segment_len);
+ ptr += segment_len;
}
*ptr = '\0';