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
use std::collections::HashSet;
use std::hash::{BuildHasher, Hash};
use TakeSome;

impl<K, S> TakeSome for HashSet<K, S>
where
    K: Hash + Eq,
    S: BuildHasher,
{
    type Item = K;

    /// `unsafe` under the cover!
    fn take_some(&mut self) -> Option<K> {
        // If the key corresponds to the "first" element (the one we store separately), we have
        // to take a "random" element from the set (`self.rest`) and put is as the "first".
        let temp_key: *const K = match self.iter().next() {
            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_key: &K = unsafe { &*temp_key };
        Some(
            self.take(temp_key)
                .expect("We've just pulled a key from the set"),
        )
    }
}

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

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

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

        let mut set: HashSet<_> = vec!["check".to_string(), "lol".into(), "wut".into()]
            .into_iter()
            .collect();
        assert!(set.take_some().is_some());
        assert_eq!(2, set.len());
    }
}