1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use std::collections::BTreeMap;
use TakeSome;

impl<K, V> TakeSome for BTreeMap<K, V>
where
    K: Ord,
{
    type Item = (K, V);

    /// Takes the "greatest" elements from the map.
    ///
    /// `unsafe` under the cover!
    fn take_some(&mut self) -> Option<(K, V)> {
        // If the key corresponds to the "first" element (the one we store separately), we have
        // to take a "random" element from the map (`self.rest`) and put is as the "first".
        let temp_max_key: *const K = match self.keys().next_back() {
            Some(x) => x,
            None => return None,
        };
        // We need that unsafe magic because we are going to remove an element a reference to
        // which we kinda hold.
        let temp_max_key: &K = unsafe { &*temp_max_key };
        let new_map = self.split_off(temp_max_key);
        // After a split we have a `new_map` which contains "everything after a given key,
        // including the key", and because it's a maximum key, the `new_map` contains of only
        // that key.
        Some(
            new_map
                .into_iter()
                .next()
                .expect("Well, it should contain a key"),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::iter::once;

    #[test]
    fn check_btree_map() {
        let mut empty: BTreeMap<String, String> = BTreeMap::new();
        assert_eq!(None, empty.take_some());

        let mut one_element: BTreeMap<_, _> =
            once(("check".to_string(), "checked".to_string())).collect();
        assert_eq!(
            Some(("check".into(), "checked".into())),
            one_element.take_some()
        );
        assert!(one_element.is_empty());

        let mut map: BTreeMap<_, _> = vec![
            ("check".to_string(), "lol".to_string()),
            ("wut".into(), "ahaha".into()),
            ("123123".into(), "....".into()),
        ].into_iter()
            .collect();
        assert_eq!(Some(("wut".into(), "ahaha".into())), map.take_some());
        assert_eq!(2, map.len());
    }
}