pub struct WeakList<T>where
T: ?Sized,{ /* private fields */ }Expand description
A list holding weak references to its elements.
The list does not hold strong references to its elements and the elements do not hold strong references to the list. You must use some other mechanism to keep all parties alive.
This list supports concurrent iteration and modification.
§Examples
use {
weak_lists::{WeakList, WeakListElement},
std::{
array,
rc::{Rc, Weak},
},
};
pub struct Service {
callbacks: WeakList<dyn Callback>,
}
pub trait Callback {
fn run(&self);
}
impl Service {
pub fn register_callback(&self, callback: &WeakListElement<dyn Callback>) {
callback.attach(&self.callbacks);
}
pub fn run_callbacks(&self) {
for callback in &self.callbacks {
callback.run();
}
}
}
struct Client {
id: usize,
entry: WeakListElement<dyn Callback>,
}
impl Callback for Client {
fn run(&self) {
eprintln!("Callback {} invoked", self.id);
if self.id == 1 {
self.entry.detach();
}
}
}
let service = Service {
callbacks: Default::default(),
};
let clients = array::from_fn::<_, 3, _>(|id| {
Rc::<Client>::new_cyclic(|slf| Client {
id,
entry: WeakListElement::new(slf.clone()),
})
});
for client in &clients {
service.register_callback(&client.entry);
}
service.run_callbacks();
// Callback 0 invoked
// Callback 1 invoked
// Callback 2 invoked
service.run_callbacks();
// Callback 0 invoked
// Callback 2 invokedImplementations§
Source§impl<T> WeakList<T>where
T: ?Sized,
impl<T> WeakList<T>where
T: ?Sized,
Sourcepub fn clear(&self)
pub fn clear(&self)
Removes all elements from the list.
§Examples
use std::rc::{Rc, Weak};
use weak_lists::{WeakList, WeakListElement};
let list = WeakList::default();
let entry = Rc::new(1);
let entry = WeakListElement::new(Rc::downgrade(&entry));
entry.attach(&list);
assert!(list.iter().next().is_some());
list.clear();
assert!(list.iter().next().is_none());Sourcepub fn iter(&self) -> Iter<'_, T> ⓘ
pub fn iter(&self) -> Iter<'_, T> ⓘ
Creates an iterator over the entries of the list.
The list can be mutated during the iteration. It is guaranteed that, if an element was part of the list when this iterator was created, and if the element was not removed during the iteration, then the element will be returned exactly once by this iterator.
Trait Implementations§
Source§impl<'a, T> IntoIterator for &'a WeakList<T>where
T: ?Sized,
impl<'a, T> IntoIterator for &'a WeakList<T>where
T: ?Sized,
Auto Trait Implementations§
impl<T> Freeze for WeakList<T>where
T: ?Sized,
impl<T> !RefUnwindSafe for WeakList<T>
impl<T> !Send for WeakList<T>
impl<T> !Sync for WeakList<T>
impl<T> Unpin for WeakList<T>where
T: ?Sized,
impl<T> !UnwindSafe for WeakList<T>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more