net-bytes 0.3.0

A Rust library for handling file sizes, download speeds, and download acceleration with support for both SI and IEC standards
Documentation
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! File size formatting utilities
//!
//! Provides functionality for formatting file sizes with support for both
//! SI (base-1000) and IEC (base-1024) standards.
//!
//! 提供文件大小格式化功能,支持 SI (base-1000) 和 IEC (base-1024) 两种标准。

use crate::{FileSizeFormat, format_parts_scaled, SCALE};
use std::num::NonZeroU64;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};

/// A non-zero file size representation
///
/// 一个表示非零文件大小的结构体。
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct NonZeroFileSize {
    bytes: NonZeroU64,
}

impl NonZeroFileSize {
    /// Create a new FileSize instance
    ///
    /// 创建一个新的 FileSize 实例
    #[inline]
    pub fn new(bytes: NonZeroU64) -> Self {
        Self { bytes }
    }

    /// Get the inner NonZeroU64 byte value
    ///
    /// 获取内部的 NonZeroU64 字节值
    #[inline]
    pub fn get_nonzero(&self) -> NonZeroU64 {
        self.bytes
    }

    /// Get the byte value as u64
    ///
    /// 以 u64 的形式获取字节值
    #[inline]
    pub fn as_u64(&self) -> u64 {
        self.bytes.get()
    }
}

// Implement FileSizeFormat for FileSize
impl FileSizeFormat for NonZeroFileSize {
    /// Returns the formatted value and unit in SI (base-1000) standard
    ///
    /// The formatted_value is returned as String to ensure correct decimal places (e.g., "1.00")
    ///
    /// 返回 SI (base-1000) 标准的 (formatted_value, unit)
    ///
    /// formatted_value 作为 String 返回,以保证正确的小数位数 (例如 "1.00")
    #[inline]
    fn get_si_parts(&self) -> (String, &'static str) {
        const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
        format_parts_scaled((self.bytes.get() as u128) * SCALE, 1000, UNITS)
    }

    /// Returns the formatted value and unit in IEC (base-1024) standard
    ///
    /// The formatted_value is returned as String to ensure correct decimal places (e.g., "1.00")
    ///
    /// 返回 IEC (base-1024) 标准的 (formatted_value, unit)
    ///
    /// formatted_value 作为 String 返回,以保证正确的小数位数 (例如 "1.00")
    #[inline]
    fn get_iec_parts(&self) -> (String, &'static str) {
        format_iec_parts(self.bytes.get())
    }
}

/// A file size representation that can be zero
///
/// 一个可以表示零的文件大小结构体。
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct FileSize {
    bytes: u64,
}

impl FileSize {
    /// Create a new FileSize instance from bytes
    ///
    /// 从字节数创建一个新的 FileSize 实例
    #[inline]
    pub const fn new(bytes: u64) -> Self {
        Self { bytes }
    }

    /// Get the byte value as u64
    ///
    /// 以 u64 的形式获取字节值
    #[inline]
    pub const fn as_u64(&self) -> u64 {
        self.bytes
    }

    /// Convert to NonZeroFileSize if the value is not zero
    ///
    /// 如果值不为零,则转换为 NonZeroFileSize
    #[inline]
    pub fn to_nonzero(&self) -> Option<NonZeroFileSize> {
        NonZeroU64::new(self.bytes).map(NonZeroFileSize::new)
    }
}

// Implement arithmetic operations for FileSize
impl Add for FileSize {
    type Output = Self;

    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        Self {
            bytes: self.bytes + rhs.bytes,
        }
    }
}

impl Sub for FileSize {
    type Output = Self;

    #[inline]
    fn sub(self, rhs: Self) -> Self::Output {
        Self {
            bytes: self.bytes.saturating_sub(rhs.bytes),
        }
    }
}

impl Mul<u64> for FileSize {
    type Output = Self;

    #[inline]
    fn mul(self, rhs: u64) -> Self::Output {
        Self {
            bytes: self.bytes.saturating_mul(rhs),
        }
    }
}

impl Div<u64> for FileSize {
    type Output = Self;

    #[inline]
    fn div(self, rhs: u64) -> Self::Output {
        Self {
            bytes: if rhs == 0 { 0 } else { self.bytes / rhs },
        }
    }
}

