From 887785f1254854ff99512efa523db71a68f667e2 Mon Sep 17 00:00:00 2001 From: BillK <35489013+Bill13579@users.noreply.github.com> Date: Thu, 18 Apr 2024 08:45:34 +0800 Subject: [PATCH] Fix statistics `sub` panic caused by unwrap on non-existent key --- cartographer/src/lib.rs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/cartographer/src/lib.rs b/cartographer/src/lib.rs index 1cff09f..5cc5430 100644 --- a/cartographer/src/lib.rs +++ b/cartographer/src/lib.rs @@ -48,6 +48,9 @@ impl Statistics { } } pub fn sub(&mut self, doc: &Document) { + if self.totalDocs == 0 { + return; + } if self.totalDocs != 1 { self.lengthAvg *= self.totalDocs as f64 / (self.totalDocs-1) as f64; } else { @@ -60,13 +63,14 @@ impl Statistics { } for (key, _) in &part.occurences { if !done_set.contains(key) { - let old_val = self.occurences.get(key).unwrap(); - if old_val - 1 == 0 { - // Remove the key from the map if they don't occur in any documents at all to avoid - // muddying the IDF calculations - self.occurences.remove(key); - } else { - self.occurences.insert(key.clone(), old_val - 1); + if let Some(old_val) = self.occurences.get(key) { + if old_val - 1 == 0 { + // Remove the key from the map if they don't occur in any documents at all to avoid + // muddying the IDF calculations + self.occurences.remove(key); + } else { + self.occurences.insert(key.clone(), old_val - 1); + } } done_set.insert(key.clone()); }