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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
mod built_in_traits;
#[cfg(feature = "serde")]
mod serde;

use core::{
    cmp::Ordering,
    fmt::{self, Alignment, Display, Formatter, Write},
};

use super::{Byte, Unit};
use crate::{common::round_fractional_part_f64, UnitType};

/// Generated from the [`Byte::get_adjusted_unit`](./struct.Byte.html#method.get_adjusted_unit) method or the the [`Byte::get_appropriate_unit`](./struct.Byte.html#method.get_appropriate_unit) method.
///
/// For accuracy representation, utilize the `Byte` struct.
#[derive(Debug, Clone, Copy)]
pub struct AdjustedByte {
    pub(crate) value: f64,
    pub(crate) unit:  Unit,
}

impl PartialEq for AdjustedByte {
    #[inline]
    fn eq(&self, other: &AdjustedByte) -> bool {
        let s = self.get_byte();
        let o = other.get_byte();

        s.eq(&o)
    }
}

impl Eq for AdjustedByte {}

impl PartialOrd for AdjustedByte {
    #[inline]
    fn partial_cmp(&self, other: &AdjustedByte) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for AdjustedByte {
    #[inline]
    fn cmp(&self, other: &AdjustedByte) -> Ordering {
        let s = self.get_byte();
        let o = other.get_byte();

        s.cmp(&o)
    }
}

impl Display for AdjustedByte {
    /// Formats the value using the given formatter.
    ///
    /// # Examples
    ///
    /// ```
    /// use byte_unit::{Byte, Unit};
    ///
    /// let byte = Byte::from_u64_with_unit(1555, Unit::KB).unwrap();
    ///
    /// let adjusted_byte = byte.get_adjusted_unit(Unit::MB);
    ///
    /// assert_eq!("1.555 MB", adjusted_byte.to_string());
    /// ```
    ///
    /// ```
    /// use byte_unit::{Byte, UnitType};
    ///
    /// let byte = Byte::from_u64(10000);
    ///
    /// let adjusted_byte_based_2 = byte.get_appropriate_unit(UnitType::Binary);
    /// let adjusted_byte_based_10 = byte.get_appropriate_unit(UnitType::Decimal);
    ///
    /// assert_eq!("9.765625 KiB", format!("{adjusted_byte_based_2}"));
    /// assert_eq!("10 KB", format!("{adjusted_byte_based_10}"));
    ///
    /// // with precision
    /// assert_eq!("9.77 KiB", format!("{adjusted_byte_based_2:.2}"));
    /// assert_eq!("10.00 KB", format!("{adjusted_byte_based_10:.2}"));
    ///
    /// // without any unnecessary fractional part
    /// assert_eq!("9.77 KiB", format!("{adjusted_byte_based_2:#.2}"));
    /// assert_eq!("10 KB", format!("{adjusted_byte_based_10:#.2}"));
    ///
    /// // with a width, left alignment
    /// assert_eq!("9.77   KiB", format!("{adjusted_byte_based_2:10.2}"));
    /// assert_eq!("10.00   KB", format!("{adjusted_byte_based_10:10.2}"));
    ///
    /// // with a width, right alignment
    /// assert_eq!("  9.77 KiB", format!("{adjusted_byte_based_2:>10.2}"));
    /// assert_eq!("  10.00 KB", format!("{adjusted_byte_based_10:>10.2}"));
    ///
    /// // with a width, right alignment, more spaces between the value and the unit
    /// assert_eq!("  9.77 KiB", format!("{adjusted_byte_based_2:>+10.2}"));
    /// assert_eq!(" 10.00  KB", format!("{adjusted_byte_based_10:>+10.2}"));
    ///
    /// // no spaces between the value and the unit
    /// assert_eq!("9.765625KiB", format!("{adjusted_byte_based_2:-}"));
    /// assert_eq!("10KB", format!("{adjusted_byte_based_10:-}"));
    /// ```
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let Self {
            value,
            unit,
        } = self;
        let handle_basic_precision = |precision: usize, f: &mut Formatter<'_>| -> fmt::Result {
            if f.alternate() {
                let value = round_fractional_part_f64(*value, precision);

                f.write_fmt(format_args!("{value}"))
            } else if matches!(unit, Unit::Bit | Unit::B) {
                f.write_fmt(format_args!("{value}"))
            } else {
                f.write_fmt(format_args!("{value:.precision$}"))
            }
        };

        let space_length = if f.sign_plus() {
            4 - unit.as_str().len()
        } else if f.sign_minus() {
            0
        } else {
            1
        };