// Implement assignment operators
impl AddAssign for FileSize {
    #[inline]
    fn add_assign(&mut self, rhs: Self) {
        self.bytes = self.bytes.saturating_add(rhs.bytes);
    }
}

impl SubAssign for FileSize {
    #[inline]
    fn sub_assign(&mut self, rhs: Self) {
        self.bytes = self.bytes.saturating_sub(rhs.bytes);
    }
}

impl MulAssign<u64> for FileSize {
    #[inline]
    fn mul_assign(&mut self, rhs: u64) {
        self.bytes = self.bytes.saturating_mul(rhs);
    }
}

impl DivAssign<u64> for FileSize {
    #[inline]
    fn div_assign(&mut self, rhs: u64) {
        if rhs != 0 {
            self.bytes /= rhs;
        } else {
            self.bytes = 0;
        }
    }
}

// Implement From and TryFrom for conversions
impl From<u64> for FileSize {
    #[inline]
    fn from(bytes: u64) -> Self {
        Self::new(bytes)
    }
}

impl From<NonZeroFileSize> for FileSize {
    #[inline]
    fn from(size: NonZeroFileSize) -> Self {
        Self::new(size.as_u64())
    }
}

impl TryFrom<FileSize> for NonZeroFileSize {
    type Error = std::num::TryFromIntError;

    #[inline]
    fn try_from(value: FileSize) -> Result<Self, Self::Error> {
        NonZeroU64::try_from(value.bytes).map(NonZeroFileSize::new)
    }
}

// Implement FileSizeFormat for FileSize
impl FileSizeFormat for FileSize {
    /// Returns the formatted value and unit in SI (base-1000) standard
    ///
    /// The formatted_value is returned as String to ensure correct decimal places (e.g., "1.00")
    ///
    /// 返回 SI (base-1000) 标准的 (formatted_value, unit)
    ///
    /// formatted_value 作为 String 返回,以保证正确的小数位数 (例如 "1.00")
    #[inline]
    fn get_si_parts(&self) -> (String, &'static str) {
        const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
        format_parts_scaled((self.bytes as u128) * SCALE, 1000, UNITS)
    }

    /// Returns the formatted value and unit in IEC (base-1024) standard
    ///
    /// The formatted_value is returned as String to ensure correct decimal places (e.g., "1.00")
    ///
    /// 返回 IEC (base-1024) 标准的 (formatted_value, unit)
    ///
    /// formatted_value 作为 String 返回,以保证正确的小数位数 (例如 "1.00")
    #[inline]
    fn get_iec_parts(&self) -> (String, &'static str) {
        format_iec_parts(self.bytes)
    }
}

/// Format bytes using IEC (base-1024) units
///
/// 使用 IEC (base-1024) 单位格式化字节数
fn format_iec_parts(bytes: u64) -> (String, &'static str) {
    const UNITS: [&str; 9] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"];
    const BASE: u64 = 1024;

    let mut value = bytes as f64;
    let mut unit_index = 0;

    while value >= (BASE as f64) && unit_index < UNITS.len() - 1 {
        value /= BASE as f64;
        unit_index += 1;
    }

    // Format with appropriate decimal places
    let formatted = if value < 10.0 {
        // Always show 2 decimal places for values < 10
        format!("{:.2}", value)
    } else {
        // Always show 1 decimal place for values >= 10
        format!("{:.1}", value)
    };

    (formatted, UNITS[unit_index])
}

// 单元测试
#[cfg(test)]
mod tests {
    use crate::{FileSizeFormat, FormattedValue, SizeStandard};

    use super::{FileSize, NonZeroFileSize};
    use std::num::NonZeroU64;

    /// Helper function - SI standard
    ///
    /// 辅助函数 - SI 标准
    fn format_test_si(bytes: u64) -> String {
        let nz = NonZeroU64::new(bytes).expect("测试值不能为零");
        FormattedValue::new(NonZeroFileSize::new(nz), SizeStandard::SI).to_string()
    }

    /// Helper function - IEC standard
    ///
    /// 辅助函数 - IEC 标准
    fn format_test_iec(bytes: u64) -> String {
        let nz = NonZeroU64::new(bytes).expect("测试值不能为零");
        FormattedValue::new(NonZeroFileSize::new(nz), SizeStandard::IEC).to_string()
    }

