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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};

#[derive(Debug, Clone)]
pub(crate) struct ConnectionIdManager(Arc<Mutex<Inner>>);

impl ConnectionIdManager {
    pub fn new() -> Self {
        ConnectionIdManager(Arc::new(Mutex::new(Inner::new())))
    }

    pub fn acquire(&self) -> ConnectionId {
        let id = {
            let mut this = self.0.lock().expect("mutex poisoned");
            this.acquire()
        };

        ConnectionId::new(id, self.clone())
    }

    fn release(&self, id: usize) {
        let mut this = self.0.lock().expect("mutex poisoned");
        this.release(id);
    }
}

#[derive(Debug)]
struct Inner {
    next: usize,
    free: Vec<usize>,
}

impl Inner {
    fn new() -> Self {
        Inner {
            next: 0,
            free: Vec::new(),
        }
    }

    fn acquire(&mut self) -> usize {
        match self.free.pop() {
            Some(id) => id,

            None => {
                let id = self.next;
                self.next += 1;
                id
            }
        }
    }

    fn release(&mut self, id: usize) {
        debug_assert!(id < self.next);
        debug_assert!(!self.free.contains(&id));

        if (id + 1) == self.next {
            self.next -= 1;
        } else {
            self.free.push(id);
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct ConnectionId(Arc<ConnectionIdInner>);

impl ConnectionId {
    fn new(id: usize, ids: ConnectionIdManager) -> Self {
        ConnectionId(Arc::new(ConnectionIdInner::new(id, ids)))
    }
}

impl PartialEq for ConnectionId {
    fn eq(&self, other: &Self) -> bool {
        self.0.id() == other.0.id()
    }
}

impl Eq for ConnectionId {}

impl Hash for ConnectionId {
    fn hash<H>(&self, state: &mut H)
    where
        H: Hasher,
    {
        self.0.id().hash(state)
    }
}

#[derive(Debug)]
struct ConnectionIdInner {
    id: usize,
    ids: ConnectionIdManager,
}

impl ConnectionIdInner {
    fn new(id: usize, ids: ConnectionIdManager) -> Self {
        ConnectionIdInner { id, ids }
    }

    fn id(&self) -> usize {
        self.id
    }
}

impl Drop for ConnectionIdInner {
    fn drop(&mut self) {
        self.ids.release(self.id);
    }
}