fdt_rs/index/
node.rs

1use core::ptr;
2use core::str::from_utf8;
3
4use super::iters::{DevTreeIndexIter, DevTreeIndexNodePropIter, DevTreeIndexNodeSiblingIter};
5use super::tree::{DTINode, DevTreeIndex};
6use crate::error::DevTreeError;
7
8#[derive(Clone)]
9pub struct DevTreeIndexNode<'a, 'i: 'a, 'dt: 'i> {
10    index: &'a DevTreeIndex<'i, 'dt>,
11    pub(super) node: &'a DTINode<'i, 'dt>,
12}
13
14impl<'a, 'i: 'a, 'dt: 'i> PartialEq for DevTreeIndexNode<'a, 'i, 'dt> {
15    fn eq(&self, other: &Self) -> bool {
16        ptr::eq(self.index, other.index) && ptr::eq(self.node, other.node)
17    }
18}
19
20impl<'a, 'i: 'a, 'dt: 'i> DevTreeIndexNode<'a, 'i, 'dt> {
21    pub(super) fn new(index: &'a DevTreeIndex<'i, 'dt>, node: &'a DTINode<'i, 'dt>) -> Self {
22        Self { index, node }
23    }
24
25    pub fn index(&self) -> &'a DevTreeIndex<'i, 'dt> {
26        self.index
27    }
28
29    pub fn name(&self) -> Result<&'dt str, DevTreeError> {
30        from_utf8(self.node.name).map_err(DevTreeError::StrError)
31    }
32
33    pub fn siblings(&self) -> DevTreeIndexNodeSiblingIter<'a, 'i, 'dt> {
34        DevTreeIndexNodeSiblingIter::from(DevTreeIndexIter::from_node(self.clone()))
35    }
36
37    pub fn props(&self) -> DevTreeIndexNodePropIter<'a, 'i, 'dt> {
38        DevTreeIndexNodePropIter(DevTreeIndexIter::from_node(self.clone()))
39    }
40
41    pub fn parent(&self) -> Option<Self> {
42        self.node.parent().map(|par| Self::new(self.index, par))
43    }
44
45    pub fn children(&self) -> DevTreeIndexNodeSiblingIter<'a, 'i, 'dt> {
46        match self.node.first_child() {
47            Some(child) => DevTreeIndexNodeSiblingIter::from(DevTreeIndexIter::from_node_include(
48                DevTreeIndexNode::new(self.index, child),
49            )),
50            None => DevTreeIndexNodeSiblingIter::from(DevTreeIndexIter::new_dead_iter(self.index)),
51        }
52    }
53
54    /// Returns true if `self` is a parent of the other [`DevTreeIndexNode`]
55    pub fn is_parent_of(&self, other: &Self) -> bool {
56        if let Some(parent) = &other.parent() {
57            return parent == self;
58        }
59        false
60    }
61
62    /// Returns true if `self` is a sibling of the other [`DevTreeIndexNode`]
63    pub fn is_sibling_of(&self, other: &Self) -> bool {
64        other.parent() == self.parent()
65    }
66}