Skip to main content

rustic_core/backend/
stdin.rs

1use std::{
2    io::{Stdin, stdin},
3    iter::{Once, once},
4    path::PathBuf,
5};
6
7use crate::{
8    backend::{ReadSource, ReadSourceEntry},
9    error::{ErrorKind, RusticError, RusticResult},
10};
11
12/// The `StdinSource` is a `ReadSource` for stdin.
13#[derive(Debug, Clone)]
14pub struct StdinSource {
15    /// The path of the stdin entry.
16    path: PathBuf,
17}
18
19impl StdinSource {
20    /// Creates a new `StdinSource`.
21    #[must_use]
22    pub const fn new(path: PathBuf) -> Self {
23        Self { path }
24    }
25}
26
27impl ReadSource for StdinSource {
28    /// The open type.
29    type Open = Stdin;
30    /// The iterator type.
31    type Iter = Once<RusticResult<ReadSourceEntry<Stdin>>>;
32
33    /// Returns the size of the source.
34    fn size(&self) -> RusticResult<Option<u64>> {
35        Ok(None)
36    }
37
38    /// Returns an iterator over the source.
39    fn entries(&self) -> Self::Iter {
40        let open = Some(stdin());
41        once(
42            ReadSourceEntry::from_path(self.path.clone(), open).map_err(|err| {
43                RusticError::with_source(
44                    ErrorKind::Backend,
45                    "Failed to create ReadSourceEntry from Stdin",
46                    err,
47                )
48            }),
49        )
50    }
51}