1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use core::fmt;

#[derive(Copy, Clone)]
pub struct CheckedRange {
    start: usize,
    end: usize,

    #[cfg(all(debug_assertions, feature = "checked_range_unsafe"))]
    original_ptr: *const u8,
}

impl CheckedRange {
    #[inline]
    pub(crate) fn new(start: usize, end: usize, original_ptr: *const u8) -> Self {
        #[cfg(not(all(debug_assertions, feature = "checked_range_unsafe")))]
        let _ = original_ptr;

        Self {
            start,
            end,
            #[cfg(all(debug_assertions, feature = "checked_range_unsafe"))]
            original_ptr,
        }
    }

    #[cfg(feature = "checked_range_unsafe")]
    #[inline]
    pub fn get<'a>(&self, slice: &'a [u8]) -> &'a [u8] {
        unsafe {
            #[cfg(debug_assertions)]
            debug_assert_eq!(slice.as_ptr().add(self.start), self.original_ptr);

            slice.get_unchecked(self.start..self.end)
        }
    }

    #[cfg(not(feature = "checked_range_unsafe"))]
    #[inline]
    pub fn get<'a>(&self, slice: &'a [u8]) -> &'a [u8] {
        &slice[self.start..self.end]
    }

    #[cfg(feature = "checked_range_unsafe")]
    #[inline]
    pub fn get_mut<'a>(&self, slice: &'a mut [u8]) -> &'a mut [u8] {
        unsafe {
            #[cfg(debug_assertions)]
            debug_assert_eq!(slice.as_ptr().add(self.start), self.original_ptr);

            slice.get_unchecked_mut(self.start..self.end)
        }
    }

    #[cfg(not(feature = "checked_range_unsafe"))]
    #[inline]
    pub fn get_mut<'a>(&self, slice: &'a mut [u8]) -> &'a mut [u8] {
        &mut slice[self.start..self.end]
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.end - self.start
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.start == self.end
    }
}

impl fmt::Debug for CheckedRange {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}..{}", self.start, self.end)
    }
}