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
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
use std::{
    io::{Error, ErrorKind, Result},
    marker::PhantomData,
    mem,
    ops::{Deref, Range, RangeFrom, RangeFull, RangeInclusive, RangeTo, RangeToInclusive},
    slice,
};

/// TryGet trait.
pub trait TryGet<T> {
    type Output;

    /// Returns a byte or subslice depending on the type of index.
    fn try_get(&self, index: T) -> Result<Self::Output>;
}

macro_rules! impl_slice_index {
    ( $( $x:ty ), * ) => {
        $(
            impl TryGet<$x> for ByteSlice {
                type Output = ByteSlice;

                fn try_get(&self, index: $x) -> Result<ByteSlice> {
                    <[u8]>::get(self, index)
                        .map(|s| unsafe { ByteSlice::from_raw_parts(s.as_ptr(), s.len()) })
                        .ok_or_else(|| Error::new(ErrorKind::Other, "out of bounds"))
                }
            }
        )*
    };
}

impl_slice_index!(
    Range<usize>,
    RangeFrom<usize>,
    RangeFull,
    RangeInclusive<usize>,
    RangeTo<usize>,
    RangeToInclusive<usize>
);

impl TryGet<usize> for ByteSlice {
    type Output = u8;

    fn try_get(&self, index: usize) -> Result<u8> {
        <[u8]>::get(self, index)
            .cloned()
            .ok_or_else(|| Error::new(ErrorKind::Other, "out of bounds"))
    }
}

/// A fixed-lifetime slice object.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct ByteSlice(&'static [u8]);

impl ByteSlice {
    /// Creates a new empty ByteSlice.
    pub fn new() -> ByteSlice {
        ByteSlice(&[])
    }

    /// Creates a new ByteSlice from a length and pointer.
    ///
    /// The pointer must be valid during the program execution.
    pub unsafe fn from_raw_parts(data: *const u8, len: usize) -> ByteSlice {
        ByteSlice(slice::from_raw_parts(data, len))
    }

    /// Returns the length of this ByteSlice.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns true if this ByteSlice has a length of zero.
    ///
    /// Returns false otherwise.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns a raw pointer to the first byte in this ByteSlice.
    pub fn as_ptr(&self) -> *const u8 {
        self.0.as_ptr()
    }
}

impl From<&'static [u8]> for ByteSlice {
    fn from(data: &'static [u8]) -> Self {
        ByteSlice(data)
    }
}

impl From<Box<[u8]>> for ByteSlice {
    fn from(data: Box<[u8]>) -> Self {
        let s = unsafe { ByteSlice::from_raw_parts(data.as_ptr(), data.len()) };
        mem::forget(data);
        s
    }
}

impl From<Vec<u8>> for ByteSlice {
    fn from(data: Vec<u8>) -> Self {
        ByteSlice::from(data.into_boxed_slice())
    }
}

impl Deref for ByteSlice {
    type Target = [u8];

    fn deref(&self) -> &'static [u8] {
        self.0
    }
}

impl AsRef<[u8]> for ByteSlice {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

#[repr(C)]
struct SafeByteSlice<'a, T: 'a> {
    ptr: *const T,
    len: u64,
    phantom: PhantomData<&'a T>,
}

impl<'a, T: 'a> SafeByteSlice<'a, T> {
    pub fn as_slice(&self) -> &[T] {
        unsafe { slice::from_raw_parts(&*self.ptr, self.len as usize) }
    }
}

impl<'a, T: 'a> Deref for SafeByteSlice<'a, T> {
    type Target = [T];

    fn deref(&self) -> &[T] {
        self.as_slice()
    }
}