Skip to main content

libsurfer/
util.rs

1//! Utility functions.
2use crate::{displayed_item_tree::VisibleItemIndex, wave_data::WaveData};
3use camino::Utf8PathBuf;
4use egui::RichText;
5#[cfg(not(target_arch = "wasm32"))]
6use std::path::{Path, PathBuf};
7
8/// This function takes a number and converts it's digits into the range
9/// a-p. This is nice because it makes for some easily typed ids.
10/// The function first formats the number as a hex digit and then performs
11/// the mapping.
12#[must_use]
13pub(crate) fn uint_idx_to_alpha_idx(idx: VisibleItemIndex, nvariables: usize) -> String {
14    // this calculates how many hex digits we need to represent nvariables
15    // unwrap because the result should always fit into usize and because
16    // we are not going to display millions of character ids.
17    let width = usize::try_from(nvariables.ilog(16)).unwrap() + 1;
18    format!("{:0width$x}", idx.0)
19        .chars()
20        .map(|c| match c {
21            '0' => 'a',
22            '1' => 'b',
23            '2' => 'c',
24            '3' => 'd',
25            '4' => 'e',
26            '5' => 'f',
27            '6' => 'g',
28            '7' => 'h',
29            '8' => 'i',
30            '9' => 'j',
31            'a' => 'k',
32            'b' => 'l',
33            'c' => 'm',
34            'd' => 'n',
35            'e' => 'o',
36            'f' => 'p',
37            _ => '?',
38        })
39        .collect()
40}
41
42/// This is the reverse function to `uint_idx_to_alpha_idx`.
43pub(crate) fn alpha_idx_to_uint_idx(idx: &str) -> Option<VisibleItemIndex> {
44    let mapped = idx
45        .chars()
46        .map(|c| match c {
47            'a' => '0',
48            'b' => '1',
49            'c' => '2',
50            'd' => '3',
51            'e' => '4',
52            'f' => '5',
53            'g' => '6',
54            'h' => '7',
55            'i' => '8',
56            'j' => '9',
57            'k' => 'a',
58            'l' => 'b',
59            'm' => 'c',
60            'n' => 'd',
61            'o' => 'e',
62            'p' => 'f',
63            _ => '?',
64        })
65        .collect::<String>();
66    usize::from_str_radix(&mapped, 16)
67        .ok()
68        .map(VisibleItemIndex)
69}
70
71#[must_use]
72pub(crate) fn get_alpha_focus_id(vidx: VisibleItemIndex, waves: &WaveData) -> RichText {
73    let alpha_id = uint_idx_to_alpha_idx(vidx, waves.displayed_items.len());
74
75    RichText::new(alpha_id).monospace()
76}
77
78/// This function searches upward from `start` for directories or files matching `item`.
79///
80/// It returns a `Vec<PathBuf>` to all found instances in order of closest to furthest away.
81/// The function only searches up within subdirectories of `end`.
82#[cfg(not(target_arch = "wasm32"))]
83pub(crate) fn search_upward(
84    start: impl AsRef<Path>,
85    end: impl AsRef<Path>,
86    item: impl AsRef<Path>,
87) -> Vec<PathBuf> {
88    start
89        .as_ref()
90        .ancestors()
91        .take_while(|p| p.starts_with(end.as_ref()))
92        .map(|p| p.join(&item))
93        .filter(|p| p.try_exists().is_ok_and(std::convert::identity))
94        .collect()
95}
96
97fn get_multi_extension_from_filename(filename: &str) -> Option<String> {
98    filename
99        .find('.')
100        .map(|pos| filename[pos + 1..].to_string())
101}
102
103/// Get the full extension of a path, including all extensions.
104/// For example, for "foo.tar.gz", this function returns "tar.gz", and not just "gz",
105/// like `path.extension()` would.
106#[must_use]
107pub(crate) fn get_multi_extension(path: &Utf8PathBuf) -> Option<String> {
108    // Find the first . in the path, if any. Return the rest of the path.
109    if let Some(filename) = path.file_name() {
110        return get_multi_extension_from_filename(filename);
111    }
112    None
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    #[test]
120    fn test_uint_idx_to_alpha_idx_basic_width_1() {
121        // nvariables determines hex width: width = ilog16(nvariables) + 1
122        // For nvariables = 1 => width = 1
123        assert_eq!(uint_idx_to_alpha_idx(VisibleItemIndex(0), 1), "a");
124        assert_eq!(uint_idx_to_alpha_idx(VisibleItemIndex(9), 1), "j");
125        assert_eq!(uint_idx_to_alpha_idx(VisibleItemIndex(15), 1), "p");
126    }
127
128    #[test]
129    fn test_uint_idx_to_alpha_idx_zero_padded_width_2() {
130        // nvariables = 16 => width = 2 (since ilog16(16) == 1)
131        assert_eq!(uint_idx_to_alpha_idx(VisibleItemIndex(0x0), 16), "aa");
132        assert_eq!(uint_idx_to_alpha_idx(VisibleItemIndex(0x1), 16), "ab");
133        assert_eq!(uint_idx_to_alpha_idx(VisibleItemIndex(0xf), 16), "ap");
134        assert_eq!(uint_idx_to_alpha_idx(VisibleItemIndex(0x10), 16), "ba");
135        assert_eq!(uint_idx_to_alpha_idx(VisibleItemIndex(0x1f), 16), "bp");
136    }
137
138    #[test]
139    fn test_alpha_idx_to_uint_idx_roundtrip() {
140        // Try a selection across multiple widths
141        let cases = [
142            (VisibleItemIndex(0x0), 1),
143            (VisibleItemIndex(0x9), 1),
144            (VisibleItemIndex(0xf), 1),
145            (VisibleItemIndex(0x10), 16),
146            (VisibleItemIndex(0x2a), 256),
147            (VisibleItemIndex(0xabc), 4096),
148        ];
149
150        for (vidx, nvars) in cases {
151            let s = uint_idx_to_alpha_idx(vidx, nvars);
152            let back = alpha_idx_to_uint_idx(&s).expect("should parse back");
153            assert_eq!(back, vidx);
154        }
155    }
156
157    #[test]
158    fn test_alpha_idx_to_uint_idx_invalid_input() {
159        // Contains invalid character 'r' which is outside a-p
160        assert!(alpha_idx_to_uint_idx("ar").is_none());
161        // Empty string should fail to parse as hex
162        assert!(alpha_idx_to_uint_idx("").is_none());
163        // Mixed case / unexpected chars
164        assert!(alpha_idx_to_uint_idx("A").is_none());
165        assert!(alpha_idx_to_uint_idx("-").is_none());
166    }
167
168    #[test]
169    fn test_get_multi_extension_from_filename() {
170        assert_eq!(
171            get_multi_extension_from_filename("foo.tar.gz"),
172            Some("tar.gz".to_string())
173        );
174        assert_eq!(
175            get_multi_extension_from_filename("foo.txt"),
176            Some("txt".to_string())
177        );
178        assert_eq!(get_multi_extension_from_filename("foo"), None);
179        // Leading dot files: first dot at 0, extension is the remainder
180        assert_eq!(
181            get_multi_extension_from_filename(".bashrc"),
182            Some("bashrc".to_string())
183        );
184        // Trailing dot: extension becomes empty string
185        assert_eq!(
186            get_multi_extension_from_filename("foo."),
187            Some(String::new())
188        );
189    }
190
191    #[test]
192    fn test_get_multi_extension_from_path() {
193        let p = Utf8PathBuf::from("/tmp/foo/bar.tar.gz");
194        assert_eq!(get_multi_extension(&p), Some("tar.gz".to_string()));
195        let p = Utf8PathBuf::from("/tmp/foo/bar");
196        assert_eq!(get_multi_extension(&p), None);
197    }
198
199    #[test]
200    fn test_get_multi_extension_with_unicode() {
201        // Ensure Unicode before the first dot does not break slicing
202        // (previous implementation mixed byte and char indexing)
203        let name = "åäö.archive.tar.gz"; // multibyte chars before '.'
204        assert_eq!(
205            get_multi_extension_from_filename(name),
206            Some("archive.tar.gz".to_string())
207        );
208
209        // Only Unicode and then dot
210        let name2 = "ß.";
211        assert_eq!(
212            get_multi_extension_from_filename(name2),
213            Some(String::new())
214        );
215    }
216
217    #[cfg(not(target_arch = "wasm32"))]
218    #[test]
219    fn test_search_upward_finds_closest_first() {
220        use std::fs;
221        use std::io::Write;
222        use std::path::Path;
223
224        // Create a temporary directory structure: root/a/b/c
225        let tmp = tempfile::tempdir().expect("tempdir");
226        let root = tmp.path();
227        let a = root.join("a");
228        let b = a.join("b");
229        let c = b.join("c");
230        fs::create_dir_all(&c).expect("dirs");
231
232        // Place target file at c and at a
233        let item_name = Path::new("target.txt");
234        let item_c = c.join(item_name);
235        let item_a = a.join(item_name);
236        {
237            let mut f = fs::File::create(&item_c).expect("create c");
238            writeln!(f, "hello").unwrap();
239        }
240        {
241            let mut f = fs::File::create(&item_a).expect("create a");
242            writeln!(f, "world").unwrap();
243        }
244
245        // Start searching from c upwards, but only within root
246        let found = search_upward(&c, root, item_name);
247        // Expect closest-first order: c/target.txt, then a/target.txt
248        assert_eq!(found, vec![item_c, item_a]);
249    }
250}