messaging_thread_pool/samples/
chat_room.rs

1use messaging_thread_pool_macros::pool_item;
2
3// Allow the macro to refer to the crate by name
4use crate as messaging_thread_pool;
5
6/// A ChatRoom is a stateful entity that manages a list of messages.
7/// It is managed by the thread pool, so we don't need internal mutexes.
8///
9/// This struct demonstrates the use of the `#[pool_item]` macro to automatically
10/// generate the necessary boilerplate for the `PoolItem` trait.
11#[derive(Debug)]
12pub struct ChatRoom {
13    #[allow(dead_code)]
14    id: u64,
15    pub history: Vec<String>,
16}
17
18impl ChatRoom {
19    /// Called by the thread pool when a room with this ID is first requested
20    pub fn new(id: u64) -> Self {
21        Self {
22            id,
23            history: Vec::new(),
24        }
25    }
26}
27
28#[pool_item]
29impl ChatRoom {
30    /// Post a message to the room.
31    /// Returns the index of the message.
32    #[messaging(PostRequest, PostResponse)]
33    pub fn post(&mut self, user: String, text: String) -> usize {
34        let entry = format!("{}: {}", user, text);
35        self.history.push(entry);
36        self.history.len() - 1
37    }
38
39    /// Retrieve the entire message history.
40    #[messaging(GetHistoryRequest, GetHistoryResponse)]
41    pub fn get_history(&self) -> Vec<String> {
42        self.history.clone()
43    }
44}