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
use std::marker::PhantomData;
use std::collections::VecDeque;
use super::keys::NaiaKey;
#[derive(Debug)]
pub struct KeyGenerator<K: NaiaKey> {
recycled_local_keys: VecDeque<u16>,
next_new_local_key: u16,
phantom: PhantomData<K>,
}
impl<K: NaiaKey> KeyGenerator<K> {
pub fn new() -> Self {
KeyGenerator {
recycled_local_keys: VecDeque::new(),
next_new_local_key: 0,
phantom: PhantomData,
}
}
pub fn generate(&mut self) -> K {
if let Some(local_key) = self.recycled_local_keys.pop_front() {
return K::from_u16(local_key);
}
let output = self.next_new_local_key;
self.next_new_local_key += 1;
return K::from_u16(output);
}
pub fn recycle_key(&mut self, local_key: &K) {
self.recycled_local_keys.push_back(local_key.to_u16());
}
}