2025-10-27 16:10:57 +01:00
|
|
|
use std::{
|
|
|
|
|
io,
|
|
|
|
|
pin::Pin,
|
|
|
|
|
task::{Context, Poll},
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
use tokio::{
|
|
|
|
|
io::{AsyncRead, DuplexStream, ReadBuf},
|
|
|
|
|
task::JoinHandle,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
/// Async reader that is backed by a spawned task writing into it.
|
2025-10-27 18:13:50 +01:00
|
|
|
///
|
|
|
|
|
/// This is generic over the error type to support both FLAC and MP3 decoders.
|
|
|
|
|
pub struct ManagedAsyncReader<E>
|
|
|
|
|
where
|
|
|
|
|
E: std::error::Error,
|
|
|
|
|
{
|
2025-10-27 16:10:57 +01:00
|
|
|
inner: Option<DuplexStream>,
|
2025-10-27 18:13:50 +01:00
|
|
|
join: Option<JoinHandle<Result<(), E>>>,
|
2025-10-27 16:10:57 +01:00
|
|
|
role: &'static str,
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-27 18:13:50 +01:00
|
|
|
impl<E> ManagedAsyncReader<E>
|
|
|
|
|
where
|
|
|
|
|
E: std::error::Error,
|
|
|
|
|
{
|
2025-10-27 20:42:16 +01:00
|
|
|
pub fn new(role: &'static str, inner: DuplexStream, join: JoinHandle<Result<(), E>>) -> Self {
|
2025-10-27 16:10:57 +01:00
|
|
|
Self {
|
|
|
|
|
inner: Some(inner),
|
|
|
|
|
join: Some(join),
|
|
|
|
|
role,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Waits for the producer task to finish.
|
2025-10-27 18:13:50 +01:00
|
|
|
pub async fn wait(mut self) -> Result<(), E>
|
|
|
|
|
where
|
|
|
|
|
E: From<String>,
|
|
|
|
|
{
|
2025-10-27 16:10:57 +01:00
|
|
|
match self.join.take() {
|
|
|
|
|
Some(handle) => match handle.await {
|
|
|
|
|
Ok(res) => res,
|
2025-10-27 18:13:50 +01:00
|
|
|
Err(err) => {
|
|
|
|
|
let msg = format!("task '{}' failed: {}", self.role, err);
|
|
|
|
|
Err(E::from(msg))
|
|
|
|
|
}
|
2025-10-27 16:10:57 +01:00
|
|
|
},
|
|
|
|
|
None => Ok(()),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn poll_read_inner(
|
|
|
|
|
&mut self,
|
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
|
buf: &mut ReadBuf<'_>,
|
|
|
|
|
) -> Poll<io::Result<()>> {
|
|
|
|
|
let inner = self
|
|
|
|
|
.inner
|
|
|
|
|
.as_mut()
|
|
|
|
|
.ok_or_else(|| io::Error::new(io::ErrorKind::BrokenPipe, "reader dropped"))?;
|
|
|
|
|
Pin::new(inner).poll_read(cx, buf)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-27 18:13:50 +01:00
|
|
|
impl<E> AsyncRead for ManagedAsyncReader<E>
|
|
|
|
|
where
|
|
|
|
|
E: std::error::Error,
|
|
|
|
|
{
|
2025-10-27 16:10:57 +01:00
|
|
|
fn poll_read(
|
|
|
|
|
mut self: Pin<&mut Self>,
|
|
|
|
|
cx: &mut Context<'_>,
|
|
|
|
|
buf: &mut ReadBuf<'_>,
|
|
|
|
|
) -> Poll<io::Result<()>> {
|
|
|
|
|
self.poll_read_inner(cx, buf)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-27 18:13:50 +01:00
|
|
|
impl<E> Drop for ManagedAsyncReader<E>
|
|
|
|
|
where
|
|
|
|
|
E: std::error::Error,
|
|
|
|
|
{
|
2025-10-27 16:10:57 +01:00
|
|
|
fn drop(&mut self) {
|
|
|
|
|
if let Some(handle) = self.join.take() {
|
|
|
|
|
handle.abort();
|
|
|
|
|
}
|
|
|
|
|
self.inner.take();
|
|
|
|
|
}
|
|
|
|
|
}
|