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

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

Към профила на Константин Илиев

Резултати

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

Код

fn main() {}

use std::collections::HashMap; use std::error::Error; use std::io; use std::io::{Read, BufReader, BufRead}; use std::path::Path; use std::fs; use std::fs::File; use std::fmt;

[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]

enum LogLevel { Error, Warn, Info, Debug, }

struct AggregateInfo { log_counts: HashMap<LogLevel, usize>, skipped_files: Vec, }

[derive(Debug)]

enum ParseLogError { Read(io::Error), ParseLine, }

impl fmt::Display for ParseLogError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { ParseLogError::Read(e) => write!(f, "I/O error while reading log file: {}", e), ParseLogError::ParseLine => write!(f, "failed to parse log line"), } } }

impl From<io::Error> for ParseLogError { fn from(e: io::Error) -> Self{ ParseLogError::Read(e) } }

enum AggregateError{ Io(io::Error), }

impl fmt::Display for AggregateError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { match self { AggregateError::Io(e) => write!(f, "I/O error while aggregating logs: {}", e), } }

}

impl From<io::Error> for AggregateError { fn from(e: io::Error) -> Self { AggregateError::Io(e) } }

fn parse_log_file(file: R, map: &mut HashMap<LogLevel, usize>) -> Result<(), ParseLogError> where R: Read, { let buf_reader = BufReader::new(file);

for line_res in buf_reader.lines(){
    let line = line_res.map_err(ParseLogError::Read)?;
    let trimmed = line.trim();
    if trimmed.is_empty(){
        continue;
    }

    let mut parts = trimmed.splitn(2, ' ');
    let level_str = parts.next().unwrap_or_default();

    let level = match level_str {
        "ERROR" => LogLevel::Error,
        "WARN"  => LogLevel::Warn,
        "INFO"  => LogLevel::Info,
        "DEBUG" => LogLevel::Debug,
        _ => return Err(ParseLogError::ParseLine),
    };

    *map.entry(level).or_insert(0) += 1;
}

Ok(())

}

fn aggregate_logs(dir: &Path) -> Result<AggregateInfo, AggregateError> { let mut total_counts: HashMap<LogLevel, usize> = HashMap::new(); let mut skipped_files: Vec = Vec::new();

for entry_res in fs::read_dir(dir)? {
    let entry = entry_res?;
    let path = entry.path();
    let path_str = path.to_string_lossy().to_string();
    let ext = path.extension().and_then(|s| s.to_str());

    if ext != Some("log") {
        skipped_files.push(path_str);
        continue;
    }

    let metadata = fs::metadata(&path)?;
    let file_size = metadata.len();

    let mut local_counts: HashMap<LogLevel, usize> = HashMap::new();
    let parse_result = if file_size > 10 * 1024 {
        let file = File::open(&path)?;
        parse_log_file(file, &mut local_counts)
    } else {
        let mut contents = String::new();
        File::open(&path)?.read_to_string(&mut contents)?;
        parse_log_file(contents.as_bytes(), &mut local_counts)
    };

    match parse_result {
        Ok(()) => {
            for (level, count) in local_counts {
                *total_counts.entry(level).or_insert(0) += count;
            }
        }
        Err(e) => {
            println!("Warning: skipping file {} due to error {}", path_str, e);
            skipped_files.push(path_str);
        }
    }
}

Ok(AggregateInfo {
    log_counts: total_counts,
    skipped_files,
})

}

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

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-sink v0.3.31
   Compiling futures-core v0.3.31
   Compiling futures-channel v0.3.31
   Compiling futures-task v0.3.31
   Compiling pin-project-lite v0.2.16
   Compiling syn v2.0.110
   Compiling futures-io v0.3.31
   Compiling memchr v2.7.6
   Compiling pin-utils v0.1.0
   Compiling slab v0.4.11
   Compiling solution v0.1.0 (/tmp/d20251120-1757769-gq3we7/solution)
warning: function `main` is never used
 --> src/lib.rs:1:4
  |
