Skip to content

Commit

Permalink
Implement core::ops::RangeBounds for range types`
Browse files Browse the repository at this point in the history
  • Loading branch information
chrismit3s committed Mar 13, 2022
1 parent ddb14c1 commit 4b92422
Showing 1 changed file with 62 additions and 2 deletions.
64 changes: 62 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ extern crate std;
extern crate num_integer as integer;
extern crate num_traits as traits;

use core::ops::{Add, Sub};
use core::ops::{Add, Bound, RangeBounds, Sub};
use core::usize;
use integer::Integer;
use traits::{CheckedAdd, One, ToPrimitive, Zero};
Expand Down Expand Up @@ -84,6 +84,16 @@ fn unsigned<T: ToPrimitive>(x: &T) -> Option<u64> {
}
}

impl<A> RangeBounds<A> for Range<A> {
fn start_bound(&self) -> Bound<&A> {
Bound::Included(&self.state)
}

fn end_bound(&self) -> Bound<&A> {
Bound::Excluded(&self.stop)
}
}

// FIXME: rust-lang/rust#10414: Unfortunate type bound
impl<A> Iterator for Range<A>
where
Expand Down Expand Up @@ -163,6 +173,16 @@ where
}
}

impl<A> RangeBounds<A> for RangeInclusive<A> {
fn start_bound(&self) -> Bound<&A> {
Bound::Included(&self.range.state)
}

fn end_bound(&self) -> Bound<&A> {
Bound::Included(&self.range.stop)
}
}

impl<A> Iterator for RangeInclusive<A>
where
A: Add<A, Output = A> + PartialOrd + Clone + ToPrimitive,
Expand All @@ -180,7 +200,7 @@ where
} else {
None
}
}
},
}
}

Expand Down Expand Up @@ -228,6 +248,16 @@ pub struct RangeStep<A> {
rev: bool,
}

impl<A> RangeBounds<A> for RangeStep<A> {
fn start_bound(&self) -> Bound<&A> {
Bound::Included(&self.state)
}

fn end_bound(&self) -> Bound<&A> {
Bound::Excluded(&self.stop)
}
}

/// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping.
#[inline]
pub fn range_step<A>(start: A, stop: A, step: A) -> RangeStep<A>
Expand Down Expand Up @@ -290,6 +320,16 @@ where
}
}

impl<A> RangeBounds<A> for RangeStepInclusive<A> {
fn start_bound(&self) -> Bound<&A> {
Bound::Included(&self.state)
}

fn end_bound(&self) -> Bound<&A> {
Bound::Included(&self.stop)
}
}

impl<A> Iterator for RangeStepInclusive<A>
where
A: CheckedAdd + PartialOrd + Clone + PartialEq,
Expand Down Expand Up @@ -337,6 +377,16 @@ where
}
}

impl<A> RangeBounds<A> for RangeFrom<A> {
fn start_bound(&self) -> Bound<&A> {
Bound::Included(&self.state)
}

fn end_bound(&self) -> Bound<&A> {
Bound::Unbounded
}
}

impl<A> Iterator for RangeFrom<A>
where
A: Add<A, Output = A> + Clone,
Expand Down Expand Up @@ -380,6 +430,16 @@ where
}
}

impl<A> RangeBounds<A> for RangeStepFrom<A> {
fn start_bound(&self) -> Bound<&A> {
Bound::Included(&self.state)
}

fn end_bound(&self) -> Bound<&A> {
Bound::Unbounded
}
}

impl<A> Iterator for RangeStepFrom<A>
where
A: Add<A, Output = A> + Clone,
Expand Down

0 comments on commit 4b92422

Please sign in to comment.