From 497ed57057438577c8524aa03fe33aa8c05477a6 Mon Sep 17 00:00:00 2001 From: Anna Schumaker Date: Tue, 11 Apr 2017 09:12:17 -0400 Subject: [PATCH] core/string: Add a function for checking if a string is a subdirectory I want to use this to prevent users from adding a subdirectory of a path that has already been added to the library. Signed-off-by: Anna Schumaker --- core/string.c | 22 ++++++++++++++++++++++ include/core/string.h | 3 +++ tests/core/string.c | 13 +++++++++++++ 3 files changed, 38 insertions(+) diff --git a/core/string.c b/core/string.c index 8c9d0853..90d84553 100644 --- a/core/string.c +++ b/core/string.c @@ -81,3 +81,25 @@ bool string_match_token(const gchar *prefix, gchar **tokens) return false; } + +bool string_is_subdir(const gchar *a, const gchar *b) +{ + gchar **parent = b ? g_strsplit(b, "/", -1) : NULL; + gchar **child = a ? g_strsplit(a, "/", -1) : NULL; + bool subdir = true; + int i; + + if (!parent || !child) + return false; + + for (i = 0; parent[i]; i++) { + if (!child[i] || g_utf8_collate(parent[i], child[i]) != 0) { + subdir = false; + break; + } + } + + g_strfreev(parent); + g_strfreev(child); + return subdir; +} diff --git a/include/core/string.h b/include/core/string.h index 63f53f9d..79ef417a 100644 --- a/include/core/string.h +++ b/include/core/string.h @@ -39,6 +39,9 @@ static inline bool string_match(const gchar *a, const gchar *b) /* Returns True if one of the tokens begins with the specified prefix. */ bool string_match_token(const gchar *, gchar **); +/* Returns True if string a is a subdirectory of string b. */ +bool string_is_subdir(const gchar *, const gchar *); + /* Return the length of the string, with NULL checks */ static inline int string_length(const gchar *str) { diff --git a/tests/core/string.c b/tests/core/string.c index 094b1ece..ac7e390f 100644 --- a/tests/core/string.c +++ b/tests/core/string.c @@ -108,6 +108,18 @@ void test_match_tokens() g_assert_false(string_match_token("rule", tokens)); } +void test_subdirectory() +{ + g_assert_false(string_is_subdir(NULL, NULL)); + g_assert_false(string_is_subdir(NULL, "/a/b")); + g_assert_false(string_is_subdir("/a/b", NULL)); + g_assert_false(string_is_subdir("/a", "/a/b")); + g_assert_false(string_is_subdir("/a", "/ab")); + g_assert_true( string_is_subdir("/a/b", "/a")); + g_assert_true( string_is_subdir("/a/b", "/a/b")); + g_assert_true( string_is_subdir("/a/b/c/d", "/a/b")); +} + void test_length() { g_assert_cmpint(string_length(NULL), ==, 0); @@ -125,6 +137,7 @@ int main(int argc, char **argv) g_test_add_func("/Core/String/Comparison/Tokens", test_compare_tokens); g_test_add_func("/Core/String/Matching", test_match); g_test_add_func("/Core/String/Matching/Tokens", test_match_tokens); + g_test_add_func("/Core/String/Subdirectory", test_subdirectory); g_test_add_func("/Core/String/Length", test_length); return g_test_run(); }