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
This commit is contained in:
Scott Lamb 2017-02-15 19:16:34 -08:00
parent 13c6af45a1
commit c6813bd886

View File

@ -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<CameraDayKey, CameraDayValue>) {
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 => {},
}
}