use rustev_contract::replay::ReplayBundle;
pub const NOTE_MAX_BYTES: usize = 256;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum BundleLoad {
Inaccessible,
Oversized,
Corrupt,
}
impl BundleLoad {
pub fn code(self) -> &'static str {
match self {
BundleLoad::Inaccessible => "bundle-inaccessible",
BundleLoad::Oversized => "bundle-oversized",
BundleLoad::Corrupt => "bundle-corrupt",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoadFailure {
pub kind: BundleLoad,
note: String,
}
impl LoadFailure {
pub fn new(kind: BundleLoad, note: &str) -> LoadFailure {
let mut end = note.len().min(NOTE_MAX_BYTES);
while !note.is_char_boundary(end) {
end -= 1;
}
LoadFailure {
kind,
note: note[..end].to_string(),
}
}
pub fn note(&self) -> &str {
&self.note
}
}
#[derive(Debug, Clone)]
pub enum BundleInput {
Loaded(Box<ReplayBundle>),
Failed(LoadFailure),
}
impl From<ReplayBundle> for BundleInput {
fn from(b: ReplayBundle) -> BundleInput {
BundleInput::Loaded(Box::new(b))
}
}
impl From<LoadFailure> for BundleInput {
fn from(f: LoadFailure) -> BundleInput {
BundleInput::Failed(f)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_note_is_cut_at_a_character_boundary() {
let long = "é".repeat(200);
let f = LoadFailure::new(BundleLoad::Corrupt, &long);
assert_eq!(f.note().len(), NOTE_MAX_BYTES);
let odd = format!("x{long}");
let f = LoadFailure::new(BundleLoad::Corrupt, &odd);
assert_eq!(f.note().len(), NOTE_MAX_BYTES - 1);
assert_eq!(
LoadFailure::new(BundleLoad::Oversized, "short").note(),
"short"
);
}
}