summaryrefslogtreecommitdiff
path: root/src/vec.cpp
blob: ad6b17258f96e28839d86c1b11bcbdba74e5960a (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
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
101
102
103
104
105
106
107
108
109
110
111
112
113
/* SPDX-License-Identifier: Unlicense
 */

#include "vec.h"

#include <cassert>
#include <cstdlib>

template <typename T>
void Vec<T>::expand(Vec<T>::size_type by)
{
    if (_size + by <= _capacity) {
        return;
    }
    const size_type new_capacity = (_size + by) * 1.5f;
    T *d{static_cast<T *>(calloc(new_capacity, sizeof (T)))};
    assert(d);
    if (_d) {
        for (size_type i = 0; i < _size; i++) {
            d[i] = static_cast<T &&>(_d[i]);
        }
        free(_d);
    }
    _d = d;
    _capacity = new_capacity;
}

template <typename T>
Vec<T>::Vec(const Vec& other)
    : _size(other._size)
    , _capacity(other._size)
    , _d(static_cast<T *>(calloc(_capacity, sizeof (T))))
{
    assert(_d);
    for (size_type i = 0; i < _size; i++) {
        _d[i] = other._d[i];
    }
}

template <typename T>
Vec<T>::Vec(const T *data, size_type nmemb)
    : _size(nmemb)
    , _capacity(nmemb)
    , _d(static_cast<T *>(calloc(_capacity, sizeof (T))))
{
    assert(_d);
    for (size_type i = 0; i < _size; i++) {
        _d[i] = static_cast<const T *>(data)[i];
    }
}

template <typename T>
Vec<T>::Vec(const void *data, size_type size)
    : _size(size / sizeof (T))
    , _capacity(size / sizeof (T))
    , _d(static_cast<T *>(calloc(_capacity, sizeof (T))))
{
    assert(_d);
    for (size_type i = 0; i < _size; i++) {
        _d[i] = static_cast<const T *>(data)[i];
    }
}

template <typename T>
Vec<T>::~Vec()
{
    if (_d == nullptr) {
        return;
    }
    for (size_type i = 0; i < _size; i++) {
        _d[i].~T();
    }
    free(_d);
    _d = nullptr;
    _capacity = _size = 0;
}

template <typename T>
Vec<T> &Vec<T>::operator=(const Vec &other)
{
    this->~Vec();
    _size = _capacity = 0;
    _d = nullptr;
    expand(other._size);
    for (size_type i = 0; i < other._size; i++) {
        _d[i] = other._d[i];
    }
    _size = other._size;
    return *this;
}

template <typename T>
bool Vec<T>::operator==(const Vec& other) const
{
    if (_size != other._size) {
        return false;
    }
    for (size_type i = 0; i < _size; i++) {
        if (_d[i] != other._d[i]) {
            return false;
        }
    }
    return true;
}

template class Vec<char>; // Used in vecutil.cpp
template class Vec<int>; // Used in vec_tests.cpp
template class Vec<Vec<int>>; // Used in vec_tests.cpp

#include "tracetab.h"

template class Vec<DataType>; // Used in tracetab.cpp
template class Vec<TraceNode>; // Used in tracetab.cpp