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

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

Към профила на Йоанна Ненкова

Резултати

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

Код

use std::collections::HashMap;
use std::error::Error;
use std::io::{self, BufRead, BufReader, Read};
use std::path::Path;
use std::fmt;
use std::fs;
use std::env;
use std::process;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum LogLevel {
Error,
Warn,
Info,
Debug,
}
impl LogLevel {
fn from_str(s: &str) -> Option<Self> {
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 log_counts = HashMap::new();
let mut skipped_files = Vec::new();
let entries = fs::read_dir(dir)?;
for entry in entries {
let entry = entry?;
let path = entry.path();
if path.extension().and_then(|s| s.to_str()) != Some("log") {
if let Some(name) = path.file_name().and_then(|s| s.to_str()) {
skipped_files.push(name.to_string());
}
continue;
}
match fs::File::open(&path) {
Ok(file) => {
if let Err(e) = parse_log_file(file, &mut log_counts) {
eprintln!("Skipped file {:?}, error: {:?}", path, e);
}
}
Err(e) => {
eprintln!("Could not open file {:?}: {}", path, e);
if let Some(name) = path.file_name().and_then(|s| s.to_str()) {
skipped_files.push(name.to_string());
}
}
}
}
Ok(AggregateInfo { log_counts, skipped_files})
}
#[derive(Debug)]
enum ParseLogError {
Read(io::Error),
ParseLine,
}
impl fmt::Display for ParseLogError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ParseLogError::Read(e) => write!(f, "Read error: {}", e),
ParseLogError::ParseLine => write!(f, "Parse error: invalid log line"),
}
}
}
impl Error for ParseLogError {}
impl From<io::Error> for ParseLogError {
fn from(err: io::Error) -> Self {
ParseLogError::Read(err)
}
}
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 first_word = line.split_whitespace().next();
match first_word.and_then(LogLevel::from_str) {
Some(level) => {
*map.entry(level).or_insert(0) += 1;
}
None => {
return Err(ParseLogError::ParseLine);
}
}
}
Ok(())
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() != 2 {
eprintln!("Usage: {} <los_directory>", args[0]);
process::exit(1);
}
let dir = Path::new(&args[1]);
let result = aggregate_logs(dir);
let info = match result {
Ok(info) => info,
Err(err) => {
eprintln!("Error: {}", err);
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!("Skipped 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-sink v0.3.31
   Compiling futures-core v0.3.31
   Compiling futures-channel v0.3.31
   Compiling pin-project-lite v0.2.16
   Compiling pin-utils v0.1.0
   Compiling slab v0.4.11
   Compiling syn v2.0.110
   Compiling futures-io v0.3.31
   Compiling memchr v2.7.6
   Compiling futures-task v0.3.31
   Compiling solution v0.1.0 (/tmp/d20251120-1757769-1feokcr/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:8
   |
19 | impl LogLevel {
   | ------------- associated function in this implementation
20 |     fn from_str(s: &str) -> Option<Self> {
   |        ^^^^^^^^

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

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

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: function `main` is never used
   --> tests/../src/lib.rs:123:4
    |
123 | fn main() {
    |    ^^^^
    |
    = note: `#[warn(dead_code)]` on by default

warning: `solution` (test "solution_test") generated 1 warning
    Finished `test` profile [unoptimized + debuginfo] target(s) in 8.99s
     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_invalid ... ok
test solution_test::test_parse_log_big_data ... ok

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

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

Йоанна качи първо решение на 19.11.2025 06:43 (преди 17 дена)