ex_cli/
total.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use std::cmp::max;

use chrono::{DateTime, Utc};

use crate::config::{Config, FileKind};
use crate::file::File;

const EXT_WIDTH: usize = 4; // (minimum width of ".txt")

pub struct Total {
    pub start_time: Option<DateTime<Utc>>,
    pub max_size: u64,
    pub total_size: u64,
    #[cfg(unix)]
    pub user_width: usize,
    #[cfg(unix)]
    pub group_width: usize,
    pub ver_width: usize,
    pub ext_width: usize,
    pub num_files: usize,
    pub num_dirs: usize,
}

// noinspection RsUnnecessaryReturn
impl Total {
    pub fn new(start_time: Option<DateTime<Utc>>) -> Total {
        Self {
            start_time,
            max_size: 0,
            total_size: 0,
            #[cfg(unix)]
            user_width: 0,
            #[cfg(unix)]
            group_width: 0,
            ver_width: 0,
            ext_width: 0,
            num_files: 0,
            num_dirs: 0,
        }
    }

    #[allow(unused_variables)]
    pub fn from_files(
        start_time: Option<DateTime<Utc>>,
        config: &Config,
        files: &Vec<File>,
    ) -> Total {
        let mut total = Self::new(start_time);
        #[cfg(unix)]
        if config.show_owner {
            total.user_width = 1;
            total.group_width = 1;
        }
        for file in files.iter() {
            total.apply_file(file);
        }
        if total.ext_width > 0 {
            total.ext_width = max(total.ext_width, EXT_WIDTH);
        }
        return total;
    }

    fn apply_file(&mut self, file: &File) {
        self.max_size = max(self.max_size, file.file_size);
        self.total_size += file.file_size;
        #[cfg(unix)]
        if let Some(user) = &file.owner_user {
            self.user_width = max(self.user_width, user.len());
        }
        #[cfg(unix)]
        if let Some(group) = &file.owner_group {
            self.group_width = max(self.group_width, group.len());
        }
        if let Some(ver) = &file.file_ver {
            self.ver_width = max(self.ver_width, ver.len());
        }
        self.ext_width = max(self.ext_width, file.file_ext.len());
        if file.file_type == FileKind::Dir {
            self.num_dirs += 1;
        } else {
            self.num_files += 1;
        }
    }
}