brk_vec/structs/
compressed.rs

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