summaryrefslogtreecommitdiff
path: root/src/utils.hh
blob: 6bfdb907da68ffeef4f558cc478df74c536b4a19 (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
#ifndef utils_hh_INCLUDED
#define utils_hh_INCLUDED

#include "exception.hh"
#include "assert.hh"

#include <memory>
#include <algorithm>

namespace Kakoune
{

template<typename Container>
struct ReversedContainer
{
    ReversedContainer(Container& container) : container(container) {}
    Container& container;

    decltype(container.rbegin()) begin() { return container.rbegin(); }
    decltype(container.rend())   end()   { return container.rend(); }
};

template<typename Container>
ReversedContainer<Container> reversed(Container& container)
{
    return ReversedContainer<Container>(container);
}

template<typename T>
bool operator== (const std::unique_ptr<T>& lhs, T* rhs)
{
    return lhs.get() == rhs;
}

template<typename T, typename F>
class AutoRaii
{
public:
    AutoRaii(T* resource, F cleanup)
        : m_resource(resource), m_cleanup(cleanup) {}

    AutoRaii(AutoRaii&& other) : m_resource(other.m_resource),
                                 m_cleanup(other.m_cleanup)
    { other.m_resource = nullptr; }

    AutoRaii(const AutoRaii&) = delete;
    AutoRaii& operator=(const AutoRaii&) = delete;

    ~AutoRaii() { if (m_resource) m_cleanup(m_resource); }

    operator T*() { return m_resource; }

private:
    T* m_resource;
    F  m_cleanup;
};

template<typename T, typename F>
AutoRaii<T, F> auto_raii(T* resource, F cleanup)
{
    return AutoRaii<T, F>(resource, cleanup);
}

template<typename T>
class Singleton
{
public:
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

    static T& instance()
    {
        assert (ms_instance);
        return *ms_instance;
    }

    static void delete_instance()
    {
        if (ms_instance)
            delete ms_instance;
    }

protected:
    Singleton()
    {
        assert(not ms_instance);
        ms_instance = static_cast<T*>(this);
    }

    ~Singleton()
    {
        assert(ms_instance == this);
        ms_instance = nullptr;
    }

private:
    static T* ms_instance;
};

template<typename T>
T* Singleton<T>::ms_instance = nullptr;

template<typename Container, typename T>
bool contains(const Container& container, const T& value)
{
    return std::find(container.begin(), container.end(), value)
           != container.end();
}

}

#endif // utils_hh_INCLUDED