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

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

Към профила на Георги Илиев

Резултати

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

Код

use std::collections::HashMap;
use std::error::Error;
use std::fmt::{self, Display};
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 from_str(s: &str) -> Result<Self, 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,
}
impl Display for ParseLogError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseLogError::Read(e) =>
write!(f, "I/O read error: {}", e),
ParseLogError::ParseLine =>
write!(f, "Invalid log line")
}
}
}
impl Error for ParseLogError {}
impl From<io::Error> for ParseLogError {
fn from(e: io::Error) -> Self {
ParseLogError::Read(e)
}
}
fn parse_log_file<R>(reader: R, map: &mut HashMap<LogLevel, usize>)
-> Result<(), ParseLogError>
where
R: Read,
{
let buf = BufReader::new(reader);
for line in buf.lines() {
let line = line.map_err(ParseLogError::Read)?;
let level_word = line.split_whitespace().next().ok_or(ParseLogError::ParseLine)?;
let lvl = LogLevel::from_str(level_word)?;
*map.entry(lvl).or_insert(0) += 1;
}
Ok(())
}
#[derive(Debug)]
enum AggregateError {
Io(io::Error),
ReadDir(io::Error),
}
impl Display for AggregateError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AggregateError::Io(e) => write!(f, "I/O file error: {}", e),
AggregateError::ReadDir(e) => write!(f, "Unable to read directory: {}", e),
}
}
}
impl Error for AggregateError {}
impl From<io::Error> for AggregateError {
fn from(e: io::Error) -> Self {
AggregateError::Io(e)
}
}
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<LogLevel, usize> = HashMap::new();
let mut skipped = vec![];
let entries = fs::read_dir(dir).map_err(AggregateError::ReadDir)?;
for entry in entries {
let entry = entry?;
let path = entry.path();
if path.extension().and_then(|s| s.to_str()) != Some("log") {
continue;
}
let filename = path.to_string_lossy().to_string();
let file = File::open(&path);
match file {
Ok(f) => {
let res = parse_log_file(f, &mut counts);
if let Err(err) = res {
eprintln!("Warning: Skipping {} due to error: {}", filename, err);
skipped.push(filename);
}
}
Err(e) => {
eprintln!("Warning: Cannot open file {}: {}", filename, e);
skipped.push(filename);
}
}
}
Ok(AggregateInfo {
log_counts: counts,
skipped_files: skipped,
})
}

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

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

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

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

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

warning: variant `ReadDir` is never constructed
  --> src/lib.rs:75:5
   |
73 | enum AggregateError {
   |      -------------- variant in this enum
74 |     Io(io::Error),
75 |     ReadDir(io::Error),
   |     ^^^^^^^
   |
   = note: `AggregateError` 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:95:8
   |
95 | struct AggregateInfo {
   |        ^^^^^^^^^^^^^

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

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
    Finished `test` profile [unoptimized + debuginfo] target(s) in 8.71s
     Running tests/solution_test.rs (target/debug/deps/solution_test-f75e629a1d90e17c)

running 4 tests
test solution_test::test_aggregate ... FAILED
test solution_test::test_parse_log_basic ... ok
test solution_test::test_parse_log_invalid ... ok
test solution_test::test_parse_log_big_data ... ok

failures:

---- solution_test::test_aggregate stdout ----
thread 'solution_test::test_aggregate' panicked at tests/solution_test.rs:139:13:
assertion `left == right` failed
  left: 0
 right: 1
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    solution_test::test_aggregate

test result: FAILED. 3 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

error: test failed, to rerun pass `--test solution_test`

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

Георги качи първо решение на 19.11.2025 23:58 (преди 16 дена)