aboutsummaryrefslogtreecommitdiff
path: root/optional.h
diff options
context:
space:
mode:
authorYaroslav de la Peña Smirnov <yps@yaroslavps.com>2023-05-30 04:31:14 +0300
committerYaroslav de la Peña Smirnov <yps@yaroslavps.com>2023-05-30 04:31:14 +0300
commitaf454b14b38175033be41220b5894e7fe975bd05 (patch)
tree8d28f455b99557b747256ef1114c3927d2104017 /optional.h
parentddd540203ed935fc387400f98ce1987f6aeeda7b (diff)
downloadc-optional-af454b14b38175033be41220b5894e7fe975bd05.tar.gz
c-optional-af454b14b38175033be41220b5894e7fe975bd05.zip
Comments and small syntax change
Diffstat (limited to 'optional.h')
-rw-r--r--optional.h56
1 files changed, 50 insertions, 6 deletions
diff --git a/optional.h b/optional.h
index ca1f732..c020abf 100644
--- a/optional.h
+++ b/optional.h
@@ -9,21 +9,65 @@
#include <stdbool.h>
+/**
+ * OPTIONAL - declare an object that optionally holds type @T
+ * @T: the type of data to hold.
+ * @name: the name of the variable or struct field.
+ */
#define OPTIONAL(T, name) struct { bool has; T data; } name
+/**
+ * OPTNONE - initialize an OPTIONAL object to hold nothing.
+ */
#define OPTNONE { .has = false }
+
+/**
+ * OPTSOME - initialize an OPTIONAL object to hold something.
+ * @d: data to hold.
+ */
#define OPTSOME(d) { .has = true, .data = d }
-#define optional_set_none(opt) opt.has = false
+/**
+ * opt_set_none - set an OPTIONAL object to hold nothing.
+ * @opt: OPTIONAL object.
+ */
+#define opt_set_none(opt) opt.has = false
-#define optional_set_some(opt, d) \
+/**
+ * opt_set_some - set an OPTIONAL object to hold something.
+ * @opt: OPTIONAL object.
+ * @d: data to hold.
+ */
+#define opt_set_some(opt, d) \
(opt.has = true, opt.data = d)
-#define optional_has(opt) (opt.has)
+/**
+ * opt_has - true if an OPTIONAL object has something.
+ * @opt: OPTIONAL object.
+ */
+#define opt_has(opt) (opt.has)
+
+/**
+ * opt_hasnt - true if an OPTIONAL object has nothing.
+ * @opt: OPTIONAL object.
+ */
+#define opt_hasnt(opt) (!opt.has)
-#define optional_hasnt(opt) (!opt.has)
+/**
+ * opt_unwrap - if there's something in @src, copy it to @dst.
+ * @src: OPTIONAL object to copy data of type T from.
+ * @dst: variable of type T to copy to.
+ *
+ * Returns true if there was something, false if there wasn't.
+ */
+#define opt_unwrap(src, dst) \
+ (opt_has(src) ? (dst = src.data, true) : (false))
-#define optional_unwrap(src, dst) \
- (optional_has(src) ? (dst = src.data, true) : (false))
+/**
+ * opt_default - get something from @src or default to @def.
+ * @src: OPTIONAL object to get data from.
+ * @def: default value if there's nothing.
+ */
+#define opt_default(src, def) opt_has(src) ? src.data : def
#endif