Решение на упр.06 задача 1 от Деян Делчев

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

Към профила на Деян Делчев

Резултати

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

Код

use std::collections::HashMap;
use std::error::Error;
use std::fmt::Display;
use std::fs::File;
use std::io::Read;
use std::io::{self, BufRead, BufReader};
use std::path::Path;
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum LogLevel {
Error,
Warn,
Info,
Debug,
}
impl FromStr for LogLevel {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"DEBUG" => Ok(LogLevel::Debug),
"INFO" => Ok(LogLevel::Info),
"WARN" => Ok(LogLevel::Warn),
"ERROR" => Ok(LogLevel::Error),
_ => Err(()),
}
}
}
struct AggregateInfo {
log_counts: HashMap<LogLevel, usize>,
skipped_files: Vec<String>,
}
const TEN_KILOBYTES: u64 = 10 * 1024;
fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, Box<dyn Error>> {
let mut log_counts = HashMap::new();
let mut skipped_files = Vec::new();
let mut dir_iter = std::fs::read_dir(dir)?;
for entry in dir_iter {
let dir_entry = entry?;
let file_path = dir_entry.path();
let file_name = file_path
.file_name()
.expect("path generated by dir_iter shouldn`t end with ..")
.to_str()
.expect("all files names must be valid utf-8")
.to_owned();
if file_path.is_dir() {
skipped_files.push(file_name);
continue;
}
let file_ext = file_path.extension().and_then(|ext| ext.to_str());
match file_ext {
None => skipped_files.push(file_name),
Some(file_ext) if file_ext != "log" => skipped_files.push(file_name),
_ => {
let file = File::open(file_path)?;
let file_size = file.metadata()?.len();
let res = parse_log_file(file, &mut log_counts);
if let Err(err) = res {
if file_size > TEN_KILOBYTES {
skipped_files.push(file_name);
} else {
return Err(err.into());
}
}
}
}
}
Ok(AggregateInfo {
log_counts,
skipped_files,
})
}
#[derive(Debug)]
enum ParseLogError {
Read(io::Error),
ParseLine,
}
impl From<io::Error> for ParseLogError {
fn from(error: io::Error) -> Self {
ParseLogError::Read(error)
}
}
impl Display for ParseLogError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ParseLogError::Read(error) => write!(f, "IO Error - failed to read: {}", error),
ParseLogError::ParseLine => write!(f, "Parsing Line Error - failed to parse a line"),
}
}
}
impl Error for ParseLogError {}
fn parse_log_file<R>(file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
where
R: Read,
{
let reader = BufReader::new(file).lines();
for read_result in reader {
let line = read_result?;
match line.split_whitespace().next() {
None => return Err(ParseLogError::ParseLine),
Some(word) => match word.parse::<LogLevel>() {
Err(_) => return Err(ParseLogError::ParseLine),
Ok(log_level) => *map.entry(log_level).or_insert(0) += 1,
},
}
}
Ok(())
}

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

Updating crates.io index
     Locking 17 packages to latest compatible versions
   Compiling proc-macro2 v1.0.103
   Compiling quote v1.0.42
   Compiling unicode-ident v1.0.22
   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 futures-io v0.3.31
   Compiling futures-task v0.3.31
   Compiling pin-utils v0.1.0
   Compiling pin-project-lite v0.2.16
   Compiling slab v0.4.11
   Compiling solution v0.1.0 (/tmp/d20251120-1757769-1qxs40e/solution)
warning: variable does not need to be mutable
  --> src/lib.rs:42:9
   |
42 |     let mut dir_iter = std::fs::read_dir(dir)?;
   |         ----^^^^^^^^
   |         |
   |         help: remove this `mut`
   |
   = note: `#[warn(unused_mut)]` on by default

warning: struct `AggregateInfo` is never constructed
  --> src/lib.rs:31:8
   |
31 | struct AggregateInfo {
   |        ^^^^^^^^^^^^^
   |
   = note: `#[warn(dead_code)]` on by default

warning: constant `TEN_KILOBYTES` is never used
  --> src/lib.rs:36:7
   |
36 | const TEN_KILOBYTES: u64 = 10 * 1024;
   |       ^^^^^^^^^^^^^

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

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

warning: `solution` (lib) generated 6 warnings (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: variable does not need to be mutable
  --> tests/../src/lib.rs:42:9
   |
42 |     let mut dir_iter = std::fs::read_dir(dir)?;
   |         ----^^^^^^^^
   |         |
   |         help: remove this `mut`
   |
   = note: `#[warn(unused_mut)]` 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 8.80s
     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 коментара)

Деян качи първо решение на 18.11.2025 21:31 (преди 17 дена)