refactor(src/pull_queue.rs): drop "end" method, add Drop impl

This makes it harder to forget to close the producer end.

Suggested-by: Fintan
Signed-off-by: Lars Wirzenius <liw@liw.fi>
This commit is contained in:
Lars Wirzenius
2025-05-14 13:17:20 +03:00
parent 19ede6dfed
commit 4577682fd6
2 changed files with 22 additions and 21 deletions
+18 -15
View File
@@ -18,7 +18,6 @@ use std::sync::{Arc, Condvar, Mutex};
/// for i in 0..10 {
/// queue.push(i);
/// }
/// queue.end();
/// });
/// let consumer = spawn(move ||
/// while let Ok(Some(i)) = clone.pop() {
@@ -38,11 +37,26 @@ impl<T> Clone for PullQueue<T> {
}
}
impl<T: Clone> Default for PullQueue<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> Drop for PullQueue<T> {
fn drop(&mut self) {
let (mutex, var) = &*self.q;
let mut locked = mutex
.lock()
.map_err(|_| PullQueueError::Mutex)
.expect("FATAL: mutex was poisoned");
locked.end();
var.notify_all();
}
}
impl<T: Clone> PullQueue<T> {
/// Create a new [`PullQueue`].
// No `Default` for this type, because we don't want to require
// the type T to implement that.
#[allow(clippy::new_without_default)]
pub fn new() -> Self {
Self {
q: Arc::new((Mutex::new(Unlocked::new()), Condvar::new())),
@@ -66,17 +80,6 @@ impl<T: Clone> PullQueue<T> {
Ok(())
}
/// As producer, tell queue there no more items can be produced.
/// This will call [`Self::pop`] to return `None` when all pushed
/// items have been consumed.
pub fn end(&mut self) -> Result<(), PullQueueError> {
let (mutex, var) = &*self.q;
let mut locked = mutex.lock().map_err(|_| PullQueueError::Mutex)?;
locked.end();
var.notify_all();
Ok(())
}
/// Consume an item, if one is available. This will block until an
/// item is available or not more items will ever be produced.
/// Return `None` when no more items will ever be produced.