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