[Libguestfs] [nbdkit PATCH v2 3/5] utils: Add nbdkit_parse_bool

Eric Blake eblake at redhat.com
Thu Nov 8 21:29:50 UTC 2018


Parses the same set of boolean parameters as libguestfs:
https://github.com/libguestfs/libguestfs/blob/dd665e4bb/common/utils/utils.c#L345
with permission from Rich Jones to relax his code to BSD licensing:
https://www.redhat.com/archives/libguestfs/2018-November/msg00094.html

Signed-off-by: Eric Blake <eblake at redhat.com>
---
 docs/nbdkit-plugin.pod  | 11 +++++++++++
 include/nbdkit-common.h |  1 +
 src/utils.c             | 25 +++++++++++++++++++++++++
 3 files changed, 37 insertions(+)

diff --git a/docs/nbdkit-plugin.pod b/docs/nbdkit-plugin.pod
index 594f2f3..4754d2c 100644
--- a/docs/nbdkit-plugin.pod
+++ b/docs/nbdkit-plugin.pod
@@ -763,6 +763,17 @@ size strings such as "100M" into the size in bytes.
 C<str> can be a string in a number of common formats.  The function
 returns the size in bytes.  If there was an error, it returns C<-1>.

+=head1 PARSING BOOLEAN PARAMETERS
+
+Use the C<nbdkit_parse_bool> utility function to parse human-readable
+strings such as "on" into a boolean value.
+
+ int nbdkit_parse_bool (const char *str);
+
+C<str> can be a string containing a case-insensitive form of various
+common toggle values.  The function returns 0 or 1 if the parse was
+successful.  If there was an error, it returns C<-1>.
+
 =head1 READING PASSWORDS

 The C<nbdkit_read_password> utility function can be used to read
diff --git a/include/nbdkit-common.h b/include/nbdkit-common.h
index 47d2c47..9295b8a 100644
--- a/include/nbdkit-common.h
+++ b/include/nbdkit-common.h
@@ -66,6 +66,7 @@ extern void nbdkit_vdebug (const char *msg, va_list args);

 extern char *nbdkit_absolute_path (const char *path);
 extern int64_t nbdkit_parse_size (const char *str);
+extern int nbdkit_parse_bool (const char *str);
 extern int nbdkit_read_password (const char *value, char **password);
 extern char *nbdkit_realpath (const char *path);

diff --git a/src/utils.c b/src/utils.c
index c9e1e14..18011fd 100644
--- a/src/utils.c
+++ b/src/utils.c
@@ -158,6 +158,31 @@ nbdkit_parse_size (const char *str)
   return size * scale;
 }

+/* Parse a string as a boolean, or return -1 after reporting the error.
+ */
+int
+nbdkit_parse_bool (const char *str)
+{
+  if (!strcmp (str, "1") ||
+      !strcasecmp (str, "true") ||
+      !strcasecmp (str, "t") ||
+      !strcasecmp (str, "yes") ||
+      !strcasecmp (str, "y") ||
+      !strcasecmp (str, "on"))
+    return 1;
+
+  if (!strcmp (str, "0") ||
+      !strcasecmp (str, "false") ||
+      !strcasecmp (str, "f") ||
+      !strcasecmp (str, "no") ||
+      !strcasecmp (str, "n") ||
+      !strcasecmp (str, "off"))
+    return 0;
+
+  nbdkit_error ("could not decipher boolean (%s)", str);
+  return -1;
+}
+
 /* Read a password from configuration value. */
 int
 nbdkit_read_password (const char *value, char **password)
-- 
2.17.2




More information about the Libguestfs mailing list