sieve/runtime/
serialize.rs

1/*
2 * Copyright (c) 2020-2023, Stalwart Labs Ltd.
3 *
4 * This file is part of the Stalwart Sieve Interpreter.
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as
8 * published by the Free Software Foundation, either version 3 of
9 * the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
15 * in the LICENSE file at the top-level directory of this distribution.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 *
19 * You can be released from the requirements of the AGPLv3 license by
20 * purchasing a commercial license. Please contact licensing@stalw.art
21 * for more details.
22*/
23
24use crate::{Compiler, Sieve};
25
26const SIEVE_MARKER: u8 = 0xff;
27
28pub enum SerializeError {
29    Other,
30}
31
32impl Sieve {
33    pub fn deserialize(bytes: &[u8]) -> Result<Self, Box<bincode::ErrorKind>> {
34        if bytes.len() > 2 && bytes[0] == SIEVE_MARKER && bytes[1] == Compiler::VERSION as u8 {
35            bincode::deserialize(&bytes[2..])
36        } else {
37            Err(Box::new(bincode::ErrorKind::Custom(
38                "Incompatible version".to_string(),
39            )))
40        }
41    }
42
43    pub fn serialize(&self) -> Result<Vec<u8>, Box<bincode::ErrorKind>> {
44        let mut buf = Vec::with_capacity(bincode::serialized_size(self)? as usize + 2);
45        buf.push(SIEVE_MARKER);
46        buf.push(Compiler::VERSION as u8);
47        bincode::serialize_into(&mut buf, self)?;
48        Ok(buf)
49    }
50}