Gateway: Add Songbird::iter (#166)

This PR allows users to iterate over all existing `Call`s via the `Songbird::iter` method.

Closes #165.
This commit is contained in:
fee1-dead
2023-03-22 01:32:36 +08:00
committed by Kyle Simpson
parent 2de071f921
commit 5bc843047f

View File

@@ -185,6 +185,16 @@ impl Songbird {
}) })
} }
/// Creates an iterator for all [`Call`]s currently managed.
pub fn iter(&self) -> Iter<'_> {
Iter {
inner: self
.calls
.iter()
.map(|x| (*x.key(), Arc::clone(&x.value()))),
}
}
/// Sets a shared configuration for all drivers created from this /// Sets a shared configuration for all drivers created from this
/// manager. /// manager.
/// ///
@@ -449,6 +459,40 @@ impl VoiceGatewayManager for Songbird {
} }
} }
type DashMapIter<'a> = dashmap::iter::Iter<'a, GuildId, Arc<Mutex<Call>>>;
/// An iterator over all [`Call`]s currently stored in the manager instance.
pub struct Iter<'a> {
inner: std::iter::Map<
DashMapIter<'a>,
fn(<DashMapIter<'a> as Iterator>::Item) -> (GuildId, Arc<Mutex<Call>>),
>,
}
impl<'a> Iterator for Iter<'a> {
type Item = (GuildId, Arc<Mutex<Call>>);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
fn count(self) -> usize {
self.inner.count()
}
fn fold<B, F>(self, init: B, f: F) -> B
where
Self: Sized,
F: FnMut(B, Self::Item) -> B,
{
self.inner.fold(init, f)
}
}
#[inline] #[inline]
fn shard_id(guild_id: u64, shard_count: u64) -> u64 { fn shard_id(guild_id: u64, shard_count: u64) -> u64 {
(guild_id >> 22) % shard_count (guild_id >> 22) % shard_count