1 | fn main() {}
  |    ^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: `solution` (lib) generated 1 warning
   Compiling futures-macro v0.3.31
   Compiling futures-util v0.3.31
   Compiling futures-executor v0.3.31
   Compiling futures v0.3.31
error[E0433]: failed to resolve: use of undeclared type `HashMap`
  --> tests/solution_test.rs:12:23
   |
12 |         let mut map = HashMap::new();
   |                       ^^^^^^^ use of undeclared type `HashMap`
   |
help: consider importing this struct
   |
6  + use std::collections::HashMap;
   |

error[E0433]: failed to resolve: use of undeclared type `HashMap`
  --> tests/solution_test.rs:29:23
   |
29 |         let mut map = HashMap::new();
   |                       ^^^^^^^ use of undeclared type `HashMap`
   |
help: consider importing this struct
   |
6  + use std::collections::HashMap;
   |

error[E0433]: failed to resolve: use of undeclared type `HashMap`
  --> tests/solution_test.rs:47:23
   |
47 |         let mut map = HashMap::new();
   |                       ^^^^^^^ use of undeclared type `HashMap`
   |
help: consider importing this struct
   |
6  + use std::collections::HashMap;
   |

error[E0433]: failed to resolve: use of undeclared type `HashMap`
  --> tests/solution_test.rs:61:23
   |
61 |         let mut map = HashMap::new();
   |                       ^^^^^^^ use of undeclared type `HashMap`
   |
help: consider importing this struct
   |
6  + use std::collections::HashMap;
   |

error[E0405]: cannot find trait `Read` in this scope
  --> tests/solution_test.rs:75:27
   |
75 |     struct ReadCounter<R: Read> {
   |                           ^^^^ not found in this scope
   |
help: consider importing this trait
   |
6  + use std::io::Read;
   |

error[E0433]: failed to resolve: use of undeclared crate or module `io`
  --> tests/solution_test.rs:81:47
   |
81 |         fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
   |                                               ^^ use of undeclared crate or module `io`
   |
help: a builtin type with a similar name exists
   |
81 |         fn read(&mut self, buf: &mut [u8]) -> i8::Result<usize> {
   |                                               ~~
help: consider importing one of these modules
   |
6  + use std::io;
   |
6  + use futures::io;
   |

error[E0433]: failed to resolve: use of undeclared type `HashMap`
  --> tests/solution_test.rs:89:19
   |
89 |     let mut map = HashMap::new();
   |                   ^^^^^^^ use of undeclared type `HashMap`
   |
help: consider importing this struct
   |
6  + use std::collections::HashMap;
   |

error[E0433]: failed to resolve: use of undeclared type `Path`
   --> tests/solution_test.rs:132:34
    |
132 |     let output = aggregate_logs(&Path::new(&dirname));
    |                                  ^^^^ use of undeclared type `Path`
    |
help: consider importing this struct
    |
6   + use std::path::Path;
    |

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
  --> tests/solution_test.rs:14:29
   |
14 |         assert_eq!(map.get(&LogLevel::Error).copied().unwrap_or(0), 0);
   |                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
  --> tests/solution_test.rs:15:29
   |
15 |         assert_eq!(map.get(&LogLevel::Warn).copied().unwrap_or(0), 0);
   |                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
  --> tests/solution_test.rs:16:29
   |
16 |         assert_eq!(map.get(&LogLevel::Info).copied().unwrap_or(0), 0);
   |                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
  --> tests/solution_test.rs:17:29
   |
17 |         assert_eq!(map.get(&LogLevel::Debug).copied().unwrap_or(0), 0);
   |                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
  --> tests/solution_test.rs:31:29
   |
31 |         assert_eq!(map.get(&LogLevel::Error).copied().unwrap_or(0), 1);
   |                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
  --> tests/solution_test.rs:32:29
   |
32 |         assert_eq!(map.get(&LogLevel::Warn).copied().unwrap_or(0), 1);
   |                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
  --> tests/solution_test.rs:33:29
   |
33 |         assert_eq!(map.get(&LogLevel::Info).copied().unwrap_or(0), 1);
   |                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
  --> tests/solution_test.rs:34:29
   |
34 |         assert_eq!(map.get(&LogLevel::Debug).copied().unwrap_or(0), 1);
   |                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
  --> tests/solution_test.rs:49:29
   |
49 |         assert_eq!(map.get(&LogLevel::Error).copied().unwrap_or(0), 0);
   |                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
  --> tests/solution_test.rs:50:29
   |
50 |         assert_eq!(map.get(&LogLevel::Warn).copied().unwrap_or(0), 1);
   |                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
  --> tests/solution_test.rs:51:29
   |
51 |         assert_eq!(map.get(&LogLevel::Info).copied().unwrap_or(0), 3);
   |                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
  --> tests/solution_test.rs:52:29
   |
52 |         assert_eq!(map.get(&LogLevel::Debug).copied().unwrap_or(0), 1);
   |                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0433]: failed to resolve: use of undeclared type `ParseLogError`
  --> tests/solution_test.rs:62:62
   |
62 |         assert!(matches!(parse_log_file(data, &mut map), Err(ParseLogError::ParseLine)));
   |                                                              ^^^^^^^^^^^^^ use of undeclared type `ParseLogError`

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
   --> tests/solution_test.rs:135:45
    |
135 |             assert_eq!(info.log_counts.get(&LogLevel::Error).copied().unwrap_or(0), 1);
    |                                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
   --> tests/solution_test.rs:136:45
    |
136 |             assert_eq!(info.log_counts.get(&LogLevel::Warn).copied().unwrap_or(0), 1);
    |                                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
   --> tests/solution_test.rs:137:45
    |
137 |             assert_eq!(info.log_counts.get(&LogLevel::Info).copied().unwrap_or(0), 4);
    |                                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0433]: failed to resolve: use of undeclared type `LogLevel`
   --> tests/solution_test.rs:138:45
    |
