aboutsummaryrefslogtreecommitdiff
path: root/optional.h
diff options
context:
space:
mode:
authorYaroslav de la Peña Smirnov <yps@yaroslavps.com>2023-05-30 03:25:37 +0300
committerYaroslav de la Peña Smirnov <yps@yaroslavps.com>2023-05-30 03:25:37 +0300
commitddd540203ed935fc387400f98ce1987f6aeeda7b (patch)
treed9047ef7f3432132be1ae833adb3e8471792646e /optional.h
downloadc-optional-ddd540203ed935fc387400f98ce1987f6aeeda7b.tar.gz
c-optional-ddd540203ed935fc387400f98ce1987f6aeeda7b.zip
init
Diffstat (limited to 'optional.h')
-rw-r--r--optional.h29
1 files changed, 29 insertions, 0 deletions
diff --git a/optional.h b/optional.h
new file mode 100644
index 0000000..ca1f732
--- /dev/null
+++ b/optional.h
@@ -0,0 +1,29 @@
+/**
+ * optional.h - some macros for optional types
+ *
+ * 2023 Yaroslav de la Peña Smirnov
+ *
+ */
+#ifndef OPTIONAL_H
+#define OPTIONAL_H
+
+#include <stdbool.h>
+
+#define OPTIONAL(T, name) struct { bool has; T data; } name
+
+#define OPTNONE { .has = false }
+#define OPTSOME(d) { .has = true, .data = d }
+
+#define optional_set_none(opt) opt.has = false
+
+#define optional_set_some(opt, d) \
+ (opt.has = true, opt.data = d)
+
+#define optional_has(opt) (opt.has)
+
+#define optional_hasnt(opt) (!opt.has)
+
+#define optional_unwrap(src, dst) \
+ (optional_has(src) ? (dst = src.data, true) : (false))
+
+#endif