        if let Some(mut width) = f.width() {
            let l = unit.as_str().len() + space_length;

            if let Some(precision) = f.precision() {
                if width > l + 1 {
                    width -= l;

                    let alignment = f.align().unwrap_or(Alignment::Left);

                    if f.alternate() {
                        let value = round_fractional_part_f64(*value, precision);

                        match alignment {
                            Alignment::Left | Alignment::Center => {
                                f.write_fmt(format_args!("{value:<width$}"))?
                            },
                            Alignment::Right => f.write_fmt(format_args!("{value:>width$}"))?,
                        }
                    } else {
                        match alignment {
                            Alignment::Left | Alignment::Center => {
                                f.write_fmt(format_args!("{value:<width$.precision$}"))?
                            },
                            Alignment::Right => {
                                f.write_fmt(format_args!("{value:>width$.precision$}"))?
                            },
                        }
                    }
                } else {
                    handle_basic_precision(precision, f)?;
                }
            } else if width > l + 1 {
                width -= l;

                let alignment = f.align().unwrap_or(Alignment::Left);

                match alignment {
                    Alignment::Left | Alignment::Center => {
                        f.write_fmt(format_args!("{value:<width$}"))?
                    },
                    Alignment::Right => f.write_fmt(format_args!("{value:>width$}"))?,
                }
            } else {
                f.write_fmt(format_args!("{value}"))?;
            }
        } else if let Some(precision) = f.precision() {
            handle_basic_precision(precision, f)?;
        } else {
            f.write_fmt(format_args!("{value}"))?;
        }

        for _ in 0..space_length {
            f.write_char(' ')?;
        }

        f.write_fmt(format_args!("{unit}"))
    }
}

/// Methods for getting values.
impl AdjustedByte {
    /// Get the value.
    #[inline]
    pub const fn get_value(&self) -> f64 {
        self.value
    }

    /// Get the unit.
    #[inline]
    pub const fn get_unit(&self) -> Unit {
        self.unit
    }

    /// Create a new `Byte` instance from this `AdjustedByte` instance.
    ///
    /// # Examples
    ///
    /// ```
    /// use byte_unit::{Byte, Unit};
    ///
    /// let byte = Byte::from_u64_with_unit(1555, Unit::KB).unwrap();
    ///
    /// let adjusted_byte = byte.get_adjusted_unit(Unit::MB);
    ///
    /// let byte_back = adjusted_byte.get_byte();
    ///
    /// assert_eq!(byte, byte_back);
    /// ```
    ///
    /// # Points to Note
    ///
    /// * The result may not be logically equal to the original `Byte` instance due to the accuracy of floating-point numbers.
    #[inline]
    pub fn get_byte(&self) -> Byte {
        Byte::from_f64_with_unit(self.value, self.unit).unwrap()
    }
}

/// Associated functions for generating `AdjustedByte`.
impl Byte {
    /// Adjust the unit and value for this `Byte` instance.
    ///
    /// # Examples
    ///
    /// ```
    /// use byte_unit::{AdjustedByte, Byte, Unit};
    ///
    /// let byte = Byte::parse_str("123KiB", true).unwrap();
    ///
    /// let adjusted_byte = byte.get_adjusted_unit(Unit::KB);
    ///
    /// assert_eq!("125.952 KB", adjusted_byte.to_string());
    /// ```
    ///
    /// ```
    /// use byte_unit::{AdjustedByte, Byte, Unit};
    ///
    /// let byte = Byte::parse_str("50.84 MB", true).unwrap();
    ///
    /// let adjusted_byte = byte.get_adjusted_unit(Unit::MiB);
    ///
    /// assert_eq!("48.48480224609375 MiB", adjusted_byte.to_string());
    /// ```
    #[inline]
    pub fn get_adjusted_unit(self, unit: Unit) -> AdjustedByte {
        let byte_v = self.as_u128();

        let value = match unit {
            Unit::Bit => (byte_v << 3) as f64,
            Unit::B => byte_v as f64,
            _ => byte_v as f64 / unit.as_bytes_u128() as f64,
        };

        AdjustedByte {
            value,
            unit,
        }
    }

    /// Find the appropriate unit and value for this `Byte` instance.
    ///
    /// # Examples
    ///
    /// ```
    /// use byte_unit::{Byte, UnitType};
    ///
    /// let byte = Byte::parse_str("123KiB", true).unwrap();
    ///
    /// let adjusted_byte = byte.get_appropriate_unit(UnitType::Decimal);
    ///
    /// assert_eq!("125.952 KB", adjusted_byte.to_string());
    /// ```
    ///
    /// ```
    /// use byte_unit::{Byte, UnitType};
    ///
    /// let byte = Byte::parse_str("50.84 MB", true).unwrap();
    ///
    /// let adjusted_byte = byte.get_appropriate_unit(UnitType::Binary);
    ///
    /// assert_eq!("48.48480224609375 MiB", adjusted_byte.to_string());
    /// ```
    pub fn get_appropriate_unit(&self, unit_type: UnitType) -> AdjustedByte {
        let a = Unit::get_multiples_bytes();

        let (skip, step) = match unit_type {
            UnitType::Binary => (0, 2),
            UnitType::Decimal => (1, 2),
            UnitType::Both => (0, 1),
        };

        let bytes_v = self.as_u128();

        for unit in a.iter().rev().skip(skip).step_by(step) {
            if bytes_v >= unit.as_bytes_u128() {
                return self.get_adjusted_unit(*unit);
            }
        }

        self.get_adjusted_unit(Unit::B)
    }
}