138 |             assert_eq!(info.log_counts.get(&LogLevel::Debug).copied().unwrap_or(0), 1);
    |                                             ^^^^^^^^ use of undeclared type `LogLevel`

error[E0425]: cannot find function `parse_log_file` in this scope
  --> tests/solution_test.rs:13:26
   |
13 |         assert!(matches!(parse_log_file(data, &mut map), Ok(())));
   |                          ^^^^^^^^^^^^^^ not found in this scope

error[E0425]: cannot find function `parse_log_file` in this scope
  --> tests/solution_test.rs:30:26
   |
30 |         assert!(matches!(parse_log_file(data, &mut map), Ok(())));
   |                          ^^^^^^^^^^^^^^ not found in this scope

error[E0425]: cannot find function `parse_log_file` in this scope
  --> tests/solution_test.rs:48:26
   |
48 |         assert!(matches!(parse_log_file(data, &mut map), Ok(())));
   |                          ^^^^^^^^^^^^^^ not found in this scope

error[E0425]: cannot find function `parse_log_file` in this scope
  --> tests/solution_test.rs:62:26
   |
62 |         assert!(matches!(parse_log_file(data, &mut map), Err(ParseLogError::ParseLine)));
   |                          ^^^^^^^^^^^^^^ not found in this scope

error[E0425]: cannot find function `parse_log_file` in this scope
  --> tests/solution_test.rs:90:11
   |
90 |     match parse_log_file(&mut reader, &mut map) {
   |           ^^^^^^^^^^^^^^ not found in this scope

error[E0425]: cannot find function `aggregate_logs` in this scope
   --> tests/solution_test.rs:132:18
    |
132 |     let output = aggregate_logs(&Path::new(&dirname));
    |                  ^^^^^^^^^^^^^^ not found in this scope

Some errors have detailed explanations: E0405, E0425, E0433.
For more information about an error, try `rustc --explain E0405`.
error: could not compile `solution` (test "solution_test") due to 31 previous errors

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

Константин качи първо решение на 19.11.2025 17:58 (преди 17 дена)