use std::{borrow::Cow, collections::BTreeMap, sync::Arc};
use crate::{
error::{Error, Result},
item::{Item, ItemInfo},
plan::{Relocate, Step, WritePlan},
range::ByteRange,
segment::{Name, Role, SegmentKind},
structure::{Attached, SegmentId, Structure, StructureBuilder, MAX_SEGMENTS},
transfer::TransferEncoding,
};
struct Shape {
kind: SegmentKind,
name: Name,
header_len: u32,
payload_len: u64,
trailer_len: u16,
subdivides: bool,
from: Option<SegmentId>,
}
struct ItemSpec {
info: ItemInfo,
extents: Vec<(SegmentId, Option<ByteRange>)>,
}
pub struct PlanBuilder<'s, 'a> {
src: &'s Structure,
shapes: Vec<Shape>,
steps: Vec<Step<'a>>,
items: Vec<ItemSpec>,
dest_of: Vec<Option<SegmentId>>,
len: u64,
attachment: Option<Arc<dyn Attached>>,
}
impl<'s, 'a> PlanBuilder<'s, 'a> {
pub fn new(src: &'s Structure) -> Self {
Self {
src,
shapes: Vec::with_capacity(src.segments().len() + 2),
steps: Vec::new(),
items: Vec::new(),
dest_of: vec![None; src.segments().len()],
len: 0,
attachment: None,
}
}
pub fn attach<T: std::any::Any + std::fmt::Debug + Send + Sync>(
&mut self,
value: T,
) -> &mut Self {
self.attachment = Some(Arc::new(value));
self
}
pub fn source(&self) -> &'s Structure {
self.src
}
pub fn len(&self) -> u64 {
self.len
}
pub fn is_empty(&self) -> bool {
self.shapes.is_empty()
}
pub fn dest_map(&self) -> &[Option<SegmentId>] {
&self.dest_of
}
pub fn dest_of(&self, src: SegmentId) -> Option<SegmentId> {
self.dest_of.get(src.index()).copied().flatten()
}
fn add(&mut self, shape: Shape) -> Result<SegmentId> {
if self.shapes.len() >= MAX_SEGMENTS {
return Err(Error::LimitExceeded {
what: "segments",
limit: MAX_SEGMENTS as u64,
});
}
let id = SegmentId::from_index(self.shapes.len())?;
self.len = (shape.header_len as u64)
.checked_add(shape.payload_len)
.and_then(|v| v.checked_add(shape.trailer_len as u64))
.and_then(|v| self.len.checked_add(v))
.ok_or(Error::LimitExceeded {
what: "output size",
limit: u64::MAX,
})?;
self.shapes.push(shape);
Ok(id)
}
pub fn shape(
&mut self,
kind: SegmentKind,
name: Name,
header_len: u32,
payload_len: u64,
trailer_len: u16,
) -> Result<SegmentId> {
self.add(Shape {
kind,
name,
header_len,
payload_len,
trailer_len,
subdivides: false,
from: None,
})
}
pub fn shape_like(&mut self, src: SegmentId) -> Result<SegmentId> {
let s = self.src.segment(src)?;
let id = self.add(Shape {
kind: s.kind(),
name: s.name(),
header_len: s.header().len() as u32,
payload_len: s.payload().len(),
trailer_len: s.trailer().len() as u16,
subdivides: s.subdivides(),
from: Some(src),
})?;
let slot = &mut self.dest_of[src.index()];
if slot.is_none() {
*slot = Some(id);
}
Ok(id)
}
pub fn copy_segment(&mut self, src: SegmentId) -> Result<SegmentId> {
let id = self.shape_like(src)?;
for (role, range) in self.src.segment(src)?.regions() {
self.copy(id, role, range);
}
Ok(id)
}
pub fn put_segment(
&mut self,
kind: SegmentKind,
name: Name,
header: impl Into<Cow<'a, [u8]>>,
payload: impl Into<Cow<'a, [u8]>>,
trailer: impl Into<Cow<'a, [u8]>>,
) -> Result<SegmentId> {
let (header, payload, trailer) = (header.into(), payload.into(), trailer.into());
let too_long = |what, limit| Error::LimitExceeded { what, limit };
let id = self.shape(
kind,
name,
u32::try_from(header.len()).map_err(|_| too_long("header size", u32::MAX as u64))?,
payload.len() as u64,
u16::try_from(trailer.len()).map_err(|_| too_long("trailer size", u16::MAX as u64))?,
)?;
for (role, data) in [
(Role::Header, header),
(Role::Payload, payload),
(Role::Trailer, trailer),
] {
if !data.is_empty() {
self.put(id, role, data);
}
}
Ok(id)
}
pub fn copy(&mut self, dest: SegmentId, role: Role, src: ByteRange) -> &mut Self {
self.steps.push(Step::Copy { dest, role, src });
self
}
pub fn put(
&mut self,
dest: SegmentId,
role: Role,
data: impl Into<Cow<'a, [u8]>>,
) -> &mut Self {
self.steps.push(Step::Put {
dest,
role,
data: data.into(),
});
self
}
pub fn relocate(
&mut self,
dest: SegmentId,
role: Role,
src: ByteRange,
rule: Relocate,
) -> &mut Self {
self.steps.push(Step::Relocate {
dest,
role,
src,
rule,
});
self
}
pub fn item(&mut self, info: ItemInfo, ids: &[SegmentId]) -> Result<()> {
if ids.is_empty() {
return Err(Error::InvalidFormat(
"item needs at least one extent".into(),
));
}
if ids.iter().any(|id| id.index() >= self.shapes.len()) {
return Err(Error::NotFound { what: "segment" });
}
self.items.push(ItemSpec {
info,
extents: ids.iter().map(|&id| (id, None)).collect(),
});
Ok(())
}
pub fn carry_items(&mut self, keep: impl Fn(&Item) -> bool) {
for e in self.src.items() {
if !keep(e) {
continue;
}
let extents: Option<Vec<_>> = e
.extents()
.map(|p| {
self.dest_of
.get(p.segment().index())
.copied()
.flatten()
.map(|d| (d, Some(p.range())))
})
.collect();
if let Some(extents) = extents {
self.items.push(ItemSpec {
info: e.info().clone(),
extents,
});
}
}
}
pub fn finish(self) -> Result<WritePlan<'a>> {
let src = self.src;
let first_of = |i: usize| -> Result<usize> {
self.dest_of
.get(i)
.copied()
.flatten()
.map(SegmentId::index)
.ok_or(Error::InvalidFormat(
"a segment that starts part of the structure was dropped".into(),
))
};
let trailing = match src.box_count() {
k if k < src.segments().len() => Some(first_of(k)?),
_ => None,
};
let mut subs = BTreeMap::new();
for sub in src.subassets().iter().skip(1) {
subs.insert(
first_of(sub.segments().start)?,
sub.media_type().map(|m| Cow::Owned(m.to_owned())),
);
}
let mut b =
StructureBuilder::new(src.handler().clone(), src.media_type().to_owned(), self.len);
b.attach_shared(self.attachment.clone());
for (i, s) in self.shapes.iter().enumerate() {
if trailing == Some(i) {
b.end_boxes()?;
}
if let Some(media) = subs.remove(&i) {
b.begin_subasset(media)?;
}
let id = b.push_span(s.kind, s.name, s.header_len, s.payload_len, s.trailer_len)?;
if let Some(from) = s.from.filter(|_| s.subdivides) {
b.split_like(id, src, from)?;
}
}
if !subs.is_empty() {
return Err(Error::InvalidFormat(
"a sub-asset starts after the last segment".into(),
));
}
for e in self.items {
let first = e.extents.first().map(|&(dest, _)| dest);
let info = match first {
Some(dest) if e.info.lacks_jumbf_type() => {
let from = self.shapes[dest.index()].from;
let ty =
jumbf_type_of(src, &self.steps, dest, from, e.info.transfer_encoding());
e.info.jumbf_type(ty)
}
_ => e.info,
};
let mut parts = Vec::with_capacity(e.extents.len());
for (dest, carried) in e.extents {
let at = b.segment(dest)?.range().offset();
let range = match carried {
None => b.segment(dest)?.payload(),
Some(r) => {
let from = self.shapes[dest.index()].from.ok_or(Error::NotFound {
what: "source segment",
})?;
let moved = at + (r.offset() - src.segment(from)?.range().offset());
ByteRange::new(moved, r.len())?
}
};
parts.push((dest, range));
}
b.item(info, &parts)?;
}
Ok(WritePlan::from_parts(b.finish()?, self.steps))
}
}
fn jumbf_type_of(
src: &Structure,
steps: &[Step<'_>],
dest: SegmentId,
from: Option<SegmentId>,
transfer: &TransferEncoding,
) -> Option<[u8; 16]> {
const STORED_HEAD: usize = 4096;
if let Some(from) = from {
return src
.items()
.filter(|item| item.encoding() == crate::Encoding::Jumbf)
.find(|item| item.extents().next().is_some_and(|x| x.segment() == from))
.and_then(Item::jumbf_type);
}
match steps
.iter()
.find(|s| s.dest() == dest && s.role() == Role::Payload)?
{
Step::Put { data, .. } => {
let stored = &data[..data.len().min(STORED_HEAD)];
let head = transfer.decode_prefix(stored, 32).ok()?;
crate::jumbf::superbox_type(&head)
}
_ => None,
}
}