Решение на упр.06 задача 1 от Ивайло Иванов

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

Към профила на Ивайло Иванов

Резултати

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

Код

use std::collections::HashMap;
use std::error::Error;
use std::fs::{self, File};
use std::io::{self, BufRead, BufReader, Read};
use std::path::Path;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum LogLevel {
Error,
Warn,
Info,
Debug,
}
impl LogLevel {
fn parse(s: &str) -> Result<LogLevel, ParseLogError> {
match s {
"ERROR" => Ok(LogLevel::Error),
"WARN" => Ok(LogLevel::Warn),
"INFO" => Ok(LogLevel::Info),
"DEBUG" => Ok(LogLevel::Debug),
_ => Err(ParseLogError::ParseLine),
}
}
}
#[derive(Debug)]
enum ParseLogError {
Read(io::Error),
ParseLine,
UnknownLevel(String),
}
impl From<io::Error> for ParseLogError {
fn from(e: io::Error) -> Self {
ParseLogError::Read(e)
}
}
struct AggregateInfo {
log_counts: HashMap<LogLevel, usize>,
skipped_files: Vec<String>,
}
fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, Box<dyn Error>> {
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();
let file_name = path.to_string_lossy().to_string();
if let Some("log") = path.extension().and_then(|s| s.to_str()) {
// файлът е log
} else {
skipped_files.push(file_name);
continue;
}
let file = match File::open(&path) {
Ok(f) => f,
Err(_) => {
skipped_files.push(file_name);
continue;
}
};
if let Err(_) = parse_log_file(file, &mut log_counts) {
skipped_files.push(file_name);
}
}
Ok(AggregateInfo {
log_counts,
skipped_files,
})
}
fn parse_log_file<R>(file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
where
R: Read,
{
let reader = BufReader::new(file);
for line in reader.lines() {
let line = line?;
if line.trim().is_empty() {
continue; //празните редове броят ли се за невалидни??
}
let mut parts = line.split_whitespace();
let level_str = parts
.next()
.ok_or_else(|| ParseLogError::ParseLine)?;
let level = LogLevel::parse(level_str)?;
*map.entry(level).or_insert(0) += 1;
}
Ok(())
}

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

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 memchr v2.7.6
   Compiling syn v2.0.110
   Compiling futures-task v0.3.31
   Compiling pin-utils v0.1.0
   Compiling pin-project-lite v0.2.16
   Compiling slab v0.4.11
   Compiling futures-io v0.3.31
   Compiling solution v0.1.0 (/tmp/d20251120-1757769-ggeb09/solution)
warning: enum `LogLevel` is never used
 --> src/lib.rs:8:6
  |
8 | enum LogLevel {
  |      ^^^^^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: associated function `parse` is never used
  --> src/lib.rs:16:8
   |
15 | impl LogLevel {
   | ------------- associated function in this implementation
16 |     fn parse(s: &str) -> Result<LogLevel, ParseLogError> {
   |        ^^^^^

warning: field `0` is never read
  --> src/lib.rs:29:10
   |
29 |     Read(io::Error),
   |     ---- ^^^^^^^^^
   |     |
   |     field in this variant
   |
   = note: `ParseLogError` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
help: consider changing the field to be of unit type to suppress this warning while preserving the field numbering, or remove the field
   |
29 |     Read(()),
   |          ~~

warning: variants `ParseLine` and `UnknownLevel` are never constructed
  --> src/lib.rs:30:5
   |
28 | enum ParseLogError {
   |      ------------- variants in this enum
29 |     Read(io::Error),
30 |     ParseLine,
   |     ^^^^^^^^^
31 |     UnknownLevel(String),
   |     ^^^^^^^^^^^^
   |
   = note: `ParseLogError` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis

warning: struct `AggregateInfo` is never constructed
  --> src/lib.rs:40:8
   |
40 | struct AggregateInfo {
   |        ^^^^^^^^^^^^^

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

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

warning: `solution` (lib) generated 7 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: field `0` is never read
  --> tests/../src/lib.rs:29:10
   |
29 |     Read(io::Error),
   |     ---- ^^^^^^^^^
   |     |
   |     field in this variant
   |
   = note: `ParseLogError` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
   = note: `#[warn(dead_code)]` on by default
help: consider changing the field to be of unit type to suppress this warning while preserving the field numbering, or remove the field
   |
29 |     Read(()),
   |          ~~

warning: variant `UnknownLevel` is never constructed
  --> tests/../src/lib.rs:31:5
   |
28 | enum ParseLogError {
   |      ------------- variant in this enum
...
31 |     UnknownLevel(String),
   |     ^^^^^^^^^^^^
   |
   = note: `ParseLogError` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis

warning: `solution` (test "solution_test") generated 2 warnings
    Finished `test` profile [unoptimized + debuginfo] target(s) in 8.62s
     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_big_data ... ok
test solution_test::test_parse_log_invalid ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

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

Ивайло качи първо решение на 19.11.2025 17:09 (преди 17 дена)