Skip to main content

flow_runner/
blob.rs

1//! A compiled flow as bytes to store, and back.
2//!
3//! A blob is the signature `FLOW`, the blob version, the flow's hash, the
4//! source, and a checksum of all that.
5
6use crate::common::checksum::{self, CHECKSUM_LEN};
7use crate::common::error::LoadError;
8use crate::common::limits::MAX_SOURCE_BYTES;
9use crate::common::versions::BLOB_VERSION;
10use crate::flow::{Flow, HASH_LEN};
11
12const SIGNATURE: [u8; 4] = *b"FLOW";
13const VERSION_AT: usize = SIGNATURE.len();
14const HASH_AT: usize = VERSION_AT + std::mem::size_of::<u32>();
15const SOURCE_AT: usize = HASH_AT + HASH_LEN;
16
17impl Flow {
18    /// The flow as bytes to store. They hold the source, which
19    /// [`from_bytes`](Self::from_bytes) compiles again.
20    pub fn to_bytes(&self) -> Vec<u8> {
21        let mut out = Vec::with_capacity(SOURCE_AT + self.source.len() + CHECKSUM_LEN);
22        out.extend_from_slice(&SIGNATURE);
23        out.extend_from_slice(&BLOB_VERSION.to_le_bytes());
24        out.extend_from_slice(&self.hash);
25        out.extend_from_slice(self.source.as_bytes());
26        checksum::append(&mut out);
27        out
28    }
29
30    /// Load a flow saved with [`to_bytes`](Self::to_bytes). Any damaged byte
31    /// is refused, and the source must compile to the hash saved with it.
32    pub fn from_bytes(bytes: &[u8]) -> Result<Flow, LoadError> {
33        if bytes.len() > SOURCE_AT + MAX_SOURCE_BYTES + CHECKSUM_LEN {
34            return Err(LoadError::corrupt("larger than any flow blob"));
35        }
36        if !bytes.starts_with(&SIGNATURE) {
37            return Err(LoadError::corrupt("not a flow blob"));
38        }
39        let body = checksum::strip(bytes).ok_or_else(|| LoadError::corrupt("checksum mismatch"))?;
40        let version = body
41            .get(VERSION_AT..HASH_AT)
42            .and_then(|version| version.try_into().ok())
43            .map(u32::from_le_bytes)
44            .ok_or_else(|| LoadError::corrupt("truncated"))?;
45        if version != BLOB_VERSION {
46            return Err(LoadError::IncompatibleVersion {
47                found: version,
48                expected: BLOB_VERSION,
49            });
50        }
51        let stored_hash = body
52            .get(HASH_AT..SOURCE_AT)
53            .ok_or_else(|| LoadError::corrupt("truncated"))?;
54        let source = std::str::from_utf8(&body[SOURCE_AT..])
55            .map_err(|_| LoadError::corrupt("the source is not valid UTF-8"))?;
56        let flow = Flow::compile(source).map_err(LoadError::Invalid)?;
57        if flow.hash[..] != *stored_hash {
58            return Err(LoadError::HashChanged);
59        }
60        Ok(flow)
61    }
62}