[librsvg: 1/4] node.rs: Add an iterator over Node's children



commit 48e3bfc7a0d6587f3583dd4f7ea4e4d9027757de
Author: Ivan Molodetskikh <yalterz gmail com>
Date:   Thu Mar 15 09:32:24 2018 +0300

    node.rs: Add an iterator over Node's children

 rsvg_internals/src/node.rs | 39 ++++++++++++++++++++++++++++++++++++++-
 1 file changed, 38 insertions(+), 1 deletion(-)
---
diff --git a/rsvg_internals/src/node.rs b/rsvg_internals/src/node.rs
index d94a21bd..95ae8984 100644
--- a/rsvg_internals/src/node.rs
+++ b/rsvg_internals/src/node.rs
@@ -3,7 +3,7 @@ use glib::translate::*;
 use glib_sys;
 use libc;
 
-use std::cell::RefCell;
+use std::cell::{Ref, RefCell};
 use std::ptr;
 use std::rc::{Rc, Weak};
 
@@ -68,6 +68,12 @@ pub struct Node {
     node_impl: Box<NodeTrait>,
 }
 
+// An iterator over the Node's children
+pub struct Children<'a> {
+    children: Ref<'a, Vec<Rc<Node>>>,
+    index: usize,
+}
+
 // Keep this in sync with rsvg-private.h:RsvgNodeType
 #[repr(C)]
 #[derive(Debug, Copy, Clone, PartialEq)]
@@ -240,6 +246,10 @@ impl Node {
         }
     }
 
+    pub fn children(&self) -> Children {
+        Children::new(self.children.borrow())
+    }
+
     pub fn has_children(&self) -> bool {
         self.children.borrow().len() > 0
     }
@@ -283,6 +293,33 @@ pub fn boxed_node_new(
     )))
 }
 
+impl<'a> Children<'a> {
+    fn new(children: Ref<'a, Vec<Rc<Node>>>) -> Self {
+        Self { children, index: 0 }
+    }
+}
+
+impl<'a> Iterator for Children<'a> {
+    type Item = Rc<Node>;
+
+    fn next(&mut self) -> Option<Self::Item> {
+        if self.index == self.children.len() {
+            return None;
+        }
+
+        let item = self.children[self.index].clone();
+        self.index += 1;
+        Some(item)
+    }
+
+    fn size_hint(&self) -> (usize, Option<usize>) {
+        let count = self.children.len() - self.index;
+        (count, Some(count))
+    }
+}
+
+impl<'a> ExactSizeIterator for Children<'a> {}
+
 #[no_mangle]
 pub extern "C" fn rsvg_node_get_type(raw_node: *const RsvgNode) -> NodeType {
     assert!(!raw_node.is_null());


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]