-
Notifications
You must be signed in to change notification settings - Fork 14
/
marker.c
48 lines (35 loc) · 1.08 KB
/
marker.c
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
// This examples demonstrates marker interfaces.
#include <interface99.h>
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
// A marker interface whose implementers can be duplicated by simply copying bits.
#define Copy_IFACE
interface(Copy);
typedef struct {
unsigned health, victories, defeats;
} PlayerStats;
impl(Copy, PlayerStats);
// This is not `Copy`able because of `.name`.
typedef struct {
const char *name;
int id;
PlayerStats stats;
} Player;
void test(Copy src, Copy dst, size_t size) {
memcpy(src.self, dst.self, size);
}
int main(void) {
const PlayerStats stats1 = {.health = 100, .victories = 5, .defeats = 2};
PlayerStats stats2;
test(DYN(PlayerStats, Copy, &stats1), DYN(PlayerStats, Copy, &stats2), sizeof(PlayerStats));
assert(memcmp(&stats1, &stats2, sizeof(PlayerStats)) == 0);
const Player p1 = {.name = "John", .id = 123, .stats = stats1};
Player p2;
// COMPILE-TIME ERROR:
// test(DYN(Player, Copy, &p1), DYN(Player, Copy, &p2), sizeof(Player));
(void)p1;
(void)p2;
return 0;
}