use std::{
borrow::Cow,
io::{Read, Seek, SeekFrom, Write},
sync::Arc,
};
use crate::{
error::{Error, Result},
execute::{Action, Execution},
range::ByteRange,
segment::{Role, Segment},
sink::Sink,
structure::{SegmentId, Structure},
task::Task,
};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct OffsetMap {
edits: Vec<(u64, i64)>,
}
impl OffsetMap {
pub fn new() -> Self {
Self::default()
}
pub fn add(&mut self, old_end: u64, delta: i64) {
if delta != 0 {
self.edits.push((old_end, delta));
}
}
pub fn is_identity(&self) -> bool {
self.edits.is_empty()
}
pub fn apply(&self, v: u64) -> Result<u64> {
let shift: i128 = self
.edits
.iter()
.filter(|(end, _)| *end <= v)
.map(|(_, d)| *d as i128)
.sum();
u64::try_from(v as i128 + shift)
.map_err(|_| Error::InvalidFormat("offset adjustment out of range".into()))
}
}
pub const MAX_RELOCATE_STRIDE: u32 = 4096;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Relocate {
map: Arc<OffsetMap>,
stride: u32,
field_off: u32,
width: u8,
}
impl Relocate {
pub fn new(map: Arc<OffsetMap>, stride: u32, field_off: u32, width: u8) -> Result<Self> {
let fits = field_off
.checked_add(width as u32)
.is_some_and(|end| end <= stride);
if !matches!(width, 4 | 8) || stride == 0 || stride > MAX_RELOCATE_STRIDE || !fits {
return Err(Error::InvalidFormat("invalid offset table geometry".into()));
}
Ok(Self {
map,
stride,
field_off,
width,
})
}
pub fn stride(&self) -> u32 {
self.stride
}
pub(crate) fn apply(&self, block: &mut [u8]) -> Result<()> {
let (off, w) = (self.field_off as usize, self.width as usize);
for entry in block.chunks_exact_mut(self.stride as usize) {
let f = &mut entry[off..off + w];
let v = self
.map
.apply(f.iter().fold(0u64, |a, &b| (a << 8) | b as u64))?;
let range = || Error::InvalidFormat("offset adjustment does not fit its field".into());
match w {
4 => f.copy_from_slice(&u32::try_from(v).map_err(|_| range())?.to_be_bytes()),
_ => f.copy_from_slice(&v.to_be_bytes()),
}
}
Ok(())
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Step<'a> {
Copy {
dest: SegmentId,
role: Role,
src: ByteRange,
},
Put {
dest: SegmentId,
role: Role,
data: Cow<'a, [u8]>,
},
Relocate {
dest: SegmentId,
role: Role,
src: ByteRange,
rule: Relocate,
},
}
impl Step<'_> {
pub fn dest(&self) -> SegmentId {
match self {
Step::Copy { dest, .. } | Step::Put { dest, .. } | Step::Relocate { dest, .. } => *dest,
}
}
pub fn role(&self) -> Role {
match self {
Step::Copy { role, .. } | Step::Put { role, .. } | Step::Relocate { role, .. } => *role,
}
}
pub fn len(&self) -> u64 {
match self {
Step::Copy { src, .. } | Step::Relocate { src, .. } => src.len(),
Step::Put { data, .. } => data.len() as u64,
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[derive(Debug)]
pub struct WritePlan<'a> {
structure: Structure,
steps: Vec<Step<'a>>,
}
impl<'a> WritePlan<'a> {
pub fn new(structure: Structure) -> Self {
Self {
structure,
steps: Vec::new(),
}
}
pub(crate) fn from_parts(structure: Structure, steps: Vec<Step<'a>>) -> Self {
Self { structure, steps }
}
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 replace(
&mut self,
dest: SegmentId,
role: Role,
data: impl Into<Cow<'a, [u8]>>,
) -> Result<&mut Self> {
let hit = |s: &Step<'_>| s.dest() == dest && s.role() == role;
let at = self
.steps
.iter()
.position(hit)
.ok_or(Error::NotFound { what: "step" })?;
self.steps.retain(|s| !hit(s));
self.steps.insert(
at,
Step::Put {
dest,
role,
data: data.into(),
},
);
Ok(self)
}
pub fn copy_segment(&mut self, dest: SegmentId, src: &Segment) -> &mut Self {
for (role, range) in src.regions() {
self.copy(dest, role, range);
}
self
}
pub fn structure(&self) -> &Structure {
&self.structure
}
pub fn steps(&self) -> &[Step<'a>] {
&self.steps
}
pub fn into_structure(self) -> Structure {
self.structure
}
pub fn start(&self) -> Execution<'_, 'a> {
Execution::new(self)
}
pub fn execute<R, W, S>(&self, src: &mut R, out: &mut W, sink: &mut S) -> Result<()>
where
R: Read + Seek + ?Sized,
W: Write + ?Sized,
S: Sink + ?Sized,
{
let mut run = self.start();
let mut at: Option<u64> = None;
loop {
match run.step(sink)? {
Action::Read { offset, buf } => {
if at != Some(offset) {
src.seek(SeekFrom::Start(offset))?;
}
src.read_exact(buf)?;
at = Some(offset + buf.len() as u64);
}
Action::Write(bytes) => out.write_all(bytes)?,
Action::Done => break,
}
}
out.flush()?;
Ok(())
}
}
impl Structure {
pub fn write_plan<'a>(
&self,
src: &mut dyn crate::handler::ReadSeek,
updates: &'a crate::Updates,
) -> Result<WritePlan<'a>> {
self.handler().write_plan(self, src, updates)
}
}
impl Structure {
pub fn write_plan_task<'f, 'a: 'f>(
&'f self,
updates: &'a crate::Updates,
) -> Task<'f, WritePlan<'a>> {
Task::new(self.total_size(), move |io| {
self.handler().write_plan_async(self, io, updates)
})
}
}
pub fn validate(plan: &WritePlan<'_>, source_len: u64) -> Result<()> {
let structure = plan.structure();
let mut pos = 0u64;
for step in plan.steps() {
let seg = structure.segment(step.dest())?;
if step.is_empty() {
continue;
}
let region = match step.role() {
Role::Header => seg.header(),
Role::Payload => seg.payload(),
Role::Trailer => seg.trailer(),
};
let end = pos.checked_add(step.len());
let fits = region.offset() <= pos && end.is_some_and(|e| e <= region.end());
if !fits {
return Err(Error::invalid_segment(
pos,
format!(
"step of {} bytes does not fit the {:?} of its segment",
step.len(),
step.role()
),
));
}
if let Step::Relocate { src, rule, .. } = step {
if !src.len().is_multiple_of(rule.stride() as u64) {
return Err(Error::invalid_segment(
src.offset(),
"offset table is not a whole number of entries",
));
}
}
if let Step::Copy { src, .. } | Step::Relocate { src, .. } = step {
if src.end() > source_len {
return Err(Error::invalid_segment(
src.offset(),
"copy reads past the end of the source",
));
}
}
pos += step.len();
}
if pos != structure.total_size() {
return Err(Error::invalid_segment(
pos,
format!(
"steps write {pos} bytes, structure is {}",
structure.total_size()
),
));
}
Ok(())
}