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