Skip to main content

tower_embed_core/
file.rs

1//! File handling utilities.
2
3use std::{
4    pin::Pin,
5    task::{Context, Poll, ready},
6};
7
8use bytes::Bytes;
9use futures_core::Stream;
10use tokio_util::io::ReaderStream;
11
12use crate::BoxError;
13
14/// An opened file handle.
15pub struct File(ReaderStream<tokio::fs::File>);
16
17impl File {
18    /// Tries to open a file in read-only mode.
19    pub async fn open(path: &std::path::Path) -> std::io::Result<Self> {
20        let file = tokio::fs::File::open(path).await?;
21        Ok(Self(ReaderStream::new(file)))
22    }
23}
24
25impl Stream for File {
26    type Item = Result<Bytes, BoxError>;
27
28    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
29        let inner = Pin::new(&mut self.0);
30        match ready!(inner.poll_next(cx)) {
31            Some(Ok(bytes)) => Some(Ok(bytes)),
32            Some(Err(err)) => Some(Err(err.into())),
33            None => None,
34        }
35        .into()
36    }
37}