43 lines
1.5 KiB
Rust
43 lines
1.5 KiB
Rust
use std::{io::Read, path::PathBuf};
|
|
use std::fs::File;
|
|
use std::io::{BufRead, BufReader, Cursor};
|
|
use std::ptr::read;
|
|
|
|
pub fn handle(path: PathBuf, filter_str:String, start_index: u32, end_index: u32) -> Box<dyn Read>{
|
|
let reader = BufReader::new(File::open(path).unwrap());
|
|
let mut lines = reader.lines().collect::<Result<Vec<_>, _>>().unwrap();
|
|
lines = filter_by_string(lines, filter_str.as_str());
|
|
lines = take(&mut lines, start_index, end_index);
|
|
|
|
Box::new(Cursor::new(lines.join("\n").into_bytes())) as Box<dyn Read>
|
|
}
|
|
|
|
fn filter_by_string(reader: Vec<String>, filter_str: &str) ->Vec<String>{
|
|
if filter_str == "" {
|
|
return reader
|
|
}
|
|
let mut result: Vec<String> = Vec::new();
|
|
result.push(reader[0].clone());
|
|
result.extend(reader.into_iter().skip(1).filter(|line| line.contains(filter_str)));
|
|
result
|
|
}
|
|
|
|
fn take(reader: &mut Vec<String>, start_index: u32, end_index: u32) -> Vec<String> {
|
|
if end_index < 0 && start_index < 0{
|
|
panic!("start_index and end_index must be positive");
|
|
}
|
|
if end_index == 0 && start_index == 0{
|
|
return reader.to_owned();
|
|
}
|
|
let header = reader[0].clone();
|
|
let mut body= Vec::new();
|
|
body.push(header);
|
|
if end_index == 0{
|
|
body.append(&mut reader[start_index as usize..].to_owned());
|
|
}else if(end_index < reader.len() as u32){
|
|
body.append(&mut reader[start_index as usize..end_index as usize].to_owned());
|
|
}else {
|
|
body.append(&mut reader[start_index as usize..].to_owned());
|
|
}
|
|
body
|
|
} |