From 63168656a5043fadf3909c12b6145a5dfb13a4bb Mon Sep 17 00:00:00 2001 From: Christian Hergert Date: Fri, 19 May 2023 10:02:20 -0700 Subject: [PATCH] libsysprof-analyze: add get_relative_path helper This acts somewhat like g_file_get_relative_path() in that if it is not a subdirectory of the parent, NULL is returned. Otherwise the relative path is returned. We can just dive into the substring instead of copying which is a bonus point. --- .../sysprof-mount-private.h | 2 +- src/libsysprof-analyze/sysprof-mount.c | 30 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/libsysprof-analyze/sysprof-mount-private.h b/src/libsysprof-analyze/sysprof-mount-private.h index 11488d05..fe965c2c 100644 --- a/src/libsysprof-analyze/sysprof-mount-private.h +++ b/src/libsysprof-analyze/sysprof-mount-private.h @@ -27,7 +27,7 @@ G_BEGIN_DECLS SysprofMount *_sysprof_mount_new_for_mountinfo (SysprofStrings *strings, const char *mountinfo); -gboolean _sysprof_mount_contains_path (SysprofMount *self, +const char *_sysprof_mount_get_relative_path (SysprofMount *self, const char *path); G_END_DECLS diff --git a/src/libsysprof-analyze/sysprof-mount.c b/src/libsysprof-analyze/sysprof-mount.c index 09f5801a..76b18b65 100644 --- a/src/libsysprof-analyze/sysprof-mount.c +++ b/src/libsysprof-analyze/sysprof-mount.c @@ -331,3 +331,33 @@ sysprof_mount_get_parent_mount_id (SysprofMount *self) { return self->parent_mount_id; } + +static inline gboolean +mount_is_root (SysprofMount *self) +{ + return self->mount_point[0] == '/' && self->mount_point[1] == 0; +} + +const char * +_sysprof_mount_get_relative_path (SysprofMount *self, + const char *path) +{ + gsize len; + + g_return_val_if_fail (SYSPROF_IS_MOUNT (self), NULL); + + if (path == NULL || self->mount_point == NULL) + return NULL; + + len = g_ref_string_length (self->mount_point); + + /* We don't care about directory paths, so ensure that we both + * have the proper prefix and that it is in a subdirectory of this + * mount point. + */ + if (!mount_is_root (self) && + (!g_str_has_prefix (path, self->mount_point) || path[len] != '/')) + return NULL; + + return &path[len]; +}