Skip to main content

lx_cli/
directory_size.rs

1use crate::dir_scan::scan;
2use crate::file_entry::FileEntry;
3use std::collections::HashMap;
4use std::path::{Path, PathBuf};
5
6#[derive(Clone, Copy, Default)]
7struct ContentsSize {
8    bytes: u64,
9    incomplete: bool,
10}
11
12impl ContentsSize {
13    fn add(&mut self, other: Self) {
14        match self.bytes.checked_add(other.bytes) {
15            Some(bytes) => self.bytes = bytes,
16            None => self.incomplete = true,
17        }
18        self.incomplete |= other.incomplete;
19    }
20}
21
22/// A directory being totalled: its files are summed on entry, and its subdirectories
23/// wait their turn on the traversal stack.
24struct DirectoryFrame {
25    path: PathBuf,
26    subdirectories: std::vec::IntoIter<PathBuf>,
27    size: ContentsSize,
28}
29
30impl DirectoryFrame {
31    fn new(path: PathBuf) -> Self {
32        let mut size = ContentsSize::default();
33        let mut subdirectories = Vec::new();
34        let scanned = scan(
35            &path,
36            |_| true,
37            |entry| match entry.and_then(|entry| Ok((entry.name, entry.stat?))) {
38                Ok((name, stat)) if stat.is_dir() => subdirectories.push(path.join(name)),
39                Ok((_, stat)) if stat.is_file() || stat.is_symlink() => size.add(ContentsSize {
40                    bytes: stat.size,
41                    incomplete: false,
42                }),
43                Ok(_) => {}
44                Err(_) => size.incomplete = true,
45            },
46        );
47        size.incomplete |= scanned.is_err();
48        Self {
49            path,
50            subdirectories: subdirectories.into_iter(),
51            size,
52        }
53    }
54}
55
56/// Contents totals shared by all entries in a listing, including nested trees.
57#[derive(Default)]
58pub struct DirectorySizeCache {
59    totals: HashMap<PathBuf, ContentsSize>,
60}
61
62impl DirectorySizeCache {
63    pub fn apply(&mut self, entries: &mut [FileEntry]) {
64        for entry in entries {
65            if entry.is_dir {
66                let size = self.contents_size(&entry.full_path);
67                entry.size = size.bytes;
68                entry.size_incomplete = size.incomplete;
69            }
70        }
71    }
72
73    fn contents_size(&mut self, path: &Path) -> ContentsSize {
74        if let Some(size) = self.totals.get(path) {
75            return *size;
76        }
77
78        // An explicit stack avoids overflowing the call stack on deep directories.
79        let mut stack = vec![DirectoryFrame::new(path.to_path_buf())];
80        while let Some(frame) = stack.last_mut() {
81            if let Some(child_path) = frame.subdirectories.next() {
82                if let Some(size) = self.totals.get(&child_path) {
83                    frame.size.add(*size);
84                } else {
85                    stack.push(DirectoryFrame::new(child_path));
86                }
87                continue;
88            }
89            let completed = stack.pop().expect("directory frame exists");
90            self.totals.insert(completed.path, completed.size);
91            if let Some(parent) = stack.last_mut() {
92                parent.size.add(completed.size);
93            } else {
94                return completed.size;
95            }
96        }
97        unreachable!("root directory frame returns its total")
98    }
99}