use std::fs::File; use std::io::{self, Seek, SeekFrom, Write}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ByteRange { pub start: u64, pub end: u64, } /// Bytes covered from offset 0 with no gap. Overlaps are merged. pub fn contiguous_from_zero(ranges: &[ByteRange]) -> u64 { let mut ordered: Vec = ranges .iter() .copied() .filter(|range| range.end > range.start) .collect(); ordered.sort_by_key(|range| (range.start, range.end)); let mut covered = 0u64; for range in ordered { if range.start > covered { break; } covered = covered.max(range.end); } covered } pub fn write_at(file: &mut File, offset: u64, data: &[u8], total: u64) -> io::Result { let end = offset.checked_add(data.len() as u64).ok_or_else(|| { io::Error::new(io::ErrorKind::InvalidInput, "chunk offset overflows") })?; if end > total { return Err(io::Error::new( io::ErrorKind::InvalidInput, "chunk exceeds the declared upload size", )); } file.seek(SeekFrom::Start(offset))?; file.write_all(data)?; Ok(ByteRange { start: offset, end }) } #[cfg(test)] mod tests { use super::*; use tempfile::NamedTempFile; #[test] fn out_of_order_chunks_cover_the_object() { assert_eq!( contiguous_from_zero(&[ByteRange { start: 4, end: 8 }]), 0 ); assert_eq!( contiguous_from_zero(&[ ByteRange { start: 4, end: 8 }, ByteRange { start: 0, end: 4 }, ]), 8 ); assert_eq!( contiguous_from_zero(&[ ByteRange { start: 0, end: 3 }, ByteRange { start: 2, end: 5 }, ]), 5 ); } #[test] fn writes_honor_offset() { let mut file = NamedTempFile::new().unwrap(); write_at(file.as_file_mut(), 3, b"def", 6).unwrap(); write_at(file.as_file_mut(), 0, b"abc", 6).unwrap(); assert!(write_at(file.as_file_mut(), 4, b"xyz", 6).is_err()); let bytes = std::fs::read(file.path()).unwrap(); assert_eq!(&bytes[..6], b"abcdef"); } }