polar_core/
messages.rs

1use std::collections::VecDeque;
2use std::sync::{Arc, Mutex};
3
4use serde::{Deserialize, Serialize};
5
6use super::warning::PolarWarning;
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub enum MessageKind {
10    Print,
11    Warning,
12}
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct Message {
16    pub kind: MessageKind,
17    pub msg: String,
18}
19
20impl Message {
21    pub fn warning(warning: PolarWarning) -> Message {
22        Self {
23            kind: MessageKind::Warning,
24            msg: warning.to_string(),
25        }
26    }
27}
28
29#[derive(Clone, Debug)]
30pub struct MessageQueue {
31    messages: Arc<Mutex<VecDeque<Message>>>,
32}
33
34impl MessageQueue {
35    pub fn new() -> Self {
36        Self {
37            messages: Arc::new(Mutex::new(VecDeque::new())),
38        }
39    }
40
41    pub fn next(&self) -> Option<Message> {
42        if let Ok(mut messages) = self.messages.lock() {
43            messages.pop_front()
44        } else {
45            None
46        }
47    }
48
49    pub fn push(&self, kind: MessageKind, msg: String) {
50        let mut messages = self.messages.lock().unwrap();
51        messages.push_back(Message { kind, msg });
52    }
53
54    pub fn extend<T: IntoIterator<Item = Message>>(&self, iter: T) {
55        let mut messages = self.messages.lock().unwrap();
56        messages.extend(iter)
57    }
58}
59
60impl Default for MessageQueue {
61    fn default() -> Self {
62        Self::new()
63    }
64}