summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authordhivael <dhivael.git@eno.space>2017-05-28 04:23:02 +0200
committerdhivael <dhivael.git@eno.space>2017-05-28 04:23:02 +0200
commit89dcad42c27c8064a6a3dd13484e2fec1706c974 (patch)
tree90ae46c352594ff5b9f3ec422fe3428538a1df6b
parent428ec39cfbbd6ef7e35148d02e3d64e436d46ef5 (diff)
make iteration non-consuming
-rw-r--r--src/lib.rs21
1 files changed, 15 insertions, 6 deletions
diff --git a/src/lib.rs b/src/lib.rs
index 7b702f4..6c3b403 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -33,17 +33,27 @@ pub struct IfAddr {
struct IfaddrHandle {
addrs: *mut libc::ifaddrs,
- cur: Option<*const libc::ifaddrs>,
+}
+
+struct IfaddrIter<'a> {
+ cur: Option<&'a libc::ifaddrs>,
}
impl IfaddrHandle {
fn new() -> Result<IfaddrHandle, errno::Errno> {
let mut addrs: *mut libc::ifaddrs = unsafe { mem::uninitialized() };
match unsafe { libc::getifaddrs(&mut addrs as *mut *mut libc::ifaddrs) } {
- 0 => Ok(IfaddrHandle{addrs: addrs, cur: Some(addrs)}),
+ 0 => Ok(IfaddrHandle{addrs: addrs}),
_ => Err(errno::errno()),
}
}
+
+ fn iter(&self) -> IfaddrIter {
+ match self.addrs as usize {
+ 0 => IfaddrIter{ cur: None },
+ _ => IfaddrIter{ cur: Some(unsafe { &*self.addrs }) },
+ }
+ }
}
impl Drop for IfaddrHandle {
@@ -52,14 +62,13 @@ impl Drop for IfaddrHandle {
}
}
-impl<'a> Iterator for &'a mut IfaddrHandle {
+impl<'a> Iterator for IfaddrIter<'a> {
type Item = &'a libc::ifaddrs;
fn next(&mut self) -> Option<Self::Item> {
match self.cur {
None => None,
Some(addr) => {
- let addr = unsafe { &*addr };
match addr.ifa_next as usize {
0 => self.cur = None,
_ => self.cur = Some(unsafe { &*addr.ifa_next }),
@@ -119,10 +128,10 @@ fn copy_name(name: *const c_char) -> Vec<u8> {
/// let lo = getifaddrs::getifaddrs().unwrap().into_iter().filter(|i| { i.index == 1 });
/// ```
pub fn getifaddrs() -> Result<Vec<IfAddr>, errno::Errno> {
- IfaddrHandle::new().and_then(|mut addrs| {
+ IfaddrHandle::new().and_then(|addrs| {
let mut result = Vec::new();
- for ifaddr in &mut addrs {
+ for ifaddr in addrs.iter() {
let index = match unsafe { libc::if_nametoindex(ifaddr.ifa_name) } {
0 => return Err(errno::errno()),
i => i,