Medlar/crates/core/src/segment.rs
2026-11-25 01:18:06 -06:00

196 lines
7.9 KiB
Rust

//! Which range a free connection takes. Decides only: no clock, no network, no disk.
use std::time::Duration;
#[derive(Debug, Clone, Copy)]
pub struct Rules {
/// No cut leaves a range shorter than this.
pub min: u64,
/// Cuts fall on multiples of this.
pub align: u64,
/// A part that ends sooner is left alone.
pub min_time: Duration,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Slot {
/// Nobody works on it.
Free,
/// Nobody works on it and nobody should yet.
Resting,
/// Bytes per second, once known.
Busy(Option<f64>),
}
/// What is left of a part: bytes `pos..end`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct View {
pub pos: u64,
pub end: u64,
pub slot: Slot,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pick {
/// The whole part, by index.
Take(usize),
/// The part ends at `at` from now on; `at..` its old end is the new one's.
Split { part: usize, at: u64 },
}
impl View {
fn left(&self) -> u64 {
self.end.saturating_sub(self.pos)
}
/// Where to cut it in halves.
fn cut(&self, rules: &Rules) -> Option<u64> {
let (min, align) = (rules.min.max(1), rules.align.max(1));
let mid = self.pos + self.left() / 2;
let down = mid / align * align;
[down, down.saturating_add(align)]
.into_iter()
.filter(|at| *at >= self.pos.saturating_add(min) && self.end >= at.saturating_add(min))
.min_by_key(|at| at.abs_diff(mid))
}
}
/// The best use of one more connection: a part nobody has, else half of the part with the longest time left.
pub fn next(parts: &[View], rules: &Rules) -> Option<Pick> {
if let Some(i) = parts.iter().position(|p| p.slot == Slot::Free && p.left() > 0) {
return Some(Pick::Take(i));
}
let speeds: Vec<f64> = parts.iter().filter_map(|p| if let Slot::Busy(s) = p.slot { s.filter(|s| *s > 0.0) } else { None }).collect();
// A new connection is taken for an average one.
let usual = if speeds.is_empty() { 1.0 } else { speeds.iter().sum::<f64>() / speeds.len() as f64 };
parts
.iter()
.enumerate()
.filter_map(|(part, p)| {
let Slot::Busy(speed) = p.slot else { return None };
let time = p.left() as f64 / speed.unwrap_or(usual);
let worth = speed.is_none() || time >= rules.min_time.as_secs_f64();
p.cut(rules).filter(|_| worth).map(|at| (time, Pick::Split { part, at }))
})
.max_by(|a, b| a.0.total_cmp(&b.0))
.map(|(_, pick)| pick)
}
/// Far slower than a connection usually is, and not about to end.
pub fn crawls(part: &View, usual: f64, patience: Duration) -> bool {
match part.slot {
Slot::Busy(Some(speed)) => speed < usual / 4.0 && part.left() as f64 > speed * patience.as_secs_f64(),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
const RULES: Rules = Rules { min: 100, align: 64, min_time: Duration::ZERO };
fn view(pos: u64, end: u64, slot: Slot) -> View {
View { pos, end, slot }
}
#[test]
fn free_parts_come_first_then_the_longest_time() {
use Slot::*;
let mut parts = vec![view(0, 10_000, Busy(Some(1000.0))), view(10_000, 12_000, Busy(Some(10.0))), view(12_000, 20_000, Resting)];
assert_eq!(next(&parts, &RULES), Some(Pick::Split { part: 1, at: 11_008 }));
parts[1].slot = Busy(None);
assert_eq!(next(&parts, &RULES), Some(Pick::Split { part: 0, at: 4992 }));
parts[0].slot = Busy(Some(0.0));
assert_eq!(next(&parts, &RULES), Some(Pick::Split { part: 0, at: 4992 }));
parts[2].slot = Free;
assert_eq!(next(&parts, &RULES), Some(Pick::Take(2)));
}
#[test]
fn small_and_short_parts_are_left_alone() {
let busy = |pos, end, speed| [view(pos, end, Slot::Busy(Some(speed)))];
assert_eq!(next(&busy(0, 199, 1.0), &RULES), None);
// Long enough, but no multiple of 64 fits.
assert_eq!(next(&busy(1, 210, 1.0), &RULES), None);
assert_eq!(next(&busy(0, 256, 1.0), &RULES), Some(Pick::Split { part: 0, at: 128 }));
let patient = Rules { min_time: Duration::from_secs(2), ..RULES };
assert_eq!(next(&busy(0, 10_000, 5001.0), &patient), None);
assert!(next(&busy(0, 10_000, 4999.0), &patient).is_some());
assert_eq!(next(&[], &RULES), None);
assert_eq!(next(&[view(0, 10_000, Slot::Resting)], &RULES), None);
assert!(next(&busy(u64::MAX / 2 - 5000, u64::MAX / 2, 1.0), &RULES).is_some());
}
#[test]
fn crawling() {
let two = Duration::from_secs(2);
assert!(crawls(&view(0, 1000, Slot::Busy(Some(10.0))), 100.0, two));
assert!(!crawls(&view(0, 1000, Slot::Busy(Some(30.0))), 100.0, two));
assert!(!crawls(&view(0, 19, Slot::Busy(Some(10.0))), 100.0, two));
assert!(!crawls(&view(0, 1000, Slot::Busy(None)), 100.0, two));
assert!(!crawls(&view(0, 1000, Slot::Free), 100.0, two));
}
/// Random progress, errors, rests and picks: every byte is in exactly one part, all the time, and the file gets done.
#[test]
fn no_gap_and_no_overlap() {
let mut seed = 0x9e37_79b9_7f4a_7c15_u64;
let mut random = move |n: u64| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed % n
};
let mut splits = 0;
for round in 0..400 {
let size = random(200_000) + 1;
let rules = Rules { min: random(5000), align: 1 << random(12), min_time: Duration::ZERO };
// Start of each part, kept apart from its view.
let mut parts = vec![(0, view(0, size, Slot::Free))];
let mut steps = 0;
while parts.iter().any(|(_, p)| p.left() > 0) {
steps += 1;
assert!(steps < 100_000, "round {round} never ends");
let i = random(parts.len() as u64) as usize;
match random(10) {
0 => {
let views: Vec<View> = parts.iter().map(|(_, p)| *p).collect();
match next(&views, &rules) {
Some(Pick::Take(i)) => {
assert_eq!(parts[i].1.slot, Slot::Free);
parts[i].1.slot = Slot::Busy(None);
}
Some(Pick::Split { part, at }) => {
let p = &mut parts[part].1;
assert!(matches!(p.slot, Slot::Busy(_)));
assert!(at - p.pos >= rules.min && p.end - at >= rules.min && at % rules.align == 0);
assert!(at > p.pos && at < p.end);
let new = view(at, p.end, Slot::Busy(None));
p.end = at;
parts.insert(part + 1, (at, new));
splits += 1;
}
None => {}
}
}
1 if parts[i].1.slot != Slot::Free && parts[i].1.left() > 0 => {
parts[i].1.slot = [Slot::Free, Slot::Resting][random(2) as usize];
}
2 if parts[i].1.slot == Slot::Resting => parts[i].1.slot = Slot::Free,
_ => {
let p = &mut parts[i].1;
if let Slot::Busy(_) = p.slot {
p.slot = Slot::Busy(Some(random(1000) as f64));
p.pos += random(2000).min(p.left());
}
}
}
assert_eq!((parts[0].0, parts.last().unwrap().1.end), (0, size));
assert!(parts.windows(2).all(|w| w[0].1.end == w[1].0));
assert!(parts.iter().all(|(start, p)| *start <= p.pos && p.pos <= p.end));
}
}
assert!(splits > 1000, "{splits}");
}
}