axdriver/structs/
dyn.rs

1#![allow(unused_imports)]
2
3use crate::prelude::*;
4use alloc::{boxed::Box, vec, vec::Vec};
5
6/// The unified type of the NIC devices.
7#[cfg(feature = "net")]
8pub type AxNetDevice = Box<dyn NetDriverOps>;
9/// The unified type of the block storage devices.
10#[cfg(feature = "block")]
11pub type AxBlockDevice = Box<dyn BlockDriverOps>;
12/// The unified type of the graphics display devices.
13#[cfg(feature = "display")]
14pub type AxDisplayDevice = Box<dyn DisplayDriverOps>;
15
16impl super::AxDeviceEnum {
17    /// Constructs a network device.
18    #[cfg(feature = "net")]
19    pub fn from_net(dev: impl NetDriverOps + 'static) -> Self {
20        Self::Net(Box::new(dev))
21    }
22
23    /// Constructs a block device.
24    #[cfg(feature = "block")]
25    pub fn from_block(dev: impl BlockDriverOps + 'static) -> Self {
26        Self::Block(Box::new(dev))
27    }
28
29    /// Constructs a display device.
30    #[cfg(feature = "display")]
31    pub fn from_display(dev: impl DisplayDriverOps + 'static) -> Self {
32        Self::Display(Box::new(dev))
33    }
34}
35
36/// A structure that contains all device drivers of a certain category.
37///
38/// If the feature `dyn` is enabled, the inner type is [`Vec<D>`]. Otherwise,
39/// the inner type is [`Option<D>`] and at most one device can be contained.
40pub struct AxDeviceContainer<D>(Vec<D>);
41
42impl<D> AxDeviceContainer<D> {
43    /// Returns number of devices in this container.
44    pub fn len(&self) -> usize {
45        self.0.len()
46    }
47
48    /// Returns whether the container is empty.
49    pub fn is_empty(&self) -> bool {
50        self.len() == 0
51    }
52
53    /// Takes one device out of the container (will remove it from the container).
54    pub fn take_one(&mut self) -> Option<D> {
55        if self.is_empty() {
56            None
57        } else {
58            Some(self.0.remove(0))
59        }
60    }
61
62    /// Constructs the container from one device.
63    pub fn from_one(dev: D) -> Self {
64        Self(vec![dev])
65    }
66
67    /// Adds one device into the container.
68    #[allow(dead_code)]
69    pub(crate) fn push(&mut self, dev: D) {
70        self.0.push(dev);
71    }
72}
73
74impl<D> core::ops::Deref for AxDeviceContainer<D> {
75    type Target = Vec<D>;
76    fn deref(&self) -> &Self::Target {
77        &self.0
78    }
79}
80
81impl<D> Default for AxDeviceContainer<D> {
82    fn default() -> Self {
83        Self(Default::default())
84    }
85}