good_os_framework/task/
signal.rs

1use alloc::{vec::Vec, vec};
2
3use crate::data::bitmap::Bitmap;
4
5/// the signal structure.
6#[derive(Debug, Clone, Copy)]
7pub struct Signal {
8    pub ty: usize,
9    pub data: [u64;8],
10}
11
12/// The signal manager.
13/// You don't need to create one by yourself.
14pub struct SignalManager {
15    signal_bitmap: Bitmap, 
16    signals: Vec<Signal>,
17    waiting_for: usize,
18}
19
20impl SignalManager {
21    pub fn new(signal_type_num: usize) -> Self {
22        Self {
23            signal_bitmap: Bitmap::new(vec![0;signal_type_num].leak()),
24            signals: Vec::new(),
25            waiting_for: 0,
26        }
27    }
28
29    /// Returns whether the signal type is registered.
30    pub fn has_signal(&self, signal_type: usize) -> bool {
31        self.signal_bitmap.get(signal_type)
32    }
33
34    /// Registers a new signal and wakes up the process if it is waiting for the signal.
35    pub fn register_signal(&mut self, signal_type: usize, signal: Signal) -> bool {
36        assert_ne!(signal_type, 0);
37        self.signal_bitmap.set(signal_type, true);
38        self.signals.push(signal);
39
40        if signal_type == self.waiting_for {
41            self.waiting_for = 0;
42            return true;
43        }
44
45        return false;
46    }
47
48    /// Starts to wait for a signal.
49    pub fn register_wait_for(&mut self, signal_type: usize) {
50        self.waiting_for = signal_type;
51    }
52
53    /// Gets a signal of the specified type. Returns None if the signal type is not registered.
54    pub fn get_signal(&mut self, signal_type: usize) -> Option<Signal> {
55        if self.signal_bitmap.get(signal_type) {
56            for idx in 0..self.signals.len() {
57                if self.signals[idx].ty == signal_type {
58                    let signal = self.signals[idx];
59                    return Some(signal);
60                }
61            }
62            return None;
63        } else {
64            None
65        }
66    }
67
68    /// Deletes a signal of the specified type. Nothing happens if the signal type is not registered.
69    pub fn delete_signal(&mut self, signal_type: usize) {
70        if self.signal_bitmap.get(signal_type) {
71            self.signal_bitmap.set(signal_type, false);
72            for idx in 0..self.signals.len() {
73                if self.signals[idx].ty == signal_type {
74                    self.signals.remove(idx);
75                }
76            }
77        }
78    }
79}
80