From 61d50a279f38987bbc125082d1775e0f348f2e1f Mon Sep 17 00:00:00 2001 From: alexmoon Date: Fri, 13 May 2022 21:03:13 -0400 Subject: Add a Connection iterator --- nrf-softdevice/src/ble/connection.rs | 39 ++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/nrf-softdevice/src/ble/connection.rs b/nrf-softdevice/src/ble/connection.rs index 1ed33d5..79e0f8f 100644 --- a/nrf-softdevice/src/ble/connection.rs +++ b/nrf-softdevice/src/ble/connection.rs @@ -1,5 +1,6 @@ use core::cell::Cell; use core::cell::UnsafeCell; +use core::iter::FusedIterator; use raw::ble_gap_conn_params_t; @@ -300,8 +301,46 @@ impl Connection { pub(crate) fn with_state(&self, f: impl FnOnce(&mut ConnectionState) -> T) -> T { with_state(self.index, f) } + + pub fn iter() -> ConnectionIter { + ConnectionIter(0) + } } +pub struct ConnectionIter(u8); + +impl Iterator for ConnectionIter { + type Item = Connection; + + fn next(&mut self) -> Option { + let n = usize::from(self.0); + if n < CONNS_MAX { + unsafe { + for (i, s) in STATES[n..].iter().enumerate() { + let state = &mut *s.get(); + if state.conn_handle.is_some() { + let index = (n + i) as u8; + state.refcount = unwrap!( + state.refcount.checked_add(1), + "Too many references to same connection" + ); + self.0 = index + 1; + return Some(Connection { index }); + } + } + } + self.0 = CONNS_MAX as u8; + } + None + } + + fn size_hint(&self) -> (usize, Option) { + (0, Some(CONNS_MAX - usize::from(self.0))) + } +} + +impl FusedIterator for ConnectionIter {} + // ConnectionStates by index. const DUMMY_STATE: UnsafeCell = UnsafeCell::new(ConnectionState::dummy()); static mut STATES: [UnsafeCell; CONNS_MAX] = [DUMMY_STATE; CONNS_MAX]; -- cgit v1.2.3