From f2315636da4fde73ccb0d37e7f7fd9f84cbc8b62 Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Sun, 3 Nov 2024 11:36:20 +0000 Subject: [PATCH] feat(fs): add .reader().bytes() --- README.md | 2 +- src/fs/reader.rs | 17 +++++++++++++++++ tests/fs.rs | 21 +++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8a6bfb8..6101895 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Provides injectable Filesystem and Network resources to make code more testable. - [x] `std::fs::create_dir_all` - `dir(path).create_all()` - Recursively create a directory and all of its parent components if they are missing. - [ ] `std::fs::hard_link` - `link(path)create()` - Creates a new hard link on the filesystem. - [ ] `std::fs::metadata` - `path(path).metadata()` - Given a path, query the file system to get information about a file, directory, etc. -- [ ] `std::fs::read` - `file(path).reader().bytes()` - Read the entire contents of a file into a bytes vector. +- [x] `std::fs::read` - `file(path).reader().bytes()` - Read the entire contents of a file into a bytes vector. - [x] `std::fs::read_dir` - `dir(path).read()` - Returns an iterator over the entries within a directory. - [ ] `std::fs::read_link` - `link(path).read()` - Reads a symbolic link, returning the file that the link points to. - [x] `std::fs::read_to_string` - `file(path).reader().to_string()` - Read the entire contents of a file into a string. diff --git a/src/fs/reader.rs b/src/fs/reader.rs index 1b64784..ae45ee5 100644 --- a/src/fs/reader.rs +++ b/src/fs/reader.rs @@ -65,6 +65,23 @@ impl Reader { 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 { diff --git a/tests/fs.rs b/tests/fs.rs index e830f50..9c2198f 100644 --- a/tests/fs.rs +++ b/tests/fs.rs @@ -403,3 +403,24 @@ mod copy { Ok(()) } } +mod reader { + use super::*; + mod bytes { + use super::*; + #[test] + fn should_return_bytes() -> TestResult { + let fs = fs::temp().expect("temp fs"); + let path = fs.base().join("foo"); + let file = fs.file(&path); + file.write("bar").expect("write"); + let reader = file.reader().expect("reader"); + let bytes = reader.bytes(); + assert_eq!(bytes.len(), 3); + assert_eq!(bytes[0], b'b'); + assert_eq!(bytes[1], b'a'); + assert_eq!(bytes[2], b'r'); + + Ok(()) + } + } +}