use std::sync::Arc;
use super::model::{CommitStatus, Error, Limits, View};
#[derive(Debug)]
pub struct Artifact {
key: Arc<str>,
revision: u64,
status: CommitStatus,
texts: [Arc<str>; 3],
supplied: [bool; 3],
}
impl Artifact {
pub fn new(
key: &str,
revision: u64,
source: &str,
proposal: Option<&str>,
evidence: Option<&str>,
limits: Limits,
) -> Result<Self, Error> {
Self::with_status(
key,
revision,
source,
proposal,
evidence,
CommitStatus::Proposed,
limits,
)
}
pub fn with_status(
key: &str,
revision: u64,
source: &str,
proposal: Option<&str>,
evidence: Option<&str>,
status: CommitStatus,
limits: Limits,
) -> Result<Self, Error> {
limits.validate()?;
Error::require(
!key.is_empty()
&& key.len() <= 512
&& !key.chars().any(char::is_control)
&& revision != 0,
Error::InvalidInput,
)?;
let texts = [
source,
match proposal {
Some(text) => text,
None => "No proposal supplied. Nothing has been applied.",
},
match evidence {
Some(text) => text,
None => "No evidence supplied. No tests or verification are claimed.",
},
];
let bytes = texts
.iter()
.try_fold(key.len(), |sum, text| sum.checked_add(text.len()))
.ok_or(Error::BudgetExceeded)?;
Error::require(bytes <= limits.text_bytes(), Error::BudgetExceeded)?;
Error::require(
!texts.iter().any(|text| text.contains('\0')),
Error::InvalidInput,
)?;
Ok(Self {
key: Arc::from(key),
revision,
status,
texts: texts.map(Arc::from),
supplied: [true, proposal.is_some(), evidence.is_some()],
})
}
#[must_use]
pub fn key(&self) -> &str {
&self.key
}
#[must_use]
pub const fn revision(&self) -> u64 {
self.revision
}
#[must_use]
pub const fn commit_status(&self) -> CommitStatus {
self.status
}
#[must_use]
pub fn text(&self, view: View) -> &str {
&self.texts[view.index()]
}
#[must_use]
pub fn supplied(&self, view: View) -> bool {
self.supplied[view.index()]
}
#[must_use]
pub fn payload_bytes(&self) -> usize {
self.texts
.iter()
.fold(self.key.len(), |sum, text| sum.saturating_add(text.len()))
}
}