Skip to main content

sark_core/deadline/
config.rs

1use std::time;
2
3use o3::base::time::{Positive, Zero};
4
5use crate::deadline;
6
7/// Validated non-empty windows shared by every protocol adapter.
8#[derive(Clone, Copy, PartialEq, Eq)]
9pub struct Config {
10    windows: [Window; Self::COUNT],
11}
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum Error {
15    ZeroWindow { source: Zero },
16}
17
18#[derive(Clone, Copy, PartialEq, Eq)]
19pub enum Window {
20    Disabled,
21    Finite(Positive),
22}
23
24impl Config {
25    const COUNT: usize = 5;
26
27    pub const fn new(phase: deadline::Phase, window: Positive) -> Self {
28        let mut windows = [Window::Disabled; Self::COUNT];
29        windows[phase as usize] = Window::Finite(window);
30        Self { windows }
31    }
32
33    pub fn try_new(phase: deadline::Phase, window: time::Duration) -> Result<Self, Error> {
34        let window = Self::validate(window)?;
35        Ok(Self::new(phase, window))
36    }
37
38    pub const fn with(mut self, phase: deadline::Phase, window: Positive) -> Self {
39        self.windows[phase as usize] = Window::Finite(window);
40        self
41    }
42
43    pub fn try_with(self, phase: deadline::Phase, window: time::Duration) -> Result<Self, Error> {
44        let window = Self::validate(window)?;
45        Ok(self.with(phase, window))
46    }
47
48    pub const fn window(self, phase: deadline::Phase) -> Window {
49        self.windows[phase as usize]
50    }
51
52    fn validate(window: time::Duration) -> Result<Positive, Error> {
53        match Positive::try_new(window) {
54            Ok(window) => Ok(window),
55            Err(source) => Err(Error::ZeroWindow { source }),
56        }
57    }
58}
59
60const _: () = {
61    assert!(std::mem::size_of::<Window>() == std::mem::size_of::<Positive>());
62    assert!(std::mem::align_of::<Window>() == std::mem::align_of::<Positive>());
63    assert!(std::mem::size_of::<Config>() == 5 * std::mem::size_of::<Positive>());
64    assert!(!std::mem::needs_drop::<Config>());
65};