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 <Anna@NoWheyCreamery.com>
This commit is contained in:
Anna Schumaker 2017-04-11 09:12:17 -04:00
parent e6f34d34f0
commit 497ed57057
3 changed files with 38 additions and 0 deletions

View File

@ -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;
}

View File

@ -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)
{

View File

@ -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();
}