Add guestfs_int_drive_index which does basically the opposite of
guestfs_int_drive_name. This commit also includes a unit test.
---
src/guestfs-internal-frontend.h | 1 +
src/test-utils.c | 22 ++++++++++++++++++++++
src/utils.c | 21 +++++++++++++++++++++
3 files changed, 44 insertions(+)
diff --git a/src/guestfs-internal-frontend.h b/src/guestfs-internal-frontend.h
index 9322201..e3f0db6 100644
--- a/src/guestfs-internal-frontend.h
+++ b/src/guestfs-internal-frontend.h
@@ -105,6 +105,7 @@ extern char **guestfs_int_split_string (char sep, const char *);
extern char *guestfs_int_exit_status_to_string (int status, const char *cmd_name, char
*buffer, size_t buflen);
extern int guestfs_int_random_string (char *ret, size_t len);
extern char *guestfs_int_drive_name (size_t index, char *ret);
+extern ssize_t guestfs_int_drive_index (const char *);
extern int guestfs_int_is_true (const char *str);
/* These functions are used internally by the CLEANUP_* macros.
diff --git a/src/test-utils.c b/src/test-utils.c
index c5e2f08..0b7714a 100644
--- a/src/test-utils.c
+++ b/src/test-utils.c
@@ -188,6 +188,27 @@ test_drive_name (void)
assert (STREQ (s, "zzz"));
}
+/* Test guestfs_int_drive_index. */
+static void
+test_drive_index (void)
+{
+ assert (guestfs_int_drive_index ("a") == 0);
+ assert (guestfs_int_drive_index ("z") == 25);
+ assert (guestfs_int_drive_index ("aa") == 26);
+ assert (guestfs_int_drive_index ("ab") == 27);
+ assert (guestfs_int_drive_index ("az") == 51);
+ assert (guestfs_int_drive_index ("ba") == 52);
+ assert (guestfs_int_drive_index ("zz") == 701);
+ assert (guestfs_int_drive_index ("aaa") == 702);
+ assert (guestfs_int_drive_index ("zzz") == 18277);
+
+ assert (guestfs_int_drive_index ("") == -1);
+ assert (guestfs_int_drive_index ("abc123") == -1);
+ assert (guestfs_int_drive_index ("123") == -1);
+ assert (guestfs_int_drive_index ("Z") == -1);
+ assert (guestfs_int_drive_index ("aB") == -1);
+}
+
int
main (int argc, char *argv[])
{
@@ -196,6 +217,7 @@ main (int argc, char *argv[])
test_join ();
test_validate_guid ();
test_drive_name ();
+ test_drive_index ();
exit (EXIT_SUCCESS);
}
diff --git a/src/utils.c b/src/utils.c
index 7cee16e..e9ec38e 100644
--- a/src/utils.c
+++ b/src/utils.c
@@ -271,6 +271,27 @@ guestfs_int_drive_name (size_t index, char *ret)
return ret;
}
+/* The opposite of guestfs_int_drive_name. Take a string like "ab"
+ * and return the index (eg 27). Note that you must remove any prefix
+ * such as "hd", "sd" etc, or any partition number before calling
the
+ * function.
+ */
+ssize_t
+guestfs_int_drive_index (const char *name)
+{
+ ssize_t r = 0;
+
+ while (*name) {
+ if (*name >= 'a' && *name <= 'z')
+ r = 26*r + (*name - 'a' + 1);
+ else
+ return -1;
+ name++;
+ }
+
+ return r-1;
+}
+
/* Similar to Tcl_GetBoolean. */
int
guestfs_int_is_true (const char *str)
--
2.3.1