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