summaryrefslogtreecommitdiffhomepage
path: root/examples/sptr_music.c
blob: fcb7a43f2da127774e03ccae89c32727a9172137 (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
// shared_ptr-examples.cpp
// based on https://docs.microsoft.com/en-us/cpp/cpp/how-to-create-and-use-shared-ptr-instances?view=msvc-160

#include <stc/cstr.h>

struct Song
{
    cstr artist;
    cstr title;
} typedef Song;

Song Song_from(const char* artist, const char* title)
    { return (Song){cstr_from(artist), cstr_from(title)}; }

void Song_del(Song* s) {
    printf("del: %s\n", s->title.str);
    c_del(cstr, &s->artist, &s->title);
}

#define i_val Song
#define i_del Song_del
#define i_tag song
#include <stc/csptr.h> // define csptr_song

#define i_val_ref csptr_song
#define i_tag song
#include <stc/cvec.h>

void example3()
{
    c_auto (cvec_song, v, v2)
    {
        c_apply(cvec_song, push_back, &v, {
            csptr_song_new(Song_from("Bob Dylan", "The Times They Are A Changing")),
            csptr_song_new(Song_from("Aretha Franklin", "Bridge Over Troubled Water")),
            csptr_song_new(Song_from("Thalia", "Entre El Mar y Una Estrella"))
        });

        c_foreach (s, cvec_song, v)
            if (!cstr_equals(s.ref->get->artist, "Bob Dylan"))
                cvec_song_emplace_back(&v2, *s.ref); // note: calls csptr_song_clone()

        c_apply(cvec_song, push_back, &v2, {
            csptr_song_new(Song_from("Michael Jackson", "Billie Jean")),
            csptr_song_new(Song_from("Rihanna", "Stay")),
        });

        c_foreach (s, cvec_song, v2)
            printf("%s - %s: refs %lu\n", s.ref->get->artist.str, s.ref->get->title.str,
                                         *s.ref->use_count);
    }
}

int main()
{
    example3();
}