blob: 28153c19088fe676bbcf20467d4aeba3ac3a4ec7 [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// Copyright (c) 2019 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef QUICHE_QUIC_CORE_QUIC_INTERVAL_SET_H_
6#define QUICHE_QUIC_CORE_QUIC_INTERVAL_SET_H_
7
8// QuicIntervalSet<T> is a data structure used to represent a sorted set of
9// non-empty, non-adjacent, and mutually disjoint intervals. Mutations to an
10// interval set preserve these properties, altering the set as needed. For
11// example, adding [2, 3) to a set containing only [1, 2) would result in the
12// set containing the single interval [1, 3).
13//
14// Supported operations include testing whether an Interval is contained in the
15// QuicIntervalSet, comparing two QuicIntervalSets, and performing
16// QuicIntervalSet union, intersection, and difference.
17//
18// QuicIntervalSet maintains the minimum number of entries needed to represent
19// the set of underlying intervals. When the QuicIntervalSet is modified (e.g.
20// due to an Add operation), other interval entries may be coalesced, removed,
21// or otherwise modified in order to maintain this invariant. The intervals are
22// maintained in sorted order, by ascending min() value.
23//
24// The reader is cautioned to beware of the terminology used here: this library
25// uses the terms "min" and "max" rather than "begin" and "end" as is
26// conventional for the STL. The terminology [min, max) refers to the half-open
27// interval which (if the interval is not empty) contains min but does not
28// contain max. An interval is considered empty if min >= max.
29//
30// T is required to be default- and copy-constructible, to have an assignment
31// operator, a difference operator (operator-()), and the full complement of
32// comparison operators (<, <=, ==, !=, >=, >). These requirements are inherited
33// from value_type.
34//
35// QuicIntervalSet has constant-time move operations.
36//
37//
38// Examples:
39// QuicIntervalSet<int> intervals;
40// intervals.Add(Interval<int>(10, 20));
41// intervals.Add(Interval<int>(30, 40));
42// // intervals contains [10,20) and [30,40).
43// intervals.Add(Interval<int>(15, 35));
44// // intervals has been coalesced. It now contains the single range [10,40).
45// EXPECT_EQ(1, intervals.Size());
46// EXPECT_TRUE(intervals.Contains(Interval<int>(10, 40)));
47//
48// intervals.Difference(Interval<int>(10, 20));
49// // intervals should now contain the single range [20, 40).
50// EXPECT_EQ(1, intervals.Size());
51// EXPECT_TRUE(intervals.Contains(Interval<int>(20, 40)));
52
53#include <stddef.h>
54#include <algorithm>
55#include <initializer_list>
56#include <set>
57#include <utility>
58#include <vector>
59
vasilvv872e7a32019-03-12 16:42:44 -070060#include <string>
61
QUICHE teama6ef0a62019-03-07 20:34:33 -050062#include "net/third_party/quiche/src/quic/core/quic_interval.h"
63#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050064
65namespace quic {
66
67template <typename T>
dschinazie2116422019-10-29 11:54:26 -070068class QUIC_NO_EXPORT QuicIntervalSet {
QUICHE teama6ef0a62019-03-07 20:34:33 -050069 public:
70 typedef QuicInterval<T> value_type;
71
72 private:
dschinazie2116422019-10-29 11:54:26 -070073 struct QUIC_NO_EXPORT IntervalLess {
QUICHE teama6ef0a62019-03-07 20:34:33 -050074 bool operator()(const value_type& a, const value_type& b) const;
75 };
wub4f59d712019-11-05 06:48:55 -080076 // TODO(wub): Switch to absl::btree_set when it is available in Chromium.
QUICHE teama6ef0a62019-03-07 20:34:33 -050077 typedef std::set<value_type, IntervalLess> Set;
78
79 public:
80 typedef typename Set::const_iterator const_iterator;
81 typedef typename Set::const_reverse_iterator const_reverse_iterator;
82
83 // Instantiates an empty QuicIntervalSet.
84 QuicIntervalSet() {}
85
86 // Instantiates an QuicIntervalSet containing exactly one initial half-open
87 // interval [min, max), unless the given interval is empty, in which case the
88 // QuicIntervalSet will be empty.
89 explicit QuicIntervalSet(const value_type& interval) { Add(interval); }
90
91 // Instantiates an QuicIntervalSet containing the half-open interval [min,
92 // max).
93 QuicIntervalSet(const T& min, const T& max) { Add(min, max); }
94
95 QuicIntervalSet(std::initializer_list<value_type> il) { assign(il); }
96
97 // Clears this QuicIntervalSet.
98 void Clear() { intervals_.clear(); }
99
100 // Returns the number of disjoint intervals contained in this QuicIntervalSet.
101 size_t Size() const { return intervals_.size(); }
102
103 // Returns the smallest interval that contains all intervals in this
104 // QuicIntervalSet, or the empty interval if the set is empty.
105 value_type SpanningInterval() const;
106
107 // Adds "interval" to this QuicIntervalSet. Adding the empty interval has no
108 // effect.
109 void Add(const value_type& interval);
110
111 // Adds the interval [min, max) to this QuicIntervalSet. Adding the empty
112 // interval has no effect.
113 void Add(const T& min, const T& max) { Add(value_type(min, max)); }
114
115 // Same semantics as Add(const value_type&), but optimized for the case where
116 // rbegin()->min() <= |interval|.min() <= rbegin()->max().
117 void AddOptimizedForAppend(const value_type& interval) {
118 if (Empty()) {
119 Add(interval);
120 return;
121 }
122
123 const_reverse_iterator last_interval = intervals_.rbegin();
124
125 // If interval.min() is outside of [last_interval->min, last_interval->max],
126 // we can not simply extend last_interval->max.
127 if (interval.min() < last_interval->min() ||
128 interval.min() > last_interval->max()) {
129 Add(interval);
130 return;
131 }
132
133 if (interval.max() <= last_interval->max()) {
134 // interval is fully contained by last_interval.
135 return;
136 }
137
138 // Extend last_interval.max to interval.max, in place.
139 //
140 // Set does not allow in-place updates due to the potential of violating its
141 // ordering requirements. But we know setting the max of the last interval
142 // is safe w.r.t set ordering and other invariants of QuicIntervalSet, so we
143 // force an in-place update for performance.
144 const_cast<value_type*>(&(*last_interval))->SetMax(interval.max());
145 }
146
147 // Same semantics as Add(const T&, const T&), but optimized for the case where
148 // rbegin()->max() == |min|.
149 void AddOptimizedForAppend(const T& min, const T& max) {
150 AddOptimizedForAppend(value_type(min, max));
151 }
152
153 // TODO(wub): Similar to AddOptimizedForAppend, we can also have a
154 // AddOptimizedForPrepend if there is a use case.
155
wub4f59d712019-11-05 06:48:55 -0800156 // Remove the first interval.
157 // REQUIRES: !Empty()
158 void PopFront() {
159 DCHECK(!Empty());
160 intervals_.erase(intervals_.begin());
161 }
162
163 // Trim all values that is smaller than |value|. Which means
164 // a) If all values in an interval is smaller than |value|, the entire
165 // interval is removed.
166 // b) If some but not all values in an interval is smaller than |value|, the
167 // min of that interval is raised to |value|.
168 // Returns true if some intervals are trimmed.
169 bool TrimLessThan(const T& value) {
170 // Number of intervals that are fully or partially trimmed.
171 size_t num_intervals_trimmed = 0;
172
173 while (!intervals_.empty()) {
174 const_iterator first_interval = intervals_.begin();
175 if (first_interval->min() >= value) {
176 break;
177 }
178
179 ++num_intervals_trimmed;
180
181 if (first_interval->max() <= value) {
182 // a) Trim the entire interval.
183 intervals_.erase(first_interval);
184 continue;
185 }
186
187 // b) Trim a prefix of the interval.
188 //
189 // Set does not allow in-place updates due to the potential of violating
190 // its ordering requirements. But increasing the min of the first interval
191 // will not break the ordering, hence the const_cast.
192 const_cast<value_type*>(&(*first_interval))->SetMin(value);
193 break;
194 }
195
196 return num_intervals_trimmed != 0;
197 }
198
QUICHE teama6ef0a62019-03-07 20:34:33 -0500199 // Returns true if this QuicIntervalSet is empty.
200 bool Empty() const { return intervals_.empty(); }
201
202 // Returns true if any interval in this QuicIntervalSet contains the indicated
203 // value.
204 bool Contains(const T& value) const;
205
206 // Returns true if there is some interval in this QuicIntervalSet that wholly
207 // contains the given interval. An interval O "wholly contains" a non-empty
208 // interval I if O.Contains(p) is true for every p in I. This is the same
209 // definition used by value_type::Contains(). This method returns false on
210 // the empty interval, due to a (perhaps unintuitive) convention inherited
211 // from value_type.
212 // Example:
213 // Assume an QuicIntervalSet containing the entries { [10,20), [30,40) }.
214 // Contains(Interval(15, 16)) returns true, because [10,20) contains
215 // [15,16). However, Contains(Interval(15, 35)) returns false.
216 bool Contains(const value_type& interval) const;
217
218 // Returns true if for each interval in "other", there is some (possibly
219 // different) interval in this QuicIntervalSet which wholly contains it. See
220 // Contains(const value_type& interval) for the meaning of "wholly contains".
221 // Perhaps unintuitively, this method returns false if "other" is the empty
222 // set. The algorithmic complexity of this method is O(other.Size() *
223 // log(this->Size())). The method could be rewritten to run in O(other.Size()
224 // + this->Size()), and this alternative could be implemented as a free
225 // function using the public API.
226 bool Contains(const QuicIntervalSet<T>& other) const;
227
228 // Returns true if there is some interval in this QuicIntervalSet that wholly
229 // contains the interval [min, max). See Contains(const value_type&).
230 bool Contains(const T& min, const T& max) const {
231 return Contains(value_type(min, max));
232 }
233
234 // Returns true if for some interval in "other", there is some interval in
235 // this QuicIntervalSet that intersects with it. See value_type::Intersects()
236 // for the definition of interval intersection.
237 bool Intersects(const QuicIntervalSet& other) const;
238
239 // Returns an iterator to the value_type in the QuicIntervalSet that contains
240 // the given value. In other words, returns an iterator to the unique interval
241 // [min, max) in the QuicIntervalSet that has the property min <= value < max.
242 // If there is no such interval, this method returns end().
243 const_iterator Find(const T& value) const;
244
245 // Returns an iterator to the value_type in the QuicIntervalSet that wholly
246 // contains the given interval. In other words, returns an iterator to the
247 // unique interval outer in the QuicIntervalSet that has the property that
248 // outer.Contains(interval). If there is no such interval, or if interval is
249 // empty, returns end().
250 const_iterator Find(const value_type& interval) const;
251
252 // Returns an iterator to the value_type in the QuicIntervalSet that wholly
253 // contains [min, max). In other words, returns an iterator to the unique
254 // interval outer in the QuicIntervalSet that has the property that
255 // outer.Contains(Interval<T>(min, max)). If there is no such interval, or if
256 // interval is empty, returns end().
257 const_iterator Find(const T& min, const T& max) const {
258 return Find(value_type(min, max));
259 }
260
261 // Returns an iterator pointing to the first value_type which contains or
262 // goes after the given value.
263 //
264 // Example:
265 // [10, 20) [30, 40)
266 // ^ LowerBound(10)
267 // ^ LowerBound(15)
268 // ^ LowerBound(20)
269 // ^ LowerBound(25)
270 const_iterator LowerBound(const T& value) const;
271
272 // Returns an iterator pointing to the first value_type which goes after
273 // the given value.
274 //
275 // Example:
276 // [10, 20) [30, 40)
277 // ^ UpperBound(10)
278 // ^ UpperBound(15)
279 // ^ UpperBound(20)
280 // ^ UpperBound(25)
281 const_iterator UpperBound(const T& value) const;
282
283 // Returns true if every value within the passed interval is not Contained
284 // within the QuicIntervalSet.
285 // Note that empty intervals are always considered disjoint from the
286 // QuicIntervalSet (even though the QuicIntervalSet doesn't `Contain` them).
287 bool IsDisjoint(const value_type& interval) const;
288
289 // Merges all the values contained in "other" into this QuicIntervalSet.
290 void Union(const QuicIntervalSet& other);
291
292 // Modifies this QuicIntervalSet so that it contains only those values that
293 // are currently present both in *this and in the QuicIntervalSet "other".
294 void Intersection(const QuicIntervalSet& other);
295
296 // Mutates this QuicIntervalSet so that it contains only those values that are
297 // currently in *this but not in "interval".
298 void Difference(const value_type& interval);
299
300 // Mutates this QuicIntervalSet so that it contains only those values that are
301 // currently in *this but not in the interval [min, max).
302 void Difference(const T& min, const T& max);
303
304 // Mutates this QuicIntervalSet so that it contains only those values that are
305 // currently in *this but not in the QuicIntervalSet "other".
306 void Difference(const QuicIntervalSet& other);
307
308 // Mutates this QuicIntervalSet so that it contains only those values that are
309 // in [min, max) but not currently in *this.
310 void Complement(const T& min, const T& max);
311
312 // QuicIntervalSet's begin() iterator. The invariants of QuicIntervalSet
313 // guarantee that for each entry e in the set, e.min() < e.max() (because the
314 // entries are non-empty) and for each entry f that appears later in the set,
315 // e.max() < f.min() (because the entries are ordered, pairwise-disjoint, and
316 // non-adjacent). Modifications to this QuicIntervalSet invalidate these
317 // iterators.
318 const_iterator begin() const { return intervals_.begin(); }
319
320 // QuicIntervalSet's end() iterator.
321 const_iterator end() const { return intervals_.end(); }
322
323 // QuicIntervalSet's rbegin() and rend() iterators. Iterator invalidation
324 // semantics are the same as those for begin() / end().
325 const_reverse_iterator rbegin() const { return intervals_.rbegin(); }
326
327 const_reverse_iterator rend() const { return intervals_.rend(); }
328
329 template <typename Iter>
330 void assign(Iter first, Iter last) {
331 Clear();
332 for (; first != last; ++first)
333 Add(*first);
334 }
335
336 void assign(std::initializer_list<value_type> il) {
337 assign(il.begin(), il.end());
338 }
339
340 // Returns a human-readable representation of this set. This will typically be
341 // (though is not guaranteed to be) of the form
342 // "[a1, b1) [a2, b2) ... [an, bn)"
343 // where the intervals are in the same order as given by traversal from
344 // begin() to end(). This representation is intended for human consumption;
345 // computer programs should not rely on the output being in exactly this form.
vasilvvc48c8712019-03-11 13:38:16 -0700346 std::string ToString() const;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500347
348 QuicIntervalSet& operator=(std::initializer_list<value_type> il) {
349 assign(il.begin(), il.end());
350 return *this;
351 }
352
353 // Swap this QuicIntervalSet with *other. This is a constant-time operation.
354 void Swap(QuicIntervalSet<T>* other) { intervals_.swap(other->intervals_); }
355
356 friend bool operator==(const QuicIntervalSet& a, const QuicIntervalSet& b) {
357 return a.Size() == b.Size() &&
358 std::equal(a.begin(), a.end(), b.begin(), NonemptyIntervalEq());
359 }
360
361 friend bool operator!=(const QuicIntervalSet& a, const QuicIntervalSet& b) {
362 return !(a == b);
363 }
364
365 private:
366 // Simple member-wise equality, since all intervals are non-empty.
dschinazie2116422019-10-29 11:54:26 -0700367 struct QUIC_NO_EXPORT NonemptyIntervalEq {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500368 bool operator()(const value_type& a, const value_type& b) const {
369 return a.min() == b.min() && a.max() == b.max();
370 }
371 };
372
373 // Removes overlapping ranges and coalesces adjacent intervals as needed.
374 void Compact(const typename Set::iterator& begin,
375 const typename Set::iterator& end);
376
377 // Returns true if this set is valid (i.e. all intervals in it are non-empty,
378 // non-adjacent, and mutually disjoint). Currently this is used as an
379 // integrity check by the Intersection() and Difference() methods, but is only
380 // invoked for debug builds (via DCHECK).
381 bool Valid() const;
382
383 // Finds the first interval that potentially intersects 'other'.
384 const_iterator FindIntersectionCandidate(const QuicIntervalSet& other) const;
385
386 // Finds the first interval that potentially intersects 'interval'.
387 const_iterator FindIntersectionCandidate(const value_type& interval) const;
388
389 // Helper for Intersection() and Difference(): Finds the next pair of
390 // intervals from 'x' and 'y' that intersect. 'mine' is an iterator
391 // over x->intervals_. 'theirs' is an iterator over y.intervals_. 'mine'
392 // and 'theirs' are advanced until an intersecting pair is found.
393 // Non-intersecting intervals (aka "holes") from x->intervals_ can be
394 // optionally erased by "on_hole".
395 template <typename X, typename Func>
396 static bool FindNextIntersectingPairImpl(X* x,
397 const QuicIntervalSet& y,
398 const_iterator* mine,
399 const_iterator* theirs,
400 Func on_hole);
401
402 // The variant of the above method that doesn't mutate this QuicIntervalSet.
403 bool FindNextIntersectingPair(const QuicIntervalSet& other,
404 const_iterator* mine,
405 const_iterator* theirs) const {
406 return FindNextIntersectingPairImpl(
407 this, other, mine, theirs,
408 [](const QuicIntervalSet*, const_iterator, const_iterator) {});
409 }
410
411 // The variant of the above method that mutates this QuicIntervalSet by
412 // erasing holes.
413 bool FindNextIntersectingPairAndEraseHoles(const QuicIntervalSet& other,
414 const_iterator* mine,
415 const_iterator* theirs) {
416 return FindNextIntersectingPairImpl(
417 this, other, mine, theirs,
418 [](QuicIntervalSet* x, const_iterator from, const_iterator to) {
419 x->intervals_.erase(from, to);
420 });
421 }
422
423 // The representation for the intervals. The intervals in this set are
424 // non-empty, pairwise-disjoint, non-adjacent and ordered in ascending order
425 // by min().
426 Set intervals_;
427};
428
429template <typename T>
430auto operator<<(std::ostream& out, const QuicIntervalSet<T>& seq)
431 -> decltype(out << *seq.begin()) {
432 out << "{";
433 for (const auto& interval : seq) {
434 out << " " << interval;
435 }
436 out << " }";
437
438 return out;
439}
440
441template <typename T>
442void swap(QuicIntervalSet<T>& x, QuicIntervalSet<T>& y);
443
444//==============================================================================
445// Implementation details: Clients can stop reading here.
446
447template <typename T>
448typename QuicIntervalSet<T>::value_type QuicIntervalSet<T>::SpanningInterval()
449 const {
450 value_type result;
451 if (!intervals_.empty()) {
452 result.SetMin(intervals_.begin()->min());
453 result.SetMax(intervals_.rbegin()->max());
454 }
455 return result;
456}
457
458template <typename T>
459void QuicIntervalSet<T>::Add(const value_type& interval) {
460 if (interval.Empty())
461 return;
462 std::pair<typename Set::iterator, bool> ins = intervals_.insert(interval);
463 if (!ins.second) {
464 // This interval already exists.
465 return;
466 }
467 // Determine the minimal range that will have to be compacted. We know that
468 // the QuicIntervalSet was valid before the addition of the interval, so only
469 // need to start with the interval itself (although Compact takes an open
470 // range so begin needs to be the interval to the left). We don't know how
471 // many ranges this interval may cover, so we need to find the appropriate
472 // interval to end with on the right.
473 typename Set::iterator begin = ins.first;
474 if (begin != intervals_.begin())
475 --begin;
476 const value_type target_end(interval.max(), interval.max());
477 const typename Set::iterator end = intervals_.upper_bound(target_end);
478 Compact(begin, end);
479}
480
481template <typename T>
482bool QuicIntervalSet<T>::Contains(const T& value) const {
483 value_type tmp(value, value);
484 // Find the first interval with min() > value, then move back one step
485 const_iterator it = intervals_.upper_bound(tmp);
486 if (it == intervals_.begin())
487 return false;
488 --it;
489 return it->Contains(value);
490}
491
492template <typename T>
493bool QuicIntervalSet<T>::Contains(const value_type& interval) const {
494 // Find the first interval with min() > value, then move back one step.
495 const_iterator it = intervals_.upper_bound(interval);
496 if (it == intervals_.begin())
497 return false;
498 --it;
499 return it->Contains(interval);
500}
501
502template <typename T>
503bool QuicIntervalSet<T>::Contains(const QuicIntervalSet<T>& other) const {
504 if (!SpanningInterval().Contains(other.SpanningInterval())) {
505 return false;
506 }
507
508 for (const_iterator i = other.begin(); i != other.end(); ++i) {
509 // If we don't contain the interval, can return false now.
510 if (!Contains(*i)) {
511 return false;
512 }
513 }
514 return true;
515}
516
517// This method finds the interval that Contains() "value", if such an interval
518// exists in the QuicIntervalSet. The way this is done is to locate the
519// "candidate interval", the only interval that could *possibly* contain value,
520// and test it using Contains(). The candidate interval is the interval with the
521// largest min() having min() <= value.
522//
523// Determining the candidate interval takes a couple of steps. First, since the
524// underlying std::set stores intervals, not values, we need to create a "probe
525// interval" suitable for use as a search key. The probe interval used is
526// [value, value). Now we can restate the problem as finding the largest
527// interval in the QuicIntervalSet that is <= the probe interval.
528//
529// This restatement only works if the set's comparator behaves in a certain way.
530// In particular it needs to order first by ascending min(), and then by
531// descending max(). The comparator used by this library is defined in exactly
532// this way. To see why descending max() is required, consider the following
533// example. Assume an QuicIntervalSet containing these intervals:
534//
535// [0, 5) [10, 20) [50, 60)
536//
537// Consider searching for the value 15. The probe interval [15, 15) is created,
538// and [10, 20) is identified as the largest interval in the set <= the probe
539// interval. This is the correct interval needed for the Contains() test, which
540// will then return true.
541//
542// Now consider searching for the value 30. The probe interval [30, 30) is
543// created, and again [10, 20] is identified as the largest interval <= the
544// probe interval. This is again the correct interval needed for the Contains()
545// test, which in this case returns false.
546//
547// Finally, consider searching for the value 10. The probe interval [10, 10) is
548// created. Here the ordering relationship between [10, 10) and [10, 20) becomes
549// vitally important. If [10, 10) were to come before [10, 20), then [0, 5)
550// would be the largest interval <= the probe, leading to the wrong choice of
551// interval for the Contains() test. Therefore [10, 10) needs to come after
552// [10, 20). The simplest way to make this work in the general case is to order
553// by ascending min() but descending max(). In this ordering, the empty interval
554// is larger than any non-empty interval with the same min(). The comparator
555// used by this library is careful to induce this ordering.
556//
557// Another detail involves the choice of which std::set method to use to try to
558// find the candidate interval. The most appropriate entry point is
559// set::upper_bound(), which finds the smallest interval which is > the probe
560// interval. The semantics of upper_bound() are slightly different from what we
561// want (namely, to find the largest interval which is <= the probe interval)
562// but they are close enough; the interval found by upper_bound() will always be
563// one step past the interval we are looking for (if it exists) or at begin()
564// (if it does not). Getting to the proper interval is a simple matter of
565// decrementing the iterator.
566template <typename T>
567typename QuicIntervalSet<T>::const_iterator QuicIntervalSet<T>::Find(
568 const T& value) const {
569 value_type tmp(value, value);
570 const_iterator it = intervals_.upper_bound(tmp);
571 if (it == intervals_.begin())
572 return intervals_.end();
573 --it;
574 if (it->Contains(value))
575 return it;
576 else
577 return intervals_.end();
578}
579
580// This method finds the interval that Contains() the interval "probe", if such
581// an interval exists in the QuicIntervalSet. The way this is done is to locate
582// the "candidate interval", the only interval that could *possibly* contain
583// "probe", and test it using Contains(). The candidate interval is the largest
584// interval that is <= the probe interval.
585//
586// The search for the candidate interval only works if the comparator used
587// behaves in a certain way. In particular it needs to order first by ascending
588// min(), and then by descending max(). The comparator used by this library is
589// defined in exactly this way. To see why descending max() is required,
590// consider the following example. Assume an QuicIntervalSet containing these
591// intervals:
592//
593// [0, 5) [10, 20) [50, 60)
594//
595// Consider searching for the probe [15, 17). [10, 20) is the largest interval
596// in the set which is <= the probe interval. This is the correct interval
597// needed for the Contains() test, which will then return true, because [10, 20)
598// contains [15, 17).
599//
600// Now consider searching for the probe [30, 32). Again [10, 20] is the largest
601// interval <= the probe interval. This is again the correct interval needed for
602// the Contains() test, which in this case returns false, because [10, 20) does
603// not contain [30, 32).
604//
605// Finally, consider searching for the probe [10, 12). Here the ordering
606// relationship between [10, 12) and [10, 20) becomes vitally important. If
607// [10, 12) were to come before [10, 20), then [0, 5) would be the largest
608// interval <= the probe, leading to the wrong choice of interval for the
609// Contains() test. Therefore [10, 12) needs to come after [10, 20). The
610// simplest way to make this work in the general case is to order by ascending
611// min() but descending max(). In this ordering, given two intervals with the
612// same min(), the wider one goes before the narrower one. The comparator used
613// by this library is careful to induce this ordering.
614//
615// Another detail involves the choice of which std::set method to use to try to
616// find the candidate interval. The most appropriate entry point is
617// set::upper_bound(), which finds the smallest interval which is > the probe
618// interval. The semantics of upper_bound() are slightly different from what we
619// want (namely, to find the largest interval which is <= the probe interval)
620// but they are close enough; the interval found by upper_bound() will always be
621// one step past the interval we are looking for (if it exists) or at begin()
622// (if it does not). Getting to the proper interval is a simple matter of
623// decrementing the iterator.
624template <typename T>
625typename QuicIntervalSet<T>::const_iterator QuicIntervalSet<T>::Find(
626 const value_type& probe) const {
627 const_iterator it = intervals_.upper_bound(probe);
628 if (it == intervals_.begin())
629 return intervals_.end();
630 --it;
631 if (it->Contains(probe))
632 return it;
633 else
634 return intervals_.end();
635}
636
637template <typename T>
638typename QuicIntervalSet<T>::const_iterator QuicIntervalSet<T>::LowerBound(
639 const T& value) const {
640 const_iterator it = intervals_.lower_bound(value_type(value, value));
641 if (it == intervals_.begin()) {
642 return it;
643 }
644
645 // The previous intervals_.lower_bound() checking is essentially based on
646 // interval.min(), so we need to check whether the `value` is contained in
647 // the previous interval.
648 --it;
649 if (it->Contains(value)) {
650 return it;
651 } else {
652 return ++it;
653 }
654}
655
656template <typename T>
657typename QuicIntervalSet<T>::const_iterator QuicIntervalSet<T>::UpperBound(
658 const T& value) const {
659 return intervals_.upper_bound(value_type(value, value));
660}
661
662template <typename T>
663bool QuicIntervalSet<T>::IsDisjoint(const value_type& interval) const {
664 if (interval.Empty())
665 return true;
666 value_type tmp(interval.min(), interval.min());
667 // Find the first interval with min() > interval.min()
668 const_iterator it = intervals_.upper_bound(tmp);
669 if (it != intervals_.end() && interval.max() > it->min())
670 return false;
671 if (it == intervals_.begin())
672 return true;
673 --it;
674 return it->max() <= interval.min();
675}
676
677template <typename T>
678void QuicIntervalSet<T>::Union(const QuicIntervalSet& other) {
679 intervals_.insert(other.begin(), other.end());
680 Compact(intervals_.begin(), intervals_.end());
681}
682
683template <typename T>
684typename QuicIntervalSet<T>::const_iterator
685QuicIntervalSet<T>::FindIntersectionCandidate(
686 const QuicIntervalSet& other) const {
687 return FindIntersectionCandidate(*other.intervals_.begin());
688}
689
690template <typename T>
691typename QuicIntervalSet<T>::const_iterator
692QuicIntervalSet<T>::FindIntersectionCandidate(
693 const value_type& interval) const {
694 // Use upper_bound to efficiently find the first interval in intervals_
695 // where min() is greater than interval.min(). If the result
696 // isn't the beginning of intervals_ then move backwards one interval since
697 // the interval before it is the first candidate where max() may be
698 // greater than interval.min().
699 // In other words, no interval before that can possibly intersect with any
700 // of other.intervals_.
701 const_iterator mine = intervals_.upper_bound(interval);
702 if (mine != intervals_.begin()) {
703 --mine;
704 }
705 return mine;
706}
707
708template <typename T>
709template <typename X, typename Func>
710bool QuicIntervalSet<T>::FindNextIntersectingPairImpl(X* x,
711 const QuicIntervalSet& y,
712 const_iterator* mine,
713 const_iterator* theirs,
714 Func on_hole) {
715 CHECK(x != nullptr);
716 if ((*mine == x->intervals_.end()) || (*theirs == y.intervals_.end())) {
717 return false;
718 }
719 while (!(**mine).Intersects(**theirs)) {
720 const_iterator erase_first = *mine;
721 // Skip over intervals in 'mine' that don't reach 'theirs'.
722 while (*mine != x->intervals_.end() && (**mine).max() <= (**theirs).min()) {
723 ++(*mine);
724 }
725 on_hole(x, erase_first, *mine);
726 // We're done if the end of intervals_ is reached.
727 if (*mine == x->intervals_.end()) {
728 return false;
729 }
730 // Skip over intervals 'theirs' that don't reach 'mine'.
731 while (*theirs != y.intervals_.end() &&
732 (**theirs).max() <= (**mine).min()) {
733 ++(*theirs);
734 }
735 // If the end of other.intervals_ is reached, we're done.
736 if (*theirs == y.intervals_.end()) {
737 on_hole(x, *mine, x->intervals_.end());
738 return false;
739 }
740 }
741 return true;
742}
743
744template <typename T>
745void QuicIntervalSet<T>::Intersection(const QuicIntervalSet& other) {
746 if (!SpanningInterval().Intersects(other.SpanningInterval())) {
747 intervals_.clear();
748 return;
749 }
750
751 const_iterator mine = FindIntersectionCandidate(other);
752 // Remove any intervals that cannot possibly intersect with other.intervals_.
753 intervals_.erase(intervals_.begin(), mine);
754 const_iterator theirs = other.FindIntersectionCandidate(*this);
755
756 while (FindNextIntersectingPairAndEraseHoles(other, &mine, &theirs)) {
757 // OK, *mine and *theirs intersect. Now, we find the largest
758 // span of intervals in other (starting at theirs) - say [a..b]
759 // - that intersect *mine, and we replace *mine with (*mine
760 // intersect x) for all x in [a..b] Note that subsequent
761 // intervals in this can't intersect any intervals in [a..b) --
762 // they may only intersect b or subsequent intervals in other.
763 value_type i(*mine);
764 intervals_.erase(mine);
765 mine = intervals_.end();
766 value_type intersection;
767 while (theirs != other.intervals_.end() &&
768 i.Intersects(*theirs, &intersection)) {
769 std::pair<typename Set::iterator, bool> ins =
770 intervals_.insert(intersection);
771 DCHECK(ins.second);
772 mine = ins.first;
773 ++theirs;
774 }
775 DCHECK(mine != intervals_.end());
776 --theirs;
777 ++mine;
778 }
779 DCHECK(Valid());
780}
781
782template <typename T>
783bool QuicIntervalSet<T>::Intersects(const QuicIntervalSet& other) const {
784 if (!SpanningInterval().Intersects(other.SpanningInterval())) {
785 return false;
786 }
787
788 const_iterator mine = FindIntersectionCandidate(other);
789 if (mine == intervals_.end()) {
790 return false;
791 }
792 const_iterator theirs = other.FindIntersectionCandidate(*mine);
793
794 return FindNextIntersectingPair(other, &mine, &theirs);
795}
796
797template <typename T>
798void QuicIntervalSet<T>::Difference(const value_type& interval) {
799 if (!SpanningInterval().Intersects(interval)) {
800 return;
801 }
802 Difference(QuicIntervalSet<T>(interval));
803}
804
805template <typename T>
806void QuicIntervalSet<T>::Difference(const T& min, const T& max) {
807 Difference(value_type(min, max));
808}
809
810template <typename T>
811void QuicIntervalSet<T>::Difference(const QuicIntervalSet& other) {
812 if (!SpanningInterval().Intersects(other.SpanningInterval())) {
813 return;
814 }
815
816 const_iterator mine = FindIntersectionCandidate(other);
817 // If no interval in mine reaches the first interval of theirs then we're
818 // done.
819 if (mine == intervals_.end()) {
820 return;
821 }
822 const_iterator theirs = other.FindIntersectionCandidate(*this);
823
824 while (FindNextIntersectingPair(other, &mine, &theirs)) {
825 // At this point *mine and *theirs overlap. Remove mine from
826 // intervals_ and replace it with the possibly two intervals that are
827 // the difference between mine and theirs.
828 value_type i(*mine);
829 intervals_.erase(mine++);
830 value_type lo;
831 value_type hi;
832 i.Difference(*theirs, &lo, &hi);
833
834 if (!lo.Empty()) {
835 // We have a low end. This can't intersect anything else.
836 std::pair<typename Set::iterator, bool> ins = intervals_.insert(lo);
837 DCHECK(ins.second);
838 }
839
840 if (!hi.Empty()) {
841 std::pair<typename Set::iterator, bool> ins = intervals_.insert(hi);
842 DCHECK(ins.second);
843 mine = ins.first;
844 }
845 }
846 DCHECK(Valid());
847}
848
849template <typename T>
850void QuicIntervalSet<T>::Complement(const T& min, const T& max) {
851 QuicIntervalSet<T> span(min, max);
852 span.Difference(*this);
853 intervals_.swap(span.intervals_);
854}
855
856template <typename T>
vasilvvc48c8712019-03-11 13:38:16 -0700857std::string QuicIntervalSet<T>::ToString() const {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500858 std::ostringstream os;
859 os << *this;
860 return os.str();
861}
862
863// This method compacts the QuicIntervalSet, merging pairs of overlapping
864// intervals into a single interval. In the steady state, the QuicIntervalSet
865// does not contain any such pairs. However, the way the Union() and Add()
866// methods work is to temporarily put the QuicIntervalSet into such a state and
867// then to call Compact() to "fix it up" so that it is no longer in that state.
868//
869// Compact() needs the interval set to allow two intervals [a,b) and [a,c)
870// (having the same min() but different max()) to briefly coexist in the set at
871// the same time, and be adjacent to each other, so that they can be efficiently
872// located and merged into a single interval. This state would be impossible
873// with a comparator which only looked at min(), as such a comparator would
874// consider such pairs equal. Fortunately, the comparator used by
875// QuicIntervalSet does exactly what is needed, ordering first by ascending
876// min(), then by descending max().
877template <typename T>
878void QuicIntervalSet<T>::Compact(const typename Set::iterator& begin,
879 const typename Set::iterator& end) {
880 if (begin == end)
881 return;
882 typename Set::iterator next = begin;
883 typename Set::iterator prev = begin;
884 typename Set::iterator it = begin;
885 ++it;
886 ++next;
887 while (it != end) {
888 ++next;
889 if (prev->max() >= it->min()) {
890 // Overlapping / coalesced range; merge the two intervals.
891 T min = prev->min();
892 T max = std::max(prev->max(), it->max());
893 value_type i(min, max);
894 intervals_.erase(prev);
895 intervals_.erase(it);
896 std::pair<typename Set::iterator, bool> ins = intervals_.insert(i);
897 DCHECK(ins.second);
898 prev = ins.first;
899 } else {
900 prev = it;
901 }
902 it = next;
903 }
904}
905
906template <typename T>
907bool QuicIntervalSet<T>::Valid() const {
908 const_iterator prev = end();
909 for (const_iterator it = begin(); it != end(); ++it) {
910 // invalid or empty interval.
911 if (it->min() >= it->max())
912 return false;
913 // Not sorted, not disjoint, or adjacent.
914 if (prev != end() && prev->max() >= it->min())
915 return false;
916 prev = it;
917 }
918 return true;
919}
920
921template <typename T>
922void swap(QuicIntervalSet<T>& x, QuicIntervalSet<T>& y) {
923 x.Swap(&y);
924}
925
926// This comparator orders intervals first by ascending min() and then by
927// descending max(). Readers who are satisified with that explanation can stop
928// reading here. The remainder of this comment is for the benefit of future
929// maintainers of this library.
930//
931// The reason for this ordering is that this comparator has to serve two
932// masters. First, it has to maintain the intervals in its internal set in the
933// order that clients expect to see them. Clients see these intervals via the
934// iterators provided by begin()/end() or as a result of invoking Get(). For
935// this reason, the comparator orders intervals by ascending min().
936//
937// If client iteration were the only consideration, then ordering by ascending
938// min() would be good enough. This is because the intervals in the
939// QuicIntervalSet are non-empty, non-adjacent, and mutually disjoint; such
940// intervals happen to always have disjoint min() values, so such a comparator
941// would never even have to look at max() in order to work correctly for this
942// class.
943//
944// However, in addition to ordering by ascending min(), this comparator also has
945// a second responsibility: satisfying the special needs of this library's
946// peculiar internal implementation. These needs require the comparator to order
947// first by ascending min() and then by descending max(). The best way to
948// understand why this is so is to check out the comments associated with the
949// Find() and Compact() methods.
950template <typename T>
951bool QuicIntervalSet<T>::IntervalLess::operator()(const value_type& a,
952 const value_type& b) const {
953 return a.min() < b.min() || (a.min() == b.min() && a.max() > b.max());
954}
955
956} // namespace quic
957
958#endif // QUICHE_QUIC_CORE_QUIC_INTERVAL_SET_H_