From 5401d837c79e8ab94605badde68012830af4d359 Mon Sep 17 00:00:00 2001 From: alemi Date: Thu, 30 Nov 2023 03:30:50 +0100 Subject: [PATCH] feat: add timeout to select_buffer --- src/tools.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/tools.rs b/src/tools.rs index 0ee4005..ce21075 100644 --- a/src/tools.rs +++ b/src/tools.rs @@ -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::Result { - let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); +pub async fn select_buffer( + buffers: &[Arc], + timeout: Option, +) -> crate::Result>> { + 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 }),