mid_idpool/
flat.rs

1use crate::error;
2
3/// Pool of ids for the clients.
4#[derive(Debug, Clone)]
5pub struct FlatIdPool {
6    mem: Vec<u16>,
7    last: u16,
8}
9
10impl FlatIdPool {
11    /// Push id to the pool. Prefixed with `_unchecked`
12    /// because it will not check id presence in the pool.
13    pub fn push_back_unchecked(&mut self, id: u16) {
14        self.mem.push(id);
15    }
16
17    /// Requests id from the pool.
18    pub fn request(&mut self) -> Result<u16, error::IdRequestError> {
19        if let Some(id) = self.mem.pop() {
20            Ok(id)
21        } else {
22            match self.last.overflowing_add(1) {
23                (_, true) => Err(error::IdRequestError::Exceeded),
24                (n, false) => {
25                    let prev = self.last;
26                    self.last = n;
27                    Ok(prev)
28                }
29            }
30        }
31    }
32
33    /// Creates pool with default
34    pub const fn new() -> Self {
35        Self {
36            mem: Vec::new(),
37            last: 0,
38        }
39    }
40}