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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
use std::error::Error as StdError;
use std::hash::Hash;
use std::path::Path as StdPath;
use std::sync::Arc;
use std::{collections::HashMap, ffi::OsString};
use std::{fmt, fs};

use lexical_sort::{lexical_cmp, PathSort};
use parking_lot::RwLock;

use crate::prelude::*;

mod path;
mod process;
pub mod xml_support;

pub use path::{PathBufExt, PathExt, TempPath};
pub use process::{ExitStatusExt, ProcessLines};

#[cfg(unix)]
pub const LINE_END: &str = "\n";
#[cfg(not(unix))]
pub const LINE_END: &str = "\r\n";

/// `Vec` utils
pub trait VecExt {
    fn remove_prefix(&mut self, size: usize) -> Self;
}

impl<T> VecExt for Vec<T>
where
    T: Clone,
{
    fn remove_prefix(&mut self, size: usize) -> Self {
        let size = size.min(self.len());
        let res = self[..size].to_vec();
        self.rotate_left(size);
        self.truncate(self.len() - size);
        res
    }
}

/// Boxed str alias and extensions for `[u8]` and `Vec<u8>`
pub type BStr = Box<str>;

/// `str` utils

pub trait StrExt {
    fn to_os_string(&self) -> OsString;
    fn clone_bstr(&self) -> Box<str>;
}

impl StrExt for str {
    fn to_os_string(&self) -> OsString {
        self.to_string().into()
    }

    fn clone_bstr(&self) -> BStr {
        Box::from(self)
    }
}

/// Apply a function to anything, like `let` in Kotlin.
pub trait Apply: Sized {
    fn apply<F, R>(self, f: F) -> R
    where
        F: FnOnce(Self) -> R;
}

impl<T> Apply for T {
    fn apply<F, R>(self, f: F) -> R
    where
        F: FnOnce(Self) -> R,
    {
        f(self)
    }
}

/// Anyhow error extension
pub trait ErrorExt {
    fn ultimate_source(&self) -> Option<&(dyn StdError + 'static)>;
}

impl ErrorExt for Error {
    fn ultimate_source(&self) -> Option<&(dyn StdError + 'static)> {
        let mut source = self.source()?;
        while let Some(next) = source.source() {
            source = next;
        }
        Some(source)
    }
}

// Lexical sorting
// Basically forwards to the lexical-sort crate

pub fn sort_lexical<S>(slice: &mut [S])
where
    S: AsRef<str>,
{
    sort_lexical_by(slice, AsRef::as_ref)
}

pub fn sort_lexical_by<T, F>(slice: &mut [T], mut key_fn: F)
where
    F: FnMut(&T) -> &str,
{
    slice.sort_by(|lhs, rhs| lexical_cmp(key_fn(lhs), key_fn(rhs)));
}

pub fn sort_paths_lexical<S>(slice: &mut [S])
where
    S: AsRef<StdPath>,
{
    slice.path_sort(lexical_cmp);
}

// fs utils

fn read_dir_all_inner(res: &mut Vec<PathBuf>, path: &Path) -> Result<()> {
    for entry in fs::read_dir(path)? {
        let entry = entry?;
        let path = entry.path();
        if entry.file_type()?.is_dir() {
            // Recurse
            read_dir_all_inner(res, &path)?;
        } else {
            res.push(path);
        }
    }

    Ok(())
}

pub fn read_dir_all<P: AsRef<Path>>(path: P) -> Result<Vec<PathBuf>> {
    let mut res = vec![];
    read_dir_all_inner(&mut res, path.as_ref())?;
    Ok(res)
}

/// A very simple cache.
#[derive(Clone)]
pub struct Cache<K, V>(Arc<RwLock<HashMap<K, V>>>);

impl<K, V> Cache<K, V> {
    pub fn new() -> Self {
        Self(Arc::new(RwLock::new(HashMap::new())))
    }
}

impl<K, V> Cache<K, V>
where
    K: Eq + Hash + Clone,
    V: Clone,
{
    pub fn try_get<E>(&self, key: &K, f: impl FnOnce() -> Result<V, E>) -> Result<V, E> {
        let cache = self.0.read();
        if let Some(value) = cache.get(key) {
            return Ok(value.clone());
        }

        drop(cache);

        let value = f()?;
        self.0.write().insert(key.clone(), value.clone());
        Ok(value)
    }
}

impl<K, V> Default for Cache<K, V> {
    fn default() -> Self {
        Self::new()
    }
}

impl<K, V> fmt::Debug for Cache<K, V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(cache) = self.0.try_read() {
            write!(f, "Cache(unlocked, {} entries)", cache.len())
        } else {
            write!(f, "Cache(locked)")
        }
    }
}

/// Cache of image dimensions.
pub type ImgCache = Cache<PathBuf, (u32, u32)>;