Решение на упр.06 задача 1 от Борис Великов

Обратно към всички решения

Към профила на Борис Великов

Резултати

  • 0 точки от тестове
  • 1 бонус точка
  • 1 точка общо
  • 0 успешни тест(а)
  • 0 неуспешни тест(а)

Код

use std::collections::HashMap;
use std::env;
use std::error::Error;
use std::fmt;
use std::fs::{self, File};
use std::io;
use std::io::{BufRead, BufReader, Read};
use std::path::Path;
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>,
}
#[derive(Debug)]
enum MyErr {
Read(io::Error),
ParseLine,
}
impl fmt::Display for MyErr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MyErr::Read(e) => write!(f, "{}", e),
MyErr::ParseLine => write!(f, "Parse line error"),
}
}
}
impl Error for MyErr {}
impl From<io::Error> for MyErr {
fn from(error: io::Error) -> Self {
MyErr::Read(error)
}
}
fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, MyErr> {
let mut log_counts = HashMap::new();
let mut skipped_files = Vec::new();
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.extension().map_or(false, |ext| ext == "log") {
let file = match File::open(&path) {
Ok(file) => file,
Err(e) => {
return Err(MyErr::Read(e));
}
};
let metadata = file.metadata()?;
if metadata.len() > 10 * 1024 {
let reader = BufReader::new(file);
if let Err(e) = parse_log_file(reader, &mut log_counts) {
eprintln!("{}", e);
continue;
}
} else {
if let Err(e) = parse_log_file(file, &mut log_counts) {
eprintln!("{}", e);
continue;
}
}
} else {
skipped_files.push(format!("{}", path.display()));
}
}
Ok(AggregateInfo {
log_counts,
skipped_files,
})
}
fn parse_log_file<R>(file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), MyErr>
where
R: Read,
{
let reader = BufReader::new(file);
for line in reader.lines() {
let line = line.map_err(MyErr::Read)?;
let level = if line.starts_with("ERROR") {
LogLevel::Error
} else if line.starts_with("WARN") {
LogLevel::Warn
} else if line.starts_with("INFO") {
LogLevel::Info
} else if line.starts_with("DEBUG") {
LogLevel::Debug
} else {
return Err(MyErr::ParseLine);
};
*map.entry(level).or_insert(0) += 1;
}
Ok(())
}
fn main() {
let args: Vec<String> = env::args().collect();
let dir_path = &args[1];
let dir = Path::new(dir_path);
// aggregate_logs
let result = match aggregate_logs(dir) {
Ok(info) => info,
Err(e) => {
eprintln!("{}: {}", dir_path, e);
process::exit(1);
}
};
// skipped_files
if !result.skipped_files.is_empty() {
for file in &result.skipped_files {
println!("{}", file);
}
println!();
}
// print
let c1 = match result.log_counts.get(&LogLevel::Debug) {
Some(num) => num,
None => &0,
};
println!("Debug: {}", c1);
let c2 = match result.log_counts.get(&LogLevel::Info) {
Some(num) => num,
None => &0,
};
println!("Info: {}", c2);
let c3 = match result.log_counts.get(&LogLevel::Warn) {
Some(num) => num,
None => &0,
};
println!("Warn: {}", c3);
let c4 = match result.log_counts.get(&LogLevel::Error) {
Some(num) => num,
None => &0,
};
println!("Error: {}", c4);
}

Лог от изпълнението

Updating crates.io index
     Locking 17 packages to latest compatible versions
   Compiling proc-macro2 v1.0.103
   Compiling unicode-ident v1.0.22
   Compiling quote v1.0.42
   Compiling futures-core v0.3.31
   Compiling futures-sink v0.3.31
   Compiling futures-channel v0.3.31
   Compiling slab v0.4.11
   Compiling syn v2.0.110
   Compiling pin-project-lite v0.2.16
   Compiling pin-utils v0.1.0
   Compiling memchr v2.7.6
   Compiling futures-io v0.3.31
   Compiling futures-task v0.3.31
   Compiling solution v0.1.0 (/tmp/d20251120-1757769-10c16tj/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: variant `ParseLine` is never constructed
  --> src/lib.rs:27:5
   |
25 | enum MyErr {
   |      ----- variant in this enum
26 |     Read(io::Error),
27 |     ParseLine,
   |     ^^^^^^^^^
   |
   = note: `MyErr` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis

warning: function `aggregate_logs` is never used
  --> src/lib.rs:47:4
   |
47 | fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, MyErr> {
   |    ^^^^^^^^^^^^^^

warning: function `parse_log_file` is never used
  --> src/lib.rs:88:4
   |
88 | fn parse_log_file<R>(file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), MyErr>
   |    ^^^^^^^^^^^^^^

warning: function `main` is never used
   --> src/lib.rs:116:4
    |
116 | fn main() {
    |    ^^^^

warning: `solution` (lib) generated 6 warnings
   Compiling futures-macro v0.3.31
   Compiling futures-util v0.3.31
   Compiling futures-executor v0.3.31
   Compiling futures v0.3.31
error[E0433]: failed to resolve: use of undeclared type `ParseLogError`
  --> tests/solution_test.rs:62:62
   |
62 |         assert!(matches!(parse_log_file(data, &mut map), Err(ParseLogError::ParseLine)));
   |                                                              ^^^^^^^^^^^^^ use of undeclared type `ParseLogError`

For more information about this error, try `rustc --explain E0433`.
error: could not compile `solution` (test "solution_test") due to 1 previous error

История (1 версия и 0 коментара)

Борис качи първо решение на 18.11.2025 17:30 (преди 18 дена)