source: src/libcfa/containers/vector.c @ 5d28a19

ADTaaron-thesisarm-ehast-experimentalcleanup-dtorsctordeferred_resndemanglerenumforall-pointer-decayjacob/cs343-translationjenkins-sandboxmemorynew-astnew-ast-unique-exprnew-envno_listpersistent-indexerpthread-emulationqualifiedEnumresolv-newwith_gc
Last change on this file since 5d28a19 was 5d28a19, checked in by Thierry Delisle <tdelisle@…>, 8 years ago

libcfa now compiles generic vector class

  • Property mode set to 100644
File size: 1.7 KB
Line 
1#include <containers/vector> 
2
3#include <stdlib>
4
5//------------------------------------------------------------------------------
6//Initialization
7forall(otype T, otype allocator_t | allocator_c(T, allocator_t))
8void ctor(vector(T, allocator_t) *const this)
9{
10        ctor(&this->storage);
11        this->size = 0;
12}
13
14forall(otype T, otype allocator_t | allocator_c(T, allocator_t))
15void dtor(vector(T, allocator_t) *const this)
16{
17        clear(this);
18        dtor(&this->storage);
19}
20
21//------------------------------------------------------------------------------
22//Modifiers
23forall(otype T, otype allocator_t | allocator_c(T, allocator_t))
24void push_back(vector(T, allocator_t) *const this, T value)
25{
26        realloc(&this->storage, this->size+1);
27        data(&this->storage)[this->size] = value;
28        this->size++;
29}
30
31forall(otype T, otype allocator_t | allocator_c(T, allocator_t))
32void pop_back(vector(T, allocator_t) *const this)
33{
34        this->size--;
35        DESTROY(data(&this->storage)[this->size]);
36}
37
38forall(otype T, otype allocator_t | allocator_c(T, allocator_t))
39void clear(vector(T, allocator_t) *const this)
40{
41        for(size_t i = 0; i < this->size; i++)
42        {
43                DESTROY(data(&this->storage)[this->size]);
44        }
45        this->size = 0;
46}
47
48//------------------------------------------------------------------------------
49//Allocator
50forall(otype T)
51void ctor(heap_allocator(T) *const this)
52{
53        this->storage = 0;
54        this->capacity = 0;
55}
56
57forall(otype T)
58void dtor(heap_allocator(T) *const this)
59{
60        free(this->storage);
61}
62
63forall(otype T)
64inline void realloc(heap_allocator(T) *const this, size_t size)
65{
66        enum { GROWTH_RATE = 2 };
67        if(size > this->capacity)
68        {
69                this->capacity = GROWTH_RATE * size;
70                this->storage = (T*)realloc((void*)this->storage, this->capacity * sizeof(T));
71        }
72}
Note: See TracBrowser for help on using the repository browser.