use crate::{
error::{Error, Result},
range::ByteRange,
};
pub mod labels {
pub const MANIFEST: &str = "manifest";
pub const ORIGINAL: &str = "original";
pub const UPDATE: &str = "update";
pub const MERKLE: &str = "merkle";
pub const SUPERSEDED: &str = "superseded";
}
pub const DEFAULT_CHUNK_SIZE: usize = 65536;
pub const MAX_SEGMENT_SIZE: u64 = 256 * 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SegmentKind {
Preamble,
Metadata,
MediaData,
Other,
}
impl SegmentKind {
pub fn as_str(&self) -> &'static str {
match self {
Self::Preamble => "preamble",
Self::Metadata => "metadata",
Self::MediaData => "media_data",
Self::Other => "other",
}
}
}
impl std::fmt::Display for SegmentKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Role {
Header,
Payload,
Trailer,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Name {
None,
Marker(u8),
FourCC([u8; 4]),
Id(u64),
}
impl std::fmt::Display for Name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Name::None => Ok(()),
Name::Marker(m) => write!(f, "0x{m:02X}"),
Name::Id(n) => write!(f, "#{n}"),
Name::FourCC(cc) => {
for &b in cc {
let c = if b.is_ascii_graphic() { b as char } else { '?' };
write!(f, "{c}")?;
}
Ok(())
}
}
}
}
impl Name {
pub const fn is_none(&self) -> bool {
matches!(self, Name::None)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Segment {
range: ByteRange,
header_len: u32,
trailer_len: u16,
kind: SegmentKind,
name: Name,
subdivides: bool,
}
impl Segment {
pub fn new(
range: ByteRange,
header_len: u32,
trailer_len: u16,
kind: SegmentKind,
name: Name,
) -> Result<Self> {
if range.is_empty() {
return Err(Error::invalid_segment(range.offset(), "empty segment"));
}
let overhead = header_len as u64 + trailer_len as u64;
if overhead > range.len() {
return Err(Error::invalid_segment(
range.offset(),
format!(
"header ({header_len}) + trailer ({trailer_len}) exceed range ({})",
range.len()
),
));
}
Ok(Self {
range,
header_len,
trailer_len,
kind,
name,
subdivides: false,
})
}
pub const fn subdivides(&self) -> bool {
self.subdivides
}
pub(crate) const fn with_subdivision(mut self) -> Self {
self.subdivides = true;
self
}
pub const fn range(&self) -> ByteRange {
self.range
}
pub const fn kind(&self) -> SegmentKind {
self.kind
}
pub const fn name(&self) -> Name {
self.name
}
pub const fn header(&self) -> ByteRange {
ByteRange::raw(self.range.offset(), self.header_len as u64)
}
pub const fn payload(&self) -> ByteRange {
ByteRange::raw(
self.range.offset() + self.header_len as u64,
self.range.len() - self.header_len as u64 - self.trailer_len as u64,
)
}
pub const fn trailer(&self) -> ByteRange {
ByteRange::raw(
self.range.end() - self.trailer_len as u64,
self.trailer_len as u64,
)
}
pub fn regions(&self) -> impl Iterator<Item = (Role, ByteRange)> {
[
(Role::Header, self.header()),
(Role::Payload, self.payload()),
(Role::Trailer, self.trailer()),
]
.into_iter()
.filter(|(_, r)| !r.is_empty())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn none_name() {
assert!(Name::None.is_none());
assert!(!Name::Marker(0xd8).is_none());
}
#[test]
fn marker_display_is_container_neutral() {
for (marker, expected) in [
(0x00, "0x00"),
(0x3b, "0x3B"),
(0xd8, "0xD8"),
(0xff, "0xFF"),
] {
assert_eq!(Name::Marker(marker).to_string(), expected);
}
}
#[test]
fn splits_range() {
let s = Segment::new(
ByteRange::new(100, 30).unwrap(),
8,
4,
SegmentKind::Other,
Name::FourCC(*b"tEXt"),
)
.unwrap();
assert_eq!(s.header(), ByteRange::new(100, 8).unwrap());
assert_eq!(s.payload(), ByteRange::new(108, 18).unwrap());
assert_eq!(s.trailer(), ByteRange::new(126, 4).unwrap());
let total: u64 = s.regions().map(|(_, r)| r.len()).sum();
assert_eq!(total, 30);
}
#[test]
fn rejects_bad_geometry() {
let r = ByteRange::new(0, 10).unwrap();
assert!(Segment::new(r, 8, 4, SegmentKind::Other, Name::None).is_err());
let empty = ByteRange::new(0, 0).unwrap();
assert!(Segment::new(empty, 0, 0, SegmentKind::Other, Name::None).is_err());
}
#[test]
fn empty_payload_has_no_payload_region() {
let s = Segment::new(
ByteRange::new(0, 12).unwrap(),
8,
4,
SegmentKind::Other,
Name::FourCC(*b"IEND"),
)
.unwrap();
assert!(s.payload().is_empty());
assert_eq!(s.regions().count(), 2);
}
}