use alloc::vec::Vec;
use core::ops::RangeInclusive;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ChunkSet {
runs: Vec<RangeInclusive<u64>>,
}
impl ChunkSet {
pub fn new() -> Self {
Self { runs: Vec::new() }
}
pub fn add(&mut self, first: u64, last: u64) {
let start = self
.runs
.partition_point(|run| run.end().saturating_add(1) < first);
let end = self
.runs
.partition_point(|run| *run.start() <= last.saturating_add(1));
let merged = self.runs[start..end]
.iter()
.fold(first..=last, |merged, run| {
*merged.start().min(run.start())..=*merged.end().max(run.end())
});
self.runs.splice(start..end, [merged]);
}
pub fn count(&self) -> u64 {
self.runs
.iter()
.map(|run| run.end() - run.start() + 1)
.sum()
}
pub fn ids(&self) -> Vec<u64> {
self.runs.iter().flat_map(|run| run.clone()).collect()
}
pub fn missing(&self, chunks: u64) -> Vec<RangeInclusive<u64>> {
let mut missing = Vec::new();
let mut next = Some(1);
for run in &self.runs {
if let Some(from) = next.filter(|from| from < run.start()) {
missing.push(from..=run.start() - 1);
}
next = run.end().checked_add(1);
}
if let Some(from) = next.filter(|from| *from <= chunks) {
missing.push(from..=chunks);
}
missing
}
}