MimIR 0.1
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
range_helper.h
Go to the documentation of this file.
1#pragma once
2
3#include <cstdint>
4
5#include <optional>
6#include <vector>
7
8namespace automaton {
9
10using Range = std::pair<std::uint64_t, std::uint64_t>;
11
13 inline bool operator()(const Range& a, const Range& b) const noexcept { return a.first < b.first; }
14};
15
16inline std::optional<Range> merge_ranges(Range a, Range b) noexcept {
17 if (!(a.second + 1 < b.first || b.second + 1 < a.first)) {
18 return {
19 {std::min(a.first, b.first), std::max(a.second, b.second)}
20 };
21 }
22 return {};
23}
24
25// precondition: ranges are sorted by increasing lower bound
26template<class Vec, class LogF> Vec merge_ranges(const Vec& old_ranges, LogF&& log) {
27 Vec new_ranges;
28 for (auto it = old_ranges.begin(); it != old_ranges.end(); ++it) {
29 auto current_range = *it;
30 log("old range: {}-{}", current_range.first, current_range.second);
31 for (auto inner = it + 1; inner != old_ranges.end(); ++inner)
32 if (auto merged = merge_ranges(current_range, *inner)) current_range = *merged;
33
34 std::vector<typename Vec::iterator> de_duplicate;
35 for (auto inner = new_ranges.begin(); inner != new_ranges.end(); ++inner) {
36 if (auto merged = merge_ranges(current_range, *inner)) {
37 current_range = *merged;
38 de_duplicate.push_back(inner);
39 }
40 }
41 for (auto dedup : de_duplicate) {
42 log("dedup {}-{}", current_range.first, current_range.second);
43 new_ranges.erase(dedup);
44 }
45 log("new range: {}-{}", current_range.first, current_range.second);
46 new_ranges.push_back(std::move(current_range));
47 }
48 return new_ranges;
49}
50
51// precondition: ranges are sorted by increasing lower bound
52template<class Vec> auto merge_ranges(const Vec& old_ranges) {
53 return merge_ranges(old_ranges, [](auto&&...) {});
54}
55
56} // namespace automaton
std::pair< std::uint64_t, std::uint64_t > Range
std::optional< Range > merge_ranges(Range a, Range b) noexcept
bool operator()(const Range &a, const Range &b) const noexcept