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

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

Към профила на Ивайло Андреев

Резултати

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

Код

use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::fs;
use std::io::{self, BufRead, BufReader, Read};
use std::path::Path;
use std::str::FromStr;
use std::collections::VecDeque;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LogLevel {
Error,
Warn,
Info,
Debug,
}
impl FromStr for LogLevel {
type Err = ParseLogError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"ERROR" => Ok(LogLevel::Error),
"WARN" => Ok(LogLevel::Warn),
"INFO" => Ok(LogLevel::Info),
"DEBUG" => Ok(LogLevel::Debug),
_ => Err(ParseLogError::ParseLine),
}
}
}
impl fmt::Display for LogLevel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LogLevel::Error => write!(f, "Error"),
LogLevel::Warn => write!(f, "Warn"),
LogLevel::Info => write!(f, "Info"),
LogLevel::Debug => write!(f, "Debug"),
}
}
}
#[derive(Debug)]
pub struct AggregateInfo {
pub log_counts: HashMap<LogLevel, usize>,
pub skipped_files: Vec<String>,
}
#[derive(Debug)]
pub enum ParseLogError {
Read(io::Error),
ParseLine,
}
impl fmt::Display for ParseLogError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseLogError::Read(err) => write!(f, "Read error: {}", err),
ParseLogError::ParseLine => write!(f, "Parse error: invalid log level"),
}
}
}
impl Error for ParseLogError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ParseLogError::Read(err) => Some(err),
ParseLogError::ParseLine => None,
}
}
}
impl From<io::Error> for ParseLogError {
fn from(err: io::Error) -> Self {
ParseLogError::Read(err)
}
}
pub fn parse_log_file<R>(file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
where
R: Read,
{
let reader = BufReader::new(file);
for line_result in reader.lines() {
let line = line_result?;
let line = line.trim();
if line.is_empty() {
continue;
}
let first_word = line.split_whitespace().next().ok_or(ParseLogError::ParseLine)?;
let level = LogLevel::from_str(first_word)?;
*map.entry(level).or_insert(0) += 1;
}
Ok(())
}
pub 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_result in entries {
let entry = entry_result?;
let path = entry.path();
if !path.is_file() {
continue;
}
let file_name = path.file_name()
.and_then(|n| n.to_str())
.unwrap_or("unknown")
.to_string();
if path.extension().and_then(|s| s.to_str()) != Some("log") {
skipped_files.push(file_name);
continue;
}
let metadata = match fs::metadata(&path) {
Ok(m) => m,
Err(e) => {
eprintln!("Warning: Could not read metadata for {}: {}", file_name, e);
skipped_files.push(file_name);
continue;
}
};
let file_size = metadata.len();
let file = match fs::File::open(&path) {
Ok(f) => f,
Err(e) => {
eprintln!("Warning: Could not open file {}: {}", file_name, e);
skipped_files.push(file_name);
continue;
}
};
if file_size > 10 * 1024 {
eprintln!("Info: Processing large file ({}KB): {}", file_size / 1024, file_name);
}
if let Err(e) = parse_log_file(file, &mut log_counts) {
eprintln!("Warning: Error parsing file {}: {}", file_name, e);
skipped_files.push(file_name);
}
}
Ok(AggregateInfo {
log_counts,
skipped_files,
})
}

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

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-task v0.3.31
   Compiling pin-utils v0.1.0
   Compiling syn v2.0.110
   Compiling futures-io v0.3.31
   Compiling memchr v2.7.6
   Compiling pin-project-lite v0.2.16
   Compiling slab v0.4.11
   Compiling solution v0.1.0 (/tmp/d20251120-1757769-g0m0rr/solution)
warning: unused import: `std::collections::VecDeque`
 --> src/lib.rs:8:5
  |
8 | use std::collections::VecDeque;
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

warning: `solution` (lib) generated 1 warning (run `cargo fix --lib -p solution` to apply 1 suggestion)
   Compiling futures-macro v0.3.31
   Compiling futures-util v0.3.31
   Compiling futures-executor v0.3.31
   Compiling futures v0.3.31
warning: unused import: `std::collections::VecDeque`
 --> tests/../src/lib.rs:8:5
  |
8 | use std::collections::VecDeque;
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

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

Ивайло качи първо решение на 16.11.2025 21:16 (преди 19 дена)