1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use arraydeque::ArrayDeque;

use crate::interrupts::TIMER_MS;

use super::Scheduler;
use super::APPS;

/// Manages and activates time-triggered activities.
///
/// The Bellringer is regularly activated and checks whether any of the bells should ring.
/// The bells are stored in a queue that is managed by the Bellringer.
/// A clever implementation avoids iterating through the whole list for every iteration by
/// keeping the bells sorted and storing delta times. This approach leads to a complexity
/// of O(1) for the method called by the timer interrupt in case no bells need to be rung.
pub struct BellRinger {
    bells: ArrayDeque<Bell, APPS>,
}

#[derive(Debug, Clone)]
struct Bell {
    thread: usize,
    offset: usize,
}
impl Bell {
    fn new(thread: usize, offset: usize) -> Self {
        Self { thread, offset }
    }
}

impl BellRinger {
    pub const fn new() -> Self {
        Self {
            bells: ArrayDeque::new(),
        }
    }

    /// Blocks the current thread for the number of milliseconds
    pub fn sleep(&mut self, scheduler: &mut Scheduler, ms: usize) {
        let tid = scheduler.active().expect("No running thread!");

        let ticks = ms * TIMER_MS;

        let mut total = 0;
        let larger = self.bells.iter().position(|bell| {
            if (total + bell.offset) > ticks {
                true
            } else {
                total += bell.offset;
                false
            }
        });

        let offset = ticks - total;
        if let Some(larger) = larger {
            self.bells.get_mut(larger).unwrap().offset -= offset;
            self.bells.insert(larger, Bell::new(tid, offset)).unwrap();
        } else {
            self.bells.push_back(Bell::new(tid, ticks)).unwrap();
        }

        scheduler.resume(false);
    }

    /// Wakes up waiting threads
    pub fn check(&mut self, scheduler: &mut Scheduler) {
        let mut ticks = 1;

        while let Some(bell) = self.bells.pop_front() {
            if bell.offset <= ticks {
                ticks -= bell.offset;
                scheduler.ready(bell.thread);
            } else {
                self.bells
                    .push_front(Bell::new(bell.thread, bell.offset - 1))
                    .unwrap();
                break;
            }
        }
    }

    pub fn is_empty(&self) -> bool {
        self.bells.is_empty()
    }
}