use std::future::Future;
use futures::StreamExt;
use crate::error::{NganoError, Result};
use crate::loader::{Loader, RowStream};
use crate::row::Row;
pub(crate) fn block_on<T, F>(fut: F) -> Result<T>
where
F: Future<Output = Result<T>>,
{
let runtime = new_runtime()?;
runtime.block_on(fut)
}
fn new_runtime() -> Result<tokio::runtime::Runtime> {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| NganoError::Runtime(e.to_string()))
}
#[derive(Debug)]
pub struct BlockingLoader {
runtime: tokio::runtime::Runtime,
loader: Loader,
}
impl BlockingLoader {
pub fn new(loader: Loader) -> Result<Self> {
Ok(Self {
runtime: new_runtime()?,
loader,
})
}
pub fn rows(self) -> Result<BlockingRows> {
let stream = self.runtime.block_on(self.loader.stream())?;
Ok(BlockingRows {
runtime: self.runtime,
stream,
})
}
}
#[derive(Debug)]
pub struct BlockingRows {
runtime: tokio::runtime::Runtime,
stream: RowStream,
}
impl BlockingRows {
pub fn emitted(&self) -> usize {
self.stream.emitted()
}
}
impl Iterator for BlockingRows {
type Item = Result<Row>;
fn next(&mut self) -> Option<Self::Item> {
let stream = &mut self.stream;
self.runtime.block_on(stream.next())
}
}