dris_rt/
lib.rs

1#![doc = include_str!("../README.md")]
2
3pub use dris_macros::{component, constructor};
4
5// 结构体字段无法写 `impl Iterator`;多组件注入用 Vec newtype 更稳妥。
6pub struct All<T>(Vec<T>);
7
8impl<T> All<T> {
9    pub fn new(items: Vec<T>) -> Self {
10        Self(items)
11    }
12}
13
14impl<T> std::ops::Deref for All<T> {
15    type Target = [T];
16
17    fn deref(&self) -> &Self::Target {
18        &self.0
19    }
20}
21
22impl<T> IntoIterator for All<T> {
23    type Item = T;
24    type IntoIter = std::vec::IntoIter<T>;
25
26    fn into_iter(self) -> Self::IntoIter {
27        self.0.into_iter()
28    }
29}
30
31impl<'a, T> IntoIterator for &'a All<T> {
32    type Item = &'a T;
33    type IntoIter = std::slice::Iter<'a, T>;
34
35    fn into_iter(self) -> Self::IntoIter {
36        self.0.iter()
37    }
38}
39
40#[derive(Clone, Copy, PartialEq, Eq, Hash)]
41pub struct Type(std::any::TypeId);
42
43impl Type {
44    pub fn of<T: 'static>() -> Self {
45        Self(std::any::TypeId::of::<T>())
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use super::*;
52    use std::collections::HashSet;
53
54    #[test]
55    fn all_覆盖new_deref_引用迭代_值迭代() {
56        let all = All::new(vec![1, 2, 3]);
57        assert_eq!(all.len(), 3);
58        assert_eq!(all[0], 1);
59
60        let by_ref: Vec<i32> = (&all).into_iter().copied().collect();
61        assert_eq!(by_ref, vec![1, 2, 3]);
62
63        let by_value: Vec<i32> = all.into_iter().collect();
64        assert_eq!(by_value, vec![1, 2, 3]);
65
66        let empty: All<i32> = All::new(Vec::new());
67        assert!((&empty).into_iter().next().is_none());
68    }
69
70    #[test]
71    fn type_of_可比较可哈希() {
72        let a = Type::of::<u8>();
73        let b = Type::of::<u8>();
74        let c = Type::of::<u16>();
75        assert!(a == b);
76        assert!(a != c);
77
78        let mut set = HashSet::new();
79        assert!(set.insert(a));
80        assert!(!set.insert(b));
81        assert!(set.insert(c));
82    }
83}