1use std::ops::{Bound, Range, RangeBounds, RangeInclusive};
4
5pub trait RangeExt<T>
7where
8 Self: Sized,
9{
10 fn from_range_bounds<B>(bounds: B, min_incl: T, max_excl: T) -> Option<Self>
12 where
13 B: RangeBounds<T>;
14}
15
16macro_rules! impl_rangeext_range_uint {
18 ($uint:ty) => {
19 impl RangeExt<$uint> for Range<$uint> {
20 fn from_range_bounds<B>(bounds: B, min_incl: $uint, max_excl: $uint) -> Option<Self>
21 where
22 B: RangeBounds<$uint>,
23 {
24 let start = match bounds.start_bound() {
26 Bound::Included(start) => *start,
27 Bound::Excluded(_) => unreachable!("excluded bounds are invalid for range starts"),
28 Bound::Unbounded => min_incl,
29 };
30 let end = match bounds.end_bound() {
31 Bound::Included(before_end) => before_end.saturating_add(1),
32 Bound::Excluded(end) => *end,
33 Bound::Unbounded => max_excl,
34 };
35
36 if start < min_incl || start > max_excl {
38 return None;
39 }
40 if end < min_incl || end > max_excl {
41 return None;
42 }
43 Some(start..end)
44 }
45 }
46 };
47}
48impl_rangeext_range_uint!(u64);
49impl_rangeext_range_uint!(usize);
50
51macro_rules! impl_rangeext_rangeinclusive_uint {
53 ($uint:ty) => {
54 impl RangeExt<$uint> for RangeInclusive<$uint> {
55 fn from_range_bounds<B>(bounds: B, min_incl: $uint, max_excl: $uint) -> Option<Self>
56 where
57 B: RangeBounds<$uint>,
58 {
59 let start = match bounds.start_bound() {
61 Bound::Included(start) => *start,
62 Bound::Excluded(_) => unreachable!("excluded bounds are invalid for range starts"),
63 Bound::Unbounded => min_incl,
64 };
65 let end_incl = match bounds.end_bound() {
66 Bound::Included(end) => *end,
67 Bound::Excluded(after_end) => after_end.saturating_sub(1),
68 Bound::Unbounded => max_excl.saturating_sub(1),
69 };
70
71 if start < min_incl || start >= max_excl {
73 return None;
74 }
75 if end_incl < min_incl || end_incl >= max_excl {
76 return None;
77 }
78 Some(start..=end_incl)
79 }
80 }
81 };
82}
83impl_rangeext_rangeinclusive_uint!(u64);
84impl_rangeext_rangeinclusive_uint!(usize);