aboutsummaryrefslogtreecommitdiffstats
path: root/util/draft/holder_vector.h
blob: 1c62055bd952ac47e8fdcf50644c261b6bf0cafa (plain) (blame)
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
#pragma once

#include <util/generic/ptr.h>
#include <util/generic/vector.h>
#include <util/generic/noncopyable.h>

template <class T, class D = TDelete>
class THolderVector: public TVector<T*>, public TNonCopyable {
    using TBase = TVector<T*>;

public:
    explicit THolderVector(size_t n = 0)
        : TBase(n)
    {
    }

    ~THolderVector() {
        Clear();
    }

    void Clear() {
        for (typename TBase::iterator it = TBase::begin(); it != TBase::end(); ++it) {
            if (*it)
                D::Destroy(*it);
        }
        TBase::clear();
    }

    size_t Size() const {
        return TBase::size();
    }

    // TVector takes ownership of T
    void PushBack(T* t) {
        try {
            TBase::push_back(t);
        } catch (...) {
            if (t)
                D::Destroy(t);
            throw;
        }
    }

    void PushBack(std::unique_ptr<T> t) {
        PushBack(t.release());
    }

    void PushBack(THolder<T> t) {
        PushBack(t.Release());
    }

    void Reset(size_t i, THolder<T> t) {
        T* current = (*this)[i];
        if (current) {
            Y_ASSERT(current != t.Get());
            D::Destroy(current);
        }
        (*this)[i] = t.Release();
    }

    void PopBack() {
        if (size()) {
            D::Destroy(back());
            TBase::pop_back();
        }
    }

    T* Release(size_t i) {
        T* t = (*this)[i];
        (*this)[i] = nullptr;
        return t;
    }

    void Resize(size_t newSize) {
        for (size_t i = newSize; i < size(); ++i) {
            D::Destroy((*this)[i]);
        }
        TBase::resize(newSize);
    }

    void Swap(THolderVector& other) {
        TBase::swap(other);
    }

    using TBase::operator[];
    using TBase::operator bool;
    using TBase::at;
    using TBase::back;
    using TBase::begin;
    using TBase::capacity;
    using TBase::empty;
    using TBase::end;
    using TBase::front;
    using TBase::reserve;
    using TBase::size;

    using typename TBase::const_iterator;
    using typename TBase::const_reverse_iterator;
    using typename TBase::iterator;
    using typename TBase::reverse_iterator;
    using typename TBase::value_type;
};