Skip to content

Commit

Permalink
Rollup merge of rust-lang#42134 - scottmcm:rangeinclusive-struct, r=a…
Browse files Browse the repository at this point in the history
…turon

Make RangeInclusive just a two-field struct

Not being an enum improves ergonomics and consistency, especially since NonEmpty variant wasn't prevented from being empty.  It can still be iterable without an extra "done" bit by making the range have !(start <= end), which is even possible without changing the Step trait.

Implements merged rust-lang/rfcs#1980; tracking issue rust-lang#28237.

This is definitely a breaking change to anything consuming `RangeInclusive` directly (not as an Iterator) or constructing it without using the sugar.  Is there some change that would make sense before this so compilation failures could be compatibly fixed ahead of time?

r? @aturon (as FCP proposer on the RFC)
  • Loading branch information
Mark-Simulacrum authored May 24, 2017
2 parents ce42e6c + 7eaca60 commit 933f3ee
Show file tree
Hide file tree
Showing 9 changed files with 149 additions and 255 deletions.
10 changes: 2 additions & 8 deletions src/libcollections/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,16 +106,10 @@ impl<T> RangeArgument<T> for Range<T> {
#[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
impl<T> RangeArgument<T> for RangeInclusive<T> {
fn start(&self) -> Bound<&T> {
match *self {
RangeInclusive::Empty{ ref at } => Included(at),
RangeInclusive::NonEmpty { ref start, .. } => Included(start),
}
Included(&self.start)
}
fn end(&self) -> Bound<&T> {
match *self {
RangeInclusive::Empty{ ref at } => Excluded(at),
RangeInclusive::NonEmpty { ref end, .. } => Included(end),
}
Included(&self.end)
}
}

Expand Down
174 changes: 55 additions & 119 deletions src/libcore/iter/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -403,61 +403,35 @@ impl<A: Step + Clone> Iterator for StepBy<A, ops::RangeInclusive<A>> {

#[inline]
fn next(&mut self) -> Option<A> {
use ops::RangeInclusive::*;

// this function has a sort of odd structure due to borrowck issues
// we may need to replace self.range, so borrows of start and end need to end early

let (finishing, n) = match self.range {
Empty { .. } => return None, // empty iterators yield no values

NonEmpty { ref mut start, ref mut end } => {
let rev = self.step_by.is_negative();

// march start towards (maybe past!) end and yield the old value
if (rev && start >= end) ||
(!rev && start <= end)
{
match start.step(&self.step_by) {
Some(mut n) => {
mem::swap(start, &mut n);
(None, Some(n)) // yield old value, remain non-empty
},
None => {
let mut n = end.clone();
mem::swap(start, &mut n);
(None, Some(n)) // yield old value, remain non-empty
}
}
} else {
// found range in inconsistent state (start at or past end), so become empty
(Some(end.replace_zero()), None)
}
}
};
let rev = self.step_by.is_negative();

// turn into an empty iterator if we've reached the end
if let Some(end) = finishing {
self.range = Empty { at: end };
if (rev && self.range.start >= self.range.end) ||
(!rev && self.range.start <= self.range.end)
{
match self.range.start.step(&self.step_by) {
Some(n) => {
Some(mem::replace(&mut self.range.start, n))
},
None => {
let last = self.range.start.replace_one();
self.range.end.replace_zero();
self.step_by.replace_one();
Some(last)
},
}
}
else {
None
}

n
}

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
use ops::RangeInclusive::*;

match self.range {
Empty { .. } => (0, Some(0)),

NonEmpty { ref start, ref end } =>
match Step::steps_between(start,
end,
&self.step_by) {
Some(hint) => (hint.saturating_add(1), hint.checked_add(1)),
None => (0, None)
}
match Step::steps_between(&self.range.start,
&self.range.end,
&self.step_by) {
Some(hint) => (hint.saturating_add(1), hint.checked_add(1)),
None => (0, None)
}
}
}
Expand Down Expand Up @@ -583,56 +557,31 @@ impl<A: Step> Iterator for ops::RangeInclusive<A> where

#[inline]
fn next(&mut self) -> Option<A> {
use ops::RangeInclusive::*;

// this function has a sort of odd structure due to borrowck issues
// we may need to replace self, so borrows of self.start and self.end need to end early

let (finishing, n) = match *self {
Empty { .. } => (None, None), // empty iterators yield no values

NonEmpty { ref mut start, ref mut end } => {
if start == end {
(Some(end.replace_one()), Some(start.replace_one()))
} else if start < end {
let mut n = start.add_one();
mem::swap(&mut n, start);

// if the iterator is done iterating, it will change from
// NonEmpty to Empty to avoid unnecessary drops or clones,
// we'll reuse either start or end (they are equal now, so
// it doesn't matter which) to pull out end, we need to swap
// something back in

(if n == *end { Some(end.replace_one()) } else { None },
// ^ are we done yet?
Some(n)) // < the value to output
} else {
(Some(start.replace_one()), None)
}
}
};

// turn into an empty iterator if this is the last value
if let Some(end) = finishing {
*self = Empty { at: end };
use cmp::Ordering::*;

match self.start.partial_cmp(&self.end) {
Some(Less) => {
let n = self.start.add_one();
Some(mem::replace(&mut self.start, n))
},
Some(Equal) => {
let last = self.start.replace_one();
self.end.replace_zero();
Some(last)
},
_ => None,
}

n
}

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
use ops::RangeInclusive::*;

match *self {
Empty { .. } => (0, Some(0)),
if !(self.start <= self.end) {
return (0, Some(0));
}

NonEmpty { ref start, ref end } =>
match Step::steps_between_by_one(start, end) {
Some(hint) => (hint.saturating_add(1), hint.checked_add(1)),
None => (0, None),
}
match Step::steps_between_by_one(&self.start, &self.end) {
Some(hint) => (hint.saturating_add(1), hint.checked_add(1)),
None => (0, None),
}
}
}
Expand All @@ -644,33 +593,20 @@ impl<A: Step> DoubleEndedIterator for ops::RangeInclusive<A> where
{
#[inline]
fn next_back(&mut self) -> Option<A> {
use ops::RangeInclusive::*;

// see Iterator::next for comments

let (finishing, n) = match *self {
Empty { .. } => return None,

NonEmpty { ref mut start, ref mut end } => {
if start == end {
(Some(start.replace_one()), Some(end.replace_one()))
} else if start < end {
let mut n = end.sub_one();
mem::swap(&mut n, end);

(if n == *start { Some(start.replace_one()) } else { None },
Some(n))
} else {
(Some(end.replace_one()), None)
}
}
};

if let Some(start) = finishing {
*self = Empty { at: start };
use cmp::Ordering::*;

match self.start.partial_cmp(&self.end) {
Some(Less) => {
let n = self.end.sub_one();
Some(mem::replace(&mut self.end, n))
},
Some(Equal) => {
let last = self.end.replace_zero();
self.start.replace_one();
Some(last)
},
_ => None,
}

n
}
}

Expand Down
40 changes: 8 additions & 32 deletions src/libcore/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2271,7 +2271,7 @@ impl<Idx: PartialOrd<Idx>> RangeTo<Idx> {
/// ```
/// #![feature(inclusive_range,inclusive_range_syntax)]
/// fn main() {
/// assert_eq!((3...5), std::ops::RangeInclusive::NonEmpty{ start: 3, end: 5 });
/// assert_eq!((3...5), std::ops::RangeInclusive{ start: 3, end: 5 });
/// assert_eq!(3+4+5, (3...5).sum());
///
/// let arr = [0, 1, 2, 3];
Expand All @@ -2281,45 +2281,23 @@ impl<Idx: PartialOrd<Idx>> RangeTo<Idx> {
/// ```
#[derive(Clone, PartialEq, Eq, Hash)] // not Copy -- see #27186
#[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
pub enum RangeInclusive<Idx> {
/// Empty range (iteration has finished)
pub struct RangeInclusive<Idx> {
/// The lower bound of the range (inclusive).
#[unstable(feature = "inclusive_range",
reason = "recently added, follows RFC",
issue = "28237")]
Empty {
/// The point at which iteration finished
#[unstable(feature = "inclusive_range",
reason = "recently added, follows RFC",
issue = "28237")]
at: Idx
},
/// Non-empty range (iteration will yield value(s))
pub start: Idx,
/// The upper bound of the range (inclusive).
#[unstable(feature = "inclusive_range",
reason = "recently added, follows RFC",
issue = "28237")]
NonEmpty {
/// The lower bound of the range (inclusive).
#[unstable(feature = "inclusive_range",
reason = "recently added, follows RFC",
issue = "28237")]
start: Idx,
/// The upper bound of the range (inclusive).
#[unstable(feature = "inclusive_range",
reason = "recently added, follows RFC",
issue = "28237")]
end: Idx,
},
pub end: Idx,
}

#[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
impl<Idx: fmt::Debug> fmt::Debug for RangeInclusive<Idx> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use self::RangeInclusive::*;

match *self {
Empty { ref at } => write!(fmt, "[empty range @ {:?}]", at),
NonEmpty { ref start, ref end } => write!(fmt, "{:?}...{:?}", start, end),
}
write!(fmt, "{:?}...{:?}", self.start, self.end)
}
}

Expand All @@ -2341,9 +2319,7 @@ impl<Idx: PartialOrd<Idx>> RangeInclusive<Idx> {
/// }
/// ```
pub fn contains(&self, item: Idx) -> bool {
if let &RangeInclusive::NonEmpty{ref start, ref end} = self {
(*start <= item) && (item <= *end)
} else { false }
self.start <= item && item <= self.end
}
}

Expand Down
Loading

0 comments on commit 933f3ee

Please sign in to comment.