Derive-C
Loading...
Searching...
No Matches
utils/option.c

Examples for using the optional type.

Examples for using the optional type.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct complex_data {
int x;
double y;
char* description;
};
void complex_data_delete(struct complex_data* self) { free(self->description); }
struct complex_data complex_data_clone(struct complex_data const* self) {
return (struct complex_data){
.x = self->x,
.y = self->y,
.description = strdup(self->description),
};
}
void complex_data_debug(struct complex_data const* self, dc_debug_fmt fmt, FILE* stream) {
fprintf(stream, "complex_data@%p {\n", self);
dc_debug_fmt_print(fmt, stream, "x: %d,\n", self->x);
dc_debug_fmt_print(fmt, stream, "y: %lf,\n", self->y);
dc_debug_fmt_print(fmt, stream, "description: %lf,\n", self->description);
}
#define ITEM struct complex_data
#define ITEM_DELETE complex_data_delete
#define ITEM_CLONE complex_data_clone
#define ITEM_DEBUG complex_data_debug
#define NAME complex_data_option
complex_data_option opt = complex_data_option_empty();
DC_ASSERT(!complex_data_option_is_present(&opt));
// when accessing a value, you get a pointer. Not present = NULL
DC_ASSERT(!complex_data_option_get(&opt));
DC_ASSERT(!complex_data_option_get_const(&opt));
complex_data_option_debug(&opt, dc_debug_fmt_new(), stdout);
bool was_present_1 = complex_data_option_replace(
&opt, (struct complex_data){.x = 42, .y = 3.14, .description = strdup("A complex data")});
DC_ASSERT(!was_present_1);
DC_ASSERT(complex_data_option_is_present(&opt));
DC_ASSERT(complex_data_option_get(&opt));
complex_data_option_debug(&opt, dc_debug_fmt_new(), stdout);
bool was_present_2 = complex_data_option_replace(
&opt,
(struct complex_data){.x = 100, .y = 2.71, .description = strdup("Another complex data")});
DC_ASSERT(was_present_2);
complex_data_option_delete(&opt);
}
int main() { option_example(); }
static void free(SELF *self, void *ptr)
Definition template.h:56
dc_debug_fmt dc_debug_fmt_scope_end(dc_debug_fmt fmt)
Definition fmt.h:39
dc_debug_fmt dc_debug_fmt_scope_begin(dc_debug_fmt fmt)
Definition fmt.h:33
static void dc_debug_fmt_print(dc_debug_fmt fmt, FILE *stream, const char *format,...)
Definition fmt.h:22
static dc_debug_fmt dc_debug_fmt_new()
Definition fmt.h:14
void complex_data_debug(struct complex_data const *self, dc_debug_fmt fmt, FILE *stream)
Definition option.c:24
void complex_data_delete(struct complex_data *self)
Definition option.c:16
struct complex_data complex_data_clone(struct complex_data const *self)
Definition option.c:17
void option_example()
Definition option.c:41
#define DC_ASSERT(expr,...)
Definition panic.h:36
int main()
Definition staticbump.c:45
double y
Definition option.c:12
char * description
Definition option.c:13
Debug format helpers for debug printin data structures.
Definition fmt.h:10
static FILE * stream(SELF *self)
Opens a file for.
Definition template.h:107