| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
#ifndef AAPT_UTIL_IMMUTABLEMAP_H |
| 18 |
#define AAPT_UTIL_IMMUTABLEMAP_H |
| 19 |
|
| 20 |
#include <utility> |
| 21 |
#include <vector> |
| 22 |
|
| 23 |
#include "util/TypeTraits.h" |
| 24 |
|
| 25 |
namespace aapt { |
| 26 |
|
| 27 |
template <typename TKey, typename TValue> |
| 28 |
class ImmutableMap { |
| 29 |
static_assert(is_comparable<TKey, TKey>::value, "key is not comparable"); |
| 30 |
|
| 31 |
public: |
| 32 |
using const_iterator = |
| 33 |
typename std::vector<std::pair<TKey, TValue>>::const_iterator; |
| 34 |
|
| 35 |
ImmutableMap(ImmutableMap&&) noexcept = default; |
| 36 |
ImmutableMap& operator=(ImmutableMap&&) noexcept = default; |
| 37 |
|
| 38 |
static ImmutableMap<TKey, TValue> CreatePreSorted( |
| 39 |
std::initializer_list<std::pair<TKey, TValue>> list) { |
| 40 |
return ImmutableMap( |
| 41 |
std::vector<std::pair<TKey, TValue>>(list.begin(), list.end())); |
| 42 |
} |
| 43 |
|
| 44 |
static ImmutableMap<TKey, TValue> CreateAndSort( |
| 45 |
std::initializer_list<std::pair<TKey, TValue>> list) { |
| 46 |
std::vector<std::pair<TKey, TValue>> data(list.begin(), list.end()); |
| 47 |
std::sort(data.begin(), data.end()); |
| 48 |
return ImmutableMap(std::move(data)); |
| 49 |
} |
| 50 |
|
| 51 |
template <typename TKey2, typename = typename std::enable_if< |
| 52 |
is_comparable<TKey, TKey2>::value>::type> |
| 53 |
const_iterator find(const TKey2& key) const { |
| 54 |
auto cmp = [](const std::pair<TKey, TValue>& candidate, |
| 55 |
const TKey2& target) -> bool { |
| 56 |
return candidate.first < target; |
| 57 |
}; |
| 58 |
|
| 59 |
const_iterator end_iter = end(); |
| 60 |
auto iter = std::lower_bound(data_.begin(), end_iter, key, cmp); |
| 61 |
if (iter == end_iter || iter->first == key) { |
| 62 |
return iter; |
| 63 |
} |
| 64 |
return end_iter; |
| 65 |
} |
| 66 |
|
| 67 |
const_iterator begin() const { return data_.begin(); } |
| 68 |
|
| 69 |
const_iterator end() const { return data_.end(); } |
| 70 |
|
| 71 |
private: |
| 72 |
DISALLOW_COPY_AND_ASSIGN(ImmutableMap); |
| 73 |
|
| 74 |
explicit ImmutableMap(std::vector<std::pair<TKey, TValue>> data) |
| 75 |
: data_(std::move(data)) {} |
| 76 |
|
| 77 |
std::vector<std::pair<TKey, TValue>> data_; |
| 78 |
}; |
| 79 |
|
| 80 |
} |
| 81 |
|
| 82 |
#endif |