sage_broker/
sessions.rs

1use crate::Session;
2use std::sync::Arc;
3
4/// Holds sessions manipulated from the Command Loop
5#[derive(Default, Debug)]
6pub struct Sessions {
7    db: Vec<Arc<Session>>,
8}
9
10impl Sessions {
11    /// Returns the number of sessions
12    pub fn len(&self) -> usize {
13        self.db.len()
14    }
15
16    /// Returns true is the collection is empty
17    pub fn is_empty(&self) -> bool {
18        self.len() == 0
19    }
20
21    /// Searches for the Session at given index and returns it.
22    /// If `take`  is set, the session will be extracted from the database
23    pub fn take(&mut self, client_id: &str) -> Option<Arc<Session>> {
24        self.db
25            .iter()
26            .position(|c| c.client_id() == client_id)
27            .map(|index| self.db.swap_remove(index))
28    }
29
30    /// Returns the client given its id. If not client exist, returns None
31    pub fn get(&self, client_id: &str) -> Option<Arc<Session>> {
32        self.db
33            .iter()
34            .position(|c| c.client_id() == client_id)
35            .map(|index| self.db[index].clone())
36    }
37
38    /// Add the given session into the database
39    pub fn add(&mut self, session: Arc<Session>) {
40        self.db.push(session);
41    }
42
43    /// Returns an iterator over sessions
44    pub fn iter(&self) -> SessionsIterator {
45        SessionsIterator {
46            inner_it: self.db.iter(),
47        }
48    }
49}
50
51pub struct SessionsIterator<'a> {
52    inner_it: std::slice::Iter<'a, Arc<Session>>,
53}
54
55impl<'a> Iterator for SessionsIterator<'a> {
56    type Item = &'a Arc<Session>;
57
58    fn next(&mut self) -> Option<Self::Item> {
59        self.inner_it.next()
60    }
61}