-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbarebones-combined.c
More file actions
100 lines (85 loc) · 2.31 KB
/
barebones-combined.c
File metadata and controls
100 lines (85 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* The `Show` typeclass allows types to be turned into their string representation */
typedef struct
{
char* (*const show)(void* self);
} ShowTC;
typedef struct
{
void* self;
ShowTC const* tc;
} Show;
/* The `Enum` typeclass allows types to be enumerable */
typedef struct
{
int (*const from_enum)(void* self);
} EnumTC;
typedef struct
{
void* self;
EnumTC const* tc;
} Enum;
/* Typeclass that asks for both `Show` and `Enum` implementation */
typedef struct
{
void* self;
ShowTC const* showtc;
EnumTC const* enumtc;
} ShowEnum;
void print_shen(ShowEnum shen)
{
char* const s = shen.showtc->show(shen.self);
int enm = shen.enumtc->from_enum(shen.self);
printf("%s : %d\n", s, enm);
free(s);
}
/* The `show` function implementation for `int` */
static char* int_show(int* x)
{
/*
Note: The `show` function of a `Show` typeclass is expected to return a malloc'ed value
The users of a generic `Show` are expected to `free` the returned pointer from the function `show`.
*/
size_t len = snprintf(NULL, 0, "%d", *x);
char* const res = malloc((len + 1) * sizeof(*res));
snprintf(res, len + 1, "%d", *x);
return res;
}
/* The wrapper function around `int_show` */
static inline char* int_show__(void* self)
{
return int_show(self);
}
/* Make function to build a generic `Show` out of a concrete type- `int` */
Show int_to_show_inst(int* x)
{
/* Build the vtable once and attach a pointer to it every time */
static ShowTC const tc = { .show = int_show__ };
return (Show){ .tc = &tc, .self = x };
}
/* The `from_enum` function implementation for `int` */
static int int_from_enum(int* x)
{
return *x;
}
/* The wrapper function around `int_from_enum` */
static inline int int_from_enum__(void* self)
{
return int_from_enum(self);
}
/* Make function to build a generic `Show` out of a concrete type- `int` */
Enum int_to_enum_inst(int* x)
{
/* Build the vtable once and attach a pointer to it every time */
static EnumTC const tc = { .from_enum = int_from_enum__ };
return (Enum){ .tc = &tc, .self = x };
}
int main(void)
{
int x = 42;
ShowEnum shen = { .self = &x, .showtc = int_to_show_inst(&x).tc, .enumtc = int_to_enum_inst(&x).tc };
print_shen(shen);
return 0;
}