From 5a7e74d79cbc0a97caeef3ce03ed57f264153e2d Mon Sep 17 00:00:00 2001 From: Tim Taubner Date: Thu, 23 Jun 2022 16:51:47 +0200 Subject: [PATCH] Binary Search to achieve promised logarithmic running time for sample (instead of linear!) (cherry picked from commit ffcf289f713d5d92a74038ffa2fb6059d9995175) --- src/spline.rs | 31 +++++++------------------------ 1 file changed, 7 insertions(+), 24 deletions(-) diff --git a/src/spline.rs b/src/spline.rs index 553ab08..485c061 100644 --- a/src/spline.rs +++ b/src/spline.rs @@ -318,37 +318,20 @@ pub struct KeyMut<'a, T, V> { } // Find the lower control point corresponding to a given time. +// It has the property to have a timestamp smaller or equal to t fn search_lower_cp(cps: &[Key], t: T) -> Option where T: PartialOrd, { - let mut i = 0; let len = cps.len(); - if len < 2 { return None; } - - loop { - let cp = &cps[i]; - let cp1 = &cps[i + 1]; - - if t >= cp1.t { - if i >= len - 2 { - return None; - } - - i += 1; - } else if t < cp.t { - if i == 0 { - return None; - } - - i -= 1; - } else { - break; // found - } + match cps.binary_search_by(|key| key.t.partial_cmp(&t).unwrap()) { + Err(i) if i >= len => None, + Err(i) if i == 0 => None, + Err(i) => Some(i-1), + Ok(i) if i == len - 1 => None, + Ok(i) => Some(i), } - - Some(i) }