OPTION macro revamped with IF_LET_SOME

This commit is contained in:
Joseph Ferano 2024-01-15 08:07:17 +07:00
parent 9f7e371a49
commit 7f094799e9
2 changed files with 34 additions and 8 deletions

View File

@ -9,7 +9,7 @@ bin_files = $(patsubst %.asm,%.bin,$(asm_files))
all: decode asm_files
decode: decode.c
decode: decode.c lib.h
$(CC) $(CFLAGS) $< -o $@
asm_files: $(bin_files)

40
lib.h
View File

@ -15,12 +15,38 @@ typedef char sbyte;
typedef ptrdiff_t size;
typedef size_t usize;
#define OPTION(type, typeName) \
struct { \
enum {NONE, SOME} tag; \
union { \
u8 none; \
type typeName; \
} some; \
enum OptionTag {NONE, SOME};
#define OPTION(type) \
typedef struct \
{ \
enum OptionTag tag; \
union { \
char none; \
type some; \
}; \
} type##_opt; \
\
static inline type##_opt none_##type(void) \
{ \
return (type##_opt){ .tag = NONE, .none = 0 }; \
} \
\
static inline type##_opt some_##type(type value) \
{ \
return (type##_opt){ .tag = SOME, .some = value }; \
} \
\
static inline int get_some_##type(type##_opt opt, type* out_value) \
{ \
if (opt.tag != SOME) return 0; \
*out_value = opt.some; \
return 1; \
}
#define IF_LET_SOME(type, var, opt) \
type var; \
if (get_some_##type(opt, &var))
OPTION(u8)