Skip to main content

cadmpeg_core/decode/
whole_input.rs

1// SPDX-License-Identifier: Apache-2.0
2//! A detection prefix proven to hold every byte of its source.
3
4use std::io::SeekFrom;
5
6use crate::decode::View;
7use crate::{CodecError, ReadSeek};
8
9/// A detection prefix that holds every byte of its source.
10///
11/// [`WholeInput::of_source`] is the only constructor, so a holder knows the
12/// source has no byte beyond the view.
13#[derive(Debug, Clone, Copy)]
14pub struct WholeInput<'a> {
15    view: View<'a>,
16}
17
18impl<'a> WholeInput<'a> {
19    /// Proves that `prefix` is the whole of `source`.
20    ///
21    /// `prefix` must start at offset 0 and its length must equal the source
22    /// length. The source position is restored on every path that returns.
23    pub fn of_source(
24        prefix: View<'a>,
25        source: &mut dyn ReadSeek,
26    ) -> Result<Option<Self>, CodecError> {
27        let entry = source.stream_position()?;
28        let length = source.seek(SeekFrom::End(0));
29        source.seek(SeekFrom::Start(entry))?;
30        let length = length?;
31        let whole =
32            prefix.start() == 0 && crate::decode::u64_from_index(prefix.window().len()) == length;
33        Ok(whole.then_some(Self { view: prefix }))
34    }
35
36    /// The bytes of the whole source.
37    pub fn view(self) -> View<'a> {
38        self.view
39    }
40}
41
42#[cfg(test)]
43mod tests;