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
use duplicate::duplicate;
use serde::{Deserialize, Serialize};
use smart_default::SmartDefault;
use std::fmt::{self, Display};

/// 文件存储类型
#[derive(Copy, Clone, Debug, Eq, PartialEq, SmartDefault, Serialize, Deserialize)]
#[serde(from = "u8", into = "u8")]
#[non_exhaustive]
pub enum FileType {
    /// 标准存储
    #[default]
    Standard,

    /// 低频存储
    InfrequentAccess,

    /// 归档存储
    Archive,

    /// 深度归档存储
    DeepArchive,

    /// 其他存储类型
    Other(u8),
}

impl Display for FileType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        usize::from(*self).fmt(f)
    }
}

#[duplicate(
    ty;
    [u8];
    [u16];
    [u32];
    [u64];
    [usize];
    [i8];
    [i16];
    [i32];
    [i64];
    [isize];
)]
impl From<FileType> for ty {
    #[inline]
    fn from(file_type: FileType) -> Self {
        match file_type {
            FileType::Standard => 0,
            FileType::InfrequentAccess => 1,
            FileType::Archive => 2,
            FileType::DeepArchive => 3,
            #[allow(clippy::unnecessary_cast)]
            FileType::Other(ft) => ft as ty,
        }
    }
}

#[duplicate(
    ty;
    [u8];
    [u16];
    [u32];
    [u64];
)]
impl From<ty> for FileType {
    fn from(value: ty) -> Self {
        #[allow(clippy::unnecessary_cast)]
        match value as u8 {
            0 => Self::Standard,
            1 => Self::InfrequentAccess,
            2 => Self::Archive,
            3 => Self::DeepArchive,
            ft => Self::Other(ft),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_file_type_serialization_and_deserialization() -> anyhow::Result<()> {
        assert_eq!(&serde_json::to_string(&FileType::Standard)?, "0");
        assert_eq!(&serde_json::to_string(&FileType::Other(5))?, "5");
        assert_eq!(serde_json::from_str::<FileType>("0")?, FileType::Standard);
        assert_eq!(serde_json::from_str::<FileType>("5")?, FileType::Other(5));
        Ok(())
    }
}