@@ -94,32 +94,30 @@ impl<I: Interval> IntervalSet<I> {
9494 // Find the first range that is not greater than the new interval.
9595 // This is the first range that could possibly be unioned with the
9696 // new interval.
97- let mut drain_end = self . ranges . len ( ) ;
98- while drain_end > 0
99- && self . ranges [ drain_end - 1 ] . lower ( ) > interval. upper ( )
100- && !self . ranges [ drain_end - 1 ] . is_contiguous ( & interval)
101- {
102- drain_end -= 1 ;
103- }
104-
105- // Try to union the new interval with old intervals backwards.
106- if drain_end > 0 && self . ranges [ drain_end - 1 ] . is_contiguous ( & interval)
107- {
108- self . ranges [ drain_end - 1 ] =
109- self . ranges [ drain_end - 1 ] . union ( & interval) . unwrap ( ) ;
110- for i in ( 0 ..drain_end - 1 ) . rev ( ) {
111- if let Some ( union) =
112- self . ranges [ drain_end - 1 ] . union ( & self . ranges [ i] )
113- {
114- self . ranges [ drain_end - 1 ] = union;
115- } else {
116- self . ranges . drain ( i + 1 ..drain_end - 1 ) ;
117- break ;
97+ for i in 0 ..self . ranges . len ( ) {
98+ if self . ranges [ i] . is_contiguous ( & interval) {
99+ self . ranges [ i] = self . ranges [ i] . union ( & interval) . unwrap ( ) ;
100+ // Try to union the new interval with all subsequent ranges.
101+ // When it's no longer possible to union, remove the remaining
102+ // ranges and return.
103+ for j in i + 1 ..self . ranges . len ( ) {
104+ if let Some ( union) = self . ranges [ i] . union ( & self . ranges [ j] )
105+ {
106+ self . ranges [ i] = union;
107+ } else {
108+ self . ranges . drain ( i + 1 ..j) ;
109+ return ;
110+ }
118111 }
112+ self . ranges . drain ( i + 1 ..) ;
113+ return ;
114+ } else if self . ranges [ i] . lower ( ) > interval. upper ( ) {
115+ self . ranges . insert ( i, interval) ;
116+ return ;
119117 }
120- } else {
121- self . ranges . insert ( drain_end, interval) ;
122118 }
119+
120+ self . ranges . push ( interval) ;
123121 }
124122
125123 /// Return an iterator over all intervals in this set.
0 commit comments