prefix_file_tree/scheme/
mod.rs

1use std::borrow::Cow;
2use std::cmp::Ordering;
3use std::ffi::{OsStr, OsString};
4
5#[cfg(feature = "data-encoding")]
6pub mod encoding;
7pub mod hex;
8
9#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
10pub enum Error {
11    #[error("Expected UTF-8")]
12    NonUtf8,
13    #[error("Invalid byte")]
14    InvalidByte(u8),
15    #[error("Invalid length")]
16    InvalidLength(usize),
17}
18
19#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
20pub enum Case {
21    #[default]
22    Lower,
23    Upper,
24    Any,
25}
26
27pub trait Scheme {
28    type Name;
29
30    #[must_use]
31    fn fixed_length() -> Option<usize> {
32        None
33    }
34
35    fn name_to_string<'a>(&self, name: &'a Self::Name) -> Cow<'a, str>;
36    fn name_from_file_stem(&self, file_stem: &OsStr) -> Result<Self::Name, Error>;
37
38    fn cmp_prefix_part(&self, a: &OsStr, b: &OsStr) -> Result<Ordering, Error> {
39        Ok(a.cmp(b))
40    }
41}
42
43#[derive(Clone, Copy, Debug, Eq, PartialEq)]
44pub struct Identity;
45
46impl Scheme for Identity {
47    type Name = OsString;
48
49    fn name_to_string<'a>(&self, name: &'a Self::Name) -> Cow<'a, str> {
50        name.as_os_str().to_string_lossy()
51    }
52
53    fn name_from_file_stem(&self, file_stem: &OsStr) -> Result<Self::Name, Error> {
54        Ok(file_stem.to_os_string())
55    }
56}
57
58#[derive(Clone, Copy, Debug, Eq, PartialEq)]
59pub struct Utf8;
60
61impl Scheme for Utf8 {
62    type Name = String;
63
64    fn name_to_string<'a>(&self, name: &'a Self::Name) -> Cow<'a, str> {
65        name.into()
66    }
67
68    fn name_from_file_stem(&self, file_stem: &OsStr) -> Result<Self::Name, Error> {
69        file_stem
70            .to_str()
71            .map(std::string::ToString::to_string)
72            .ok_or(Error::NonUtf8)
73    }
74}