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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use crate::{node::Node, tree::Tree};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Entry<T> {
    Free { next_free: Option<usize> },
    Occupied(Node<T>),
}

impl<T> Entry<T> {
    pub fn replace(&mut self, val: Self) -> Self {
        std::mem::replace(self, val)
    }

    pub fn is_node(&self) -> bool {
        matches!(self, Entry::Occupied(..))
    }

    pub fn unwrap(self) -> Node<T> {
        match self {
            Entry::Free { .. } => panic!("the entry is free"),
            Entry::Occupied(node) => node,
        }
    }

    pub fn unwrap_ref(&self) -> &Node<T> {
        match self {
            Entry::Free { .. } => panic!("the entry is free"),
            Entry::Occupied(node) => node,
        }
    }

    pub fn unwrap_mut(&mut self) -> &mut Node<T> {
        match self {
            Entry::Free { .. } => panic!("the entry is free"),
            Entry::Occupied(node) => node,
        }
    }

    pub fn unwrap_free(&self) -> Option<usize> {
        match self {
            Entry::Free { next_free } => *next_free,
            Entry::Occupied(_) => panic!("the entry is occupied"),
        }
    }

    pub fn map_ref<'a, U, F>(&'a self, f: F) -> Option<U>
    where
        F: FnOnce(&'a Node<T>) -> U,
    {
        match self {
            Entry::Free { .. } => None,
            Entry::Occupied(node) => Some(f(node)),
        }
    }

    pub fn map_mut<'a, U, F>(&'a mut self, f: F) -> Option<U>
    where
        F: FnOnce(&'a mut Node<T>) -> U,
    {
        match self {
            Entry::Free { .. } => None,
            Entry::Occupied(node) => Some(f(node)),
        }
    }
}

impl<T> Tree<T> {
    pub(crate) fn get_first_free(&self) -> usize {
        self.first_free.unwrap_or(self.nodes.len())
    }

    pub(crate) fn allocate_node(&mut self, node: Node<T>) -> usize {
        match self.first_free {
            Some(index) => {
                let entry = self.nodes[index].replace(Entry::Occupied(node));

                self.first_free = entry.unwrap_free();

                index
            }
            None => {
                let index = self.nodes.len();

                self.nodes.push(Entry::Occupied(node));

                index
            }
        }
    }

    pub(super) fn free_node(&mut self, index: usize) -> Entry<T> {
        let next_free = self.first_free.replace(index);

        self.nodes[index].replace(Entry::Free { next_free })
    }
}