#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ByteRangeSpan {
pub offset: u64,
pub length: u64,
}
impl ByteRangeSpan {
#[must_use]
pub const fn end(self) -> Option<u64> {
self.offset.checked_add(self.length)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ByteRangeValidity {
Valid,
GapContaining,
Truncated,
Overlapping,
Malformed,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ByteRangeAssessment {
pub validity: ByteRangeValidity,
pub covered: Vec<ByteRangeSpan>,
pub detail: Option<String>,
}
#[must_use]
pub fn assess(entries: &[Option<i64>], file_len: u64) -> ByteRangeAssessment {
let malformed = |detail: String| ByteRangeAssessment {
validity: ByteRangeValidity::Malformed,
covered: Vec::new(),
detail: Some(detail),
};
if entries.len() < 4 {
return malformed(format!("fewer than four numbers (found {})", entries.len()));
}
if !entries.len().is_multiple_of(2) {
return malformed(format!("odd entry count ({})", entries.len()));
}
if entries.iter().any(Option::is_none) {
return malformed("a non-integer entry is present".to_owned());
}
let values: Vec<i64> = entries.iter().map(|entry| entry.unwrap_or(0)).collect();
if values.iter().any(|value| *value < 0) {
return malformed("a negative value is present".to_owned());
}
let covered: Vec<ByteRangeSpan> = values
.chunks_exact(2)
.map(|pair| ByteRangeSpan {
offset: pair[0] as u64,
length: pair[1] as u64,
})
.collect();
let mut reach: u64 = 0;
for (index, span) in covered.iter().enumerate() {
let offset = span.offset;
let end = span.end();
if offset < reach {
return ByteRangeAssessment {
validity: ByteRangeValidity::Overlapping,
covered,
detail: Some(format!(
"pair {index} starts at {offset} before the previous pair ends at {reach}"
)),
};
}
match end {
Some(end) if end <= file_len => reach = end,
_ => {
return ByteRangeAssessment {
validity: ByteRangeValidity::Truncated,
covered,
detail: Some(format!(
"pair {index} ends past the file end ({file_len} bytes)"
)),
};
}
}
}
let starts_at_zero = covered.first().is_some_and(|span| span.offset == 0);
if starts_at_zero && reach == file_len {
ByteRangeAssessment {
validity: ByteRangeValidity::Valid,
covered,
detail: None,
}
} else {
ByteRangeAssessment {
validity: ByteRangeValidity::GapContaining,
covered,
detail: Some(format!("covered runs end at byte {reach} of {file_len}")),
}
}
}