-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathDiscreteRange.h
More file actions
1473 lines (1289 loc) · 46.2 KB
/
DiscreteRange.h
File metadata and controls
1473 lines (1289 loc) · 46.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// Copyright 2014 Network Geographics
/** @file
Support classes for creating intervals of numeric values.
The template class can be used directly via a @c typedef or
used as a base class if additional functionality is required.
*/
#pragma once
#include <limits>
#include <functional>
#include "swoc/swoc_version.h"
#include "swoc/swoc_meta.h"
#include "swoc/RBTree.h"
#include "swoc/MemArena.h"
namespace swoc { inline namespace SWOC_VERSION_NS {
namespace detail {
/// A set of metafunctions to get extrema from a metric type.
/// These probe for a static member and falls back to @c std::numeric_limits.
/// @{
template<typename M>
constexpr auto
maximum(meta::CaseTag<0>) -> M {
return std::numeric_limits<M>::max();
}
template<typename M>
constexpr auto
maximum(meta::CaseTag<1>) -> decltype(M::MAX) {
return M::MAX;
}
template<typename M>
constexpr M
maximum() {
return maximum<M>(meta::CaseArg);
}
template<typename M>
constexpr auto
minimum(meta::CaseTag<0>) -> M {
return std::numeric_limits<M>::min();
}
template<typename M>
constexpr auto
minimum(meta::CaseTag<1>) -> decltype(M::MIN) {
return M::MIN;
}
template<typename M>
constexpr M
minimum() {
return minimum<M>(meta::CaseArg);
}
/// @}
} // namespace detail
/// Relationship between two intervals.
enum class DiscreteRangeRelation : uint8_t {
NONE, ///< No common elements.
EQUAL, ///< Identical ranges.
SUBSET, ///< All elements in LHS are also in RHS.
SUPERSET, ///< Every element in RHS is in LHS.
OVERLAP, ///< There exists at least one element in both LHS and RHS.
ADJACENT ///< The two intervals are adjacent and disjoint.
};
/// Relationship between one edge of an interval and the "opposite" edge of another.
enum class DiscreteRangeEdgeRelation : uint8_t {
NONE, ///< Edge is on the opposite side of the relating edge.
GAP, ///< There is a gap between the edges.
ADJ, ///< The edges are adjacent.
OVLP, ///< Edge is inside interval.
};
/** A range over a discrete finite value metric.
@tparam T The type for the range values.
The template argument @a T is presumed to
- be completely ordered.
- have prefix increment and decrement operators
- equality operator
- have value semantics
- have minimum and maximum values either
- members @c MIN and @c MAX that define static instances
- support @c std::numeric_limits<T>
The interval is always an inclusive (closed) contiguous interval,
defined by the minimum and maximum values contained in the interval.
An interval can be @em empty and contain no values. This is the state
of a default constructed interval.
*/
template<typename T> class DiscreteRange {
using self_type = DiscreteRange;
protected:
T _min; ///< The minimum value in the interval
T _max; ///< the maximum value in the interval
public:
using metric_type = T; ///< Export metric type.
using Relation = DiscreteRangeRelation; ///< Import type for convenience.
using EdgeRelation = DiscreteRangeEdgeRelation; ///< Import type for convenience.
/** Default constructor.
An invalid (empty) range is constructed.
*/
constexpr DiscreteRange() : _min(detail::maximum<T>()), _max(detail::minimum<T>()) {}
/** Construct a singleton range.
* @param value Single value to be contained by the interval.
*
* @note Not marked @c explicit and so serves as a conversion from scalar values to an interval.
*/
constexpr DiscreteRange(T const& value) : _min(value), _max(value) {};
/** Constructor.
*
* @param min Minimum value in the interval.
* @param max Maximum value in the interval.
*/
constexpr DiscreteRange(T const& min, T const& max) : _min(min), _max(max) {}
~DiscreteRange() = default;
/** Check if there are no values in the range.
*
* @return @c true if the range is empty (contains no values), @c false if it contains at least
* one value.
*/
bool empty() const;
self_type& assign(metric_type const& min, metric_type const& max);
/// Set the interval to be a singleton.
self_type& assign(metric_type const& singleton);
self_type& assign_min(metric_type const& min);
self_type& assign_max(metric_type const& max);
/** Decrement the maximum value.
*
* @return @a this.
*/
self_type& clip_max() {
--_max;
return *this;
}
/** Get the minimum value in the interval.
@note The return value is unspecified if the interval is empty.
*/
metric_type const& min() const;
/** Get the maximum value in the interval.
@note The return value is unspecified if the interval is empty.
*/
metric_type const& max() const;
/// Test for equality.
bool operator == (self_type const& that) const {
return _min == that._min && _max == that._max;
}
/// Test for inequality.
bool operator != (self_type const& that) const {
return _min != that._min | _max != that._max;
}
/** Check if a value is in @a this range.
*
* @param m Metric value to check.
* @return @c true if @a m is in the range, @c false if not.
*/
bool contains(metric_type const& m) {
return _min <= m && m <= _max;
}
/** Logical intersection test for two intervals.
@return @c true if there is at least one common value in the
two intervals, @c false otherwise.
*/
bool has_intersection_with(self_type const& that) const;
/** Compute the intersection of two intervals
@return The interval consisting of values that are contained by
both intervals. This may be the empty interval if the intervals
are disjoint.
@internal Co-variant
*/
self_type intersection(self_type const& that) const;
/** Test for adjacency.
@return @c true if the intervals are adjacent.
@note Only disjoint intervals can be adjacent.
*/
bool is_adjacent_to(self_type const& that) const;
/** Test for @a this being adjacent on the left of @a that.
*
* @param that Range to check for adjacency.
* @return @c true if @a this ends exactly the value before @a that begins.
*/
bool is_left_adjacent_to(self_type const& that) const;
//! Test if the union of two intervals is also an interval.
bool has_union(self_type const& that) const;
/** Test if an interval is a superset of or equal to another.
@return @c true if every value in @c that is also in @c this.
*/
bool is_superset_of(self_type const& that) const;
/** Test if an interval is a subset or equal to another.
@return @c true if every value in @c this is also in @c that.
*/
bool is_subset_of(self_type const& that) const;
/** Test if an interval is a strict superset of another.
@return @c true if @c this is strictly a superset of @a rhs.
*/
bool is_strict_superset_of(self_type const& that) const;
/** Test if an interval is a strict subset of another.
@return @c true if @c this is strictly a subset of @a that.
*/
bool is_strict_subset_of(self_type const& that) const;
/** Determine the relationship between @c this and @a that interval.
@return The relationship type.
*/
Relation relationship(self_type const& that) const;
/** Determine the relationship of the left edge of @a that with @a this.
*
* @param that The other interval.
* @return The edge relationship.
*
* This checks the right edge of @a this against the left edge of @a that.
*
* - GAP: @a that left edge is right of @a this.
* - ADJ: @a that left edge is right adjacent to @a this.
* - OVLP: @a that left edge is inside @a this.
* - NONE: @a that left edge is left of @a this.
*/
EdgeRelation left_edge_relationship(self_type const& that) const {
if (_max < that._max) {
return ++metric_type(_max) < that._max ? EdgeRelation::GAP : EdgeRelation::ADJ;
}
return _min >= that._min ? EdgeRelation::NONE : EdgeRelation::OVLP;
}
/** Compute the convex hull of this interval and another one.
@return The smallest interval that is a superset of @c this
and @a that interval.
@internal Co-variant
*/
self_type hull(self_type const& that) const;
//! Check if the interval is exactly one element.
bool is_singleton() const;
/** Test for empty, operator form.
@return @c true if the interval is empty, @c false otherwise.
*/
bool operator!() const { return _min > _max; }
/** Test for non-empty.
*
* @return @c true if there values in the range, @c false if no values in the range.
*/
explicit operator bool() const { return _min <= _max; }
/// @return @c true if the range is maximal, @c false otherwise.
bool is_maximal() const;
/** Clip interval.
Remove all element in @c this interval not in @a that interval.
*/
self_type& operator&=(self_type const& that);
/** Convex hull.
Extend interval to cover all elements in @c this and @a that.
*/
self_type& operator|=(self_type const& that);
self_type& clear() {
_min = detail::maximum<T>();
_max = detail::minimum<T>();
return *this;
}
/** Functor for lexicographic ordering.
If, for some reason, an interval needs to be put in a container
that requires a strict weak ordering, the default @c operator @c < will
not work. Instead, this functor should be used as the comparison
functor. E.g.
@code
typedef std::set<Interval<T>, Interval<T>::lexicographic_order> container;
@endcode
@note Lexicographic ordering is a standard tuple ordering where the
order is determined by pairwise comparing the elements of both tuples.
The first pair of elements that are not equal determine the ordering
of the overall tuples.
*/
struct lexicographic_order : public std::binary_function<self_type, self_type, bool> {
//! Functor operator.
bool operator()(self_type const& lhs, self_type const& rhs) const;
};
};
template<typename T>
bool
DiscreteRange<T>::lexicographic_order::operator()(DiscreteRange::self_type const& lhs
, DiscreteRange::self_type const& rhs) const {
return lhs._min == rhs._min ? lhs._max < rhs._max : lhs._min < rhs._min;
}
template<typename T>
DiscreteRange<T>&
DiscreteRange<T>::assign(metric_type const& min, metric_type const& max) {
_min = min;
_max = max;
return *this;
}
template<typename T>
DiscreteRange<T>
DiscreteRange<T>::hull(DiscreteRange::self_type const& that) const {
// need to account for invalid ranges.
return !*this ? that : !that ? *this
: self_type(std::min(_min, that._min), std::max(_max, that._max));
}
template<typename T>
typename DiscreteRange<T>::Relation
DiscreteRange<T>::relationship(self_type const& that) const {
Relation retval = Relation::NONE;
if (this->has_intersection(that)) {
if (*this == that)
retval = Relation::EQUAL;
else if (this->is_subset_of(that))
retval = Relation::SUBSET;
else if (this->is_superset_of(that))
retval = Relation::SUPERSET;
else
retval = Relation::OVERLAP;
} else if (this->is_adjacent_to(that)) {
retval = Relation::ADJACENT;
}
return retval;
}
template<typename T>
DiscreteRange<T>&
DiscreteRange<T>::assign(metric_type const& singleton) {
_min = singleton;
_max = singleton;
return *this;
}
template<typename T>
DiscreteRange<T>&
DiscreteRange<T>::assign_min(metric_type const& min) {
_min = min;
return *this;
}
template<typename T>
bool
DiscreteRange<T>::is_singleton() const {
return _min == _max;
}
template<typename T>
bool
DiscreteRange<T>::empty() const {
return _min > _max;
}
template<typename T>
bool
DiscreteRange<T>::is_maximal() const {
return _min == detail::minimum<T>() && _max == detail::maximum<T>();
}
template<typename T>
bool
DiscreteRange<T>::is_strict_superset_of(DiscreteRange::self_type const& that) const {
return (_min < that._min && that._max <= _max) || (_min <= that._min && that._max < _max);
}
template<typename T>
DiscreteRange<T>&
DiscreteRange<T>::operator|=(DiscreteRange::self_type const& that) {
if (!*this) {
*this = that;
} else if (that) {
if (that._min < _min) {
_min = that._min;
}
if (that._max > _max) {
_max = that._max;
}
}
return *this;
}
template<typename T>
DiscreteRange<T>&
DiscreteRange<T>::assign_max(metric_type const& max) {
_max = max;
return *this;
}
template<typename T>
bool
DiscreteRange<T>::is_strict_subset_of(DiscreteRange::self_type const& that) const {
return that.is_strict_superset_of(*this);
}
template<typename T>
bool
DiscreteRange<T>::is_subset_of(DiscreteRange::self_type const& that) const {
return that.is_superset_of(*this);
}
template<typename T>
T const&
DiscreteRange<T>::min() const {
return _min;
}
template<typename T>
T const&
DiscreteRange<T>::max() const {
return _max;
}
template<typename T>
bool
DiscreteRange<T>::has_union(DiscreteRange::self_type const& that) const {
return this->has_intersection(that) || this->is_adjacent_to(that);
}
template<typename T>
DiscreteRange<T>&
DiscreteRange<T>::operator&=(DiscreteRange::self_type const& that) {
*this = this->intersection(that);
return *this;
}
template<typename T>
bool
DiscreteRange<T>::has_intersection_with(DiscreteRange::self_type const& that) const {
return (that._min <= _min && _min <= that._max) || (_min <= that._min && that._min <= _max);
}
template<typename T>
bool
DiscreteRange<T>::is_superset_of(DiscreteRange::self_type const& that) const {
return _min <= that._min && that._max <= _max;
}
template<typename T>
bool
DiscreteRange<T>::is_adjacent_to(DiscreteRange::self_type const& that) const {
return this->is_left_adjacent_to(that) || that.is_left_adjacent_to(*this);
}
template<typename T>
bool
DiscreteRange<T>::is_left_adjacent_to(DiscreteRange::self_type const& that) const {
/* Need to be careful here. We don't know much about T and we certainly don't know if "t+1"
* even compiles for T. We do require the increment operator, however, so we can use that on a
* copy to get the equivalent of t+1 for adjacency testing. We must also handle the possibility
* T has a modulus and not depend on ++t > t always being true. However, we know that if t1 >
* t0 then ++t0 > t0.
*/
return _max < that._min && ++metric_type(_max) == that._min;
}
template<typename T>
DiscreteRange<T>
DiscreteRange<T>::intersection(DiscreteRange::self_type const& that) const {
return {std::max(_min, that._min), std::min(_max, that._max)};
}
/** Equality.
Two intervals are equal if their min and max values are equal.
@relates interval
*/
template<typename T>
bool
operator==(DiscreteRange<T> const& lhs, DiscreteRange<T> const& rhs) {
return lhs.min() == rhs.min() && lhs.max() == rhs.max();
}
/** Inequality.
Two intervals are equal if their min and max values are equal.
@relates interval
*/
template<typename T>
bool
operator!=(DiscreteRange<T> const& lhs, DiscreteRange<T> const& rhs) {
return !(lhs == rhs);
}
/** Operator form of logical intersection test for two intervals.
@return @c true if there is at least one common value in the
two intervals, @c false otherwise.
@note Yeah, a bit ugly, using an operator that is not standardly
boolean but
- There don't seem to be better choices (&&,|| not good)
- The assymmetry between intersection and union makes for only three natural operators
- ^ at least looks like "intersects"
@relates interval
*/
template<typename T>
bool
operator^(DiscreteRange<T> const& lhs, DiscreteRange<T> const& rhs) {
return lhs.has_intersection(rhs);
}
/** Containment ordering.
@return @c true if @c this is a strict subset of @a rhs.
@note Equivalent to @c is_strict_subset.
@relates interval
*/
template<typename T>
inline bool
operator<(DiscreteRange<T> const& lhs, DiscreteRange<T> const& rhs) {
return rhs.is_strict_superset_of(lhs);
}
/** Containment ordering.
@return @c true if @c this is a subset of @a rhs.
@note Equivalent to @c is_subset.
@relates interval
*/
template<typename T>
inline bool
operator<=(DiscreteRange<T> const& lhs, DiscreteRange<T> const& rhs) {
return rhs.is_superset_of(lhs);
}
/** Containment ordering.
@return @c true if @c this is a strict superset of @a rhs.
@note Equivalent to @c is_strict_superset.
@relates interval
*/
template<typename T>
inline bool
operator>(DiscreteRange<T> const& lhs, DiscreteRange<T> const& rhs) {
return lhs.is_strict_superset_of(rhs);
}
/** Containment ordering.
@return @c true if @c this is a superset of @a rhs.
@note Equivalent to @c is_superset.
@relates interval
*/
template<typename T>
inline bool
operator>=(DiscreteRange<T> const& lhs, DiscreteRange<T> const& rhs) {
return lhs.is_superset_of(rhs);
}
/** A space for a discrete @c METRIC.
*
* @tparam METRIC Value type for the space.
* @tparam PAYLOAD Data stored with values in the space.
*
* This is a range based mapping of all values in @c METRIC (the "space") to @c PAYLOAD.
*
* @c PAYLOAD is presumed to be relatively cheap to construct and copy.
*
* @c METRIC must be
* - discrete and finite valued type with increment and decrement operations.
*/
template<typename METRIC, typename PAYLOAD> class DiscreteSpace {
using self_type = DiscreteSpace;
protected:
using metric_type = METRIC; ///< Export.
using payload_type = PAYLOAD; ///< Export.
using range_type = DiscreteRange<METRIC>;
/// A node in the range tree.
class Node : public detail::RBNode {
using self_type = Node; ///< Self reference type.
using super_type = detail::RBNode; ///< Parent class.
friend class DiscreteSpace;
range_type _range; ///< Range covered by this node.
range_type _hull; ///< Range covered by subtree rooted at this node.
PAYLOAD _payload{}; ///< Default constructor, should zero init if @c PAYLOAD is a pointer.
public:
/// Linkage for @c IntrusiveDList.
using Linkage = swoc::IntrusiveLinkageRebind<self_type, super_type::Linkage>;
Node() = default; ///< Construct empty node.
/// Construct from @a range and @a payload.
Node(range_type const& range, PAYLOAD const& payload) : _range(range), _payload(payload) {}
/// Construct from two metrics and a payload
Node(METRIC const& min, METRIC const& max, PAYLOAD const& payload)
: _range(min, max), _payload(payload) {}
/// @return The payload in the node.
PAYLOAD& payload();
/** Set the @a range of a node.
*
* @param range Range to use.
* @return @a this
*/
self_type& assign(range_type const& range);
/** Set the @a payload for @a this node.
*
* @param payload Payload to use.
* @return @a this
*/
self_type& assign(PAYLOAD const& payload);
range_type const& range() const { return _range; }
self_type&
assign_min(METRIC const& m) {
_range.assign_min(m);
this->ripple_structure_fixup();
return *this;
}
self_type&
assign_max(METRIC const& m) {
_range.assign_max(m);
this->ripple_structure_fixup();
return *this;
}
/** Decrement the maximum value in the range.
*
* The range for the node is reduced by one.
*
* @return @a this
*/
self_type&
dec_max() {
_range.dec_max();
this->ripple_structure_fixup();
return *this;
}
METRIC const&
min() const {
return _range.min();
}
METRIC const&
max() const {
return _range.max();
}
void structure_fixup() override;
self_type *left() { return static_cast<self_type *>(_left); }
self_type *right() { return static_cast<self_type *>(_right); }
};
using Direction = typename Node::Direction;
Node *_root = nullptr; ///< Root node.
IntrusiveDList<typename Node::Linkage> _list; ///< In order list of nodes.
swoc::MemArena _arena{4000}; ///< Memory Storage.
swoc::FixedArena<Node> _fa{_arena}; ///< Node allocator and free list.
// Utility methods to avoid having casts scattered all over.
Node *
prev(Node *n) {
return Node::Linkage::prev_ptr(n);
}
Node *
next(Node *n) {
return Node::Linkage::next_ptr(n);
}
Node *
left(Node *n) {
return static_cast<Node *>(n->_left);
}
Node *
right(Node *n) {
return static_cast<Node *>(n->_right);
}
public:
using iterator = typename decltype(_list)::iterator;
using const_iterator = typename decltype(_list)::const_iterator;
DiscreteSpace() = default;
~DiscreteSpace();
/** Set the @a payload for a @a range
*
* @param range Range to mark.
* @param payload Payload to set.
* @return @a this
*
* Values in @a range are set to @a payload regardless of the current state.
*/
self_type& mark(range_type const& range, PAYLOAD const& payload);
/** Erase a @a range.
*
* @param range Range to erase.
* @return @a this
*
* All values in @a range are removed from the space.
*/
self_type& erase(range_type const& range);
/** Blend a @a color to a @a range.
*
* @tparam F Functor to blend payloads.
* @tparam U type to blend in to payloads.
* @param range Range for blending.
* @param color Payload to blend.
* @return @a this
*
* @a color is blended to values in @a range. If an address in @a range does not have a payload,
* its payload is set a default constructed @c PAYLOAD blended with @a color. If such an address
* does have a payload, @a color is blended in to that payload using @blender. The existing color
* is passed as the first argument and @a color as the second argument. The functor is expected to
* update the first argument to be the blended color. The function must return a @c bool to
* indicate whether the blend resulted in a valid color. If @c false is returned, the blended
* region is removed from the space.
*/
template<typename F, typename U = PAYLOAD>
self_type& blend(range_type const& range, U const& color, F&& blender);
/** Fill @a range with @a payload.
*
* @param range Range to fill.
* @param payload Payload to use.
* @return @a this
*
* Values in @a range that do not have a payload are set to @a payload. Values in the space are
* not changed.
*/
self_type& fill(range_type const& range, PAYLOAD const& payload);
/** Find the payload at @a metric.
*
* @param metric The metric for which to search.
* @return The payload for @a metric if found, @c nullptr if not found.
*/
iterator find(METRIC const& metric);
/// @return The number of distinct ranges.
size_t count() const;
iterator begin() { return _list.begin(); }
iterator end() { return _list.end(); }
/// Remove all ranges.
void clear() {
for (auto& node : _list) {
std::destroy_at(&node.payload());
}
_list.clear();
_root = nullptr;
_arena.clear();
_fa.clear();
}
protected:
/** Find the lower bound range for @a target.
*
* @param target Lower bound value.
* @return The rightmost range that starts at or before @a target, or @c nullptr if all ranges start
* after @a target.
*/
Node *lower_bound(METRIC const& target);
/// @return The first node in the tree.
Node *head();
/** Insert @a node before @a spot.
*
* @param spot Target node.
* @param node Node to insert.
*/
void insert_before(Node *spot, Node *node);
/** Insert @a node after @a spot.
*
* @param spot Target node.
* @param node Node to insert.
*/
void insert_after(Node *spot, Node *node);
void prepend(Node *node);
void append(Node *node);
void
remove(Node *node) {
_root = static_cast<Node *>(node->remove());
_list.erase(node);
_fa.destroy(node);
}
};
// ---
template<typename METRIC, typename PAYLOAD>
PAYLOAD&
DiscreteSpace<METRIC, PAYLOAD>::Node::payload() {
return _payload;
}
template<typename METRIC, typename PAYLOAD>
auto
DiscreteSpace<METRIC, PAYLOAD>::Node::assign(DiscreteSpace::range_type const& range) -> self_type& {
_range = range;
return *this;
}
template<typename METRIC, typename PAYLOAD>
auto
DiscreteSpace<METRIC, PAYLOAD>::Node::assign(PAYLOAD const& payload) -> self_type& {
_payload = payload;
return *this;
}
template<typename METRIC, typename PAYLOAD>
void DiscreteSpace<METRIC, PAYLOAD>::Node::structure_fixup() {
// Invariant: The hulls of all children are correct.
if (_left && _right) {
// If both children, local range must be inside the hull of the children and irrelevant.
_hull.assign(this->left()->_hull.min(), this->right()->_hull.max());
} else if (_left) {
_hull.assign(this->left()->_hull.min(), _range.max());
} else if (_right) {
_hull.assign(_range.min(), this->right()->_hull.max());
} else {
_hull = _range;
}
}
// ---
template<typename METRIC, typename PAYLOAD>
DiscreteSpace<METRIC, PAYLOAD>::~DiscreteSpace() {
// Destruct all the payloads - the nodes themselves are in the arena and disappear with it.
for (auto& node : _list) {
std::destroy_at(&node.payload());
}
}
template<typename METRIC, typename PAYLOAD>
size_t DiscreteSpace<METRIC, PAYLOAD>::count() const { return _list.count(); }
template<typename METRIC, typename PAYLOAD>
auto
DiscreteSpace<METRIC, PAYLOAD>::head() -> Node * {
return static_cast<Node *>(_list.head());
}
template<typename METRIC, typename PAYLOAD>
auto
DiscreteSpace<METRIC, PAYLOAD>::find(METRIC const& metric) -> iterator {
auto n = _root; // current node to test.
while (n) {
if (metric < n->min()) {
if (n->_hull.contains(metric)) {
n = n->left();
} else {
return this->end();
}
} else if (n->max() < metric) {
if (n->_hull.contains(metric)) {
n = n->right();
} else {
return this->end();
}
} else {
return _list.iterator_for(n);
}
}
return this->end();
}
template<typename METRIC, typename PAYLOAD>
auto DiscreteSpace<METRIC, PAYLOAD>::lower_bound(METRIC const& target) -> Node * {
Node *n = _root; // current node to test.
Node *zret = nullptr; // best node so far.
// Fast check for sequential insertion
if (auto ln = _list.tail() ; ln != nullptr && ln->max() < target) {
return ln;
}
while (n) {
if (target < n->min()) {
n = left(n);
} else {
zret = n; // this is a better candidate.
if (n->max() < target) {
n = right(n);
} else {
break;
}
}
}
return zret;
}
template<typename METRIC, typename PAYLOAD>
void DiscreteSpace<METRIC, PAYLOAD>::prepend(DiscreteSpace::Node *node) {
if (!_root) {
_root = node;
} else {
_root = static_cast<Node *>(_list.head()->set_child(node, Direction::LEFT)->rebalance_after_insert());
}
_list.prepend(node);
}
template<typename METRIC, typename PAYLOAD>
void DiscreteSpace<METRIC, PAYLOAD>::append(DiscreteSpace::Node *node) {
if (!_root) {
_root = node;
} else {
// The last node has no right child, or it wouldn't be the last.
_root = static_cast<Node *>(_list.tail()->set_child(node, Direction::RIGHT)->rebalance_after_insert());
}
_list.append(node);
}
template<typename METRIC, typename PAYLOAD>
void
DiscreteSpace<METRIC, PAYLOAD>::insert_before(DiscreteSpace::Node *spot
, DiscreteSpace::Node *node) {
if (left(spot) == nullptr) {
spot->set_child(node, Direction::LEFT);
} else {
// If there's a left child, there's a previous node, therefore spot->_prev is valid.
// Further, the previous node must be the rightmost descendant node of the left subtree
// and therefore has no current right child.
spot->_prev->set_child(node, Direction::RIGHT);
}
_list.insert_before(spot, node);
_root = static_cast<Node *>(node->rebalance_after_insert());
}
template<typename METRIC, typename PAYLOAD>
void
DiscreteSpace<METRIC, PAYLOAD>::insert_after(DiscreteSpace::Node *spot, DiscreteSpace::Node *node) {
if (right(spot) == nullptr) {
spot->set_child(node, Direction::RIGHT);
} else {
// If there's a right child, there's a successor node, and therefore @a _next is valid.
// Further, the successor node must be the left most descendant of the right subtree
// therefore it doesn't have a left child.
spot->_next->set_child(node, Direction::LEFT);
}
_list.insert_after(spot, node);
_root = static_cast<Node *>(node->rebalance_after_insert());
}
template<typename METRIC, typename PAYLOAD>
DiscreteSpace<METRIC, PAYLOAD>&
DiscreteSpace<METRIC, PAYLOAD>::erase(DiscreteSpace::range_type const& range) {
Node *n = this->lower_bound(range.min()); // current node.
while (n) {
auto nn = next(n); // cache in case @a n disappears.
if (n->min() > range.max()) { // cleared the target range, done.
break;
}
if (n->max() >= range.min()) { // some overlap