aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/containers/comptrie/array_with_size.h
blob: 148200fe6aeceb97e8533a1c4abb5d9b1f522400 (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
#pragma once

#include <util/generic/ptr.h>
#include <util/generic/noncopyable.h>
#include <util/generic/utility.h>
#include <util/system/sys_alloc.h> 

template <typename T>
class TArrayWithSizeHolder : TNonCopyable { 
    typedef TArrayWithSizeHolder<T> TThis;

    T* Data;

public:
    TArrayWithSizeHolder() 
        : Data(nullptr) 
    { 
    } 

    ~TArrayWithSizeHolder() {
        if (!Data)
            return;
        for (size_t i = 0; i < Size(); ++i) {
            try {
                Data[i].~T();
            } catch (...) {
            }
        }
        y_deallocate(((size_t*)Data) - 1); 
    }

    void Swap(TThis& copy) {
        DoSwap(Data, copy.Data);
    }

    void Resize(size_t newSize) {
        if (newSize == Size())
            return;
        TThis copy;
        copy.Data = (T*)(((size_t*)y_allocate(sizeof(size_t) + sizeof(T) * newSize)) + 1); 
        // does not handle constructor exceptions properly
        for (size_t i = 0; i < Min(Size(), newSize); ++i) {
            new (copy.Data + i) T(Data[i]);
        }
        for (size_t i = Min(Size(), newSize); i < newSize; ++i) {
            new (copy.Data + i) T;
        }
        ((size_t*)copy.Data)[-1] = newSize; 
        Swap(copy);
    }

    size_t Size() const {
        return Data ? ((size_t*)Data)[-1] : 0; 
    }

    bool Empty() const {
        return Size() == 0;
    }

    T* Get() {
        return Data;
    }

    const T* Get() const {
        return Data;
    }
};