Skip to main content

wmjtyd_libstock/file/
reader.rs

1//! Read the specified file and return the content stream.
2
3use chrono::{Duration, Local};
4use std::{fs::File, io::Read};
5
6use crate::file::{datadir::get_ident_path, ident::get_ident, timestamp::fmt_timestamp};
7
8pub struct FileReader {
9    file: File,
10}
11
12impl FileReader {
13    pub fn new(filename: String, day: i64) -> Option<FileReader> {
14        let time = Local::now() - Duration::days(day);
15        let timestamp = fmt_timestamp(&time);
16
17        let identifier = get_ident(&filename, &timestamp);
18        let path = get_ident_path(&identifier);
19
20        File::open(path).ok().map(|file| FileReader { file })
21    }
22}
23
24// http utp utp:quic
25impl Iterator for FileReader {
26    type Item = Vec<u8>;
27
28    fn next(&mut self) -> Option<Self::Item> {
29        let mut data_len_section = [0u8; 2];
30        if let Ok(data_size) = self.file.read(&mut data_len_section) {
31            if 2 != data_size {
32                return None;
33            }
34            let data_len = u16::from_be_bytes(data_len_section) as usize;
35            let mut data = Vec::<u8>::with_capacity(data_len);
36
37            if let Err(e) = self.file.read_exact(&mut data) {
38                tracing::error!("Failed to read the complete data: {e}. Returning None.");
39                None
40            } else {
41                Some(data)
42            }
43        } else {
44            None
45        }
46    }
47}