weak_lists/sync/
list.rs

1use {
2    crate::sync::{Iter, SyncWeakList, WeakListData},
3    alloc::sync::Arc,
4    core::fmt::{Debug, Formatter},
5    parking_lot::Mutex,
6};
7
8impl<T> SyncWeakList<T>
9where
10    T: ?Sized,
11{
12    /// Removes all elements from the list.
13    ///
14    /// # Examples
15    ///
16    /// ```
17    /// use std::sync::Arc;
18    /// use weak_lists::{SyncWeakList, SyncWeakListElement};
19    ///
20    /// let list = SyncWeakList::default();
21    /// let entry = Arc::new(1);
22    /// let entry = SyncWeakListElement::new(Arc::downgrade(&entry));
23    /// entry.attach(&list);
24    /// assert!(list.iter().next().is_some());
25    /// list.clear();
26    /// assert!(list.iter().next().is_none());
27    /// ```
28    pub fn clear(&self) {
29        let data = &mut *self.data.lock();
30        data.members.clear();
31    }
32
33    /// Creates an iterator over the entries of the list.
34    ///
35    /// The list can be mutated during the iteration. It is guaranteed that, if an element
36    /// was part of the list when this iterator was created, and if the element was not
37    /// removed during the iteration, then the element will be returned exactly once by
38    /// this iterator.
39    pub fn iter(&self) -> Iter<'_, T> {
40        let data = &mut *self.data.lock();
41        if data.active_iterators == 0 {
42            data.members.compact();
43        }
44        data.active_iterators += 1;
45        Iter {
46            iter: 0..data.members.index_len(),
47            data: &self.data,
48        }
49    }
50}
51
52impl<T> Default for SyncWeakList<T>
53where
54    T: ?Sized,
55{
56    fn default() -> Self {
57        Self {
58            data: Arc::new(Mutex::new(WeakListData {
59                next_id: 0,
60                active_iterators: 0,
61                members: Default::default(),
62            })),
63        }
64    }
65}
66
67impl<'a, T> IntoIterator for &'a SyncWeakList<T>
68where
69    T: ?Sized,
70{
71    type Item = Arc<T>;
72    type IntoIter = Iter<'a, T>;
73
74    fn into_iter(self) -> Self::IntoIter {
75        self.iter()
76    }
77}
78
79impl<T> Debug for SyncWeakList<T>
80where
81    T: ?Sized,
82{
83    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
84        f.debug_struct("SyncWeakList")
85            .field("id", &Arc::as_ptr(&self.data))
86            .finish_non_exhaustive()
87    }
88}