Skip to main content

oxabl_cache_format/
commit_response.rs

1//! `OXCA` commit response.
2
3use crate::cursor::Cursor;
4use crate::error::{FormatError, Result};
5use crate::frame::{read_header, write_header};
6use crate::limits::COMMIT_ENTRIES;
7use crate::writer::{Writer, len32};
8
9const MAGIC: [u8; 4] = *b"OXCA";
10
11/// Outcome of one entry of a commit.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum CommitStatus {
14    Committed,
15    Exists,
16    Invalid,
17    MissingDictionary,
18}
19
20impl CommitStatus {
21    fn to_u8(self) -> u8 {
22        match self {
23            Self::Committed => 0,
24            Self::Exists => 1,
25            Self::Invalid => 2,
26            Self::MissingDictionary => 3,
27        }
28    }
29
30    fn from_u8(v: u8) -> Result<Self> {
31        match v {
32            0 => Ok(Self::Committed),
33            1 => Ok(Self::Exists),
34            2 => Ok(Self::Invalid),
35            3 => Ok(Self::MissingDictionary),
36            _ => Err(FormatError::Invalid("commit status")),
37        }
38    }
39}
40
41/// A commit response: one status per entry, in request order.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct CommitResponse {
44    pub statuses: Vec<CommitStatus>,
45}
46
47impl CommitResponse {
48    pub fn encode(&self) -> Result<Vec<u8>> {
49        if self.statuses.len() > COMMIT_ENTRIES {
50            return Err(FormatError::LimitExceeded("entries"));
51        }
52        let mut w = Writer::with_capacity(12 + self.statuses.len());
53        write_header(&mut w, MAGIC, 0);
54        w.u16(0);
55        w.u32(len32(self.statuses.len(), "entries")?);
56        for s in &self.statuses {
57            w.u8(s.to_u8());
58        }
59        Ok(w.into_vec())
60    }
61
62    pub fn decode(bytes: &[u8]) -> Result<Self> {
63        let mut c = Cursor::new(bytes);
64        read_header(&mut c, MAGIC, 0)?;
65        c.reserved_u16()?;
66        let count = c.count32(COMMIT_ENTRIES, "entries", 1)?;
67        let mut statuses = Vec::with_capacity(count);
68        for _ in 0..count {
69            statuses.push(CommitStatus::from_u8(c.u8()?)?);
70        }
71        c.finish()?;
72        Ok(Self { statuses })
73    }
74}