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

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

Към профила на Милан Стойчев

Резултати

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

Код

use std::collections::HashMap;
use std::error::Error;
use std::fmt;
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,
}
#[derive(Debug)]
struct AggregateInfo {
log_counts: HashMap<LogLevel, usize>,
skipped_files: Vec<String>,
}
#[derive(Debug)]
enum AggregateError {
Io(io::Error),
Other(String),
}
impl fmt::Display for AggregateError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AggregateError::Io(e) => write!(f, "I/O error: {}", e),
AggregateError::Other(s) => write!(f, "{}", s),
}
}
}
impl Error for AggregateError {}
impl From<io::Error> for AggregateError {
fn from(err: io::Error) -> Self {
AggregateError::Io(err)
}
}
#[derive(Debug)]
enum ParseLogError {
Read(io::Error),
ParseLine,
UnknownLevel,
}
impl From<io::Error> for ParseLogError {
fn from(err: io::Error) -> Self {
ParseLogError::Read(err)
}
}
fn parse_log_file<R>(mut file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
where
R: Read,
{
let mut buf = String::new();
file.read_to_string(&mut buf)?;
for line in buf.lines() {
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(ParseLogError::UnknownLevel);
};
*map.entry(level).or_insert(0) += 1;
}
Ok(())
}
fn parse_log_file_stream<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.map_err(ParseLogError::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(ParseLogError::UnknownLevel);
};
*map.entry(level).or_insert(0) += 1;
}
Ok(())
}
fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, Box<dyn Error>> {
let mut counts = HashMap::new();
let mut skipped = Vec::new();
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.extension().map(|ext| ext == "log").unwrap_or(false) {
let metadata = fs::metadata(&path)?;
let file = File::open(&path)?;
let res = if metadata.len() > 10 * 1024 {
parse_log_file_stream(file, &mut counts)
} else {
parse_log_file(file, &mut counts)
};
if let Err(e) = res {
eprintln!("Warning: skipping file {:?} due to error {:?}", path, e);
skipped.push(path.to_string_lossy().to_string());
}
}
}
Ok(AggregateInfo {
log_counts: counts,
skipped_files: skipped,
})
}
fn main() {
use std::env;
use std::process;
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
eprintln!("Usage: {} <log_dir>", args[0]);
process::exit(1);
}
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) => {
eprintln!("Error: {}", e);
process::exit(1);
}
}
}

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

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

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

warning: variant `Other` is never constructed
  --> src/lib.rs:25:5
   |
23 | enum AggregateError {
   |      -------------- variant in this enum
24 |     Io(io::Error),
25 |     Other(String),
   |     ^^^^^
   |
   = note: `AggregateError` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis

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

warning: variants `ParseLine` and `UnknownLevel` are never constructed
  --> src/lib.rs:47:5
   |
45 | enum ParseLogError {
   |      ------------- variants in this enum
46 |     Read(io::Error),
47 |     ParseLine,
   |     ^^^^^^^^^
48 |     UnknownLevel,
   |     ^^^^^^^^^^^^
   |
   = 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:57:4
   |
57 | fn parse_log_file<R>(mut file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
   |    ^^^^^^^^^^^^^^

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

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

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

warning: `solution` (lib) generated 9 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: variant `Other` is never constructed
  --> tests/../src/lib.rs:25:5
   |
23 | enum AggregateError {
   |      -------------- variant in this enum
24 |     Io(io::Error),
25 |     Other(String),
   |     ^^^^^
   |
   = note: `AggregateError` has a derived impl for the trait `Debug`, but this is intentionally ignored during dead code analysis
   = note: `#[warn(dead_code)]` on by default

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

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

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

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

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

---- solution_test::test_parse_log_invalid stdout ----
thread 'solution_test::test_parse_log_invalid' panicked at tests/solution_test.rs:62:9:
assertion failed: matches!(parse_log_file(data, &mut map), Err(ParseLogError::ParseLine))


failures:
    solution_test::test_aggregate
    solution_test::test_parse_log_invalid

test result: FAILED. 2 passed; 2 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 21:44 (преди 16 дена)