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

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

Към профила на Георги Стоянов

Резултати

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

Код

use std::collections::HashMap;
use std::env;
use std::process;
use std::io::BufReader;
use std::io::BufRead;
use std::error::Error;
use std::io;
use std::io::Read;
use std::path::Path;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum LogLevel {
Error,
Warn,
Info,
Debug,
}
impl LogLevel {
pub fn from_str(s: &str) -> Option<LogLevel> {
match s {
"ERROR" => Some(LogLevel::Error),
"WARN" => Some(LogLevel::Warn),
"INFO" => Some(LogLevel::Info),
"DEBUG" => Some(LogLevel::Debug),
_ => None,
}
}
}
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::new();
let mut skipped = Vec::new();
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
// тестът ИЗРИЧНО иска file3.txt да присъства в skipped_files
if path.extension().and_then(|s| s.to_str()) != Some("log") {
skipped.push(path.to_string_lossy().into());
continue;
}
let file = match std::fs::File::open(&path) {
Ok(f) => f,
Err(_) => {
skipped.push(path.to_string_lossy().into());
continue;
}
};
if let Err(_) = parse_log_file(file, &mut counts) {
skipped.push(path.to_string_lossy().into());
}
}
Ok(AggregateInfo {
log_counts: counts,
skipped_files: skipped,
})
}
#[derive(Debug)]
enum ParseLogError {
Read(io::Error),
ParseLine,
}
impl From<io::Error> for ParseLogError {
fn from(e: io::Error) -> Self {
ParseLogError::Read(e)
}
}
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?; // io::Error → ParseLogError::Read
let mut parts = line.split_whitespace();
let first = parts.next().ok_or(ParseLogError::ParseLine)?;
let level = LogLevel::from_str(first).ok_or(ParseLogError::ParseLine)?;
*map.entry(level).or_insert(0) += 1;
}
Ok(())
}
fn main() {
let mut args = env::args().skip(1);
let dir = match args.next() {
Some(d) => d,
None => {
eprintln!("Usage: program <log_directory>");
process::exit(1);
}
};
let path = Path::new(&dir);
let result = aggregate_logs(path);
let info = match result {
Ok(info) => info,
Err(e) => {
eprintln!("Error: {}", e);
process::exit(1);
}
};
println!(
"Debug: {}",
info.log_counts.get(&LogLevel::Debug).copied().unwrap_or(0)
);
println!(
"Info: {}",
info.log_counts.get(&LogLevel::Info).copied().unwrap_or(0)
);
println!(
"Warn: {}",
info.log_counts.get(&LogLevel::Warn).copied().unwrap_or(0)
);
println!(
"Error: {}",
info.log_counts.get(&LogLevel::Error).copied().unwrap_or(0)
);
if !info.skipped_files.is_empty() {
println!("\nSkipped files:");
for file in info.skipped_files {
println!(" {}", file);
}
}
}

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

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

warning: associated function `from_str` is never used
  --> src/lib.rs:20:12
   |
19 | impl LogLevel {
   | ------------- associated function in this implementation
20 |     pub fn from_str(s: &str) -> Option<LogLevel> {
   |            ^^^^^^^^

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

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

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

warning: variant `ParseLine` is never constructed
  --> src/lib.rs:72:5
   |
70 | enum ParseLogError {
   |      ------------- variant in this enum
71 |     Read(io::Error),
72 |     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:81:4
   |
81 | fn parse_log_file<R>(file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
   |    ^^^^^^^^^^^^^^

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

warning: `solution` (lib) generated 8 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:71:10
   |
71 |     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
   |
71 |     Read(()),
   |          ~~

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

warning: `solution` (test "solution_test") generated 2 warnings
    Finished `test` profile [unoptimized + debuginfo] target(s) in 8.91s
     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 20:13 (преди 16 дена)