    // --- Tests for SI (base-1000) standard ---
    // --- SI (base-1000) 测试 ---
    #[test]
    fn test_si_bytes() {
        assert_eq!(format_test_si(512), "512.0 B");
        assert_eq!(format_test_si(999), "999.0 B");
    }

    #[test]
    fn test_si_kilobytes() {
        assert_eq!(format_test_si(1000), "1.00 KB");
        // 1.024 -> 1.02 (2 位小数)
        assert_eq!(format_test_si(1024), "1.02 KB");
        // 9.999 -> 10.00 (2 位小数, 舍入)
        assert_eq!(format_test_si(9999), "10.00 KB");
        // 10.0 (1 位小数)
        assert_eq!(format_test_si(10000), "10.0 KB");
        // 100.0 (1 位小数)
        assert_eq!(format_test_si(100000), "100.0 KB");
    }

    #[test]
    fn test_si_megabytes() {
        assert_eq!(format_test_si(1_000_000), "1.00 MB");
    }

    // --- Tests for IEC (base-1024) standard ---
    // --- IEC (base-1024) 测试 ---
    #[test]
    fn test_iec_bytes() {
        assert_eq!(format_test_iec(512), "512.0 B");
        assert_eq!(format_test_iec(1023), "1023.0 B");
    }

    #[test]
    fn test_iec_kibibytes() {
        assert_eq!(format_test_iec(1024), "1.00 KiB");
        // 1.464... -> 1.46 (2 位小数)
        assert_eq!(format_test_iec(1500), "1.46 KiB");
        // 9.999... -> 10.00 (2 位小数, 舍入)
        let bytes_near_10 = (9.999 * 1024.0) as u64;
        assert_eq!(format_test_iec(bytes_near_10), "10.00 KiB");
        // 10.0 (1 位小数)
        assert_eq!(format_test_iec(10 * 1024), "10.0 KiB");
        // 100.0 (1 位小数)
        assert_eq!(format_test_iec(100 * 1024), "100.0 KiB");
    }

    #[test]
    fn test_iec_mebibytes() {
        assert_eq!(format_test_iec(1024 * 1024), "1.00 MiB");
    }

    // --- Tests for FileSize ---
    // --- FileSize 测试 ---
    #[test]
    fn test_filesize_arithmetic() {
        let size1 = FileSize::new(1024);
        let size2 = FileSize::new(2048);

        // Addition
        assert_eq!((size1 + size2).as_u64(), 3072);

        // Subtraction
        assert_eq!((size2 - size1).as_u64(), 1024);
        assert_eq!((size1 - size2).as_u64(), 0); // Saturating sub

        // Multiplication
        assert_eq!((size1 * 2).as_u64(), 2048);

        // Division
        assert_eq!((size2 / 2).as_u64(), 1024);

        // Division by zero
        assert_eq!((size1 / 0).as_u64(), 0);
    }

    #[test]
    fn test_filesize_formatting() {
        let size = FileSize::new(1500);

        // Test SI formatting
        let (value, unit) = size.get_si_parts();
        assert_eq!(&value, "1.50");
        assert_eq!(unit, "KB");

        // Test IEC formatting
        let (value, unit) = size.get_iec_parts();
        assert_eq!(&value, "1.46");
        assert_eq!(unit, "KiB");
    }

    #[test]
    fn test_filesize_conversions() {
        // From u64
        let size = FileSize::from(1024u64);
        assert_eq!(size.as_u64(), 1024);

        // From NonZeroFileSize
        let non_zero = NonZeroFileSize::new(NonZeroU64::new(2048).unwrap());
        let size = FileSize::from(non_zero);
        assert_eq!(size.as_u64(), 2048);

        // To NonZeroFileSize
        let size = FileSize::new(1024);
        let non_zero = NonZeroFileSize::try_from(size);
        assert!(non_zero.is_ok());
        assert_eq!(non_zero.unwrap().as_u64(), 1024);

        // Zero to NonZeroFileSize should fail
        let zero = FileSize::new(0);
        let result = NonZeroFileSize::try_from(zero);
        assert!(result.is_err());
    }
}