aboutsummaryrefslogtreecommitdiff
path: root/reference_set.cc
blob: 963e814103fd785a87614da304a8c4a3821b6230 (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
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/zucchini/reference_set.h"

#include <algorithm>
#include <iterator>

#include "base/logging.h"
#include "base/macros.h"
#include "components/zucchini/target_pool.h"

namespace zucchini {

namespace {

// Returns true if |refs| is sorted by location.
bool IsReferenceListSorted(const std::vector<IndirectReference>& refs) {
  return std::is_sorted(
      refs.begin(), refs.end(),
      [](const IndirectReference& a, const IndirectReference& b) {
        return a.location < b.location;
      });
}

}  // namespace

ReferenceSet::ReferenceSet(const ReferenceTypeTraits& traits,
                           const TargetPool& target_pool)
    : traits_(traits), target_pool_(target_pool) {}
ReferenceSet::ReferenceSet(ReferenceSet&&) = default;
ReferenceSet::~ReferenceSet() = default;

void ReferenceSet::InitReferences(ReferenceReader&& ref_reader) {
  DCHECK(references_.empty());
  for (auto ref = ref_reader.GetNext(); ref.has_value();
       ref = ref_reader.GetNext()) {
    references_.push_back(
        {ref->location, target_pool_.KeyForOffset(ref->target)});
  }
  DCHECK(IsReferenceListSorted(references_));
}

void ReferenceSet::InitReferences(const std::vector<Reference>& refs) {
  DCHECK(references_.empty());
  references_.reserve(refs.size());
  std::transform(refs.begin(), refs.end(), std::back_inserter(references_),
                 [&](const Reference& ref) -> IndirectReference {
                   return {ref.location, target_pool_.KeyForOffset(ref.target)};
                 });
  DCHECK(IsReferenceListSorted(references_));
}

IndirectReference ReferenceSet::at(offset_t offset) const {
  auto pos =
      std::upper_bound(references_.begin(), references_.end(), offset,
                       [](offset_t offset, const IndirectReference& ref) {
                         return offset < ref.location;
                       });

  DCHECK(pos != references_.begin());  // Iterators.
  --pos;
  DCHECK_LT(offset, pos->location + width());
  return *pos;
}

}  // namespace zucchini