rustbook/examples/ex03/src/file_ops.rs

197 lines
5.3 KiB
Rust

use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::Path;
use crate::error::FileError;
use crate::traits::{ContentAnalyzer, ContentTransformer, FileProcessor, LineFilter};
/// 安全的文件读取器
pub struct SafeFileReader {
path: String,
}
impl SafeFileReader {
/// 创建新的文件读取器
///
/// # 参数
/// * `path` - 文件路径
pub fn new(path: String) -> Self {
SafeFileReader { path }
}
/// 读取文件内容
///
/// # 返回
/// * `Result<String, FileError>` - 文件内容或错误
pub fn read(&self) -> Result<String, FileError> {
let path = Path::new(&self.path);
if !path.exists() {
return Err(FileError::NotFound(self.path.clone()));
}
fs::read_to_string(path)
.map_err(|e| match e.kind() {
io::ErrorKind::PermissionDenied => FileError::PermissionDenied(self.path.clone()),
_ => FileError::ReadError(e.to_string()),
})
}
/// 读取并处理文件内容
///
/// # 参数
/// * `processor` - 实现了FileProcessor trait的处理器
///
/// # 返回
/// * `Result<String, FileError>` - 处理后的内容或错误
pub fn read_and_process<P>(&self, processor: &P) -> Result<String, FileError>
where
P: FileProcessor,
{
let content = self.read()?;
processor.process(&content)
.map_err(|e| FileError::ProcessError(format!("{:?}", e)))
}
/// 读取并分析文件内容
///
/// # 参数
/// * `analyzer` - 实现了ContentAnalyzer trait的分析器
///
/// # 返回
/// * `Result<T, FileError>` - 分析结果或错误
pub fn read_and_analyze<A, T>(&self, analyzer: &A) -> Result<T, FileError>
where
A: ContentAnalyzer<T>,
{
let content = self.read()?;
analyzer.analyze(&content)
.map_err(|e| FileError::ProcessError(format!("{:?}", e)))
}
/// 读取并过滤文件内容
///
/// # 参数
/// * `filter` - 实现了LineFilter trait的过滤器
///
/// # 返回
/// * `Result<String, FileError>` - 过滤后的内容或错误
pub fn read_and_filter<F>(&self, filter: &F) -> Result<String, FileError>
where
F: LineFilter,
{
let content = self.read()?;
let filtered = content
.lines()
.filter(|line| filter.should_keep(line))
.collect::<Vec<&str>>()
.join("\n");
Ok(filtered)
}
}
/// 安全的文件写入器
pub struct SafeFileWriter {
path: String,
}
impl SafeFileWriter {
/// 创建新的文件写入器
///
/// # 参数
/// * `path` - 文件路径
pub fn new(path: String) -> Self {
SafeFileWriter { path }
}
/// 写入内容到文件
///
/// # 参数
/// * `content` - 要写入的内容
///
/// # 返回
/// * `Result<(), FileError>` - 成功或错误
pub fn write(&self, content: &str) -> Result<(), FileError> {
let mut file = File::create(&self.path)
.map_err(|e| match e.kind() {
io::ErrorKind::PermissionDenied => FileError::PermissionDenied(self.path.clone()),
_ => FileError::WriteError(e.to_string()),
})?;
file.write_all(content.as_bytes())
.map_err(|e| FileError::WriteError(e.to_string()))?;
Ok(())
}
/// 转换并写入内容到文件
///
/// # 参数
/// * `content` - 原始内容
/// * `transformer` - 实现了ContentTransformer trait的转换器
///
/// # 返回
/// * `Result<(), FileError>` - 成功或错误
pub fn transform_and_write<T>(&self, content: &str, transformer: &T) -> Result<(), FileError>
where
T: ContentTransformer,
{
let transformed = transformer.transform(content)
.map_err(|e| FileError::ProcessError(format!("{:?}", e)))?;
self.write(&transformed)
}
}
/// 文件处理管道
///
/// 允许链式调用多个处理器
pub struct ProcessingPipeline<'a> {
processors: Vec<&'a dyn FileProcessor<Error = String>>,
}
impl<'a> ProcessingPipeline<'a> {
/// 创建新的处理管道
pub fn new() -> Self {
ProcessingPipeline {
processors: Vec::new(),
}
}
/// 添加处理器到管道
///
/// # 参数
/// * `processor` - 实现了FileProcessor trait的处理器
pub fn add_processor(&mut self, processor: &'a dyn FileProcessor<Error = String>) -> &mut Self {
self.processors.push(processor);
self
}
/// 执行处理管道
///
/// # 参数
/// * `content` - 要处理的内容
///
/// # 返回
/// * `Result<String, FileError>` - 处理后的内容或错误
pub fn process(&self, content: &str) -> Result<String, FileError> {
let mut result = content.to_string();
for processor in &self.processors {
result = processor.process(&result)
.map_err(|e| FileError::ProcessError(e))?;
}
Ok(result)
}
}
impl<'a> Default for ProcessingPipeline<'a> {
fn default() -> Self {
Self::new()
}
}