blob: 407fbf13e4516ecd5a6ee83601cc157587aa23e4 [file] [log] [blame]
John Zulauf57845342022-02-21 14:44:16 -07001/* Copyright (c) 2019-2022 The Khronos Group Inc.
2 * Copyright (c) 2019-2022 Valve Corporation
3 * Copyright (c) 2019-2022 LunarG, Inc.
4 * Copyright (C) 2019-2022 Google Inc.
John Zulauf11211402019-11-15 14:02:36 -07005 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 * John Zulauf <jzulauf@lunarg.com>
19 *
20 */
21#pragma once
22
23#ifndef RANGE_VECTOR_H_
24#define RANGE_VECTOR_H_
25
26#include <algorithm>
27#include <cassert>
John Zulauf81408f12019-11-27 16:40:27 -070028#include <limits>
John Zulauf11211402019-11-15 14:02:36 -070029#include <map>
30#include <utility>
hedmo511b3062020-03-18 20:23:13 +010031#include <cstdint>
Jeremy Gebbencbf22862021-03-03 12:01:22 -070032#include "vk_layer_data.h"
John Zulauf11211402019-11-15 14:02:36 -070033
34#define RANGE_ASSERT(b) assert(b)
35
36namespace sparse_container {
37// range_map
38//
39// Implements an ordered map of non-overlapping, non-empty ranges
40//
41template <typename Index>
42struct range {
43 using index_type = Index;
44 index_type begin; // Inclusive lower bound of range
45 index_type end; // Exlcusive upper bound of range
46
47 inline bool empty() const { return begin == end; }
48 inline bool valid() const { return begin <= end; }
49 inline bool invalid() const { return !valid(); }
50 inline bool non_empty() const { return begin < end; } // valid and !empty
51
52 inline bool is_prior_to(const range &other) const { return end == other.begin; }
53 inline bool is_subsequent_to(const range &other) const { return begin == other.end; }
54 inline bool includes(const index_type &index) const { return (begin <= index) && (index < end); }
55 inline bool includes(const range &other) const { return (begin <= other.begin) && (other.end <= end); }
56 inline bool excludes(const index_type &index) const { return (index < begin) || (end <= index); }
57 inline bool excludes(const range &other) const { return (other.end <= begin) || (end <= other.begin); }
58 inline bool intersects(const range &other) const { return includes(other.begin) || other.includes(begin); }
59 inline index_type distance() const { return end - begin; }
60
61 inline bool operator==(const range &rhs) const { return (begin == rhs.begin) && (end == rhs.end); }
62 inline bool operator!=(const range &rhs) const { return (begin != rhs.begin) || (end != rhs.end); }
63
64 inline range &operator-=(const index_type &offset) {
65 begin = begin - offset;
66 end = end - offset;
67 return *this;
68 }
69
70 inline range &operator+=(const index_type &offset) {
71 begin = begin + offset;
72 end = end + offset;
73 return *this;
74 }
75
John Zulauf31e08792020-04-03 12:47:40 -060076 inline range operator+(const index_type &offset) const { return range(begin + offset, end + offset); }
77
John Zulauf11211402019-11-15 14:02:36 -070078 // for a reversible/transitive < operator compare first on begin and then end
79 // only less or begin is less or if end is less when begin is equal
80 bool operator<(const range &rhs) const {
81 bool result = false;
82 if (invalid()) {
83 // all invalid < valid, allows map/set validity check by looking at begin()->first
84 // all invalid are equal, thus only equal if this is invalid and rhs is valid
85 result = rhs.valid();
86 } else if (begin < rhs.begin) {
87 result = true;
88 } else if ((begin == rhs.begin) && (end < rhs.end)) {
89 result = true; // Simple common case -- boundary case require equality check for correctness.
90 }
91 return result;
92 }
93
94 // use as "strictly less/greater than" to check for non-overlapping ranges
95 bool strictly_less(const range &rhs) const { return end <= rhs.begin; }
96 bool strictly_less(const index_type &index) const { return end <= index; }
97 bool strictly_greater(const range &rhs) const { return rhs.end <= begin; }
98 bool strictly_greater(const index_type &index) const { return index < begin; }
99
100 range &operator=(const range &rhs) {
101 begin = rhs.begin;
102 end = rhs.end;
103 return *this;
104 }
105
106 range operator&(const range &rhs) const {
107 if (includes(rhs.begin)) {
108 return range(rhs.begin, std::min(end, rhs.end));
109 } else if (rhs.includes(begin)) {
110 return range(begin, std::min(end, rhs.end));
111 }
112 return range(); // Empty default range on non-intersection
113 }
114
John Zulauf57845342022-02-21 14:44:16 -0700115 index_type size() const { return end - begin; }
John Zulauf11211402019-11-15 14:02:36 -0700116 range() : begin(), end() {}
117 range(const index_type &begin_, const index_type &end_) : begin(begin_), end(end_) {}
Mike Schuchardtf27101e2020-04-06 21:39:35 -0700118 range(const range &other) : begin(other.begin), end(other.end) {}
John Zulauf11211402019-11-15 14:02:36 -0700119};
120
John Zulauf2076e812020-01-08 14:55:54 -0700121template <typename Range>
122class range_view {
123 public:
124 using index_type = typename Range::index_type;
125 class iterator {
126 public:
127 iterator &operator++() {
128 ++current;
129 return *this;
130 }
131 const index_type &operator*() const { return current; }
132 bool operator!=(const iterator &rhs) const { return current != rhs.current; }
133 iterator(index_type value) : current(value) {}
134
135 private:
136 index_type current;
137 };
138 range_view(const Range &range) : range_(range) {}
139 const iterator begin() const { return iterator(range_.begin); }
140 const iterator end() const { return iterator(range_.end); }
141
142 private:
143 const Range &range_;
144};
145
John Zulauf81408f12019-11-27 16:40:27 -0700146// Type parameters for the range_map(s)
147struct insert_range_no_split_bounds {
148 const static bool split_boundaries = false;
149};
150
151struct insert_range_split_bounds {
152 const static bool split_boundaries = true;
153};
154
155struct split_op_keep_both {
156 static constexpr bool keep_lower() { return true; }
157 static constexpr bool keep_upper() { return true; }
158};
159
160struct split_op_keep_lower {
161 static constexpr bool keep_lower() { return true; }
162 static constexpr bool keep_upper() { return false; }
163};
164
165struct split_op_keep_upper {
166 static constexpr bool keep_lower() { return false; }
167 static constexpr bool keep_upper() { return true; }
168};
169
170enum class value_precedence { prefer_source, prefer_dest };
171
172// The range based sparse map implemented on the ImplMap
173template <typename Key, typename T, typename RangeKey = range<Key>, typename ImplMap = std::map<RangeKey, T>>
John Zulauf11211402019-11-15 14:02:36 -0700174class range_map {
175 public:
176 protected:
John Zulauf11211402019-11-15 14:02:36 -0700177 using MapKey = RangeKey;
John Zulauf11211402019-11-15 14:02:36 -0700178 ImplMap impl_map_;
179 using ImplIterator = typename ImplMap::iterator;
180 using ImplConstIterator = typename ImplMap::const_iterator;
181
182 public:
183 using mapped_type = typename ImplMap::mapped_type;
184 using value_type = typename ImplMap::value_type;
185 using key_type = typename ImplMap::key_type;
186 using index_type = typename key_type::index_type;
John Zulauf3da08bb2022-08-01 17:56:56 -0600187 using size_type = typename ImplMap::size_type;
John Zulauf11211402019-11-15 14:02:36 -0700188
John Zulauf11211402019-11-15 14:02:36 -0700189 protected:
190 template <typename ThisType>
191 using ConstCorrectImplIterator = decltype(std::declval<ThisType>().impl_begin());
192
193 template <typename ThisType, typename WrappedIterator = ConstCorrectImplIterator<ThisType>>
194 static WrappedIterator lower_bound_impl(ThisType &that, const key_type &key) {
195 if (key.valid()) {
196 // ImplMap doesn't give us what want with a direct query, it will give us the first entry contained (if any) in key,
197 // not the first entry intersecting key, so, first look for the the first entry that starts at or after key.begin
198 // with the operator > in range, we can safely use an empty range for comparison
199 auto lower = that.impl_map_.lower_bound(key_type(key.begin, key.begin));
200
201 // If there is a preceding entry it's possible that begin is included, as all we know is that lower.begin >= key.begin
202 // or lower is at end
203 if (!that.at_impl_begin(lower)) {
204 auto prev = lower;
205 --prev;
206 // If the previous entry includes begin (and we know key.begin > prev.begin) then prev is actually lower
207 if (key.begin < prev->first.end) {
208 lower = prev;
209 }
210 }
211 return lower;
212 }
213 // Key is ill-formed
214 return that.impl_end(); // Point safely to nothing.
215 }
216
217 ImplIterator lower_bound_impl(const key_type &key) { return lower_bound_impl(*this, key); }
218
219 ImplConstIterator lower_bound_impl(const key_type &key) const { return lower_bound_impl(*this, key); }
220
221 template <typename ThisType, typename WrappedIterator = ConstCorrectImplIterator<ThisType>>
222 static WrappedIterator upper_bound_impl(ThisType &that, const key_type &key) {
223 if (key.valid()) {
224 // the upper bound is the first range that is full greater (upper.begin >= key.end
225 // we can get close by looking for the first to exclude key.end, then adjust to account for the fact that key.end is
226 // exclusive and we thus ImplMap::upper_bound may be off by one here, i.e. the previous may be the upper bound
227 auto upper = that.impl_map_.upper_bound(key_type(key.end, key.end));
228 if (!that.at_impl_end(upper) && (upper != that.impl_begin())) {
229 auto prev = upper;
230 --prev;
231 // We know key.end is >= prev.begin, the only question is whether it's ==
232 if (prev->first.begin == key.end) {
233 upper = prev;
234 }
235 }
236 return upper;
237 }
238 return that.impl_end(); // Point safely to nothing.
239 }
240
241 ImplIterator upper_bound_impl(const key_type &key) { return upper_bound_impl(*this, key); }
242
243 ImplConstIterator upper_bound_impl(const key_type &key) const { return upper_bound_impl(*this, key); }
244
245 ImplIterator impl_find(const key_type &key) { return impl_map_.find(key); }
246 ImplConstIterator impl_find(const key_type &key) const { return impl_map_.find(key); }
247 bool impl_not_found(const key_type &key) const { return impl_end() == impl_find(key); }
248
249 ImplIterator impl_end() { return impl_map_.end(); }
250 ImplConstIterator impl_end() const { return impl_map_.end(); }
251
252 ImplIterator impl_begin() { return impl_map_.begin(); }
253 ImplConstIterator impl_begin() const { return impl_map_.begin(); }
254
255 inline bool at_impl_end(const ImplIterator &pos) { return pos == impl_end(); }
256 inline bool at_impl_end(const ImplConstIterator &pos) const { return pos == impl_end(); }
257
258 inline bool at_impl_begin(const ImplIterator &pos) { return pos == impl_begin(); }
259 inline bool at_impl_begin(const ImplConstIterator &pos) const { return pos == impl_begin(); }
260
261 ImplIterator impl_erase(const ImplIterator &pos) { return impl_map_.erase(pos); }
262
263 template <typename Value>
264 ImplIterator impl_insert(const ImplIterator &hint, Value &&value) {
265 RANGE_ASSERT(impl_not_found(value.first));
266 RANGE_ASSERT(value.first.non_empty());
267 return impl_map_.emplace_hint(hint, std::forward<Value>(value));
268 }
269 ImplIterator impl_insert(const ImplIterator &hint, const key_type &key, const mapped_type &value) {
270 return impl_insert(hint, std::make_pair(key, value));
271 }
272
273 ImplIterator impl_insert(const ImplIterator &hint, const index_type &begin, const index_type &end, const mapped_type &value) {
274 return impl_insert(hint, key_type(begin, end), value);
275 }
276
277 template <typename SplitOp>
278 ImplIterator split_impl(const ImplIterator &split_it, const index_type &index, const SplitOp &) {
279 // Make sure contains the split point
280 if (!split_it->first.includes(index)) return split_it; // If we don't have a valid split point, just return the iterator
281
282 const auto range = split_it->first;
283 key_type lower_range(range.begin, index);
284 if (lower_range.empty() && SplitOp::keep_upper()) {
285 return split_it; // this is a noop we're keeping the upper half which is the same as split_it;
286 }
287 // Save the contents of it and erase it
arno-lunarg0dd88812022-09-01 12:33:34 +0200288 auto value = split_it->second;
John Zulauf11211402019-11-15 14:02:36 -0700289 auto next_it = impl_map_.erase(split_it); // Keep this, just in case the split point results in an empty "keep" set
290
291 if (lower_range.empty() && !SplitOp::keep_upper()) {
292 // This effectively an erase...
293 return next_it;
294 }
295 // Upper range cannot be empty
296 key_type upper_range(index, range.end);
297 key_type move_range;
298 key_type copy_range;
299
300 // Were either going to keep one or both of the split pieces. If we keep both, we'll copy value to the upper,
301 // and move to the lower, and return the lower, else move to, and return the kept one.
302 if (SplitOp::keep_lower() && !lower_range.empty()) {
303 move_range = lower_range;
304 if (SplitOp::keep_upper()) {
305 copy_range = upper_range; // only need a valid copy range if we keep both.
306 }
307 } else if (SplitOp::keep_upper()) { // We're not keeping the lower split because it's either empty or not wanted
308 move_range = upper_range; // this will be non_empty as index is included ( < end) in the original range)
309 }
310
311 // we insert from upper to lower because that's what emplace_hint can do in constant time. (not log time in C++11)
312 if (!copy_range.empty()) {
313 // We have a second range to create, so do it by copy
314 RANGE_ASSERT(impl_map_.find(copy_range) == impl_map_.end());
315 next_it = impl_map_.emplace_hint(next_it, std::make_pair(copy_range, value));
316 }
317
318 if (!move_range.empty()) {
319 // Whether we keep one or both, the one we return gets value moved to it, as the other one already has a copy
320 RANGE_ASSERT(impl_map_.find(move_range) == impl_map_.end());
321 next_it = impl_map_.emplace_hint(next_it, std::make_pair(move_range, std::move(value)));
322 }
323
324 // point to the beginning of the inserted elements (or the next from the erase
325 return next_it;
326 }
327
328 // do an ranged insert that splits existing ranges at the boundaries, and writes value to any non-initialized sub-ranges
329 range<ImplIterator> infill_and_split(const key_type &bounds, const mapped_type &value, ImplIterator lower, bool split_bounds) {
330 auto pos = lower;
331 if (at_impl_end(pos)) return range<ImplIterator>(pos, pos); // defensive...
332
333 // Logic assumes we are starting at lower bound
334 RANGE_ASSERT(lower == lower_bound_impl(bounds));
335
336 // Trim/infil the beginning if needed
337 const auto first_begin = pos->first.begin;
338 if (bounds.begin > first_begin && split_bounds) {
339 pos = split_impl(pos, bounds.begin, split_op_keep_both());
340 lower = pos;
341 ++lower;
342 RANGE_ASSERT(lower == lower_bound_impl(bounds));
343 } else if (bounds.begin < first_begin) {
344 pos = impl_insert(pos, bounds.begin, first_begin, value);
345 lower = pos;
346 RANGE_ASSERT(lower == lower_bound_impl(bounds));
347 }
348
349 // in the trim case pos starts one before lower_bound, but that allows trimming a single entry range in loop.
350 // NOTE that the loop is trimming and infilling at pos + 1
351 while (!at_impl_end(pos) && pos->first.begin < bounds.end) {
352 auto last_end = pos->first.end;
353 // check for in-fill
354 ++pos;
355 if (at_impl_end(pos)) {
356 if (last_end < bounds.end) {
357 // Gap after last entry in impl_map and before end,
358 pos = impl_insert(pos, last_end, bounds.end, value);
359 ++pos; // advances to impl_end, as we're at upper boundary
360 RANGE_ASSERT(at_impl_end(pos));
361 }
362 } else if (pos->first.begin != last_end) {
363 // we have a gap between last entry and current... fill, but not beyond bounds
364 if (bounds.includes(pos->first.begin)) {
365 pos = impl_insert(pos, last_end, pos->first.begin, value);
366 // don't further advance pos, because we may need to split the next entry and thus can't skip it.
367 } else if (last_end < bounds.end) {
368 // Non-zero length final gap in-bounds
369 pos = impl_insert(pos, last_end, bounds.end, value);
370 ++pos; // advances back to the out of bounds entry which we inserted just before
371 RANGE_ASSERT(!bounds.includes(pos->first.begin));
372 }
373 } else if (pos->first.includes(bounds.end)) {
374 if (split_bounds) {
375 // extends past the end of the bounds range, snip to only include the bounded section
376 // NOTE: this splits pos, but the upper half of the split should now be considered upper_bound
377 // for the range
378 pos = split_impl(pos, bounds.end, split_op_keep_both());
379 }
380 // advance to the upper haf of the split which will be upper_bound or to next which will both be out of bounds
381 ++pos;
382 RANGE_ASSERT(!bounds.includes(pos->first.begin));
383 }
384 }
385 // Return the current position which should be the upper_bound for bounds
386 RANGE_ASSERT(pos == upper_bound_impl(bounds));
387 return range<ImplIterator>(lower, pos);
388 }
389
390 ImplIterator impl_erase_range(const key_type &bounds, ImplIterator lower) {
391 // Logic assumes we are starting at a valid lower bound
392 RANGE_ASSERT(!at_impl_end(lower));
393 RANGE_ASSERT(lower == lower_bound_impl(bounds));
394
395 // Trim/infil the beginning if needed
396 auto current = lower;
397 const auto first_begin = current->first.begin;
398 if (bounds.begin > first_begin) {
399 // Preserve the portion of lower bound excluded from bounds
John Zulauf38c85f32020-02-06 11:14:27 -0700400 if (current->first.end <= bounds.end) {
401 // If current ends within the erased bound we can discard the the upper portion of current
402 current = split_impl(current, bounds.begin, split_op_keep_lower());
403 } else {
404 // Keep the upper portion of current for the later split below
405 current = split_impl(current, bounds.begin, split_op_keep_both());
406 }
John Zulauf11211402019-11-15 14:02:36 -0700407 // Exclude the preserved portion
408 ++current;
409 RANGE_ASSERT(current == lower_bound_impl(bounds));
410 }
411
412 // Loop over completely contained entries and erase them
413 while (!at_impl_end(current) && (current->first.end <= bounds.end)) {
414 current = impl_erase(current);
415 }
416
417 if (!at_impl_end(current) && current->first.includes(bounds.end)) {
418 // last entry extends past the end of the bounds range, snip to only erase the bounded section
419 current = split_impl(current, bounds.end, split_op_keep_upper());
420 }
421
422 RANGE_ASSERT(current == upper_bound_impl(bounds));
423 return current;
424 }
425
426 template <typename ValueType, typename WrappedIterator_>
427 struct iterator_impl {
428 public:
429 friend class range_map;
430 using WrappedIterator = WrappedIterator_;
431
432 private:
433 WrappedIterator pos_;
434
435 // Create an iterator at a specific internal state -- only from the parent container
436 iterator_impl(const WrappedIterator &pos) : pos_(pos) {}
437
438 public:
439 iterator_impl() : iterator_impl(WrappedIterator()){};
440 iterator_impl(const iterator_impl &other) : pos_(other.pos_){};
441
442 iterator_impl &operator=(const iterator_impl &rhs) {
443 pos_ = rhs.pos_;
444 return *this;
445 }
446
447 inline bool operator==(const iterator_impl &rhs) const { return pos_ == rhs.pos_; }
448
449 inline bool operator!=(const iterator_impl &rhs) const { return pos_ != rhs.pos_; }
450
451 ValueType &operator*() const { return *pos_; }
452 ValueType *operator->() const { return &*pos_; }
453
454 iterator_impl &operator++() {
455 ++pos_;
456 return *this;
457 }
458
459 iterator_impl &operator--() {
460 --pos_;
461 return *this;
462 }
John Zulauf81408f12019-11-27 16:40:27 -0700463
464 // To allow for iterator -> const_iterator construction
465 // NOTE: while it breaks strict encapsulation, it does so less than friend
466 const WrappedIterator &get_pos() const { return pos_; };
John Zulauf11211402019-11-15 14:02:36 -0700467 };
468
469 public:
470 using iterator = iterator_impl<value_type, ImplIterator>;
John Zulauf81408f12019-11-27 16:40:27 -0700471
472 // The const iterator must be derived to allow the conversion from iterator, which iterator doesn't support
473 class const_iterator : public iterator_impl<const value_type, ImplConstIterator> {
474 using Base = iterator_impl<const value_type, ImplConstIterator>;
475 friend range_map;
476
477 public:
Mike Schuchardtf27101e2020-04-06 21:39:35 -0700478 const_iterator &operator=(const const_iterator &other) {
479 Base::operator=(other);
480 return *this;
481 }
John Zulauf81408f12019-11-27 16:40:27 -0700482 const_iterator(const const_iterator &other) : Base(other){};
483 const_iterator(const iterator &it) : Base(ImplConstIterator(it.get_pos())) {}
484 const_iterator() : Base() {}
485
486 private:
487 const_iterator(const ImplConstIterator &pos) : Base(pos) {}
488 };
John Zulauf11211402019-11-15 14:02:36 -0700489
490 protected:
491 inline bool at_end(const iterator &it) { return at_impl_end(it.pos_); }
492 inline bool at_end(const const_iterator &it) const { return at_impl_end(it.pos_); }
493 inline bool at_begin(const iterator &it) { return at_impl_begin(it.pos_); }
494
495 template <typename That, typename Iterator>
496 static bool is_contiguous_impl(That *const that, const key_type &range, const Iterator &lower) {
497 // Search range or intersection is empty
498 if (lower == that->impl_end() || lower->first.excludes(range)) return false;
499
500 if (lower->first.includes(range)) {
501 return true; // there is one entry that contains the whole key range
502 }
503
504 bool contiguous = true;
505 for (auto pos = lower; contiguous && pos != that->impl_end() && range.includes(pos->first.begin); ++pos) {
506 // if current doesn't cover the rest of the key range, check to see that the next is extant and abuts
507 if (pos->first.end < range.end) {
508 auto next = pos;
John Zulauff3eeba62019-11-22 15:09:07 -0700509 ++next;
John Zulauf11211402019-11-15 14:02:36 -0700510 contiguous = (next != that->impl_end()) && pos->first.is_prior_to(next->first);
511 }
512 }
513 return contiguous;
514 }
515
516 public:
517 iterator end() { return iterator(impl_map_.end()); } // policy and bounds don't matter for end
518 const_iterator end() const { return const_iterator(impl_map_.end()); } // policy and bounds don't matter for end
519 iterator begin() { return iterator(impl_map_.begin()); } // with default policy, and thus no bounds
520 const_iterator begin() const { return const_iterator(impl_map_.begin()); } // with default policy, and thus no bounds
521 const_iterator cbegin() const { return const_iterator(impl_map_.cbegin()); } // with default policy, and thus no bounds
522 const_iterator cend() const { return const_iterator(impl_map_.cend()); } // with default policy, and thus no bounds
523
524 iterator erase(const iterator &pos) {
525 RANGE_ASSERT(!at_end(pos));
526 return iterator(impl_erase(pos.pos_));
527 }
528
529 iterator erase(range<iterator> bounds) {
530 auto current = bounds.begin.pos_;
531 while (current != bounds.end.pos_) {
532 RANGE_ASSERT(!at_impl_end(current));
533 current = impl_map_.erase(current);
534 }
535 RANGE_ASSERT(current == bounds.end.pos_);
536 return current;
537 }
538
539 iterator erase(iterator first, iterator last) { return erase(range<iterator>(first, last)); }
540
541 iterator erase_range(const key_type &bounds) {
542 auto lower = lower_bound_impl(bounds);
543
544 if (at_impl_end(lower) || !bounds.intersects(lower->first)) {
545 // There is nothing in this range lower bound is above bound
546 return iterator(lower);
547 }
548 auto next = impl_erase_range(bounds, lower);
549 return iterator(next);
550 }
551
552 void clear() { impl_map_.clear(); }
553
554 iterator find(const key_type &key) { return iterator(impl_map_.find(key)); }
555
556 const_iterator find(const key_type &key) const { return const_iterator(impl_map_.find(key)); }
557
558 iterator find(const index_type &index) {
559 auto lower = lower_bound(range<index_type>(index, index + 1));
560 if (!at_end(lower) && lower->first.includes(index)) {
561 return lower;
562 }
563 return end();
564 }
565
566 const_iterator find(const index_type &index) const {
567 auto lower = lower_bound(key_type(index, index + 1));
568 if (!at_end(lower) && lower->first.includes(index)) {
569 return lower;
570 }
571 return end();
572 }
573
John Zulauf11211402019-11-15 14:02:36 -0700574 iterator lower_bound(const key_type &key) { return iterator(lower_bound_impl(key)); }
575
576 const_iterator lower_bound(const key_type &key) const { return const_iterator(lower_bound_impl(key)); }
577
578 iterator upper_bound(const key_type &key) { return iterator(upper_bound_impl(key)); }
579
580 const_iterator upper_bound(const key_type &key) const { return const_iterator(upper_bound_impl(key)); }
581
582 range<iterator> bounds(const key_type &key) { return {lower_bound(key), upper_bound(key)}; }
583 range<const_iterator> cbounds(const key_type &key) const { return {lower_bound(key), upper_bound(key)}; }
584 range<const_iterator> bounds(const key_type &key) const { return cbounds(key); }
585
586 using insert_pair = std::pair<iterator, bool>;
587
588 // This is traditional no replacement insert.
John Zulauf81408f12019-11-27 16:40:27 -0700589 insert_pair insert(const value_type &value) {
John Zulauf11211402019-11-15 14:02:36 -0700590 const auto &key = value.first;
591 if (!key.non_empty()) {
592 // It's an invalid key, early bail pointing to end
593 return std::make_pair(end(), false);
594 }
595
596 // Look for range conflicts (and an insertion point, which makes the lower_bound *not* wasted work)
597 // we don't have to check upper if just check that lower doesn't intersect (which it would if lower != upper)
598 auto lower = lower_bound_impl(key);
599 if (at_impl_end(lower) || !lower->first.intersects(key)) {
600 // range is not even paritally overlapped, and lower is strictly > than key
John Zulauf81408f12019-11-27 16:40:27 -0700601 auto impl_insert = impl_map_.emplace_hint(lower, value);
John Zulauf11211402019-11-15 14:02:36 -0700602 // auto impl_insert = impl_map_.emplace(value);
603 iterator wrap_it(impl_insert);
604 return std::make_pair(wrap_it, true);
605 }
606 // We don't replace
607 return std::make_pair(iterator(lower), false);
608 };
609
John Zulauf81408f12019-11-27 16:40:27 -0700610 iterator insert(const_iterator hint, const value_type &value) {
611 bool hint_open;
612 ImplConstIterator impl_next = hint.pos_;
613 if (impl_map_.empty()) {
614 hint_open = true;
615 } else if (impl_next == impl_map_.cbegin()) {
616 hint_open = value.first.strictly_less(impl_next->first);
617 } else if (impl_next == impl_map_.cend()) {
618 auto impl_prev = impl_next;
619 --impl_prev;
620 hint_open = value.first.strictly_greater(impl_prev->first);
621 } else {
622 auto impl_prev = impl_next;
623 --impl_prev;
624 hint_open = value.first.strictly_greater(impl_prev->first) && value.first.strictly_less(impl_next->first);
625 }
626
627 if (!hint_open) {
628 // Hint was unhelpful, fall back to the non-hinted version
629 auto plain_insert = insert(value);
630 return plain_insert.first;
631 }
632
633 auto impl_insert = impl_map_.insert(impl_next, value);
634 return iterator(impl_insert);
635 }
636
John Zulauf11211402019-11-15 14:02:36 -0700637 template <typename SplitOp>
638 iterator split(const iterator whole_it, const index_type &index, const SplitOp &split_op) {
639 auto split_it = split_impl(whole_it.pos_, index, split_op);
640 return iterator(split_it);
641 }
642
643 // The overwrite hint here is lower.... and if it's not right... this fails
644 template <typename Value>
645 iterator overwrite_range(const iterator &lower, Value &&value) {
646 // We're not robust to a bad hint, so detect it with extreme prejudice
647 // TODO: Add bad hint test to make this robust...
648 auto lower_impl = lower.pos_;
649 auto insert_hint = lower_impl;
650 if (!at_impl_end(lower_impl)) {
651 // If we're at end (and the hint is good, there's nothing to erase
652 RANGE_ASSERT(lower == lower_bound(value.first));
653 insert_hint = impl_erase_range(value.first, lower_impl);
654 }
655 auto inserted = impl_insert(insert_hint, std::forward<Value>(value));
656 return iterator(inserted);
657 }
658
659 template <typename Value>
660 iterator overwrite_range(Value &&value) {
661 auto lower = lower_bound(value.first);
662 return overwrite_range(lower, value);
663 }
664
John Zulauf11211402019-11-15 14:02:36 -0700665 bool empty() const { return impl_map_.empty(); }
John Zulauf3da08bb2022-08-01 17:56:56 -0600666 size_type size() const { return impl_map_.size(); }
John Zulauf81408f12019-11-27 16:40:27 -0700667
668 // For configuration/debug use // Use with caution...
669 ImplMap &get_implementation_map() { return impl_map_; }
670 const ImplMap &get_implementation_map() const { return impl_map_; }
John Zulauf11211402019-11-15 14:02:36 -0700671};
672
673template <typename Container>
674using const_correct_iterator = decltype(std::declval<Container>().begin());
675
John Zulauf81408f12019-11-27 16:40:27 -0700676// The an array based small ordered map for range keys for use as the range map "ImplMap" as an alternate to std::map
677//
678// Assumes RangeKey::index_type is unsigned (TBD is it useful to generalize to unsigned?)
679// Assumes RangeKey implements begin, end, < and (TBD) from template range above
680template <typename Key, typename T, typename RangeKey = range<Key>, size_t N = 64, typename SmallIndex = uint8_t>
681class small_range_map {
682 using SmallRange = range<SmallIndex>;
683
684 public:
685 using mapped_type = T;
686 using key_type = RangeKey;
687 using value_type = std::pair<const key_type, mapped_type>;
688 using index_type = typename key_type::index_type;
689
690 using size_type = SmallIndex;
691 template <typename Map_, typename Value_>
692 struct IteratorImpl {
693 public:
694 using Map = Map_;
695 using Value = Value_;
696 friend Map;
697 Value *operator->() const { return map_->get_value(pos_); }
698 Value &operator*() const { return *(map_->get_value(pos_)); }
699 IteratorImpl &operator++() {
700 pos_ = map_->next_range(pos_);
701 return *this;
702 }
703 IteratorImpl &operator--() {
704 pos_ = map_->prev_range(pos_);
705 return *this;
706 }
707 IteratorImpl &operator=(const IteratorImpl &other) {
708 map_ = other.map_;
709 pos_ = other.pos_;
710 return *this;
711 }
712 bool operator==(const IteratorImpl &other) const {
713 if (at_end() && other.at_end()) {
714 return true; // all ends are equal
715 }
716 return (map_ == other.map_) && (pos_ == other.pos_);
717 }
718 bool operator!=(const IteratorImpl &other) const { return !(*this == other); }
719
720 // At end()
721 IteratorImpl() : map_(nullptr), pos_(N) {}
Mike Schuchardtf27101e2020-04-06 21:39:35 -0700722 IteratorImpl(const IteratorImpl &other) : map_(other.map_), pos_(other.pos_) {}
John Zulauf81408f12019-11-27 16:40:27 -0700723
724 // Raw getters to allow for const_iterator conversion below
725 Map *get_map() const { return map_; }
726 SmallIndex get_pos() const { return pos_; }
727
728 bool at_end() const { return (map_ == nullptr) || (pos_ >= map_->get_limit()); }
729
730 protected:
731 IteratorImpl(Map *map, SmallIndex pos) : map_(map), pos_(pos) {}
732
733 private:
734 Map *map_;
735 SmallIndex pos_; // the begin of the current small_range
736 };
737 using iterator = IteratorImpl<small_range_map, value_type>;
738
739 // The const iterator must be derived to allow the conversion from iterator, which iterator doesn't support
740 class const_iterator : public IteratorImpl<const small_range_map, const value_type> {
741 using Base = IteratorImpl<const small_range_map, const value_type>;
742 friend small_range_map;
743
744 public:
745 const_iterator(const iterator &it) : Base(it.get_map(), it.get_pos()) {}
746 const_iterator() : Base() {}
747
748 private:
749 const_iterator(const small_range_map *map, SmallIndex pos) : Base(map, pos) {}
750 };
751
752 iterator begin() {
753 // Either ranges of 0 is valid and begin is 0 and begin *or* it's invalid an points to the first valid range (or end)
754 return iterator(this, ranges_[0].begin);
755 }
756 const_iterator cbegin() const { return const_iterator(this, ranges_[0].begin); }
757 const_iterator begin() const { return cbegin(); }
758 iterator end() { return iterator(); }
759 const_iterator cend() const { return const_iterator(); }
760 const_iterator end() const { return cend(); }
761
762 void clear() {
763 const SmallRange clear_range(limit_, 0);
764 for (SmallIndex i = 0; i < limit_; ++i) {
765 auto &range = ranges_[i];
766 if (range.begin == i) {
767 // Clean up the backing store
768 destruct_value(i);
769 }
770 range = clear_range;
771 }
772 size_ = 0;
773 }
774
775 // Find entry with an exact key match (uncommon use case)
776 iterator find(const key_type &key) {
777 RANGE_ASSERT(in_bounds(key));
778 if (key.begin < limit_) {
779 const SmallIndex small_begin = static_cast<SmallIndex>(key.begin);
780 const auto &range = ranges_[small_begin];
781 if (range.begin == small_begin) {
782 const auto small_end = static_cast<SmallIndex>(key.end);
783 if (range.end == small_end) return iterator(this, small_begin);
784 }
785 }
786 return end();
787 }
788 const_iterator find(const key_type &key) const {
789 RANGE_ASSERT(in_bounds(key));
790 if (key.begin < limit_) {
791 const SmallIndex small_begin = static_cast<SmallIndex>(key.begin);
792 const auto &range = ranges_[small_begin];
793 if (range.begin == small_begin) {
794 const auto small_end = static_cast<SmallIndex>(key.end);
795 if (range.end == small_end) return const_iterator(this, small_begin);
796 }
797 }
798 return end();
799 }
800
801 iterator find(const index_type &index) {
802 if (index < get_limit()) {
803 const SmallIndex small_index = static_cast<SmallIndex>(index);
804 const auto &range = ranges_[small_index];
805 if (range.valid()) {
806 return iterator(this, range.begin);
807 }
808 }
809 return end();
810 }
811
812 const_iterator find(const index_type &index) const {
813 if (index < get_limit()) {
814 const SmallIndex small_index = static_cast<SmallIndex>(index);
815 const auto &range = ranges_[small_index];
816 if (range.valid()) {
817 return const_iterator(this, range.begin);
818 }
819 }
820 return end();
821 }
822
823 size_type size() const { return size_; }
824 bool empty() const { return 0 == size_; }
825
826 iterator erase(const_iterator pos) {
827 RANGE_ASSERT(pos.map_ == this);
828 return erase_impl(pos.get_pos());
829 }
830
831 iterator erase(iterator pos) {
832 RANGE_ASSERT(pos.map_ == this);
833 return erase_impl(pos.get_pos());
834 }
835
836 // Must be called with rvalue or lvalue of value_type
837 template <typename Value>
838 iterator emplace(Value &&value) {
839 const auto &key = value.first;
840 RANGE_ASSERT(in_bounds(key));
841 if (key.begin >= limit_) return end(); // Invalid key (end is checked in "is_open")
842 const SmallRange range(static_cast<SmallIndex>(key.begin), static_cast<SmallIndex>(key.end));
843 if (is_open(key)) {
844 // This needs to be the fast path, but I don't see how we can avoid the sanity checks above
845 for (auto i = range.begin; i < range.end; ++i) {
846 ranges_[i] = range;
847 }
848 // Update the next information for the previous unused slots (as stored in begin invalidly)
849 auto prev = range.begin;
850 while (prev > 0) {
851 --prev;
852 if (ranges_[prev].valid()) break;
853 ranges_[prev].begin = range.begin;
854 }
855 // Placement new into the storage interpreted as Value
856 construct_value(range.begin, value_type(std::forward<Value>(value)));
857 auto next = range.end;
858 // update the previous range information for the next unsed slots (as stored in end invalidly)
859 while (next < limit_) {
860 // End is exclusive... increment *after* update
861 if (ranges_[next].valid()) break;
862 ranges_[next].end = range.end;
863 ++next;
864 }
865 return iterator(this, range.begin);
866 } else {
867 // Can't insert into occupied ranges.
868 // if ranges_[key.begin] is valid then this is the collision (starting at .begin
869 // if it's invalid .begin points to the overlapping entry from is_open (or end if key was out of range)
870 return iterator(this, ranges_[range.begin].begin);
871 }
872 }
873
874 // As hint is going to be ignored, make it as lightweight as possible, by reference and no conversion construction
875 template <typename Value>
876 iterator emplace_hint(const const_iterator &hint, Value &&value) {
877 // We have direct access so we can drop the hint
878 return emplace(std::forward<Value>(value));
879 }
880
881 template <typename Value>
882 iterator emplace_hint(const iterator &hint, Value &&value) {
883 // We have direct access so we can drop the hint
884 return emplace(std::forward<Value>(value));
885 }
886
887 // Again, hint is going to be ignored, make it as lightweight as possible, by reference and no conversion construction
888 iterator insert(const const_iterator &hint, const value_type &value) { return emplace(value); }
889 iterator insert(const iterator &hint, const value_type &value) { return emplace(value); }
890
891 std::pair<iterator, bool> insert(const value_type &value) {
892 const auto &key = value.first;
893 RANGE_ASSERT(in_bounds(key));
894 if (key.begin >= limit_) return std::make_pair(end(), false); // Invalid key, not inserted.
895 if (is_open(key)) {
896 return std::make_pair(emplace(value), true);
897 }
898 // If invalid we point to the subsequent range that collided, if valid begin is the start of the valid range
899 const auto &collision_begin = ranges_[key.begin].begin;
900 RANGE_ASSERT(ranges_[collision_begin].valid());
901 return std::make_pair(iterator(this, collision_begin), false);
902 }
903
904 template <typename SplitOp>
905 iterator split(const iterator whole_it, const index_type &index, const SplitOp &split_op) {
906 if (!whole_it->first.includes(index)) return whole_it; // If we don't have a valid split point, just return the iterator
907
908 const auto &key = whole_it->first;
909 const auto small_key = make_small_range(key);
910 key_type lower_key(key.begin, index);
911 if (lower_key.empty() && SplitOp::keep_upper()) {
912 return whole_it; // this is a noop we're keeping the upper half which is the same as whole_it;
913 }
914
915 if ((lower_key.empty() && !SplitOp::keep_upper()) || !(SplitOp::keep_lower() || SplitOp::keep_upper())) {
916 // This effectively an erase... so erase.
917 return erase(whole_it);
918 }
919
920 // Upper range cannot be empty (because the split point would be included...
921 const auto small_lower_key = make_small_range(lower_key);
922 const SmallRange small_upper_key{small_lower_key.end, small_key.end};
923 if (SplitOp::keep_upper()) {
924 // Note: create the upper section before the lower, as processing the lower may erase it
925 RANGE_ASSERT(!small_upper_key.empty());
926 const key_type upper_key{lower_key.end, key.end};
927 if (SplitOp::keep_lower()) {
928 construct_value(small_upper_key.begin, std::make_pair(upper_key, get_value(small_key.begin)->second));
929 } else {
930 // If we aren't keeping the lower, move instead of copy
931 construct_value(small_upper_key.begin, std::make_pair(upper_key, std::move(get_value(small_key.begin)->second)));
932 }
933 for (auto i = small_upper_key.begin; i < small_upper_key.end; ++i) {
934 ranges_[i] = small_upper_key;
935 }
936 } else {
937 // rewrite "end" to the next valid range (or end)
938 RANGE_ASSERT(SplitOp::keep_lower());
939 auto next = next_range(small_key.begin);
940 rerange(small_upper_key, SmallRange(next, small_lower_key.end));
941 // for any already invalid, we just rewrite the end.
942 rerange_end(small_upper_key.end, next, small_lower_key.end);
943 }
944 SmallIndex split_index;
945 if (SplitOp::keep_lower()) {
946 resize_value(small_key.begin, lower_key.end);
947 rerange_end(small_lower_key.begin, small_lower_key.end, small_lower_key.end);
948 split_index = small_lower_key.begin;
949 } else {
950 // Remove lower and rewrite empty space
951 RANGE_ASSERT(SplitOp::keep_upper());
952 destruct_value(small_key.begin);
953
954 // Rewrite prior empty space (if any)
955 auto prev = prev_range(small_key.begin);
956 SmallIndex limit = small_lower_key.end;
957 SmallIndex start = 0;
958 if (small_key.begin != 0) {
959 const auto &prev_start = ranges_[prev];
960 if (prev_start.valid()) {
961 // If there is a previous used range, the empty space starts after it.
962 start = prev_start.end;
963 } else {
964 RANGE_ASSERT(prev == 0); // prev_range only returns invalid ranges "off the front"
965 start = prev;
966 }
967 // for the section *prior* to key begin only need to rewrite the "invalid" begin (i.e. next "in use" begin)
968 rerange_begin(start, small_lower_key.begin, limit);
969 }
970 // for the section being erased rewrite the invalid range reflecting the empty space
971 rerange(small_lower_key, SmallRange(limit, start));
972 split_index = small_lower_key.end;
973 }
974
975 return iterator(this, split_index);
976 }
977
978 // For the value.first range rewrite the range...
979 template <typename Value>
980 iterator overwrite_range(Value &&value) {
981 const auto &key = value.first;
982
983 // Small map only has a restricted range supported
984 RANGE_ASSERT(in_bounds(key));
985 if (key.end > get_limit()) {
986 return end();
987 }
988
989 const auto small_key = make_small_range(key);
990 clear_out_range(small_key, /* valid clear range */ true);
991 construct_value(small_key.begin, std::forward<Value>(value));
992 return iterator(this, small_key.begin);
993 }
994
995 // We don't need a hint...
996 template <typename Value>
997 iterator overwrite_range(const iterator &hint, Value &&value) {
998 return overwrite_range(std::forward<Value>(value));
999 }
1000
1001 // For the range erase all contents within range, trimming any overlapping ranges
1002 iterator erase_range(const key_type &range) {
1003 // Small map only has a restricted range supported
1004 RANGE_ASSERT(in_bounds(range));
1005 if (range.end > get_limit() || range.empty()) {
1006 return end();
1007 }
1008 const auto empty = clear_out_range(make_small_range(range), /* valid clear range */ false);
1009 return iterator(this, empty.end);
1010 }
1011
1012 template <typename Iterator>
1013 iterator erase(const Iterator &first, const Iterator &last) {
1014 RANGE_ASSERT(this == first.map_);
1015 RANGE_ASSERT(this == last.map_);
1016 auto first_pos = !first.at_end() ? first.pos_ : limit_;
1017 auto last_pos = !last.at_end() ? last.pos_ : limit_;
1018 RANGE_ASSERT(first_pos <= last_pos);
1019 const SmallRange clear_me(first_pos, last_pos);
1020 if (!clear_me.empty()) {
1021 const SmallRange empty_range(find_empty_left(clear_me), last_pos);
1022 clear_and_set_range(empty_range.begin, empty_range.end, make_invalid_range(empty_range));
1023 }
1024 return iterator(this, last_pos);
1025 }
1026
1027 iterator lower_bound(const key_type &key) { return iterator(this, lower_bound_impl(this, key)); }
1028 const_iterator lower_bound(const key_type &key) const { return const_iterator(this, lower_bound_impl(this, key)); }
1029
1030 iterator upper_bound(const key_type &key) { return iterator(this, upper_bound_impl(this, key)); }
1031 const_iterator upper_bound(const key_type &key) const { return const_iterator(this, upper_bound_impl(this, key)); }
1032
1033 small_range_map(index_type limit = N) : size_(0), limit_(static_cast<SmallIndex>(limit)) {
1034 RANGE_ASSERT(limit <= std::numeric_limits<SmallIndex>::max());
1035 init_range();
1036 }
1037
1038 // Only valid for empty maps
1039 void set_limit(size_t limit) {
1040 RANGE_ASSERT(size_ == 0);
1041 RANGE_ASSERT(limit <= std::numeric_limits<SmallIndex>::max());
1042 limit_ = static_cast<SmallIndex>(limit);
1043 init_range();
1044 }
1045 inline index_type get_limit() const { return static_cast<index_type>(limit_); }
1046
1047 private:
1048 inline bool in_bounds(index_type index) const { return index < get_limit(); }
1049 inline bool in_bounds(const RangeKey &key) const { return key.begin < get_limit() && key.end <= get_limit(); }
1050
1051 inline SmallRange make_small_range(const RangeKey &key) const {
1052 RANGE_ASSERT(in_bounds(key));
1053 return SmallRange(static_cast<SmallIndex>(key.begin), static_cast<SmallIndex>(key.end));
1054 }
1055
1056 inline SmallRange make_invalid_range(const SmallRange &key) const { return SmallRange(key.end, key.begin); }
1057
1058 bool is_open(const key_type &key) const {
1059 // Remebering that invalid range.begin is the beginning the next used range.
1060 const auto small_key = make_small_range(key);
1061 const auto &range = ranges_[small_key.begin];
1062 return range.invalid() && small_key.end <= range.begin;
1063 }
1064 // Only call this with a valid beginning index
1065 iterator erase_impl(SmallIndex erase_index) {
1066 RANGE_ASSERT(erase_index == ranges_[erase_index].begin);
1067 auto &range = ranges_[erase_index];
1068 destruct_value(erase_index);
1069 // Need to update the ranges to accommodate the erasure
1070 SmallIndex prev = 0; // This is correct for the case erase_index is 0....
1071 if (erase_index != 0) {
1072 prev = prev_range(erase_index);
1073 // This works if prev is valid or invalid, because the invalid end will be either 0 (and correct) or the end of the
1074 // prior valid range and the valid end will be the end of the previous range (and thus correct)
1075 prev = ranges_[prev].end;
1076 }
1077 auto next = next_range(erase_index);
1078 // We have to be careful of next == limit_...
1079 if (next < limit_) {
1080 next = ranges_[next].begin;
1081 }
1082 // Rewrite both adjoining and newly empty entries
1083 SmallRange infill(next, prev);
1084 for (auto i = prev; i < next; ++i) {
1085 ranges_[i] = infill;
1086 }
1087 return iterator(this, next);
1088 }
1089 // This implements the "range lower bound logic" directly on the ranges
1090 template <typename Map>
1091 static SmallIndex lower_bound_impl(Map *const that, const key_type &key) {
1092 if (!that->in_bounds(key.begin)) return that->limit_;
1093 // If range is invalid, then begin points to the next valid (or end) with must be the lower bound
1094 // If range is valid, the begin points to a the lowest range that interects key
1095 const auto lb = that->ranges_[static_cast<SmallIndex>(key.begin)].begin;
1096 return lb;
1097 }
1098
1099 template <typename Map>
1100 static SmallIndex upper_bound_impl(Map *that, const key_type &key) {
1101 const auto limit = that->get_limit();
1102 if (key.end >= limit) return that->limit_; // at end
1103 const auto &end_range = that->ranges_[key.end];
1104 // If range is invalid, then begin points to the next valid (or end) with must be the upper bound (key < range because
1105 auto ub = end_range.begin;
1106 // If range is valid, the begin points to a range that may interects key, which is be upper iff range.begin == key.end
1107 if (end_range.valid() && (key.end > end_range.begin)) {
1108 // the ub candidate *intersects* the key, so we have to go to the next range.
1109 ub = that->next_range(end_range.begin);
1110 }
1111 return ub;
1112 }
1113
1114 // This is and inclusive "inuse", the entry itself
1115 SmallIndex find_inuse_right(const SmallRange &range) const {
1116 if (range.end >= limit_) return limit_;
1117 // if range is valid, begin is the first use (== range.end), else it's the first used after the invalid range
1118 return ranges_[range.end].begin;
1119 }
1120 // This is an exclusive "inuse", the end of the previous range
1121 SmallIndex find_inuse_left(const SmallRange &range) const {
1122 if (range.begin == 0) return 0;
1123 // if range is valid, end is the end of the first use (== range.begin), else it's the end of the in use range before the
1124 // invalid range
1125 return ranges_[range.begin - 1].end;
1126 }
1127 SmallRange find_empty(const SmallRange &range) const { return SmallRange(find_inuse_left(range), find_inuse_right(range)); }
1128
1129 // Clear out the given range, trimming as needed. The clear_range can be set as valid or invalid
1130 SmallRange clear_out_range(const SmallRange &clear_range, bool valid_clear_range) {
1131 // By copy to avoid reranging side affect
1132 auto first_range = ranges_[clear_range.begin];
1133
1134 // fast path for matching ranges...
1135 if (first_range == clear_range) {
1136 // clobber the existing value
1137 destruct_value(clear_range.begin);
1138 if (valid_clear_range) {
1139 return clear_range; // This is the overwrite fastpath for matching range
1140 } else {
1141 const auto empty_range = find_empty(clear_range);
1142 rerange(empty_range, make_invalid_range(empty_range));
1143 return empty_range;
1144 }
1145 }
1146
1147 SmallRange empty_left(clear_range.begin, clear_range.begin);
1148 SmallRange empty_right(clear_range.end, clear_range.end);
1149
1150 // The clearout is entirely within a single extant range, trim and set.
1151 if (first_range.valid() && first_range.includes(clear_range)) {
1152 // Shuffle around first_range, three cases...
1153 if (first_range.begin < clear_range.begin) {
1154 // We have a lower trimmed area to preserve.
1155 resize_value(first_range.begin, clear_range.begin);
1156 rerange_end(first_range.begin, clear_range.begin, clear_range.begin);
1157 if (first_range.end > clear_range.end) {
1158 // And an upper portion of first that needs to copy from the lower
1159 construct_value(clear_range.end, std::make_pair(key_type(clear_range.end, first_range.end),
1160 get_value(first_range.begin)->second));
1161 rerange_begin(clear_range.end, first_range.end, clear_range.end);
1162 } else {
1163 RANGE_ASSERT(first_range.end == clear_range.end);
1164 empty_right.end = find_inuse_right(clear_range);
1165 }
1166 } else {
1167 RANGE_ASSERT(first_range.end > clear_range.end);
1168 RANGE_ASSERT(first_range.begin == clear_range.begin);
1169 // Only an upper trimmed area to preserve, so move the first range value to the upper trim zone.
1170 resize_value_right(first_range, clear_range.end);
1171 rerange_begin(clear_range.end, first_range.end, clear_range.end);
1172 empty_left.begin = find_inuse_left(clear_range);
1173 }
1174 } else {
1175 if (first_range.valid()) {
1176 if (first_range.begin < clear_range.begin) {
1177 // Trim left.
1178 RANGE_ASSERT(first_range.end < clear_range.end); // we handled the "includes" case above
1179 resize_value(first_range.begin, clear_range.begin);
1180 rerange_end(first_range.begin, clear_range.begin, clear_range.begin);
1181 }
1182 } else {
1183 empty_left.begin = find_inuse_left(clear_range);
1184 }
1185
1186 // rewrite excluded portion of final range
1187 if (clear_range.end < limit_) {
1188 const auto &last_range = ranges_[clear_range.end];
1189 if (last_range.valid()) {
1190 // for a valid adjoining range we don't have to change empty_right, but we may have to trim
1191 if (last_range.begin < clear_range.end) {
1192 resize_value_right(last_range, clear_range.end);
1193 rerange_begin(clear_range.end, last_range.end, clear_range.end);
1194 }
1195 } else {
1196 // Note: invalid ranges "begin" and the next inuse range (or end)
1197 empty_right.end = last_range.begin;
1198 }
1199 }
1200 }
1201
1202 const SmallRange empty(empty_left.begin, empty_right.end);
1203 // Clear out the contents
1204 for (auto i = empty.begin; i < empty.end; ++i) {
1205 const auto &range = ranges_[i];
1206 if (range.begin == i) {
1207 RANGE_ASSERT(range.valid());
1208 // Clean up the backing store
1209 destruct_value(i);
1210 }
1211 }
1212
1213 // Rewrite the ranges
1214 if (valid_clear_range) {
1215 rerange_begin(empty_left.begin, empty_left.end, clear_range.begin);
1216 rerange(clear_range, clear_range);
1217 rerange_end(empty_right.begin, empty_right.end, clear_range.end);
1218 } else {
1219 rerange(empty, make_invalid_range(empty));
1220 }
1221 RANGE_ASSERT(empty.end == limit_ || ranges_[empty.end].valid());
1222 RANGE_ASSERT(empty.begin == 0 || ranges_[empty.begin - 1].valid());
1223 return empty;
1224 }
1225
1226 void init_range() {
1227 const SmallRange init_val(limit_, 0);
1228 for (SmallIndex i = 0; i < limit_; ++i) {
1229 ranges_[i] = init_val;
1230 in_use_[i] = false;
1231 }
1232 }
1233 value_type *get_value(SmallIndex index) {
1234 RANGE_ASSERT(index < limit_); // Must be inbounds
1235 return reinterpret_cast<value_type *>(&(backing_store_[index]));
1236 }
1237 const value_type *get_value(SmallIndex index) const {
1238 RANGE_ASSERT(index < limit_); // Must be inbounds
1239 RANGE_ASSERT(index == ranges_[index].begin); // Must be the record at begin
1240 return reinterpret_cast<const value_type *>(&(backing_store_[index]));
1241 }
1242
1243 template <typename Value>
1244 void construct_value(SmallIndex index, Value &&value) {
1245 RANGE_ASSERT(!in_use_[index]);
1246 new (get_value(index)) value_type(std::forward<Value>(value));
1247 in_use_[index] = true;
1248 ++size_;
1249 }
1250
1251 void destruct_value(SmallIndex index) {
1252 // there are times when the range and destruct logic clash... allow for double attempted deletes
1253 if (in_use_[index]) {
1254 RANGE_ASSERT(size_ > 0);
1255 --size_;
1256 get_value(index)->~value_type();
1257 in_use_[index] = false;
1258 }
1259 }
1260
1261 // No need to move around the value, when just the key is moving
1262 // Use the destructor/placement new just in case of a complex key with range's semantics
1263 // Note: Call resize before rewriting ranges_
1264 void resize_value(SmallIndex current_begin, index_type new_end) {
1265 // Destroy and rewrite the key in place
1266 RANGE_ASSERT(ranges_[current_begin].end != new_end);
1267 key_type new_key(current_begin, new_end);
1268 key_type *key = const_cast<key_type *>(&get_value(current_begin)->first);
1269 key->~key_type();
1270 new (key) key_type(new_key);
1271 }
1272
1273 inline void rerange_end(SmallIndex old_begin, SmallIndex new_end, SmallIndex new_end_value) {
1274 for (auto i = old_begin; i < new_end; ++i) {
1275 ranges_[i].end = new_end_value;
1276 }
1277 }
1278 inline void rerange_begin(SmallIndex new_begin, SmallIndex old_end, SmallIndex new_begin_value) {
1279 for (auto i = new_begin; i < old_end; ++i) {
1280 ranges_[i].begin = new_begin_value;
1281 }
1282 }
1283 inline void rerange(const SmallRange &range, const SmallRange &range_value) {
1284 for (auto i = range.begin; i < range.end; ++i) {
1285 ranges_[i] = range_value;
1286 }
1287 }
1288
1289 // for resize right need both begin and end...
1290 void resize_value_right(const SmallRange &current_range, index_type new_begin) {
1291 // Use move semantics for (potentially) heavyweight mapped_type's
1292 RANGE_ASSERT(current_range.begin != new_begin);
1293 // Move second from it's current location and update the first at the same time
1294 construct_value(static_cast<SmallIndex>(new_begin),
1295 std::make_pair(key_type(new_begin, current_range.end), std::move(get_value(current_range.begin)->second)));
1296 destruct_value(current_range.begin);
1297 }
1298
1299 // Now we can walk a range and rewrite it cleaning up any live contents
1300 void clear_and_set_range(SmallIndex rewrite_begin, SmallIndex rewrite_end, const SmallRange &new_range) {
1301 for (auto i = rewrite_begin; i < rewrite_end; ++i) {
1302 auto &range = ranges_[i];
1303 if (i == range.begin) {
1304 destruct_value(i);
1305 }
1306 range = new_range;
1307 }
1308 }
1309
1310 SmallIndex next_range(SmallIndex current) const {
1311 SmallIndex next = ranges_[current].end;
1312 // If the next range is invalid, skip to the next range, which *must* be (or be end)
1313 if ((next < limit_) && ranges_[next].invalid()) {
1314 // For invalid ranges, begin is the beginning of the next range
1315 next = ranges_[next].begin;
1316 RANGE_ASSERT(next == limit_ || ranges_[next].valid());
1317 }
1318 return next;
1319 }
1320
1321 SmallIndex prev_range(SmallIndex current) const {
1322 if (current == 0) {
1323 return 0;
1324 }
1325
1326 auto prev = current - 1;
1327 if (ranges_[prev].valid()) {
1328 // For valid ranges, the range denoted by begin (as that's where the backing store keeps values
1329 prev = ranges_[prev].begin;
1330 } else if (prev != 0) {
1331 // Invalid but not off the front, we can recur (only once) from the end of the prev range to get the answer
1332 // For invalid ranges this is the end of the previous range
1333 prev = prev_range(ranges_[prev].end);
1334 }
1335 return prev;
1336 }
1337
1338 friend iterator;
1339 friend const_iterator;
1340 // Stores range boundaries only
1341 // open ranges, stored as inverted, invalid range (begining of next, end of prev]
1342 // inuse(begin, end) for all entries on (begin, end]
1343 // Used for placement new of T for each range begin.
1344 struct alignas(alignof(value_type)) BackingStore {
1345 uint8_t data[sizeof(value_type)];
1346 };
1347
1348 SmallIndex size_;
1349 SmallIndex limit_;
1350 std::array<SmallRange, N> ranges_;
1351 std::array<BackingStore, N> backing_store_;
1352 std::array<bool, N> in_use_;
1353};
1354
John Zulauf11211402019-11-15 14:02:36 -07001355// Forward index iterator, tracking an index value and the appropos lower bound
1356// returns an index_type, lower_bound pair. Supports ++, offset, and seek affecting the index,
1357// lower bound updates as needed. As the index may specify a range for which no entry exist, dereferenced
1358// iterator includes an "valid" field, true IFF the lower_bound is not end() and contains [index, index +1)
1359//
1360// Must be explicitly invalidated when the underlying map is changed.
1361template <typename Map>
1362class cached_lower_bound_impl {
1363 using plain_map_type = typename std::remove_const<Map>::type; // Allow instatiation with const or non-const Map
1364 public:
1365 using iterator = const_correct_iterator<Map>;
1366 using key_type = typename plain_map_type::key_type;
1367 using mapped_type = typename plain_map_type::mapped_type;
1368 // Both sides of the return pair are const'd because we're returning references/pointers to the *internal* state
1369 // and we don't want and caller altering internal state.
1370 using index_type = typename Map::index_type;
1371 struct value_type {
1372 const index_type &index;
1373 const iterator &lower_bound;
1374 const bool &valid;
1375 value_type(const index_type &index_, const iterator &lower_bound_, bool &valid_)
1376 : index(index_), lower_bound(lower_bound_), valid(valid_) {}
1377 };
1378
1379 private:
1380 Map *const map_;
John Zulaufb58415b2019-12-09 15:02:32 -07001381 const iterator end_;
John Zulauf11211402019-11-15 14:02:36 -07001382 value_type pos_;
1383
1384 index_type index_;
1385 iterator lower_bound_;
1386 bool valid_;
1387
1388 bool is_valid() const { return includes(index_); }
1389
1390 // Allow reuse of a type with const semantics
1391 void set_value(const index_type &index, const iterator &it) {
John Zulauf6066f732019-11-21 13:15:10 -07001392 RANGE_ASSERT(it == lower_bound(index));
John Zulauf11211402019-11-15 14:02:36 -07001393 index_ = index;
1394 lower_bound_ = it;
1395 valid_ = is_valid();
1396 }
John Zulauf6066f732019-11-21 13:15:10 -07001397
John Zulauf11211402019-11-15 14:02:36 -07001398 void update(const index_type &index) {
John Zulauf6066f732019-11-21 13:15:10 -07001399 RANGE_ASSERT(lower_bound_ == lower_bound(index));
1400 index_ = index;
1401 valid_ = is_valid();
John Zulauf11211402019-11-15 14:02:36 -07001402 }
John Zulauf6066f732019-11-21 13:15:10 -07001403
John Zulauf11211402019-11-15 14:02:36 -07001404 inline iterator lower_bound(const index_type &index) { return map_->lower_bound(key_type(index, index + 1)); }
John Zulaufb58415b2019-12-09 15:02:32 -07001405 inline bool at_end(const iterator &it) const { return it == end_; }
John Zulauf11211402019-11-15 14:02:36 -07001406
1407 bool is_lower_than(const index_type &index, const iterator &it) { return at_end(it) || (index < it->first.end); }
1408
1409 public:
John Zulauf22aefed2021-03-11 18:14:35 -07001410 // The cached lower bound knows the parent map, and thus can tell us this...
1411 inline bool at_end() const { return at_end(lower_bound_); }
John Zulauf11211402019-11-15 14:02:36 -07001412 // includes(index) is a convenience function to test if the index would be in the currently cached lower bound
1413 bool includes(const index_type &index) const { return !at_end() && lower_bound_->first.includes(index); }
1414
1415 // The return is const because we are sharing the internal state directly.
1416 const value_type &operator*() const { return pos_; }
1417 const value_type *operator->() const { return &pos_; }
1418
1419 // Advance the cached location by 1
1420 cached_lower_bound_impl &operator++() {
1421 const index_type next = index_ + 1;
1422 if (is_lower_than(next, lower_bound_)) {
1423 update(next);
1424 } else {
1425 // if we're past pos_->second, next *must* be the new lower bound.
1426 // NOTE: that next can't be past end, so lower_bound_ isn't end.
1427 auto next_it = lower_bound_;
1428 ++next_it;
1429 set_value(next, next_it);
1430
1431 // However we *must* not be past next.
1432 RANGE_ASSERT(is_lower_than(next, next_it));
1433 }
1434
1435 return *this;
1436 }
1437
John Zulauf6066f732019-11-21 13:15:10 -07001438 // seek(index) updates lower_bound for index, updating lower_bound_ as needed.
1439 cached_lower_bound_impl &seek(const index_type &seek_to) {
1440 // Optimize seeking to forward
1441 if (index_ == seek_to) {
1442 // seek to self is a NOOP. To reset lower bound after a map change, use invalidate
1443 } else if (index_ < seek_to) {
1444 // See if the current or next ranges are the appropriate lower_bound... should be a common use case
1445 if (is_lower_than(seek_to, lower_bound_)) {
1446 // lower_bound_ is still the correct lower bound
1447 update(seek_to);
1448 } else {
1449 // Look to see if the next range is the new lower_bound (and we aren't at end)
1450 auto next_it = lower_bound_;
1451 ++next_it;
1452 if (is_lower_than(seek_to, next_it)) {
1453 // next_it is the correct new lower bound
1454 set_value(seek_to, next_it);
1455 } else {
1456 // We don't know where we are... and we aren't going to walk the tree looking for seek_to.
1457 set_value(seek_to, lower_bound(seek_to));
1458 }
1459 }
1460 } else {
1461 // General case... this is += so we're not implmenting optimized negative offset logic
1462 set_value(seek_to, lower_bound(seek_to));
1463 }
1464 return *this;
John Zulauf11211402019-11-15 14:02:36 -07001465 }
1466
1467 // Advance the cached location by offset.
1468 cached_lower_bound_impl &offset(const index_type &offset) {
1469 const index_type next = index_ + offset;
John Zulauf6066f732019-11-21 13:15:10 -07001470 return seek(next);
John Zulauf11211402019-11-15 14:02:36 -07001471 }
1472
1473 // invalidate() resets the the lower_bound_ cache, needed after insert/erase/overwrite/split operations
John Zulauf8bf934f2020-01-15 10:10:05 -07001474 // Pass index by value in case we are invalidating to index_ and set_value does a modify-in-place on index_
1475 cached_lower_bound_impl &invalidate(index_type index) {
John Zulauf6066f732019-11-21 13:15:10 -07001476 set_value(index, lower_bound(index));
1477 return *this;
John Zulauf11211402019-11-15 14:02:36 -07001478 }
1479
John Zulauf5637af72020-04-24 15:06:17 -06001480 // For times when the application knows what it's done to the underlying map... (with assert in set_value)
1481 cached_lower_bound_impl &invalidate(const iterator &hint, index_type index) {
1482 set_value(index, hint);
1483 return *this;
1484 }
1485
John Zulauf8bf934f2020-01-15 10:10:05 -07001486 cached_lower_bound_impl &invalidate() { return invalidate(index_); }
1487
John Zulauf11211402019-11-15 14:02:36 -07001488 // Allow a hint for a *valid* lower bound for current index
1489 // TODO: if the fail-over becomes a hot-spot, the hint logic could be far more clever (looking at previous/next...)
John Zulauf6066f732019-11-21 13:15:10 -07001490 cached_lower_bound_impl &invalidate(const iterator &hint) {
John Zulaufb58415b2019-12-09 15:02:32 -07001491 if ((hint != end_) && hint->first.includes(index_)) {
John Zulauf11211402019-11-15 14:02:36 -07001492 auto index = index_; // by copy set modifies in place
1493 set_value(index, hint);
1494 } else {
1495 invalidate();
1496 }
John Zulauf6066f732019-11-21 13:15:10 -07001497 return *this;
John Zulauf11211402019-11-15 14:02:36 -07001498 }
1499
1500 // The offset in index type to the next change (the end of the current range, or the transition from invalid to
1501 // valid. If invalid and at_end, returns index_type(0)
1502 index_type distance_to_edge() {
1503 if (valid_) {
1504 // Distance to edge of
1505 return lower_bound_->first.end - index_;
1506 } else if (at_end()) {
1507 return index_type(0);
1508 } else {
1509 return lower_bound_->first.begin - index_;
1510 }
1511 }
1512
John Zulauf62f10592020-04-03 12:20:02 -06001513 Map &map() { return *map_; }
1514 const Map &map() const { return *map_; }
1515
John Zulauf11211402019-11-15 14:02:36 -07001516 // Default constructed object reports valid (correctly) as false, but otherwise will fail (assert) under nearly any use.
John Zulaufb58415b2019-12-09 15:02:32 -07001517 cached_lower_bound_impl()
1518 : map_(nullptr), end_(), pos_(index_, lower_bound_, valid_), index_(0), lower_bound_(), valid_(false) {}
John Zulauf6066f732019-11-21 13:15:10 -07001519 cached_lower_bound_impl(Map &map, const index_type &index)
John Zulaufb58415b2019-12-09 15:02:32 -07001520 : map_(&map),
1521 end_(map.end()),
1522 pos_(index_, lower_bound_, valid_),
1523 index_(index),
1524 lower_bound_(lower_bound(index)),
1525 valid_(is_valid()) {}
John Zulauf11211402019-11-15 14:02:36 -07001526};
1527
1528template <typename CachedLowerBound, typename MappedType = typename CachedLowerBound::mapped_type>
1529const MappedType &evaluate(const CachedLowerBound &clb, const MappedType &default_value) {
1530 if (clb->valid) {
1531 return clb->lower_bound->second;
1532 }
1533 return default_value;
1534}
1535
John Zulauf62f10592020-04-03 12:20:02 -06001536// Split a range into pieces bound by the interection of the interator's range and the supplied range
1537template <typename Iterator, typename Map, typename Range>
1538Iterator split(Iterator in, Map &map, const Range &range) {
1539 assert(in != map.end()); // Not designed for use with invalid iterators...
1540 const auto in_range = in->first;
1541 const auto split_range = in_range & range;
1542
1543 if (split_range.empty()) return map.end();
1544
1545 auto pos = in;
1546 if (split_range.begin != in_range.begin) {
1547 pos = map.split(pos, split_range.begin, sparse_container::split_op_keep_both());
1548 ++pos;
1549 }
1550 if (split_range.end != in_range.end) {
1551 pos = map.split(pos, split_range.end, sparse_container::split_op_keep_both());
1552 }
1553 return pos;
1554}
1555
John Zulauf11211402019-11-15 14:02:36 -07001556// Parallel iterator
1557// Traverse to range maps over the the same range, but without assumptions of aligned ranges.
1558// ++ increments to the next point where on of the two maps changes range, giving a range over which the two
1559// maps do not transition ranges
John Zulauf2076e812020-01-08 14:55:54 -07001560template <typename MapA, typename MapB = MapA, typename KeyType = typename MapA::key_type>
John Zulauf11211402019-11-15 14:02:36 -07001561class parallel_iterator {
1562 public:
1563 using key_type = KeyType;
1564 using index_type = typename key_type::index_type;
1565
1566 // The traits keep the iterator/const_interator consistent with the constness of the map.
1567 using map_type_A = MapA;
1568 using plain_map_type_A = typename std::remove_const<MapA>::type; // Allow instatiation with const or non-const Map
1569 using key_type_A = typename plain_map_type_A::key_type;
1570 using index_type_A = typename plain_map_type_A::index_type;
1571 using iterator_A = const_correct_iterator<map_type_A>;
1572 using lower_bound_A = cached_lower_bound_impl<map_type_A>;
1573
1574 using map_type_B = MapB;
1575 using plain_map_type_B = typename std::remove_const<MapB>::type;
1576 using key_type_B = typename plain_map_type_B::key_type;
1577 using index_type_B = typename plain_map_type_B::index_type;
1578 using iterator_B = const_correct_iterator<map_type_B>;
1579 using lower_bound_B = cached_lower_bound_impl<map_type_B>;
1580
1581 // This is the value we'll always be returning, but the referenced object will be updated by the operations
1582 struct value_type {
1583 const key_type &range;
1584 const lower_bound_A &pos_A;
1585 const lower_bound_B &pos_B;
1586 value_type(const key_type &range_, const lower_bound_A &pos_A_, const lower_bound_B &pos_B_)
1587 : range(range_), pos_A(pos_A_), pos_B(pos_B_) {}
1588 };
1589
1590 private:
1591 lower_bound_A pos_A_;
1592 lower_bound_B pos_B_;
1593 key_type range_;
1594 value_type pos_;
1595 index_type compute_delta() {
1596 auto delta_A = pos_A_.distance_to_edge();
1597 auto delta_B = pos_B_.distance_to_edge();
1598 index_type delta_min;
1599
1600 // If either A or B are at end, there distance is *0*, so shouldn't be considered in the "distance to edge"
1601 if (delta_A == 0) { // lower A is at end
1602 delta_min = static_cast<index_type>(delta_B);
1603 } else if (delta_B == 0) { // lower B is at end
1604 delta_min = static_cast<index_type>(delta_A);
1605 } else {
1606 // Neither are at end, use the nearest edge, s.t. over this range A and B are both constant
1607 delta_min = std::min(static_cast<index_type>(delta_A), static_cast<index_type>(delta_B));
1608 }
1609 return delta_min;
1610 }
1611
1612 public:
1613 // Default constructed object will report range empty (for end checks), but otherwise is unsafe to use
1614 parallel_iterator() : pos_A_(), pos_B_(), range_(), pos_(range_, pos_A_, pos_B_) {}
1615 parallel_iterator(map_type_A &map_A, map_type_B &map_B, index_type index)
1616 : pos_A_(map_A, static_cast<index_type_A>(index)),
1617 pos_B_(map_B, static_cast<index_type_B>(index)),
1618 range_(index, index + compute_delta()),
1619 pos_(range_, pos_A_, pos_B_) {}
1620
1621 // Advance to the next spot one of the two maps changes
1622 parallel_iterator &operator++() {
1623 const auto start = range_.end; // we computed this the last time we set range
1624 const auto delta = range_.distance(); // we computed this the last time we set range
1625 RANGE_ASSERT(delta != 0); // Trying to increment past end
1626
1627 pos_A_.offset(static_cast<index_type_A>(delta));
1628 pos_B_.offset(static_cast<index_type_B>(delta));
1629
1630 range_ = key_type(start, start + compute_delta()); // find the next boundary (must be after offset)
1631 RANGE_ASSERT(pos_A_->index == start);
1632 RANGE_ASSERT(pos_B_->index == start);
1633
1634 return *this;
1635 }
1636
1637 // Seeks to a specific index in both maps reseting range. Cannot guarantee range.begin is on edge boundary,
1638 /// but range.end will be. Lower bound objects assumed to invalidate their cached lower bounds on seek.
1639 parallel_iterator &seek(const index_type &index) {
1640 pos_A_.seek(static_cast<index_type_A>(index));
1641 pos_B_.seek(static_cast<index_type_B>(index));
1642 range_ = key_type(index, index + compute_delta());
1643 RANGE_ASSERT(pos_A_->index == index);
1644 RANGE_ASSERT(pos_A_->index == pos_B_->index);
1645 return *this;
1646 }
1647
1648 // Invalidates the lower_bound caches, reseting range. Cannot guarantee range.begin is on edge boundary,
1649 // but range.end will be.
1650 parallel_iterator &invalidate() {
1651 const index_type start = range_.begin;
1652 seek(start);
1653 return *this;
1654 }
John Zulauf5637af72020-04-24 15:06:17 -06001655
John Zulauf11211402019-11-15 14:02:36 -07001656 parallel_iterator &invalidate_A() {
1657 const index_type index = range_.begin;
John Zulauf8bf934f2020-01-15 10:10:05 -07001658 pos_A_.invalidate(static_cast<index_type_A>(index));
John Zulauf11211402019-11-15 14:02:36 -07001659 range_ = key_type(index, index + compute_delta());
1660 return *this;
1661 }
John Zulauf5637af72020-04-24 15:06:17 -06001662
1663 parallel_iterator &invalidate_A(const iterator_A &hint) {
1664 const index_type index = range_.begin;
1665 pos_A_.invalidate(hint, static_cast<index_type_A>(index));
1666 range_ = key_type(index, index + compute_delta());
1667 return *this;
1668 }
1669
John Zulauf11211402019-11-15 14:02:36 -07001670 parallel_iterator &invalidate_B() {
1671 const index_type index = range_.begin;
John Zulauf8bf934f2020-01-15 10:10:05 -07001672 pos_B_.invalidate(static_cast<index_type_B>(index));
John Zulauf11211402019-11-15 14:02:36 -07001673 range_ = key_type(index, index + compute_delta());
1674 return *this;
1675 }
1676
John Zulauf5637af72020-04-24 15:06:17 -06001677 parallel_iterator &invalidate_B(const iterator_B &hint) {
1678 const index_type index = range_.begin;
1679 pos_B_.invalidate(hint, static_cast<index_type_B>(index));
1680 range_ = key_type(index, index + compute_delta());
1681 return *this;
1682 }
1683
John Zulauf62f10592020-04-03 12:20:02 -06001684 parallel_iterator &trim_A() {
1685 if (pos_A_->valid && (range_ != pos_A_->lower_bound->first)) {
1686 split(pos_A_->lower_bound, pos_A_.map(), range_);
1687 invalidate_A();
1688 }
1689 return *this;
1690 }
1691
John Zulauf11211402019-11-15 14:02:36 -07001692 // The return is const because we are sharing the internal state directly.
1693 const value_type &operator*() const { return pos_; }
1694 const value_type *operator->() const { return &pos_; }
1695};
1696
Jeremy Gebbena72a0b12021-04-13 16:45:09 -06001697template <typename DstRangeMap, typename SrcRangeMap, typename Updater,
1698 typename SourceIterator = typename SrcRangeMap::const_iterator>
1699bool splice(DstRangeMap &to, const SrcRangeMap &from, SourceIterator begin, SourceIterator end, const Updater &updater) {
John Zulauf11211402019-11-15 14:02:36 -07001700 if (from.empty() || (begin == end) || (begin == from.cend())) return false; // nothing to merge.
1701
Jeremy Gebbena72a0b12021-04-13 16:45:09 -06001702 using ParallelIterator = parallel_iterator<DstRangeMap, const SrcRangeMap>;
1703 using Key = typename SrcRangeMap::key_type;
1704 using CachedLowerBound = cached_lower_bound_impl<DstRangeMap>;
1705 using ConstCachedLowerBound = cached_lower_bound_impl<const SrcRangeMap>;
1706 ParallelIterator par_it(to, from, begin->first.begin);
John Zulauf11211402019-11-15 14:02:36 -07001707 bool updated = false;
1708 while (par_it->range.non_empty() && par_it->pos_B->lower_bound != end) {
1709 const Key &range = par_it->range;
1710 const CachedLowerBound &to_lb = par_it->pos_A;
1711 const ConstCachedLowerBound &from_lb = par_it->pos_B;
1712 if (from_lb->valid) {
1713 auto read_it = from_lb->lower_bound;
1714 auto write_it = to_lb->lower_bound;
1715 // Because of how the parallel iterator walk, "to" is valid over the whole range or it isn't (ranges don't span
1716 // transitions between map entries or between valid and invalid ranges)
1717 if (to_lb->valid) {
Jeremy Gebben65f83fb2021-05-12 14:05:26 -06001718 if (write_it->first == range) {
1719 // if the source and destination ranges match we can overwrite everything
1720 updated |= updater.update(write_it->second, read_it->second);
1721 } else {
1722 // otherwise we need to split the destination range.
1723 auto value_to_update = write_it->second; // intentional copy
1724 updated |= updater.update(value_to_update, read_it->second);
Jeremy Gebben53585a62021-06-30 14:50:43 -06001725 auto intersected_range = write_it->first & range;
1726 to.overwrite_range(to_lb->lower_bound, std::make_pair(intersected_range, value_to_update));
Jeremy Gebben65f83fb2021-05-12 14:05:26 -06001727 par_it.invalidate_A(); // we've changed map 'to' behind to_lb's back... let it know.
1728 }
John Zulauf11211402019-11-15 14:02:36 -07001729 } else {
1730 // Insert into the gap.
Jeremy Gebbena72a0b12021-04-13 16:45:09 -06001731 auto opt = updater.insert(read_it->second);
1732 if (opt) {
1733 to.insert(write_it, std::make_pair(range, std::move(*opt)));
1734 updated = true;
1735 par_it.invalidate_A(); // we've changed map 'to' behind to_lb's back... let it know.
1736 }
John Zulauf11211402019-11-15 14:02:36 -07001737 }
1738 }
1739 ++par_it; // next range over which both 'to' and 'from' stay constant
1740 }
1741 return updated;
1742}
1743// And short hand for "from begin to end"
Jeremy Gebbena72a0b12021-04-13 16:45:09 -06001744template <typename DstRangeMap, typename SrcRangeMap, typename Updater>
1745bool splice(DstRangeMap &to, const SrcRangeMap &from, const Updater &updater) {
1746 return splice(to, from, from.cbegin(), from.cend(), updater);
1747}
1748
1749template <typename T>
1750struct update_prefer_source {
1751 bool update(T &dst, const T &src) const {
1752 if (dst != src) {
1753 dst = src;
1754 return true;
1755 }
1756 return false;
1757 }
1758
1759 layer_data::optional<T> insert(const T &src) const { return layer_data::optional<T>(layer_data::in_place, src); }
1760};
1761
1762template <typename T>
1763struct update_prefer_dest {
1764 bool update(T &dst, const T &src) const { return false; }
1765
1766 layer_data::optional<T> insert(const T &src) const { return layer_data::optional<T>(layer_data::in_place, src); }
1767};
1768
1769template <typename RangeMap, typename SourceIterator = typename RangeMap::const_iterator>
1770bool splice(RangeMap &to, const RangeMap &from, value_precedence arbiter, SourceIterator begin, SourceIterator end) {
1771 if (arbiter == value_precedence::prefer_source) {
1772 return splice(to, from, from.cbegin(), from.cend(), update_prefer_source<typename RangeMap::mapped_type>());
1773 } else {
1774 return splice(to, from, from.cbegin(), from.cend(), update_prefer_dest<typename RangeMap::mapped_type>());
1775 }
1776}
1777
1778// And short hand for "from begin to end"
John Zulauf11211402019-11-15 14:02:36 -07001779template <typename RangeMap>
Jeremy Gebbena72a0b12021-04-13 16:45:09 -06001780bool splice(RangeMap &to, const RangeMap &from, value_precedence arbiter) {
John Zulauf11211402019-11-15 14:02:36 -07001781 return splice(to, from, arbiter, from.cbegin(), from.cend());
1782}
1783
John Zulauf81408f12019-11-27 16:40:27 -07001784template <typename Map, typename Range = typename Map::key_type, typename MapValue = typename Map::mapped_type>
1785bool update_range_value(Map &map, const Range &range, MapValue &&value, value_precedence precedence) {
1786 using CachedLowerBound = typename sparse_container::cached_lower_bound_impl<Map>;
1787 CachedLowerBound pos(map, range.begin);
1788
1789 bool updated = false;
1790 while (range.includes(pos->index)) {
1791 if (!pos->valid) {
1792 if (precedence == value_precedence::prefer_source) {
1793 // We can convert this into and overwrite...
1794 map.overwrite_range(pos->lower_bound, std::make_pair(range, std::forward<MapValue>(value)));
1795 return true;
1796 }
1797 // Fill in the leading space (or in the case of pos at end the trailing space
1798 const auto start = pos->index;
1799 auto it = pos->lower_bound;
1800 const auto limit = (it != map.end()) ? std::min(it->first.begin, range.end) : range.end;
1801 map.insert(it, std::make_pair(Range(start, limit), value));
1802 // We inserted before pos->lower_bound, so pos->lower_bound isn't invalid, but the associated index *is* and seek
1803 // will fix this (and move the state to valid)
1804 pos.seek(limit);
1805 updated = true;
1806 }
1807 // Note that after the "fill" operation pos may have become valid so we check again
1808 if (pos->valid) {
1809 if ((precedence == value_precedence::prefer_source) && (pos->lower_bound->second != value)) {
1810 // We've found a place where we're changing the value, at this point might as well simply over write the range
John Zulaufb58415b2019-12-09 15:02:32 -07001811 // and be done with it. (save on later merge operations....)
Tony-LunarG0d4e65d2020-01-28 11:38:11 -07001812 pos.seek(range.begin);
John Zulauf81408f12019-11-27 16:40:27 -07001813 map.overwrite_range(pos->lower_bound, std::make_pair(range, std::forward<MapValue>(value)));
1814 return true;
John Zulaufb58415b2019-12-09 15:02:32 -07001815
John Zulauf81408f12019-11-27 16:40:27 -07001816 } else {
1817 // "prefer_dest" means don't overwrite existing values, so we'll skip this interval.
1818 // Point just past the end of this section, if it's within the given range, it will get filled next iteration
1819 // ++pos could move us past the end of range (which would exit the loop) so we don't use it.
1820 pos.seek(pos->lower_bound->first.end);
1821 }
1822 }
1823 }
1824 return updated;
1825}
1826
John Zulauf90040ec2022-09-21 14:46:54 -06001827// combines directly adjacent ranges with equal RangeMap::mapped_type .
1828template <typename RangeMap>
1829void consolidate(RangeMap &map) {
1830 using Value = typename RangeMap::value_type;
1831 using Key = typename RangeMap::key_type;
1832 using It = typename RangeMap::iterator;
1833
1834 It current = map.begin();
1835 const It map_end = map.end();
1836
1837 // To be included in a merge range there must be no gap in the Key space, and the mapped_type values must match
1838 auto can_merge = [](const It &last, const It &cur) {
1839 return cur->first.begin == last->first.end && cur->second == last->second;
1840 };
1841
1842 while (current != map_end) {
1843 // Establish a trival merge range at the current location, advancing current. Merge range is inclusive of merge_last
1844 const It merge_first = current;
1845 It merge_last = current;
1846 ++current;
1847
1848 // Expand the merge range as much as possible
1849 while (current != map_end && can_merge(merge_last, current)) {
1850 merge_last = current;
1851 ++current;
1852 }
1853
1854 // Current isn't in the active merge range. If there is a non-trivial merge range, we resolve it here.
1855 if (merge_first != merge_last) {
1856 // IFF there is more than one range in (merge_first, merge_last) <- again noting the *inclusive* last
1857 // Create a new Val spanning (first, last), substitute it for the multiple entries.
1858 Value merged_value = std::make_pair(Key(merge_first->first.begin, merge_last->first.end), merge_last->second);
1859 // Note that current points to merge_last + 1, and is valid even if at map_end for these operations
1860 map.erase(merge_first, current);
1861 map.insert(current, std::move(merged_value));
1862 }
1863 }
1864}
1865
John Zulauf11211402019-11-15 14:02:36 -07001866} // namespace sparse_container
1867
1868#endif