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

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

Към профила на Йоан Грозев

Резултати

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

Код

use std::collections::HashMap;
use std::error::Error;
use std::fs;
use std::io;
use std::path::Path;
use std::io::{Read, BufRead, BufReader};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum LogLevel
{
Error,
Warn,
Info,
Debug,
}
struct AggregateInfo
{
log_counts: HashMap<LogLevel, usize>,
skipped_files: Vec<String>,
}
fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, Box<dyn Error>>
{
let mut result = AggregateInfo
{
log_counts: HashMap::new(),
skipped_files: Vec::new(),
};
let entries = fs::read_dir(dir)?;
for i in entries
{
let i = match i
{
Ok(e) => e,
Err(e) => return Err(Box::new(e)),
};
let path = i.path();
let name = path.to_string_lossy().to_string();
if path.extension().and_then(|s| s.to_str()) != Some("log")
{
result.skipped_files.push(name);
continue;
}
let metadata = fs::metadata(&path)?;
let file = fs::File::open(&path);
let file = match file
{
Ok(f) => f,
Err(e) => return Err(Box::new(e)),
};
let parse_result = if metadata.len() > 10 * 1024
{
let reader = BufReader::new(file);
parse_log_file(reader, &mut result.log_counts)
}
else
{
parse_log_file(file, &mut result.log_counts)
};
if let Err(_) = parse_result
{
result.skipped_files.push(name);
continue;
}
}
Ok(result)
}
#[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>(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 i in buf.lines()
{
let level = if i.starts_with("ERROR")
{
LogLevel::Error
}
else if i.starts_with("WARN")
{
LogLevel::Warn
}
else if i.starts_with("INFO")
{
LogLevel::Info
}
else if i.starts_with("DEBUG")
{
LogLevel::Debug
}
else
{
return Err(ParseLogError::ParseLine);
};
*map.entry(level).or_insert(0) += 1;
}
Ok(())
}

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

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

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: function `aggregate_logs` is never used
  --> src/lib.rs:23:4
   |
23 | fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, Box<dyn Error>> 
   |    ^^^^^^^^^^^^^^

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

warning: variant `ParseLine` is never constructed
  --> src/lib.rs:83:5
   |
80 | enum ParseLogError 
   |      ------------- variant in this enum
...
83 |     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:94:4
   |
94 | fn parse_log_file<R>(mut file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError>
   |    ^^^^^^^^^^^^^^

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: unused import: `BufRead`
 --> tests/../src/lib.rs:6:21
  |
6 | use std::io::{Read, BufRead, BufReader};
  |                     ^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

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

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