Skip to content

Commit

Permalink
Export SocketIter and remove SocketIter cloneing
Browse files Browse the repository at this point in the history
This fixes the SocketIter type (again) by holding a reference to the
socket (instead of cloneing). Doing this removes unecessary calls to
`ref` and `unref` when cloning and droping the iterator.

Also - the SocketIter type is exported as MonitorSocketIter. This allows
creating custom Iter types which can be used to map off the event types.

Signed-off-by: thomas <[email protected]>
  • Loading branch information
TomzBench committed Nov 3, 2022
1 parent 3002527 commit 00ca2de
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 20 deletions.
5 changes: 4 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ pub use enumerator::{Devices, Enumerator};
#[cfg(feature = "hwdb")]
pub use hwdb::Hwdb;
pub use list::{Entry, List};
pub use monitor::{Builder as MonitorBuilder, Event, EventType, Socket as MonitorSocket};
pub use monitor::{
Builder as MonitorBuilder, Event, EventType, Socket as MonitorSocket,
SocketIter as MonitorSocketIter,
};
pub use udev::Udev;

macro_rules! try_alloc {
Expand Down
29 changes: 10 additions & 19 deletions src/monitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ pub struct Socket {
impl Socket {
/// Create an iterator of socket event messages
pub fn iter(&self) -> SocketIter {
SocketIter::new(self)
SocketIter::new(&self)
}
}

Expand All @@ -161,37 +161,28 @@ impl AsRawFd for Socket {
}
}

pub struct SocketIter {
udev: Udev,
monitor: *mut ffi::udev_monitor,
/// Iterator of socket events
pub struct SocketIter<'a> {
socket: &'a Socket,
}

impl SocketIter {
impl<'a> SocketIter<'a> {
/// Create a socket by cloning the underlying udev instance
fn new(socket: &Socket) -> SocketIter {
SocketIter {
udev: socket.inner.udev.clone(),
monitor: unsafe { ffi::udev_monitor_ref(socket.inner.monitor) },
}
}
}

impl Drop for SocketIter {
fn drop(&mut self) {
unsafe { ffi::udev_monitor_unref(self.monitor) };
fn new(socket: &'a Socket) -> SocketIter<'a> {
SocketIter { socket }
}
}

impl Iterator for SocketIter {
impl<'a> Iterator for SocketIter<'a> {
type Item = Event;

fn next(&mut self) -> Option<Event> {
let ptr = unsafe { ffi::udev_monitor_receive_device(self.monitor) };
let ptr = unsafe { ffi::udev_monitor_receive_device(self.socket.inner.monitor) };

if ptr.is_null() {
None
} else {
let device = Device::from_raw(self.udev.clone(), ptr);
let device = Device::from_raw(self.socket.inner.udev.clone(), ptr);
Some(Event { device })
}
}
Expand Down

0 comments on commit 00ca2de

Please sign in to comment.