[sheepdog] [PATCH 1/9] util: add helper functions to process a requested URI

MORITA Kazutaka morita.kazutaka at gmail.com
Thu Oct 31 08:48:59 CET 2013


From: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>

Signed-off-by: MORITA Kazutaka <morita.kazutaka at lab.ntt.co.jp>
---
 include/util.h |  3 +++
 lib/util.c     | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 56 insertions(+)

diff --git a/include/util.h b/include/util.h
index 6593604..f9bda11 100644
--- a/include/util.h
+++ b/include/util.h
@@ -118,6 +118,9 @@ int tkill(int tid, int sig);
 bool is_xattr_enabled(const char *path);
 const char *my_exe_path(void);
 
+int split_path(const char *path, size_t nr_segs, char **segs);
+void make_path(char *path, size_t size, size_t nr_segs, const char **segs);
+
 void find_zero_blocks(const void *buf, uint64_t *poffset, uint32_t *plen);
 void trim_zero_blocks(void *buf, uint64_t *offset, uint32_t *len);
 void untrim_zero_blocks(void *buf, uint64_t offset, uint32_t len,
diff --git a/lib/util.c b/lib/util.c
index 7c7785d..06ff8fd 100644
--- a/lib/util.c
+++ b/lib/util.c
@@ -573,6 +573,59 @@ const char *my_exe_path(void)
 }
 
 /*
+ * Split the given path and sets the splitted parts to 'segs'.
+ *
+ * This returns the number of splitted segments.
+ *
+ * For example:
+ *   split_path("/a/b/c", 3, segs);
+ *     -> Returns 3 and segs will be { "a", "b", "c" }.
+ *   split_path("/a//b//c", 3, segs);
+ *     -> Returns 3 and segs will be { "a", "b", "c" }.
+ *   split_path("/a/b/c", 2, segs);
+ *     -> Returns 2 and segs will be { "a", "b/c" }.
+ *   split_path("/a/b/c", 4, segs);
+ *     -> Returns 3 and segs will be { "a", "b", "c", undefined }.
+ */
+int split_path(const char *path, size_t nr_segs, char **segs)
+{
+	for (int i = 0; i < nr_segs; i++) {
+		while (*path == '/')
+			path++;
+
+		if (*path == '\0')
+			return i;
+
+		if (i == nr_segs - 1) {
+			segs[i] = strdup(path);
+			if (segs[i] == NULL)
+				panic("OOM");
+		} else {
+			char *p = strchrnul(path, '/');
+			int len = p - path;
+
+			segs[i] = xmalloc(len + 1);
+			memcpy(segs[i], path, len);
+			segs[i][len] = '\0';
+
+			path = p;
+		}
+	}
+
+	return nr_segs;
+}
+
+/* Concatenate 'segs' with '/' separators. */
+void make_path(char *path, size_t size, size_t nr_segs, const char **segs)
+{
+	for (int i = 0; i < nr_segs; i++) {
+		int len = snprintf(path, size, "/%s", segs[i]);
+		path += len;
+		size -= len;
+	}
+}
+
+/*
  * If force_create is true, this function create the file even when the
  * temporary file exists.
  */
-- 
1.8.1.2




More information about the sheepdog mailing list