vecdb/variants/stored/
format.rs

1use std::{fs, io, path::Path};
2
3use serde_derive::{Deserialize, Serialize};
4
5use crate::{Error, Result};
6
7#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
8pub enum Format {
9    Compressed,
10    #[default]
11    Raw,
12}
13
14impl Format {
15    pub fn write(&self, path: &Path) -> Result<(), io::Error> {
16        fs::write(path, self.as_bytes())
17    }
18
19    pub fn is_raw(&self) -> bool {
20        *self == Self::Raw
21    }
22
23    pub fn is_compressed(&self) -> bool {
24        *self == Self::Compressed
25    }
26
27    fn as_bytes(&self) -> Vec<u8> {
28        if self.is_compressed() {
29            vec![1]
30        } else {
31            vec![0]
32        }
33    }
34
35    fn from_bytes(bytes: &[u8]) -> Self {
36        if bytes.len() != 1 {
37            panic!();
38        }
39        if bytes[0] == 1 {
40            Self::Compressed
41        } else if bytes[0] == 0 {
42            Self::Raw
43        } else {
44            panic!()
45        }
46    }
47
48    pub fn validate(&self, path: &Path) -> Result<()> {
49        if let Ok(prev_compressed) = Format::try_from(path)
50            && prev_compressed != *self
51        {
52            return Err(Error::DifferentCompressionMode);
53        }
54
55        Ok(())
56    }
57}
58
59impl TryFrom<&Path> for Format {
60    type Error = Error;
61    fn try_from(value: &Path) -> Result<Self, Self::Error> {
62        Ok(Self::from_bytes(&fs::read(value)?))
63    }
64}