summaryrefslogtreecommitdiff
path: root/src/idvaluemap.hh
blob: e11c327ae2fe9db5b22c35b013f5900cef9bfe61 (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
#ifndef idvaluemap_hh_INCLUDED
#define idvaluemap_hh_INCLUDED

#include <vector>
#include "completion.hh"

namespace Kakoune
{

template<typename _Id, typename _Value>
class idvaluemap
{
public:
    typedef std::pair<_Id, _Value> value_type;
    typedef std::vector<value_type> container_type;
    typedef typename container_type::iterator iterator;
    typedef typename container_type::const_iterator const_iterator;

    void append(const value_type& value)
    {
        m_content.push_back(value);
    }

    void append(value_type&& value)
    {
        m_content.push_back(std::forward<value_type>(value));
    }

    iterator find(const _Id& id)
    {
        for (auto it = begin(); it != end(); ++it)
        {
            if (it->first == id)
                return it;
        }
        return end();
    }

    const_iterator find(const _Id& id) const
    {
        for (auto it = begin(); it != end(); ++it)
        {
            if (it->first == id)
                return it;
        }
        return end();
    }

    bool contains(const _Id& id) const
    {
        return find(id) != end();
    }

    void remove(const _Id& id)
    {
        for (auto it = m_content.begin(); it != m_content.end(); ++it)
        {
            if (it->first == id)
            {
                m_content.erase(it);
                return;
            }
        }
    }

    template<typename _Condition>
    CandidateList complete_id_if(const String& prefix,
                                 ByteCount cursor_pos,
                                 _Condition condition)
    {
        String real_prefix = prefix.substr(0, cursor_pos);
        CandidateList result;
        for (auto& value : m_content)
        {
            if (not condition(value))
                continue;

            String id_str = value.first;
            if (id_str.substr(0, real_prefix.length()) == real_prefix)
                result.push_back(std::move(id_str));
        }
        return result;
    }

    CandidateList complete_id(const String& prefix,
                              ByteCount cursor_pos)
    {
        return complete_id_if(
            prefix, cursor_pos, [](const value_type&) { return true; });
    }

    iterator       begin()       { return m_content.begin(); }
    iterator       end()         { return m_content.end(); }
    const_iterator begin() const { return m_content.begin(); }
    const_iterator end()   const { return m_content.end(); }

private:
    container_type m_content;
};

}

#endif // idvaluemap_hh_INCLUDED