1
Fork 0

core: add inclusive ranges to core::ops

Since it removes the old iter::{range_inclusive, RangeInclusive} which
were unstable and deprecated, this is a [breaking-change] on nightly.
This commit is contained in:
Alex Burka 2016-01-13 16:48:58 -05:00
parent f1e191c0b9
commit c5d58de665
3 changed files with 167 additions and 91 deletions

View file

@ -67,8 +67,11 @@
#![stable(feature = "rust1", since = "1.0.0")]
use marker::{Sized, Unsize};
use cmp::PartialOrd;
use fmt;
use convert::From;
use marker::{Sized, Unsize};
use num::One;
/// The `Drop` trait is used to run some code when a value goes out of scope.
/// This is sometimes called a 'destructor'.
@ -1530,6 +1533,73 @@ impl<Idx: fmt::Debug> fmt::Debug for RangeTo<Idx> {
}
}
/// An inclusive range which is bounded at both ends.
#[derive(Copy, Clone, PartialEq, Eq)]
#[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
pub enum RangeInclusive<Idx> {
/// Empty range (iteration has finished)
Empty {
/// The point at which iteration finished
at: Idx
},
/// Non-empty range (iteration will yield value(s))
NonEmpty {
/// The lower bound of the range (inclusive).
start: Idx,
/// The upper bound of the range (inclusive).
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),
}
}
}
#[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
impl<Idx: PartialOrd + One + Sub<Output=Idx>> From<Range<Idx>> for RangeInclusive<Idx> {
fn from(range: Range<Idx>) -> RangeInclusive<Idx> {
use self::RangeInclusive::*;
if range.start < range.end {
NonEmpty {
start: range.start,
end: range.end - Idx::one() // can't underflow because end > start >= MIN
}
} else {
Empty {
at: range.start
}
}
}
}
/// An inclusive range which is only bounded above.
#[derive(Copy, Clone, PartialEq, Eq)]
#[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
pub struct RangeToInclusive<Idx> {
/// The upper bound of the range (inclusive)
#[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
pub end: Idx,
}
#[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
impl<Idx: fmt::Debug> fmt::Debug for RangeToInclusive<Idx> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "...{:?}", self.end)
}
}
// RangeToInclusive<Idx> cannot impl From<RangeTo<Idx>>
// because underflow would be possible with (..0).into()
/// The `Deref` trait is used to specify the functionality of dereferencing
/// operations, like `*v`.
///