kxio 3.0.0

Provides injectable Filesystem and Network resources to make code more testable
Documentation
//
use std::{fmt::Display, path::Path, str::Lines};

use crate::fs::Result;

use super::Error;

/// A reader for a file.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Reader {
    contents: String,
}
impl Reader {
    pub(super) fn new(path: &Path) -> Result<Self> {
        let contents = std::fs::read_to_string(path).map_err(Error::Io)?;
        Ok(Self { contents })
    }

    /// Returns the contents of the file as a string.
    ///
    /// ```
    /// # use kxio::fs::Result;
    /// # fn main() -> Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let path = fs.base().join("foo");
    /// let file = fs.file(&path);
    /// # file.write("new file contents")?;
    /// let contents = file.reader()?.as_str();
    /// #    Ok(())
    /// # }
    /// ```
    pub fn as_str(&self) -> &str {
        &self.contents
    }

    /// Returns an iterator over the lines in the file.
    ///
    /// ```
    /// # use kxio::fs::Result;
    /// # fn main() -> Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let path = fs.base().join("foo");
    /// let file = fs.file(&path);
    /// # file.write("new file contents")?;
    /// let lines = file.reader()?.lines();
    /// #    Ok(())
    /// # }
    /// ```
    pub fn lines(&self) -> Lines<'_> {
        self.contents.lines()
    }

    /// Returns the contents of the file as bytes.
    ///
    /// ```
    /// # use kxio::fs::Result;
    /// # fn main() -> Result<()> {
    /// let fs = kxio::fs::temp()?;
    /// let path = fs.base().join("foo");
    /// let file = fs.file(&path);
    /// # file.write("new file contents")?;
    /// let bytes = file.reader()?.bytes();
    /// #    Ok(())
    /// # }
    /// ```
    pub fn bytes(&self) -> &[u8] {
        self.contents.as_bytes()
    }
}
impl Display for Reader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.contents)
    }
}