aboutsummaryrefslogtreecommitdiffstats
path: root/vespalib/src/vespa/vespalib/metrics/point_map_collection.cpp
blob: d9b7362521b529a55c148042d9e2a752c3aca5dd (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "point_map_collection.h"
#include <assert.h>

namespace vespalib {
namespace metrics {

HashedPointMap::HashedPointMap(PointMap &&from)
    : _map(std::move(from)),
      _hash(0)
{
    for (const PointMap::value_type &entry : _map) {
        _hash = (_hash << 7) + (_hash >> 31) + entry.first.id();
        _hash = (_hash << 7) + (_hash >> 31) + entry.second.id();
    }
}

bool
HashedPointMap::operator< (const HashedPointMap &other) const
{
    // cheap comparison first
    if (_hash != other._hash) {
        return _hash < other._hash;
    }
    if (_map.size() != other._map.size()) {
        return _map.size() < other._map.size();
    }
    // sizes equal, fall back to std::map::operator<
    return _map < other._map; 
}

using Guard = std::lock_guard<std::mutex>;

const PointMap &
PointMapCollection::lookup(size_t id) const
{
    Guard guard(_lock);
    assert(id < _vec.size());
    PointMapMap::const_iterator iter = _vec[id];
    return iter->first.backingMap();
}

size_t
PointMapCollection::resolve(PointMap map)
{
    Guard guard(_lock);
    size_t nextId = _vec.size();
    auto iter_check = _map.emplace(std::move(map), nextId);
    if (iter_check.second) {
        _vec.push_back(iter_check.first);
    }
    return iter_check.first->second;
}

size_t
PointMapCollection::size() const
{
    Guard guard(_lock);
    return _vec.size();
}

} // namespace vespalib::metrics
} // namespace vespalib