use anyhash::Hasher;
use crate::prelude::*;
pub struct EntryBuilder<const MCL: usize, const MCC: usize, const MPL: usize, N, S, PD> {
namespace_id: Option<N>,
subspace_id: Option<S>,
path: Option<Path<MCL, MCC, MPL>>,
timestamp: Option<Timestamp>,
payload_length: Option<u64>,
payload_digest: Option<PD>,
}
impl<const MCL: usize, const MCC: usize, const MPL: usize, N, S, PD>
EntryBuilder<MCL, MCC, MPL, N, S, PD>
{
pub(crate) fn create_empty() -> Self {
Self {
namespace_id: None,
subspace_id: None,
path: None,
timestamp: None,
payload_length: None,
payload_digest: None,
}
}
pub fn namespace_id(&mut self, value: N) -> &mut Self {
let new = self;
new.namespace_id = Some(value);
new
}
pub fn subspace_id(&mut self, value: S) -> &mut Self {
let new = self;
new.subspace_id = Some(value);
new
}
pub fn path(&mut self, value: Path<MCL, MCC, MPL>) -> &mut Self {
let new = self;
new.path = Some(value);
new
}
pub fn timestamp<T: Into<Timestamp>>(&mut self, value: T) -> &mut Self {
let new = self;
new.timestamp = Some(value.into());
new
}
pub fn payload_length(&mut self, value: u64) -> &mut Self {
let new = self;
new.payload_length = Some(value);
new
}
pub fn payload_digest(&mut self, value: PD) -> &mut Self {
let new = self;
new.payload_digest = Some(value);
new
}
pub fn payload<Payload: AsRef<[u8]>, H, Digest>(&mut self, payload: Payload) -> &mut Self
where
H: Default + Hasher<Digest>,
Digest: Into<PD>,
{
let new = self;
let mut hasher = H::default();
hasher.write(payload.as_ref());
new.payload_digest = Some(hasher.finish().into());
new.payload_length = Some(payload.as_ref().len() as u64);
new
}
#[cfg(feature = "std")]
pub fn now(&mut self) -> Result<&mut Self, HifitimeError> {
let new = self;
new.timestamp = Some(Timestamp::now()?);
Ok(new)
}
pub fn build(&mut self) -> Result<Entry<MCL, MCC, MPL, N, S, PD>, EntryBuilderError> {
Ok(Entry {
namespace_id: self
.namespace_id
.take()
.ok_or(EntryBuilderError::MissingNamespaceId)?,
subspace_id: self
.subspace_id
.take()
.ok_or(EntryBuilderError::MissingSubespaceId)?,
path: self.path.take().ok_or(EntryBuilderError::MissingPath)?,
timestamp: self
.timestamp
.take()
.ok_or(EntryBuilderError::MissingTimestamp)?,
payload_length: self
.payload_length
.take()
.ok_or(EntryBuilderError::MissingPayloadLength)?,
payload_digest: self
.payload_digest
.take()
.ok_or(EntryBuilderError::MissingPayloadDigest)?,
})
}
}
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum EntryBuilderError {
MissingNamespaceId,
MissingSubespaceId,
MissingPath,
MissingTimestamp,
MissingPayloadLength,
MissingPayloadDigest,
}