Skip to main content

react_rs_core/
children.rs

1use std::ops::Deref;
2
3pub struct Children<T>(Vec<T>);
4
5impl<T> Children<T> {
6    pub fn new(children: Vec<T>) -> Self {
7        Self(children)
8    }
9
10    pub fn is_empty(&self) -> bool {
11        self.0.is_empty()
12    }
13
14    pub fn len(&self) -> usize {
15        self.0.len()
16    }
17
18    pub fn iter(&self) -> impl Iterator<Item = &T> {
19        self.0.iter()
20    }
21
22    pub fn into_vec(self) -> Vec<T> {
23        self.0
24    }
25}
26
27impl<T> Deref for Children<T> {
28    type Target = [T];
29
30    fn deref(&self) -> &Self::Target {
31        &self.0
32    }
33}
34
35impl<T> Default for Children<T> {
36    fn default() -> Self {
37        Self(Vec::new())
38    }
39}
40
41impl<T> FromIterator<T> for Children<T> {
42    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
43        Self(iter.into_iter().collect())
44    }
45}
46
47impl<T> IntoIterator for Children<T> {
48    type Item = T;
49    type IntoIter = std::vec::IntoIter<T>;
50
51    fn into_iter(self) -> Self::IntoIter {
52        self.0.into_iter()
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn test_children_basic() {
62        let children: Children<String> = vec!["a".to_string(), "b".to_string(), "c".to_string()]
63            .into_iter()
64            .collect();
65
66        assert_eq!(children.len(), 3);
67        assert!(!children.is_empty());
68    }
69
70    #[test]
71    fn test_children_iteration() {
72        let children: Children<i32> = vec![1, 2, 3].into_iter().collect();
73        let sum: i32 = children.iter().sum();
74        assert_eq!(sum, 6);
75    }
76
77    #[test]
78    fn test_children_default() {
79        let children: Children<String> = Children::default();
80        assert!(children.is_empty());
81        assert_eq!(children.len(), 0);
82    }
83}