feat: add timeout to select_buffer

This commit is contained in:
əlemi 2023-11-30 03:30:50 +01:00
parent 9d349e1b1e
commit 5401d837c7

View file

@ -1,4 +1,6 @@
use crate::{Error, api::Controller};
use std::sync::Arc;
use tokio::sync::mpsc;
/// invoke .poll() on all buffer controllers and wait, return name of first one ready
///
@ -8,19 +10,29 @@ use crate::{Error, api::Controller};
///
/// this is not super efficient as of now but has room for improvement. using this API may
/// provide significant improvements on editor-side
pub async fn select_buffer(buffers: &[std::sync::Arc<crate::buffer::Controller>]) -> crate::Result<String> {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
pub async fn select_buffer(
buffers: &[Arc<crate::buffer::Controller>],
timeout: Option<std::time::Duration>,
) -> crate::Result<Option<Arc<crate::buffer::Controller>>> {
let (tx, mut rx) = mpsc::unbounded_channel();
let mut tasks = Vec::new();
for buffer in buffers {
let _tx = tx.clone();
let _buffer = buffer.clone();
tasks.push(tokio::spawn(async move {
match _buffer.poll().await {
Ok(()) => _tx.send(Ok(_buffer.name.clone())),
Ok(()) => _tx.send(Ok(Some(_buffer))),
Err(_) => _tx.send(Err(Error::Channel { send: true })),
}
}))
}
if let Some(d) = timeout {
let _tx = tx.clone();
tasks.push(tokio::spawn(async move {
tokio::time::sleep(d).await;
_tx.send(Ok(None))
}));
}
loop {
match rx.recv().await {
None => return Err(Error::Channel { send: false }),