use std::path::Path;
use std::time::Duration;
use std::{future::Future, io};
use crate::error::{Error, Result};
pub async fn read_file(path: impl AsRef<Path>) -> Result<Vec<u8>> {
use tokio::fs;
let path = path.as_ref().to_path_buf();
fs::read(&path).await.map_err(|e| crate::error::Error::Io {
path: Some(path),
error: e,
})
}
pub async fn read_to_string(path: impl AsRef<Path>) -> Result<String> {
use tokio::fs;
let path = path.as_ref().to_path_buf();
fs::read_to_string(&path)
.await
.map_err(|e| crate::error::Error::Io {
path: Some(path),
error: e,
})
}
pub fn watch<T, F, Fut>(
period: Duration,
mut snapshot: F,
) -> impl futures_core::Stream<Item = Result<T>>
where
F: FnMut() -> Fut,
Fut: Future<Output = Result<T>>,
{
async_stream::stream! {
if period.is_zero() {
yield Err(Error::Io {
path: None,
error: io::Error::new(
io::ErrorKind::InvalidInput,
"polling period must be non-zero",
),
});
return;
}
let mut ticker = tokio::time::interval(period);
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
ticker.tick().await;
match snapshot().await {
Ok(value) => yield Ok(value),
Err(error) => {
yield Err(error);
return;
}
}
}
}
}