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
use super::*;

#[derive(Debug)]
pub struct ByteSliceDriver<'a> {
    mode: DriverMode,
    input: &'a [u8],
    depth: usize,
    max_depth: usize,
}

impl<'a> ByteSliceDriver<'a> {
    pub fn new(input: &'a [u8], options: &Options) -> Self {
        let mode = options.driver_mode.unwrap_or(DriverMode::Direct);
        let max_depth = options.max_depth_or_default();

        Self {
            input,
            mode,
            depth: 0,
            max_depth,
        }
    }
}

impl<'a> FillBytes for ByteSliceDriver<'a> {
    #[inline]
    fn mode(&self) -> DriverMode {
        self.mode
    }

    #[inline]
    fn peek_bytes(&mut self, offset: usize, bytes: &mut [u8]) -> Option<()> {
        match self.mode {
            DriverMode::Direct => {
                if (offset + bytes.len()) > self.input.len() {
                    None
                } else {
                    bytes.copy_from_slice(&self.input[offset..(offset + bytes.len())]);
                    Some(())
                }
            }
            DriverMode::Forced => {
                if offset < self.input.len() {
                    let copy_len = core::cmp::min(bytes.len(), self.input.len() - offset);
                    bytes[..copy_len].copy_from_slice(&self.input[offset..(offset + copy_len)]);
                    bytes[copy_len..].fill(0);
                } else {
                    bytes.fill(0);
                }
                Some(())
            }
        }
    }

    #[inline]
    fn consume_bytes(&mut self, consumed: usize) {
        self.input = &self.input[core::cmp::min(consumed, self.input.len())..];
    }
}

impl<'a> Driver for ByteSliceDriver<'a> {
    gen_from_bytes!();

    #[inline]
    fn gen_from_bytes<Hint, Gen, T>(&mut self, _hint: Hint, mut gen: Gen) -> Option<T>
    where
        Hint: FnOnce() -> (usize, Option<usize>),
        Gen: FnMut(&[u8]) -> Option<(usize, T)>,
    {
        let slice = self.input;
        let (len, value) = gen(slice)?;
        self.consume_bytes(len);
        Some(value)
    }

    #[inline]
    fn depth(&self) -> usize {
        self.depth
    }

    #[inline]
    fn set_depth(&mut self, depth: usize) {
        self.depth = depth;
    }

    #[inline]
    fn max_depth(&self) -> usize {
        self.max_depth
    }
}