Решение на упр.06 задача 1 от Пламен Колев
Резултати
- 4 точки от тестове
- 1 бонус точка
- 5 точки общо
- 4 успешни тест(а)
- 0 неуспешни тест(а)
Код
use std::collections::HashMap;
use std::error::Error;
use std::io;
use std::io::Read;
use std::path::Path;
use std::io::BufRead;
use std::io::BufReader;
use std::env;
use std::process;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum LogLevel {
Error,
Warn,
Info,
Debug,
}
struct AggregateInfo {
log_counts: HashMap<LogLevel, usize>,
skipped_files: Vec<String>,
}
fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, Box<dyn Error>> {
let mut counts = HashMap::new();
let mut skipped = Vec::new();
for entry in std::fs::read_dir(dir)? {
let path = entry?.path();
let path_str = path.to_string_lossy().to_string();
if !path_str.ends_with(".log") {
skipped.push(path_str);
continue;
}
if let Ok(file) = std::fs::File::open(&path) {
if let Err(_) = parse_log_file(file, &mut counts) {
skipped.push(path_str);
}
} else {
skipped.push(path_str);
}
}
Ok(AggregateInfo {
log_counts: counts,
skipped_files: skipped,
})
}
#[derive(Debug)]
#[allow(dead_code)]
enum ParseLogError {
Read(io::Error),
ParseLine,
}
fn parse_log_file<R>(file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
where
R: Read,
{
let buf_reder = BufReader::new(file);
for line in buf_reder.lines() {
let l = line.map_err(ParseLogError::Read)?;
let first = l.split_whitespace().next().ok_or(ParseLogError::ParseLine)?;
let error_type = match first {
"ERROR" => LogLevel::Error,
"WARN" => LogLevel::Warn,
"INFO" => LogLevel::Info,
"DEBUG" => LogLevel::Debug,
_ => return Err(ParseLogError::ParseLine),
};
*map.entry(error_type).or_insert(0) += 1;
}
Ok(())
}
fn main() {
let args: Vec<String> = env::args().collect();
let dir = Path::new(&args[1]);
match aggregate_logs(dir) {
Ok(info) => {
println!("Debug: {}", info.log_counts.get(&LogLevel::Debug).unwrap_or(&0));
println!("Info: {}", info.log_counts.get(&LogLevel::Info).unwrap_or(&0));
println!("Warn: {}", info.log_counts.get(&LogLevel::Warn).unwrap_or(&0));
println!("Error: {}", info.log_counts.get(&LogLevel::Error).unwrap_or(&0));
if !info.skipped_files.is_empty() {
println!("Skipped files:");
for f in info.skipped_files {
println!(" {}", f);
}
}
}
Err(e) => {
println!("Error: {}", e);
process::exit(1);
}
}
}
Лог от изпълнението
Updating crates.io index
Locking 17 packages to latest compatible versions
Compiling proc-macro2 v1.0.103
Compiling quote v1.0.42
Compiling unicode-ident v1.0.22
Compiling futures-sink v0.3.31
Compiling futures-core v0.3.31
Compiling futures-channel v0.3.31
Compiling pin-project-lite v0.2.16
Compiling futures-task v0.3.31
Compiling syn v2.0.110
Compiling pin-utils v0.1.0
Compiling slab v0.4.11
Compiling futures-io v0.3.31
Compiling memchr v2.7.6
Compiling solution v0.1.0 (/tmp/d20251120-1757769-11gdpu2/solution)
warning: enum `LogLevel` is never used
--> src/lib.rs:12:6
|
12 | enum LogLevel {
| ^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: struct `AggregateInfo` is never constructed
--> src/lib.rs:19:8
|
19 | struct AggregateInfo {
| ^^^^^^^^^^^^^
warning: function `aggregate_logs` is never used
--> src/lib.rs:24:4
|
24 | fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, Box<dyn Error>> {
| ^^^^^^^^^^^^^^
warning: function `parse_log_file` is never used
--> src/lib.rs:59:4
|
59 | fn parse_log_file<R>(file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
| ^^^^^^^^^^^^^^
warning: function `main` is never used
--> src/lib.rs:83:4
|
83 | fn main() {
| ^^^^
warning: `solution` (lib) generated 5 warnings
Compiling futures-macro v0.3.31
Compiling futures-util v0.3.31
Compiling futures-executor v0.3.31
Compiling futures v0.3.31
warning: function `main` is never used
--> tests/../src/lib.rs:83:4
|
83 | fn main() {
| ^^^^
|
= note: `#[warn(dead_code)]` on by default
warning: `solution` (test "solution_test") generated 1 warning
Finished `test` profile [unoptimized + debuginfo] target(s) in 8.55s
Running tests/solution_test.rs (target/debug/deps/solution_test-f75e629a1d90e17c)
running 4 tests
test solution_test::test_parse_log_basic ... ok
test solution_test::test_aggregate ... ok
test solution_test::test_parse_log_invalid ... ok
test solution_test::test_parse_log_big_data ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
