rosier 0.2.0

A fast picture and video viewer for large folders
//! Finding media files under a root directory.

use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    Image,
    Video,
}

#[derive(Debug, Clone)]
pub struct Entry {
    /// Row id in the index; 0 for files that are not indexed (bench tools).
    pub id: i64,
    pub path: PathBuf,
    pub kind: Kind,
    pub size: u64,
    pub mtime: u64,
}

impl Entry {
    pub fn is_jpeg(&self) -> bool {
        matches!(ext_lower(&self.path).as_deref(), Some("jpg" | "jpeg"))
    }
}

fn ext_lower(path: &Path) -> Option<String> {
    Some(path.extension()?.to_str()?.to_ascii_lowercase())
}

pub fn kind_of(path: &Path) -> Option<Kind> {
    match ext_lower(path)?.as_str() {
        "jpg" | "jpeg" | "png" | "gif" | "webp" | "bmp" | "tif" | "tiff" => Some(Kind::Image),
        "mp4" | "mkv" | "avi" | "mov" | "webm" | "m4v" | "ts" | "wmv" | "flv" => Some(Kind::Video),
        _ => None,
    }
}

/// Walks `root` in parallel and returns every image and video, sorted by path.
pub fn scan(root: &Path) -> Vec<Entry> {
    let mut v: Vec<Entry> = jwalk::WalkDir::new(root)
        .skip_hidden(true)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_type().is_file())
        .filter_map(|e| {
            let path = e.path();
            let kind = kind_of(&path)?;
            let md = e.metadata().ok()?;
            let mtime = md.modified().ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map_or(0, |d| d.as_secs());
            Some(Entry { id: 0, path, kind, size: md.len(), mtime })
        })
        .collect();
    v.sort_by(|a, b| natural_cmp(&a.path, &b.path));
    v
}

/// Compares paths the way people count: "clip_2" before "clip_10".
pub fn natural_cmp(a: &Path, b: &Path) -> std::cmp::Ordering {
    use std::cmp::Ordering;
    let (a, b) = (a.as_os_str().as_encoded_bytes(), b.as_os_str().as_encoded_bytes());
    let (mut i, mut j) = (0, 0);
    while i < a.len() && j < b.len() {
        if a[i].is_ascii_digit() && b[j].is_ascii_digit() {
            let si = i;
            while i < a.len() && a[i].is_ascii_digit() {
                i += 1;
            }
            let sj = j;
            while j < b.len() && b[j].is_ascii_digit() {
                j += 1;
            }
            // Compare digit runs by value: drop leading zeros, then length,
            // then digits. Ties on value fall back to the shorter run.
            let (na, nb) = (&a[si..i], &b[sj..j]);
            let ta = &na[na.iter().take_while(|&&c| c == b'0').count()..];
            let tb = &nb[nb.iter().take_while(|&&c| c == b'0').count()..];
            let ord = ta.len().cmp(&tb.len()).then_with(|| ta.cmp(tb)).then_with(|| na.len().cmp(&nb.len()));
            if ord != Ordering::Equal {
                return ord;
            }
        } else {
            let (ca, cb) = (a[i].to_ascii_lowercase(), b[j].to_ascii_lowercase());
            if ca != cb {
                return ca.cmp(&cb);
            }
            i += 1;
            j += 1;
        }
    }
    (a.len() - i).cmp(&(b.len() - j)).then_with(|| a.cmp(b))
}

#[cfg(test)]
mod tests {
    use super::natural_cmp;
    use std::cmp::Ordering::*;
    use std::path::Path;

    #[test]
    fn numbers_compare_by_value() {
        let c = |a: &str, b: &str| natural_cmp(Path::new(a), Path::new(b));
        assert_eq!(c("clip_2.mp4", "clip_10.mp4"), Less);
        assert_eq!(c("clip_10.mp4", "clip_2.mp4"), Greater);
        assert_eq!(c("a/img_001.jpg", "a/img_2.jpg"), Less);
        assert_eq!(c("Ep 9", "ep 10"), Less);
        assert_eq!(c("x", "x"), Equal);
        // A folder's files stay together: "a/z" sorts before "a_b/a".
        assert_eq!(c("a/z.jpg", "a/zz.jpg"), Less);
    }
}