summaryrefslogtreecommitdiffhomepage
path: root/examples/sptr_to_maps.c
blob: 6b4dd35948879bff701b5e67339266c40eb8687f (plain)
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
// Create a stack and a list of shared pointers to maps,
// and demonstrate sharing and cloning of maps.
#define i_type Map
#define i_key_str // strings
#define i_val int
#define i_keydrop(p) (printf("drop name: %s\n", (p)->str), cstr_drop(p))
#include <stc/csmap.h>

#define i_type Arc // (atomic) ref. counted type
#define i_val Map
#define i_drop(p) (printf("drop Arc:\n"), Map_drop(p))
// no need for atomic ref. count in single thread:
// no compare function available for csmap:
#define i_opt c_no_atomic|c_no_cmp
#include <stc/csptr.h>

#define i_type Stack
#define i_val_ref Arc // define i_val_bind for csptr/cbox value (not i_val)
#include <stc/cstack.h>

#define i_type List
#define i_val_ref Arc // as above
#include <stc/clist.h>

int main()
{
    c_auto (Stack, stack)
    c_auto (List, list)
    {
        // POPULATE stack with shared pointers to Maps:
        Map *map;
        map = Stack_push(&stack, Arc_from(Map_init()))->get;
        c_apply(v, Map_emplace(map, c_pair(v)), Map_rawvalue, {
            {"Joey", 1990}, {"Mary", 1995}, {"Joanna", 1992}
        });
        map = Stack_push(&stack, Arc_from(Map_init()))->get;
        c_apply(v, Map_emplace(map, c_pair(v)), Map_rawvalue, {
            {"Rosanna", 2001}, {"Brad", 1999}, {"Jack", 1980}
        });

        // POPULATE list:
        map = List_push_back(&list, Arc_from(Map_init()))->get;
        c_apply(v, Map_emplace(map, c_pair(v)), Map_rawvalue, {
            {"Steve", 1979}, {"Rick", 1974}, {"Tracy", 2003}
        });
        
        // Share two Maps from the stack with the list using emplace (clone the csptr):
        List_push_back(&list, Arc_clone(stack.data[0]));
        List_push_back(&list, Arc_clone(stack.data[1]));
        
        // Clone (deep copy) a Map from the stack to the list
        // List will contain two shared and two unshared maps.
        map = List_push_back(&list, Arc_from(Map_clone(*stack.data[1].get)))->get;
        
        // Add one more element to the cloned map:
        Map_emplace_or_assign(map, "CLONED", 2021);

        // Add one more element to the shared map:
        Map_emplace_or_assign(stack.data[1].get, "SHARED", 2021);


        puts("STACKS");
        c_foreach (i, Stack, stack) {
            c_forpair (name, year, Map, *i.ref->get)
                printf(" %s:%d", _.name.str, _.year);
            puts("");
        }
        puts("LIST");
        c_foreach (i, List, list) {
            c_forpair (name, year, Map, *i.ref->get)
                printf(" %s:%d", _.name.str, _.year);
            puts("");
        }
    }
}