Bash++
Bash++ compiler internal documentation
IntervalTree.h
Go to the documentation of this file.
1
7#pragma once
8
9#include <memory>
10#include <vector>
11#include <cstdint>
12#include <cassert>
13#include <algorithm>
14
38template <class T>
40private:
41 struct Interval {
42 uint64_t low, high;
44
45 bool contains(uint64_t point) const { return low <= point && point <= high; }
46 bool contains(const Interval& other) const { return low <= other.low && high >= other.high; }
47 };
48
49 std::vector<Interval> intervals;
50 bool sorted = false;
51
53 if (!sorted) {
54 // Sort by low, then by high (descending) so wider intervals come first
55 std::sort(intervals.begin(), intervals.end(),
56 [](const Interval& a, const Interval& b) {
57 return a.low < b.low || (a.low == b.low && a.high > b.high);
58 });
59 sorted = true;
60 }
61 }
62
63public:
64 void insert(uint64_t low, uint64_t high, T payload) {
65 // TODO(@rail5): Assertions to ensure that our invariants are maintained
66 intervals.push_back({low, high, payload});
67 sorted = false;
68 }
69
79 T find_innermost_overlap(uint64_t point) {
81
82 // Binary search for first interval with low <= point
83 auto it = std::upper_bound(intervals.begin(), intervals.end(), point,
84 [](uint64_t point, const Interval& interval) {
85 return point < interval.low;
86 });
87
88 if (it == intervals.begin()) return T();
89
90 // Scan backwards to find innermost (since sorted by low then wide-first)
91 --it;
92 const Interval* best = nullptr;
93 for (; it >= intervals.begin() && it->low <= point; --it) {
94 if (it->contains(point)) {
95 if (!best || it->low > best->low) {
96 best = &*it;
97 }
98 }
99
100 if (it == intervals.begin()) break; // Prevent underflow/UB
101 }
102 return best ? best->payload : T();
103 }
104};
A specialized implementation of an Interval Tree optimized for Bash++'s particular use case.
Definition IntervalTree.h:39
void ensure_sorted()
Definition IntervalTree.h:52
void insert(uint64_t low, uint64_t high, T payload)
Definition IntervalTree.h:64
bool sorted
Definition IntervalTree.h:50
T find_innermost_overlap(uint64_t point)
Find the innermost interval that overlaps a given point.
Definition IntervalTree.h:79
std::vector< Interval > intervals
Definition IntervalTree.h:49
Definition IntervalTree.h:41
bool contains(const Interval &other) const
Definition IntervalTree.h:46
uint64_t low
Definition IntervalTree.h:42
uint64_t high
Definition IntervalTree.h:42
bool contains(uint64_t point) const
Definition IntervalTree.h:45
T payload
Definition IntervalTree.h:43