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