misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
Tests: a long list's linear time is checked against the same work at a smaller size, not a fixed number of seconds (#895)
Ahmed Nefzaoui4328526e8cda
diff --git a/ROADMAP.md b/ROADMAP.mdindex 198e1698..f9e2d1cb 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -557,6 +557,10 @@ Bug fixes from the first days of 0.5.0, a Safari extension, and more file types.These ship in the next version.+- ✅ Tests: the five that checked a long list is read in linear time against a fixed number of+ seconds (one failed on a slow macOS runner) now time the same work at two sizes, eight times+ apart, and fail only when the larger one costs over 24 times as much (a square costs 64 times),+ whatever the machine's speed- ✅ Touch screens: a tap on a menu's item chooses it (the menu bar's, right-click menus,drop-downs), where only a mouse could([#733](https://github.com/anefzaoui/misterdownloadmanager/issues/733))diff --git a/crates/app/src/grabber.rs b/crates/app/src/grabber.rsindex 702279d1..058185bd 100644--- a/crates/app/src/grabber.rs+++ b/crates/app/src/grabber.rs@@ -1195,24 +1195,26 @@ mod tests {#[test]fn a_long_list_is_added_at_once_each_link_once() {// #805: 20,000 links, each compared with every other, held the window's thread.- let many: Vec<Imported> = (0..20_000)- .map(|i| link(&format!("https://dl.example.com/f/{i}.zip"), None))- .collect();- let mut g = grabber();- let t = std::time::Instant::now();- g.add(many.clone(), "list.txt".into(), |_| false);- // Added again (and with a #fragment): nothing more.- let again: Vec<Imported> = many- .iter()- .map(|d| link(&format!("{}#again", d.url), None))- .collect();- g.add(again, "list.txt".into(), |_| false);+ let lists = |n: usize| {+ let many: Vec<Imported> = (0..n)+ .map(|i| link(&format!("https://dl.example.com/f/{i}.zip"), None))+ .collect();+ // Added again (and with a #fragment): nothing more.+ let again: Vec<Imported> = many+ .iter()+ .map(|d| link(&format!("{}#again", d.url), None))+ .collect();+ (grabber(), many, again)+ };+ let add = |(mut g, many, again): (Grabber, Vec<Imported>, Vec<Imported>)| {+ g.add(many, "list.txt".into(), |_| false);+ g.add(again, "list.txt".into(), |_| false);+ g+ };+ // Each link compared once: 8 times the links cost about 8 times as long (not 64).+ mdm_labserver::growth::assert_linear(1_000, &lists, &add);+ let g = add(lists(20_000));assert_eq!(g.links.len(), 20_000);- assert!(- t.elapsed() < std::time::Duration::from_secs(10),- "{:?}",- t.elapsed()- );// Settled as before: one package of archives, to extract.assert_eq!(g.packages.len(), 1);assert!(g.packages[0].extract);diff --git a/crates/app/src/transfer.rs b/crates/app/src/transfer.rsindex 4668195b..c72e053d 100644--- a/crates/app/src/transfer.rs+++ b/crates/app/src/transfer.rs@@ -562,20 +562,17 @@ mod tests {#[test]fn a_large_list_is_searched_in_linear_time() {- // 200,000 addresses (about 8 MiB) and as much text that only looks like them: the- // search goes through it once (a quadratic one would take minutes here).- let mut text = String::new();- for i in 0..200_000 {- text.push_str(&format!("https://dl.example.com/files/{i}.zip\n"));- text.push_str("abc:// not an address ://\n");- }- let t = std::time::Instant::now();- let found = import(&text);- assert_eq!(found.len(), 200_000);- assert!(- t.elapsed() < std::time::Duration::from_secs(10),- "{:?}",- t.elapsed()- );+ // Addresses and as much text that only looks like them: the search goes through it+ // once, 8 times the list costing about 8 times as long (not 64), on any machine.+ let list = |n: usize| {+ let mut text = String::new();+ for i in 0..n {+ text.push_str(&format!("https://dl.example.com/files/{i}.zip\n"));+ text.push_str("abc:// not an address ://\n");+ }+ text+ };+ assert_eq!(import(&list(1_000)).len(), 1_000);+ mdm_labserver::growth::assert_linear(5_000, list, |text| import(&text));}}diff --git a/crates/engine/src/naming.rs b/crates/engine/src/naming.rsindex e7bba55e..1615bc01 100644--- a/crates/engine/src/naming.rs+++ b/crates/engine/src/naming.rs@@ -784,16 +784,17 @@ mod tests {assert_eq!(stems.pick("Song.mp4"), d.join("Song (4).mp4"));assert_eq!(stems.pick("Songs.mp3"), d.join("Songs (1).mp3"));assert_eq!(stems.pick("Song extra.mp4"), d.join("Song extra.mp4"));- let t = std::time::Instant::now();- for i in 0..5000 {- stems.pick(&format!("Video {}.mp4", i % 2500));+ // Many names, each twice: each looked up, not compared with every other one.+ fn pick_all((mut stems, n): (Stems, usize)) -> Stems {+ for i in 0..n {+ stems.pick(&format!("Video {}.mp4", i % (n / 2)));+ }+ stems}+ stems = pick_all((stems, 5000));assert_eq!(stems.pick("Video 7.mp4"), d.join("Video 7 (2).mp4"));- assert!(- t.elapsed() < std::time::Duration::from_secs(2),- "{:?}",- t.elapsed()- );+ // 8 times the names cost about 8 times as long (not 64), on any machine.+ mdm_labserver::growth::assert_linear(1000, |n| (Stems::new(d, []), n), pick_all);}#[test]diff --git a/crates/labserver/src/growth.rs b/crates/labserver/src/growth.rsnew file mode 100644index 00000000..3bcabcad--- /dev/null+++ b/crates/labserver/src/growth.rs@@ -0,0 +1,90 @@+//! How a piece of work grows with its input, for tests: linear, or worse.+//!+//! A test that times its work against a fixed limit ("under 10 s") fails on a slow or busy+//! machine and passes a quadratic search on a fast one. This one times the same work at `n`+//! and at `SCALE × n` on the same machine, a moment apart, and compares the two: linear work+//! costs about `SCALE` times more, quadratic work `SCALE²` times more, whatever the machine's+//! speed.++use std::time::{Duration, Instant};++/// The larger input is this many times the smaller one.+pub const SCALE: usize = 8;++/// The most the larger input may cost, in times the smaller one's cost. Linear work costs+/// `SCALE` (8) times more, `n log n` work about 10, quadratic work 64: 24 leaves room for the+/// caches a larger input misses and a busy machine, and none for a square.+pub const LIMIT: f64 = 24.0;++/// Each size runs this many times, interleaved, and its fastest run counts: a pause of the+/// machine (another program, a busy shared runner) only ever adds time to a run.+const RUNS: usize = 3;++/// Asserts that `work` grows linearly with its input (see the module): `make(n)` builds an+/// input of size `n`, untimed; `work` is timed on it. `small` is the smaller size: large+/// enough that `work` takes a few milliseconds on it, so that a square would show.+///+/// # Panics+///+/// When the larger input costs more than `LIMIT` times the smaller one, with both times.+pub fn assert_linear<T, R>(+ small: usize,+ mut make: impl FnMut(usize) -> T,+ mut work: impl FnMut(T) -> R,+) {+ let mut time = |n: usize| {+ let input = make(n);+ let t = Instant::now();+ let out = work(input);+ let took = t.elapsed();+ drop(std::hint::black_box(out));+ took+ };+ // A warm-up: the first run pays for the allocator's first pages and lazy statics.+ time(small);+ let (mut a, mut b) = (Duration::MAX, Duration::MAX);+ for _ in 0..RUNS {+ a = a.min(time(small));+ b = b.min(time(small * SCALE));+ }+ let ratio = b.as_secs_f64() / a.as_secs_f64().max(1e-6);+ assert!(+ ratio < LIMIT,+ "{} items took {a:?}, {} took {b:?}: {ratio:.1} times as long (linear: {SCALE}, the limit \+ {LIMIT})",+ small,+ small * SCALE,+ );+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn linear_work_passes() {+ assert_linear(+ 200_000,+ |n| (0..n as u64).collect::<Vec<_>>(),+ |v| v.iter().map(|x| x.wrapping_mul(31)).sum::<u64>(),+ );+ }++ #[test]+ #[should_panic(expected = "times as long")]+ fn quadratic_work_fails() {+ assert_linear(+ 1_000,+ |n| (0..n as u64).collect::<Vec<_>>(),+ |v| {+ let mut seen = Vec::new();+ for x in &v {+ if !seen.contains(x) {+ seen.push(*x);+ }+ }+ seen.len()+ },+ );+ }+}diff --git a/crates/labserver/src/lib.rs b/crates/labserver/src/lib.rsindex 77261cba..98b5a2c1 100644--- a/crates/labserver/src/lib.rs+++ b/crates/labserver/src/lib.rs@@ -8,6 +8,7 @@ pub mod drive;pub mod faults;mod feeds;pub mod ftp;+pub mod growth;mod pages;mod server;mod streams;diff --git a/crates/tools/src/manifest.rs b/crates/tools/src/manifest.rsindex fbdd59e0..aaf54cdd 100644--- a/crates/tools/src/manifest.rs+++ b/crates/tools/src/manifest.rs@@ -1111,24 +1111,25 @@ mod tests {/// than any real line), and a line just under the cap is read in linear time.#[test]fn crafted_attribute_lines_cost_no_square() {- let t = std::time::Instant::now();- for line in [- format!("#EXT-X-KEY:{}", "A".repeat(MAX_BYTES)),- format!("#EXT-X-KEY:{}", "A=\"".repeat(MAX_BYTES / 3)),- format!("#EXT-X-KEY:{}", "A".repeat(MAX_ATTRIBUTE_LINE - 20)),- format!(- "#EXT-X-KEY:METHOD=AES-128,{}",- "B".repeat(MAX_ATTRIBUTE_LINE - 40)- ),- ] {- let _ = attributes(&line);- }- assert!(- t.elapsed() < std::time::Duration::from_secs(1),- "{:?}",- t.elapsed()- );+ // Longer than any real line: refused from its length alone.assert!(attributes(&format!("#EXT-X-KEY:{}", "A".repeat(MAX_BYTES))).is_none());+ assert!(attributes(&format!("#EXT-X-KEY:{}", "A=\"".repeat(MAX_BYTES / 3))).is_none());+ // Under the cap: 8 times the line costs about 8 times as long (not 64), on any machine.+ let crafted = |n: usize| {+ [+ format!("#EXT-X-KEY:{}", "A".repeat(n)),+ format!("#EXT-X-KEY:{}", "A=\"".repeat(n / 3)),+ format!("#EXT-X-KEY:METHOD=AES-128,{}", "B".repeat(n)),+ ]+ };+ let small = (MAX_ATTRIBUTE_LINE - 40) / mdm_labserver::growth::SCALE;+ mdm_labserver::growth::assert_linear(small, crafted, |lines| {+ for _ in 0..20 {+ for line in &lines {+ std::hint::black_box(attributes(line));+ }+ }+ });// The run's skip changes nothing: a key after a failed run is still found.let a = attributes("#EXT-X-KEY:AAAA BBB-9 METHOD=NONE").unwrap();assert_eq!(a.get("METHOD").map(String::as_str), Some("NONE"));diff --git a/crates/tools/src/playlist.rs b/crates/tools/src/playlist.rsindex 82016527..c1d1a4de 100644--- a/crates/tools/src/playlist.rs+++ b/crates/tools/src/playlist.rs@@ -311,22 +311,25 @@ mod tests {/// skipped, the list capped at MAX_ENTRIES, and quickly (no quadratic step).#[test]fn a_long_list_is_read_in_order_and_capped() {- let mut text = String::new();- for i in 1..=MAX_ENTRIES + 500 {- text.push_str(&format!(- r#"{{"url": "https://v.example/{i}", "title": "Video {i}", "playlist_index": {i}}}"#- ));- text.push('\n');- if i == 3 {+ let lines = |n: usize, giant: bool| {+ let mut text = String::new();+ for i in 1..=n {text.push_str(&format!(- "{{\"title\": \"{}\"}}\n",- "x".repeat(MAX_LINE * 2)+ r#"{{"url": "https://v.example/{i}", "title": "Video {i}", "playlist_index": {i}}}"#));- text.push_str("garbage\n");+ text.push('\n');+ if giant && i == 3 {+ text.push_str(&format!(+ "{{\"title\": \"{}\"}}\n",+ "x".repeat(MAX_LINE * 2)+ ));+ text.push_str("garbage\n");+ }}- }+ text+ };+ let text = lines(MAX_ENTRIES + 500, true);let shared = Mutex::new(Shared::default());- let t = std::time::Instant::now();read(text.as_bytes(), &shared, 1);let sh = shared.lock().unwrap();assert_eq!(sh.entries.len(), MAX_ENTRIES);@@ -335,10 +338,11 @@ mod tests {sh.entries[3].title, "Video 4","the giant line skipped, order kept");- assert!(- t.elapsed() < std::time::Duration::from_secs(5),- "{:?}",- t.elapsed()+ // 8 times the lines cost about 8 times as long (not 64), on any machine.+ mdm_labserver::growth::assert_linear(+ MAX_ENTRIES / 10,+ |n| (lines(n, false), Mutex::new(Shared::default())),+ |(text, shared)| read(text.as_bytes(), &shared, 1),);}}