use prikk_error::{PrikkError, Result};
use crate::payload::blob::BlobKind;
pub const NODE_ID_BYTES: usize = 32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NodeId([u8; NODE_ID_BYTES]);
impl NodeId {
#[must_use]
pub const fn from_bytes(bytes: [u8; NODE_ID_BYTES]) -> Self {
Self(bytes)
}
pub fn try_from_bytes(bytes: [u8; NODE_ID_BYTES]) -> Result<Self> {
if bytes == [0_u8; NODE_ID_BYTES] {
return Err(PrikkError::MalformedData(
"node_id must be nonzero".to_string(),
));
}
Ok(Self(bytes))
}
#[must_use]
pub const fn as_bytes(&self) -> &[u8; NODE_ID_BYTES] {
&self.0
}
#[must_use]
pub fn is_zero(&self) -> bool {
self.0 == [0_u8; NODE_ID_BYTES]
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum NodeKind {
TextFile = 0x0001,
BinaryFile = 0x0002,
Symlink = 0x0003,
}
impl NodeKind {
#[must_use]
pub const fn code(self) -> u16 {
self as u16
}
pub fn from_code(code: u16) -> Result<Self> {
match code {
0x0001 => Ok(Self::TextFile),
0x0002 => Ok(Self::BinaryFile),
0x0003 => Ok(Self::Symlink),
other => Err(PrikkError::MalformedData(format!(
"unknown or reserved node_kind code: {other:#06x}"
))),
}
}
pub fn from_file_blob_kind(blob_kind: BlobKind) -> Result<Self> {
match blob_kind {
BlobKind::Text => Ok(Self::TextFile),
BlobKind::Binary => Ok(Self::BinaryFile),
BlobKind::Snapshot => Err(PrikkError::MalformedData(
"file node must not reference a SNAPSHOT blob".to_string(),
)),
}
}
}