shared: add path_compare(), an ordering path comparison

... and make path_equal() a simple wrapper around it.

Signed-off-by: Anthony G. Basile <blueness@gentoo.org>
This commit is contained in:
Michal Schmidt 2015-03-19 16:54:15 -04:00 committed by Anthony G. Basile
parent c42184ebda
commit 252b174d23
2 changed files with 28 additions and 10 deletions

View File

@ -280,12 +280,18 @@ char* path_startswith(const char *path, const char *prefix) {
}
}
bool path_equal(const char *a, const char *b) {
int path_compare(const char *a, const char *b) {
int d;
assert(a);
assert(b);
if ((a[0] == '/') != (b[0] == '/'))
return false;
/* A relative path and an abolute path must not compare as equal.
* Which one is sorted before the other does not really matter.
* Here a relative path is ordered before an absolute path. */
d = (a[0] == '/') - (b[0] == '/');
if (d)
return d;
for (;;) {
size_t j, k;
@ -294,25 +300,36 @@ bool path_equal(const char *a, const char *b) {
b += strspn(b, "/");
if (*a == 0 && *b == 0)
return true;
return 0;
if (*a == 0 || *b == 0)
return false;
/* Order prefixes first: "/foo" before "/foo/bar" */
if (*a == 0)
return -1;
if (*b == 0)
return 1;
j = strcspn(a, "/");
k = strcspn(b, "/");
if (j != k)
return false;
/* Alphabetical sort: "/foo/aaa" before "/foo/b" */
d = memcmp(a, b, MIN(j, k));
if (d)
return (d > 0) - (d < 0); /* sign of d */
if (memcmp(a, b, j) != 0)
return false;
/* Sort "/foo/a" before "/foo/aaa" */
d = (j > k) - (j < k); /* sign of (j - k) */
if (d)
return d;
a += j;
b += k;
}
}
bool path_equal(const char *a, const char *b) {
return path_compare(a, b) == 0;
}
int path_is_mount_point(const char *t, bool allow_symlink) {
union file_handle_union h = FILE_HANDLE_INIT;

View File

@ -28,6 +28,7 @@ char* path_make_absolute(const char *p, const char *prefix);
char* path_make_absolute_cwd(const char *p);
char* path_kill_slashes(char *path);
char* path_startswith(const char *path, const char *prefix) _pure_;
int path_compare(const char *a, const char *b) _pure_;
bool path_equal(const char *a, const char *b) _pure_;
char** path_strv_resolve(char **l, const char *prefix);