diff options
Diffstat (limited to 'runtime/src/descriptor_range_changes.h')
| -rw-r--r-- | runtime/src/descriptor_range_changes.h | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/runtime/src/descriptor_range_changes.h b/runtime/src/descriptor_range_changes.h new file mode 100644 index 000000000..5a4d7717f --- /dev/null +++ b/runtime/src/descriptor_range_changes.h | |||
| @@ -0,0 +1,46 @@ | |||
| 1 | #pragma once | ||
| 2 | #include <algorithm> | ||
| 3 | #include <array> | ||
| 4 | #include <cstdint> | ||
| 5 | #include <vector> | ||
| 6 | |||
| 7 | namespace leonida { | ||
| 8 | // A separate cursor per console heap. The owning backing/alias registry locks record() and read(). | ||
| 9 | struct DescriptorRanges { | ||
| 10 | struct Range { uint64_t first, last; }; // inclusive, including UINT64_MAX | ||
| 11 | std::vector<Range> ranges; | ||
| 12 | void merge() { | ||
| 13 | std::sort(ranges.begin(), ranges.end(), [](auto a, auto b) { return a.first < b.first; }); | ||
| 14 | size_t n = 0; | ||
| 15 | for (auto r : ranges) { | ||
| 16 | if (n && r.first <= ranges[n-1].last) | ||
| 17 | ranges[n-1].last = (std::max)(ranges[n-1].last, r.last); | ||
| 18 | else ranges[n++] = r; | ||
| 19 | } | ||
| 20 | ranges.resize(n); | ||
| 21 | } | ||
| 22 | bool overlaps(uint64_t base, uint64_t bytes) const { | ||
| 23 | if (!bytes) return false; | ||
| 24 | auto it = std::lower_bound(ranges.begin(), ranges.end(), base, | ||
| 25 | [](auto r, uint64_t v) { return r.last < v; }); | ||
| 26 | return it != ranges.end() && (it->first <= base || it->first - base < bytes); | ||
| 27 | } | ||
| 28 | }; | ||
| 29 | class DescriptorRangeChanges { | ||
| 30 | std::array<DescriptorRanges::Range, 4096> ring_{}; | ||
| 31 | uint64_t serial_{}; | ||
| 32 | public: | ||
| 33 | void record(uint64_t start, uint64_t bytes) { | ||
| 34 | if (bytes) { | ||
| 35 | ring_[serial_++ % ring_.size()] = {start, start + (std::min)(UINT64_MAX-start, bytes-1)}; | ||
| 36 | } | ||
| 37 | } | ||
| 38 | bool read(uint64_t& cursor, DescriptorRanges& out) const { | ||
| 39 | const auto previous = cursor; | ||
| 40 | cursor = serial_; | ||
| 41 | if (serial_ - previous > ring_.size()) return false; | ||
| 42 | for (auto i = previous; i != serial_; ++i) out.ranges.push_back(ring_[i % ring_.size()]); | ||
| 43 | return true; | ||
| 44 | } | ||
| 45 | }; | ||
| 46 | } | ||