checked_array/
misc.rs

1use crate::std::{
2    fmt::{ self, Display, Formatter },
3    ops::{ Range, RangeBounds, Bound }
4};
5#[cfg(feature = "std")]
6use crate::std::error::Error;
7
8
9/// An error indicating that a buffer is too small
10#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
11pub struct BufferTooSmall;
12impl Display for BufferTooSmall {
13    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
14        write!(f, "Buffer is too small")
15    }
16}
17#[cfg(feature = "std")]
18impl Error for BufferTooSmall {}
19
20
21/// An error which indicates that an implementation will always panic instead of returning an error
22#[derive(Debug)]
23#[non_exhaustive]
24pub enum WillPanic {}
25
26
27/// An extension to the range bounds trait
28pub trait RangeBoundsExt<T> {
29    /// Computes an absolute range from `self` using `default_start` and `default_end` as hints if the range is
30    /// (partially) open
31    fn into_absolute(self, default_start: T, default_end: T) -> Option<Range<T>>;
32}
33impl<T> RangeBoundsExt<usize> for T where T: RangeBounds<usize> {
34    fn into_absolute(self, default_start: usize, default_end: usize) -> Option<Range<usize>> {
35        // Translate start and end
36        let start = match self.start_bound() {
37            Bound::Included(start) => *start,
38            Bound::Excluded(start) => start.checked_add(1)?,
39            Bound::Unbounded => default_start
40        };
41        let end = match self.end_bound() {
42            Bound::Excluded(end) => *end,
43            Bound::Included(end) => end.checked_add(1)?,
44            Bound::Unbounded => default_end
45        };
46        
47        match start <= end {
48            true => Some(start..end),
49            false => None
50        }
51    }
52}