use crate::php::streams::{FileStream, StreamError, StreamMode, StreamResult};
pub struct StreamBuilder {
path: Option<String>,
mode: StreamMode,
buffered: bool,
}
impl StreamBuilder {
pub fn new() -> Self {
Self {
path: None,
mode: StreamMode::Read,
buffered: false,
}
}
pub fn path(mut self, path: &str) -> Self {
self.path = Some(path.to_string());
self
}
pub fn mode(mut self, mode: StreamMode) -> Self {
self.mode = mode;
self
}
pub fn buffered(mut self, buffered: bool) -> Self {
self.buffered = buffered;
self
}
pub fn build(self) -> StreamResult<FileStream> {
let path = self.path.ok_or_else(|| StreamError::InvalidOperation)?;
FileStream::open(&path, self.mode)
}
pub fn read(path: &str) -> StreamResult<FileStream> {
Self::new().path(path).mode(StreamMode::Read).build()
}
pub fn write(path: &str) -> StreamResult<FileStream> {
Self::new().path(path).mode(StreamMode::Write).build()
}
pub fn append(path: &str) -> StreamResult<FileStream> {
Self::new().path(path).mode(StreamMode::Append).build()
}
pub fn read_write(path: &str) -> StreamResult<FileStream> {
Self::new().path(path).mode(StreamMode::ReadWrite).build()
}
}
impl Default for StreamBuilder {
fn default() -> Self {
Self::new()
}
}
pub fn read_file_contents(path: &str) -> StreamResult<String> {
let mut stream = StreamBuilder::read(path)?;
let mut contents = String::new();
use std::io::Read;
stream.read_to_string(&mut contents)
.map_err(|e| StreamError::IoError(e.to_string()))?;
Ok(contents)
}
pub fn write_file_contents(path: &str, contents: &str) -> StreamResult<()> {
let mut stream = StreamBuilder::write(path)?;
use std::io::Write;
stream.write_all(contents.as_bytes())
.map_err(|e| StreamError::IoError(e.to_string()))?;
stream.flush()
.map_err(|e| StreamError::IoError(e.to_string()))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn test_stream_builder_read() {
let test_path = "/tmp/test_stream_read.txt";
let test_content = "Hello, World!";
fs::write(test_path, test_content).unwrap();
let result = StreamBuilder::read(test_path);
assert!(result.is_ok());
let _ = fs::remove_file(test_path);
}
#[test]
fn test_stream_builder_write() {
let test_path = "/tmp/test_stream_write.txt";
let result = StreamBuilder::write(test_path);
assert!(result.is_ok());
let _ = fs::remove_file(test_path);
}
#[test]
fn test_read_write_helpers() {
let test_path = "/tmp/test_stream_helpers.txt";
let test_content = "Test content for helpers";
let write_result = write_file_contents(test_path, test_content);
assert!(write_result.is_ok());
let read_result = read_file_contents(test_path);
assert!(read_result.is_ok());
assert_eq!(read_result.unwrap(), test_content);
let _ = fs::remove_file(test_path);
}
}