cargo_file_gen/
file_size.rs

1use crate::error::FileGenError;
2
3pub struct FileSize {
4    pub amount: u64,
5    pub size: SizeType,
6}
7
8impl FileSize {
9    pub fn byte_amount(&self) -> u64 {
10        self.amount * self.size.to_byte_factor()
11    }
12}
13
14impl TryInto<FileSize> for String {
15    type Error = FileGenError;
16
17    fn try_into(self) -> Result<FileSize, Self::Error> {
18        let mut amount = String::new();
19        let mut size_type = String::new();
20
21        let mut amount_ended = false;
22        for x in self.chars() {
23            match x {
24                '0'..='9' => {}
25                _ => {
26                    amount_ended = true;
27                }
28            }
29
30            if amount_ended {
31                size_type.push(x);
32            } else {
33                amount.push(x);
34            }
35        }
36
37        let amount = match amount.parse::<u64>() {
38            Ok(ok) => ok,
39            Err(_err) => return Err(FileGenError::InvalidAmountForSizeError),
40        };
41        Ok(FileSize {
42            amount,
43            size: size_type.try_into()?,
44        })
45    }
46}
47
48pub enum SizeType {
49    Byte,
50    KiloByte,
51    MegaByte,
52    GigaByte,
53}
54
55impl SizeType {
56    pub fn to_byte_factor(&self) -> u64 {
57        match self {
58            SizeType::Byte => 1,
59            SizeType::KiloByte => 1024,
60            SizeType::MegaByte => 1024 * 1024,
61            SizeType::GigaByte => 1024 * 1024 * 1024,
62        }
63    }
64}
65
66impl TryInto<SizeType> for String {
67    type Error = FileGenError;
68
69    fn try_into(self) -> Result<SizeType, Self::Error> {
70        let name = self.to_lowercase();
71        let size_type = match name.as_str() {
72            "b" => SizeType::Byte,
73            "kb" => SizeType::KiloByte,
74            "mb" => SizeType::MegaByte,
75            "gb" => SizeType::GigaByte,
76            _ => return Err(FileGenError::InvalidTypeForSizeError),
77        };
78
79        Ok(size_type)
80    }
81}