1 // Copyright 2017 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "components/zucchini/reference_set.h"
6
7 #include <algorithm>
8 #include <iterator>
9
10 #include "base/check_op.h"
11 #include "components/zucchini/target_pool.h"
12
13 namespace zucchini {
14
15 namespace {
16
17 // Returns true if |refs| is sorted by location.
IsReferenceListSorted(const std::vector<Reference> & refs)18 bool IsReferenceListSorted(const std::vector<Reference>& refs) {
19 return std::is_sorted(refs.begin(), refs.end(),
20 [](const Reference& a, const Reference& b) {
21 return a.location < b.location;
22 });
23 }
24
25 } // namespace
26
ReferenceSet(const ReferenceTypeTraits & traits,const TargetPool & target_pool)27 ReferenceSet::ReferenceSet(const ReferenceTypeTraits& traits,
28 const TargetPool& target_pool)
29 : traits_(traits), target_pool_(target_pool) {}
30 ReferenceSet::ReferenceSet(ReferenceSet&&) = default;
31 ReferenceSet::~ReferenceSet() = default;
32
InitReferences(ReferenceReader && ref_reader)33 void ReferenceSet::InitReferences(ReferenceReader&& ref_reader) {
34 DCHECK(references_.empty());
35 for (auto ref = ref_reader.GetNext(); ref.has_value();
36 ref = ref_reader.GetNext()) {
37 references_.push_back(*ref);
38 }
39 DCHECK(IsReferenceListSorted(references_));
40 }
41
InitReferences(const std::vector<Reference> & refs)42 void ReferenceSet::InitReferences(const std::vector<Reference>& refs) {
43 DCHECK(references_.empty());
44 DCHECK(IsReferenceListSorted(references_));
45 references_.assign(refs.begin(), refs.end());
46 }
47
at(offset_t offset) const48 Reference ReferenceSet::at(offset_t offset) const {
49 auto pos = std::upper_bound(references_.begin(), references_.end(), offset,
50 [](offset_t offset, const Reference& ref) {
51 return offset < ref.location;
52 });
53
54 DCHECK(pos != references_.begin()); // Iterators.
55 --pos;
56 DCHECK_LT(offset, pos->location + width());
57 return *pos;
58 }
59
60 } // namespace zucchini
61