From 06ce0eb13aef499b11f5d8ba5fdacaeccb6d8919 Mon Sep 17 00:00:00 2001 From: veclavtalica Date: Tue, 30 Jul 2024 15:22:07 +0300 Subject: [PATCH] option macros --- src/macros/concatenate.h | 8 +++++ src/macros/option.h | 65 ++++++++++++++++++++++++++++++++++++++++ src/macros/varargcount.h | 9 ++++++ 3 files changed, 82 insertions(+) create mode 100644 src/macros/concatenate.h create mode 100644 src/macros/option.h create mode 100644 src/macros/varargcount.h diff --git a/src/macros/concatenate.h b/src/macros/concatenate.h new file mode 100644 index 0000000..4c0040e --- /dev/null +++ b/src/macros/concatenate.h @@ -0,0 +1,8 @@ +#ifndef CONCATENATE_H +#define CONCATENATE_H + +#define m_concatenate(p_a, p_b) m_concatenate_(p_a, p_b) +#define m_concatenate_(p_a, p_b) m_concatenate__(p_a, p_b) +#define m_concatenate__(p_a, p_b) p_a##p_b + +#endif diff --git a/src/macros/option.h b/src/macros/option.h new file mode 100644 index 0000000..60238fe --- /dev/null +++ b/src/macros/option.h @@ -0,0 +1,65 @@ +#ifndef OPTION_H +#define OPTION_H + +#include "concatenate.h" +#include "varargcount.h" + +#include + +/* usage example: + * + * struct result { + * float f; + * m_option_list( + * int, v + * ) + * } + * + * struct result = { + * m_set(f, 1.0), -- non options could be set with this + * m_opt(v, 5), -- options are supposed to be initialized like that + * } + * + */ + +#define m_set(p_member, p_value) .p_member = (p_value) + +#define m_opt(p_member, p_value) .p_member##_opt = (p_value), .p_member##_opt_set = 1 + +#define m_is_set(p_value, p_member) ((p_value).p_member##_opt_set) + +/* warn: beware of double evaluation! */ +#define m_or(p_value, p_member, p_default) ((p_value).p_member##_opt_set ? (p_value).p_member##_opt : (p_default)) + +#define m_option_list_2(t0, m0) \ + t0 m0##_opt; \ + bool m0##_opt_set : 1; \ + +#define m_option_list_4(t0, m0, t1, m1) \ + t0 m0##_opt; \ + t1 m1##_opt; \ + bool m0##_opt_set : 1; \ + bool m1##_opt_set : 1; \ + +#define m_option_list_6(t0, m0, t1, m1, t2, m2) \ + t0 m0##_opt; \ + t1 m1##_opt; \ + t2 m1##_opt; \ + bool m0##_opt_set : 1; \ + bool m1##_opt_set : 1; \ + bool m2##_opt_set : 1; \ + +#define m_option_list_8(t0, m0, t1, m1, t2, m2, t3, m3) \ + t0 m0##_opt; \ + t1 m1##_opt; \ + t2 m2##_opt; \ + t3 m3##_opt; \ + bool m0##_opt_set : 1; \ + bool m1##_opt_set : 1; \ + bool m2##_opt_set : 1; \ + bool m3##_opt_set : 1; \ + +#define m_option_list_(p_n, ...) m_concatenate(m_option_list_, p_n)(__VA_ARGS__) +#define m_option_list(...) m_option_list_(m_narg(__VA_ARGS__), __VA_ARGS__) + +#endif diff --git a/src/macros/varargcount.h b/src/macros/varargcount.h new file mode 100644 index 0000000..cf0364a --- /dev/null +++ b/src/macros/varargcount.h @@ -0,0 +1,9 @@ +#ifndef VARARGCOUNT_H +#define VARARGCOUNT_H + +#define m_narg(...) m_narg_(__VA_ARGS__, m_rseq_n_()) +#define m_narg_(...) m_arg_n_(__VA_ARGS__) +#define m_arg_n_(_1, _2, _3, _4, _5, _6, _7, _8, N, ...) N +#define m_rseq_n_() 8, 7, 6, 5, 4, 3, 2, 1, 0 + +#endif