block_buffer/
read.rs

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
142
143
144
145
146
147
148
149
150
151
152
153
154
use super::{Array, ArraySize, Error};

use core::{fmt, slice};
#[cfg(feature = "zeroize")]
use zeroize::Zeroize;

/// Buffer for reading block-generated data.
pub struct ReadBuffer<BS: ArraySize> {
    // The first byte of the block is used as position.
    buffer: Array<u8, BS>,
}

impl<BS: ArraySize> fmt::Debug for ReadBuffer<BS> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ReadBuffer")
            .field("remaining_data", &self.get_pos())
            .finish()
    }
}

impl<BS: ArraySize> Default for ReadBuffer<BS> {
    #[inline]
    fn default() -> Self {
        let mut buffer = Array::<u8, BS>::default();
        buffer[0] = BS::U8;
        Self { buffer }
    }
}

impl<BS: ArraySize> Clone for ReadBuffer<BS> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            buffer: self.buffer.clone(),
        }
    }
}

impl<BS: ArraySize> ReadBuffer<BS> {
    /// Return current cursor position.
    #[inline(always)]
    pub fn get_pos(&self) -> usize {
        let pos = self.buffer[0];
        if pos == 0 || pos > BS::U8 {
            debug_assert!(false);
            // SAFETY: `pos` never breaks the invariant
            unsafe {
                core::hint::unreachable_unchecked();
            }
        }
        pos as usize
    }

    /// Return size of the internal buffer in bytes.
    #[inline(always)]
    pub fn size(&self) -> usize {
        BS::USIZE
    }

    /// Return number of remaining bytes in the internal buffer.
    #[inline(always)]
    pub fn remaining(&self) -> usize {
        self.size() - self.get_pos()
    }

    #[inline(always)]
    fn set_pos_unchecked(&mut self, pos: usize) {
        debug_assert!(pos <= BS::USIZE);
        self.buffer[0] = pos as u8;
    }

    /// Write remaining data inside buffer into `data`, fill remaining space
    /// in `data` with blocks generated by `gen_block`, and save leftover data
    /// from the last generated block into buffer for future use.
    #[inline]
    pub fn read(&mut self, mut data: &mut [u8], mut gen_block: impl FnMut(&mut Array<u8, BS>)) {
        let pos = self.get_pos();
        let r = self.remaining();
        let n = data.len();

        if r != 0 {
            if n < r {
                // double slicing allows to remove panic branches
                data.copy_from_slice(&self.buffer[pos..][..n]);
                self.set_pos_unchecked(pos + n);
                return;
            }
            let (left, right) = data.split_at_mut(r);
            data = right;
            left.copy_from_slice(&self.buffer[pos..]);
        }

        let (blocks, leftover) = Self::to_blocks_mut(data);
        for block in blocks {
            gen_block(block);
        }

        let n = leftover.len();
        if n != 0 {
            let mut block = Default::default();
            gen_block(&mut block);
            leftover.copy_from_slice(&block[..n]);
            self.buffer = block;
            self.set_pos_unchecked(n);
        } else {
            self.set_pos_unchecked(BS::USIZE);
        }
    }

    /// Serialize buffer into a byte array.
    #[inline]
    pub fn serialize(&self) -> Array<u8, BS> {
        let mut res = self.buffer.clone();
        let pos = self.get_pos();
        // zeroize "garbage" data
        for b in res[1..pos].iter_mut() {
            *b = 0;
        }
        res
    }

    /// Deserialize buffer from a byte array.
    #[inline]
    pub fn deserialize(buffer: &Array<u8, BS>) -> Result<Self, Error> {
        let pos = buffer[0];
        if pos == 0 || pos > BS::U8 || buffer[1..pos as usize].iter().any(|&b| b != 0) {
            Err(Error)
        } else {
            Ok(Self {
                buffer: buffer.clone(),
            })
        }
    }

    /// Split message into mutable slice of parallel blocks, blocks, and leftover bytes.
    #[inline(always)]
    fn to_blocks_mut(data: &mut [u8]) -> (&mut [Array<u8, BS>], &mut [u8]) {
        let nb = data.len() / BS::USIZE;
        let (left, right) = data.split_at_mut(nb * BS::USIZE);
        let p = left.as_mut_ptr() as *mut Array<u8, BS>;
        // SAFETY: we guarantee that `blocks` does not point outside of `data`, and `p` is valid for
        // mutation
        let blocks = unsafe { slice::from_raw_parts_mut(p, nb) };
        (blocks, right)
    }
}

#[cfg(feature = "zeroize")]
impl<BS: ArraySize> Zeroize for ReadBuffer<BS> {
    #[inline]
    fn zeroize(&mut self) {
        self.buffer.zeroize();
    }
}