Решение на упр.06 задача 1 от Димитър Николов

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

Към профила на Димитър Николов

Резултати

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

Код

use std::collections::HashMap;
use std::error::Error;
use std::fs;
use std::io;
use std::io::BufRead;
use std::io::Read;
use std::path::Path;
use std::path::PathBuf;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum LogLevel {
Error,
Warn,
Info,
Debug,
}
impl TryFrom<&str> for LogLevel {
type Error = ParseLogError;
fn try_from(value: &str) -> Result<Self, <Self as TryFrom<&str>>::Error> {
match value {
"ERROR" => Ok(LogLevel::Error),
"WARN" => Ok(LogLevel::Warn),
"INFO" => Ok(LogLevel::Info),
"DEBUG" => Ok(LogLevel::Debug),
_ => Err(ParseLogError::ParseLine),
}
}
}
struct AggregateInfo {
log_counts: HashMap<LogLevel, usize>,
skipped_files: Vec<String>,
}
fn path_ends_with(filename: &PathBuf, suffix: &str) -> bool {
filename.extension().and_then(|s| s.to_str()) == Some(suffix)
}
fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, Box<dyn Error>> {
let entries = fs::read_dir(dir)?;
let mut log_counts: HashMap<LogLevel, usize> = HashMap::new();
let mut skipped_files: Vec<String> = Vec::new();
for entry in entries {
let Ok(entry) = entry else {
eprintln!("Failed reading dir entry: {:?}", entry);
continue;
};
let path = entry.path();
let filename = path.to_string_lossy().to_string();
if !path.is_file() {
eprintln!("Skipping over '{}' - not a file", filename);
skipped_files.push(filename);
continue;
}
if !path_ends_with(&path, "log") {
eprintln!("Skipping over non-log file: '{}'", filename);
skipped_files.push(filename);
continue;
}
let Ok(file) = fs::File::open(path) else {
eprintln!("Failed opening file '{}'", filename);
skipped_files.push(filename);
continue;
};
if let Err(err) = parse_log_file(file, &mut log_counts) {
eprintln!("Failed parsing file '{}': {:?}", filename, err);
skipped_files.push(filename);
}
}
Ok(AggregateInfo {
log_counts,
skipped_files,
})
}
#[derive(Debug)]
enum ParseLogError {
Read(io::Error),
ParseLine,
}
impl From<io::Error> for ParseLogError {
fn from(value: io::Error) -> Self {
ParseLogError::Read(value)
}
}
fn parse_log_file<R>(file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
where
R: Read,
{
let reader = std::io::BufReader::new(file);
for line in reader.lines() {
let line = line?;
let Some(first_word) = line.split_whitespace().next() else {
return Err(ParseLogError::ParseLine);
};
let log_level = LogLevel::try_from(first_word)?;
println!("log_level: {:?}", log_level);
*map.entry(log_level).or_insert(0) += 1;
}
Ok(())
}

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

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-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 futures-io v0.3.31
   Compiling memchr v2.7.6
   Compiling slab v0.4.11
   Compiling pin-utils v0.1.0
   Compiling solution v0.1.0 (/tmp/d20251120-1757769-2smljj/solution)
warning: struct `AggregateInfo` is never constructed
  --> src/lib.rs:32:8
   |
32 | struct AggregateInfo {
   |        ^^^^^^^^^^^^^
   |
   = note: `#[warn(dead_code)]` on by default

warning: function `path_ends_with` is never used
  --> src/lib.rs:37:4
   |
37 | fn path_ends_with(filename: &PathBuf, suffix: &str) -> bool {
   |    ^^^^^^^^^^^^^^

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

warning: field `0` is never read
  --> src/lib.rs:87:10
   |
87 |     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
   |
87 |     Read(()),
   |          ~~

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

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: field `0` is never read
  --> tests/../src/lib.rs:87:10
   |
87 |     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
   |
87 |     Read(()),
   |          ~~

warning: `solution` (test "solution_test") generated 1 warning
    Finished `test` profile [unoptimized + debuginfo] target(s) in 8.66s
     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 коментара)

Димитър качи първо решение на 17.11.2025 01:54 (преди 19 дена)