From c6813bd886f0f1402c49c87644c7065f8df65c5b Mon Sep 17 00:00:00 2001 From: Scott Lamb Date: Wed, 15 Feb 2017 19:16:34 -0800 Subject: [PATCH] clean up adjust_day implementation Entry::Occupied has a remove_entry method that allows this to be a little more readable, and a little more efficient (one btree traversal rather than two). mmstick on reddit pointed this out: https://www.reddit.com/r/rust/comments/5tzw5q/how_are_if_else_scopes_are_handled_in_rust/dds0r37/?context=3 --- src/db.rs | 33 ++++++++++++++------------------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/src/db.rs b/src/db.rs index abecad9..8758d1e 100644 --- a/src/db.rs +++ b/src/db.rs @@ -364,29 +364,24 @@ pub struct CameraChange { pub sub_rtsp_path: String, } -/// Adds `delta` to the day represented by `day` in the map `m`. +/// Adds non-zero `delta` to the day represented by `day` in the map `m`. /// Inserts a map entry if absent; removes the entry if it has 0 entries on exit. fn adjust_day(day: CameraDayKey, delta: CameraDayValue, m: &mut BTreeMap) { - enum Do { - Insert, - Remove, - Nothing - }; - let what_to_do = match m.get_mut(&day) { - None => { - Do::Insert + use ::std::collections::btree_map::Entry; + match m.entry(day) { + Entry::Vacant(e) => { e.insert(delta); }, + Entry::Occupied(mut e) => { + let remove = { + let v = e.get_mut(); + v.recordings += delta.recordings; + v.duration += delta.duration; + v.recordings == 0 + }; + if remove { + e.remove_entry(); + } }, - Some(ref mut v) => { - v.recordings += delta.recordings; - v.duration += delta.duration; - if v.recordings == 0 { Do::Remove } else { Do::Nothing } - }, - }; - match what_to_do { - Do::Insert => { m.insert(day, delta); }, - Do::Remove => { m.remove(&day); }, - Do::Nothing => {}, } }