refactor: Update filter API to use Read/Write traits

Co-authored-by: aider (openai/andrew/openrouter/deepseek/deepseek-chat-v3.1) <aider@aider.chat>
This commit is contained in:
Andrew Phillips
2025-09-02 11:12:50 -03:00
parent fc413738b7
commit 099f3cde69
4 changed files with 63 additions and 114 deletions

View File

@@ -1,5 +1,5 @@
use crate::filter_plugin::{FilterChain, parse_filter_string};
use std::io::Result;
use std::io::{Result, Read, Write};
pub struct FilterService;
@@ -16,44 +16,33 @@ impl FilterService {
}
}
pub fn process_data(&self, chain: &mut Option<FilterChain>, data: &[u8]) -> Result<Vec<u8>> {
pub fn filter_data<R: Read, W: Write>(
&self,
chain: &mut Option<FilterChain>,
reader: &mut R,
writer: &mut W
) -> Result<()> {
if let Some(chain) = chain {
chain.process(data)
chain.filter(reader, writer)
} else {
Ok(data.to_vec())
// If no filter chain, just copy the input to output
std::io::copy(reader, writer)?;
Ok(())
}
}
pub fn finish_processing(&self, chain: &mut Option<FilterChain>) -> Result<Vec<u8>> {
if let Some(chain) = chain {
chain.finish()
} else {
Ok(Vec::new())
}
}
// Add a method to process data through the filter chain and handle finish automatically
pub fn process_all_data(&self, chain: &mut Option<FilterChain>, data: &[u8]) -> Result<Vec<u8>> {
let mut processed = if let Some(chain) = chain {
chain.process(data)?
} else {
data.to_vec()
};
// If we have a chain, also get any remaining data from finish()
if chain.is_some() {
let finished = self.finish_processing(chain)?;
if !finished.is_empty() {
processed.extend(finished);
}
}
Ok(processed)
}
// Helper method to create and process data with a filter string in one call
// Helper method to process data with a filter string in one call
pub fn process_with_filter(&self, data: &[u8], filter_str: Option<&str>) -> Result<Vec<u8>> {
let mut chain = self.create_filter_chain(filter_str)?;
self.process_all_data(&mut chain, data)
let mut reader = std::io::Cursor::new(data);
let mut writer = Vec::new();
if let Some(ref mut chain) = chain {
chain.filter(&mut reader, &mut writer)?;
} else {
std::io::copy(&mut reader, &mut writer)?;
}
Ok(writer)
}
}