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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
/*!
# Byte Unit

A library for interaction with units of bytes.

The units are **B** for 1 byte, **KB** for 1000 bytes, **KiB** for 1024 bytes, **MB** for 1000000 bytes, **MiB** for 1048576 bytes, etc, and up to **PiB** which is 1125899906842624 bytes.

The data type for storing the size of bytes is `u128`, so don't worry about the overflow problem.

## Usage

### Macros

There are `n_*_bytes` macros can be used. The star `*` means the unit. For example, `n_gb_bytes` can be used to get a **n-GB** value in bytes.

```rust
#[macro_use] extern crate byte_unit;

let result = n_gb_bytes!(4);

assert_eq!(4000000000u128, result);
```

You may need to assign a primitive type if the `n` is not an integer.

```rust
#[macro_use] extern crate byte_unit;

let result = n_gb_bytes!(2.5, f64);

assert_eq!(2500000000u128, result);
```

### Byte

The `Byte` structure can be used for representing a size of bytes.

The `from_str` associated function can parse any **SIZE** string and return a `Byte` instance in common usage. The format of a **SIZE** string is like "123", "123KiB" or "50.84 MB".

```rust
extern crate byte_unit;

use byte_unit::Byte;

let result = Byte::from_str("50.84 MB").unwrap();

assert_eq!(50840000u128, result.get_bytes());
```

You can also use the `from_bytes` and `from_unit` associated functions to create a `Byte` instance.

```rust
extern crate byte_unit;

use byte_unit::Byte;

let result = Byte::from_bytes(1500000u128);

assert_eq!(1500000u128, result.get_bytes());
```

```rust
extern crate byte_unit;

use byte_unit::{Byte, ByteUnit};

let result = Byte::from_unit(1500f64, ByteUnit::KB).unwrap();

assert_eq!(1500000u128, result.get_bytes());
```

### AdjustedByte

To change the unit of a `Byte` instance, you can use the `get_adjusted_unit` method.

```rust
extern crate byte_unit;

use byte_unit::{Byte, ByteUnit};

let byte = Byte::from_str("123KiB").unwrap();

let adjusted_byte = byte.get_adjusted_unit(ByteUnit::KB);

assert_eq!("125.95 KB", adjusted_byte.to_string());
```

To change the unit of a `Byte` instance automatically and appropriately, you can use the `get_appropriate_unit` method.

```rust
extern crate byte_unit;

use byte_unit::Byte;

let byte = Byte::from_bytes(1500000u128);

let adjusted_byte = byte.get_appropriate_unit(false);

assert_eq!("1.50 MB", adjusted_byte.to_string());
```

```rust
extern crate byte_unit;

use byte_unit::Byte;

let byte = Byte::from_bytes(1500000u128);

let adjusted_byte = byte.get_appropriate_unit(true);

assert_eq!("1.43 MiB", adjusted_byte.to_string());
```

The number of fractional digits created by the `to_string` method of a `AdjustedByte` instance is always 2.

To change the number of fractional digits in the formatted string, you can use the `format` method instead.

```rust
extern crate byte_unit;

use byte_unit::Byte;

let byte = Byte::from_bytes(1500000u128);

let adjusted_byte = byte.get_appropriate_unit(false);

assert_eq!("1.5 MB", adjusted_byte.format(1));
```
*/

#![no_std]

#[macro_use]
extern crate alloc;

mod byte_unit;
mod macros;

pub use crate::byte_unit::ByteUnit;

use alloc::fmt::{self, Display, Formatter};
use alloc::str::FromStr;
use alloc::string::String;

#[derive(Debug, PartialEq, Eq)]
/// Different error types for `Byte` and `ByteUnit`.
pub enum ByteError {
    ValueIncorrect(String),
    UnitIncorrect(String),
}

#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq)]
/// Represent the n-bytes data. Use associated functions: `from_unit`, `from_bytes`, `from_str`, to create the instance.
pub struct Byte {
    bytes: u128,
}

impl Display for Byte {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        f.write_fmt(format_args!("{}", self.bytes))
    }
}

impl FromStr for Byte {
    type Err = ByteError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Byte::from_str(s)
    }
}

impl Byte {
    /// Create a new `Byte` object from a specified value and a unit. **Accuracy** should be taken care of.
    ///
    /// ## Examples
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::{Byte, ByteUnit};
    ///
    /// let result = Byte::from_unit(1500f64, ByteUnit::KB).unwrap();
    ///
    /// assert_eq!(result.get_bytes(), 1500000u128);
    /// ```
    #[inline]
    pub fn from_unit(value: f64, unit: ByteUnit) -> Result<Byte, ByteError> {
        if value < 0f64 {
            return Err(ByteError::ValueIncorrect(format!(
                "The value `{}` for creating a `Byte` instance is negative.",
                value
            )));
        }

        let bytes = get_bytes(value, unit);

        Ok(Byte {
            bytes,
        })
    }

    /// Create a new `Byte` object from bytes.
    ///
    /// ## Examples
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::{Byte, ByteUnit};
    ///
    /// let result = Byte::from_bytes(1500000u128);
    ///
    /// assert_eq!(result.get_bytes(), 1500000u128);
    /// ```
    #[inline]
    pub fn from_bytes(bytes: u128) -> Byte {
        Byte {
            bytes,
        }
    }

    /// Create a new `Byte` object from string. **Accuracy** should be taken care of.
    ///
    /// ## Examples
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::{Byte, ByteUnit};
    ///
    /// let result = Byte::from_str("123KiB").unwrap();
    ///
    /// assert_eq!(result, Byte::from_unit(123f64, ByteUnit::KiB).unwrap());
    /// ```
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::{Byte, ByteUnit};
    ///
    /// let result = Byte::from_str("50.84 MB").unwrap();
    ///
    /// assert_eq!(result, Byte::from_unit(50.84f64, ByteUnit::MB).unwrap());
    /// ```
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::{Byte, ByteUnit};
    ///
    /// let result = Byte::from_str("8 B").unwrap(); // 8 bytes
    ///
    /// assert_eq!(result.get_bytes(), 8u128);
    /// ```
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::{Byte, ByteUnit};
    ///
    /// let result = Byte::from_str("8").unwrap(); // 8 bytes
    ///
    /// assert_eq!(result.get_bytes(), 8u128);
    /// ```
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::{Byte, ByteUnit};
    ///
    /// let result = Byte::from_str("8 b").unwrap(); // 8 bytes
    ///
    /// assert_eq!(result.get_bytes(), 8u128);
    /// ```
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::{Byte, ByteUnit};
    ///
    /// let result = Byte::from_str("8 kb").unwrap(); // 8K bytes
    ///
    /// assert_eq!(result.get_bytes(), 8000u128);
    /// ```
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::{Byte, ByteUnit};
    ///
    /// let result = Byte::from_str("8 kib").unwrap(); // 8Ki bytes
    ///
    /// assert_eq!(result.get_bytes(), 8192u128);
    /// ```
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::{Byte, ByteUnit};
    ///
    /// let result = Byte::from_str("8 k").unwrap(); // 8K bytes
    ///
    /// assert_eq!(result.get_bytes(), 8000u128);
    /// ```
    #[allow(clippy::should_implement_trait)]
    pub fn from_str<S: AsRef<str>>(s: S) -> Result<Byte, ByteError> {
        let s = s.as_ref().trim();

        let mut chars = s.chars();

        let mut value = match chars.next() {
            Some(c) => {
                match c {
                    '0'..='9' => f64::from(c as u8 - b'0'),
                    _ => {
                        return Err(ByteError::ValueIncorrect(format!(
                            "The character {:?} is not a number.",
                            c
                        )))
                    }
                }
            }
            None => return Err(ByteError::ValueIncorrect(String::from("No value."))),
        };

        let c = 'outer: loop {
            match chars.next() {
                Some(c) => {
                    match c {
                        '0'..='9' => {
                            value = value * 10.0 + f64::from(c as u8 - b'0');
                        }
                        '.' => {
                            let mut i = 0.1;

                            loop {
                                match chars.next() {
                                    Some(c) => {
                                        if c >= '0' && c <= '9' {
                                            value += f64::from(c as u8 - b'0') * i;

                                            i /= 10.0;
                                        } else {
                                            if (i * 10.0) as u8 == 1 {
                                                return Err(ByteError::ValueIncorrect(format!(
                                                    "The character {:?} is not a number.",
                                                    c
                                                )));
                                            }

                                            match c {
                                                ' ' => {
                                                    loop {
                                                        match chars.next() {
                                                            Some(c) => {
                                                                match c {
                                                                    ' ' => (),
                                                                    _ => break 'outer Some(c),
                                                                }
                                                            }
                                                            None => break 'outer None,
                                                        }
                                                    }
                                                }
                                                _ => break 'outer Some(c),
                                            }
                                        }
                                    }
                                    None => {
                                        if (i * 10.0) as u8 == 1 {
                                            return Err(ByteError::ValueIncorrect(format!(
                                                "The character {:?} is not a number.",
                                                c
                                            )));
                                        }

                                        break 'outer None;
                                    }
                                }
                            }
                        }
                        ' ' => {
                            loop {
                                match chars.next() {
                                    Some(c) => {
                                        match c {
                                            ' ' => (),
                                            _ => break 'outer Some(c),
                                        }
                                    }
                                    None => break 'outer None,
                                }
                            }
                        }
                        _ => break 'outer Some(c),
                    }
                }
                None => break None,
            }
        };

        let unit = match c {
            Some(c) => {
                match c.to_ascii_uppercase() {
                    'B' => if chars.next().is_some() {
                        return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. No character is expected.", c)));
                    } else {
                        ByteUnit::B
                    }
                    'K' => match chars.next() {
                        Some(c) => match c.to_ascii_uppercase() {
                            'I' => match chars.next() {
                                Some(c) => match c.to_ascii_uppercase() {
                                    'B' => ByteUnit::KiB,
                                    _ => return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. A 'B' is expected.", c)))
                                }
                                None => ByteUnit::KiB
                            }
                            'B' => if chars.next().is_some() {
                                return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. No character is expected.", c)));
                            } else {
                                ByteUnit::KB
                            }
                            _ => return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. A 'B' or an 'i' is expected.", c)))
                        }
                        None => ByteUnit::KB
                    }
                    'M' => match chars.next() {
                        Some(c) => match c.to_ascii_uppercase() {
                            'I' => match chars.next() {
                                Some(c) => match c.to_ascii_uppercase() {
                                    'B' => ByteUnit::MiB,
                                    _ => return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. A 'B' is expected.", c)))
                                }
                                None => ByteUnit::MiB
                            }
                            'B' => if chars.next().is_some() {
                                return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. No character is expected.", c)));
                            } else {
                                ByteUnit::MB
                            },
                            _ => return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. A 'B' or an 'i' is expected.", c)))
                        }
                        None => ByteUnit::MB
                    },
                    'G' => match chars.next() {
                        Some(c) => match c.to_ascii_uppercase() {
                            'I' => match chars.next() {
                                Some(c) => match c.to_ascii_uppercase() {
                                    'B' => ByteUnit::GiB,
                                    _ => return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. A 'B' is expected.", c)))
                                }
                                None => ByteUnit::GiB
                            }
                            'B' => if chars.next().is_some() {
                                return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. No character is expected.", c)));
                            } else {
                                ByteUnit::GB
                            },
                            _ => return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. A 'B' or an 'i' is expected.", c)))
                        }
                        None => ByteUnit::GB
                    },
                    'T' => match chars.next() {
                        Some(c) => match c.to_ascii_uppercase() {
                            'I' => match chars.next() {
                                Some(c) => match c.to_ascii_uppercase() {
                                    'B' => ByteUnit::TiB,
                                    _ => return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. A 'B' is expected.", c)))
                                }
                                None => ByteUnit::TiB
                            }
                            'B' => if chars.next().is_some() {
                                return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. No character is expected.", c)));
                            } else {
                                ByteUnit::TB
                            },
                            _ => return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. A 'B' or an 'i' is expected.", c)))
                        }
                        None => ByteUnit::TB
                    },
                    'P' => match chars.next() {
                        Some(c) => match c.to_ascii_uppercase() {
                            'I' => match chars.next() {
                                Some(c) => match c.to_ascii_uppercase() {
                                    'B' => ByteUnit::PiB,
                                    _ => return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. A 'B' is expected.", c)))
                                }
                                None => ByteUnit::PiB
                            }
                            'B' => if chars.next().is_some() {
                                return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. No character is expected.", c)));
                            } else {
                                ByteUnit::PB
                            },
                            _ => return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. A 'B' or an 'i' is expected.", c)))
                        }
                        None => ByteUnit::PB
                    },
                    _ => return Err(ByteError::UnitIncorrect(format!("The character {:?} is incorrect. A 'B', a 'K', a 'M', a 'G', a 'T', a 'P' or no character is expected.", c)))
                }
            }
            None => ByteUnit::B
        };

        let bytes = get_bytes(value, unit);

        Ok(Byte {
            bytes,
        })
    }

    /// Get bytes represented by a `Byte` object.
    ///
    /// ## Examples
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::Byte;
    ///
    /// let byte = Byte::from_str("123KiB").unwrap();
    ///
    /// let result = byte.get_bytes();
    ///
    /// assert_eq!(result, 125952);
    /// ```
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::Byte;
    ///
    /// let byte = Byte::from_str("50.84 MB").unwrap();
    ///
    /// let result = byte.get_bytes();
    ///
    /// assert_eq!(result, 50840000);
    /// ```
    #[inline]
    pub fn get_bytes(&self) -> u128 {
        self.bytes
    }

    /// Find the appropriate unit and value for `Byte` object. **Accuracy** should be taken care of.
    ///
    /// ## Examples
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::Byte;
    ///
    /// let byte = Byte::from_str("123KiB").unwrap();
    ///
    /// let adjusted_byte = byte.get_appropriate_unit(false);
    ///
    /// assert_eq!(adjusted_byte.to_string(), "125.95 KB");
    /// ```
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::Byte;
    ///
    /// let byte = Byte::from_str("50.84 MB").unwrap();
    ///
    /// let adjusted_byte = byte.get_appropriate_unit(true);
    ///
    /// assert_eq!(adjusted_byte.to_string(), "48.48 MiB");
    /// ```
    #[allow(clippy::unnecessary_cast)]
    pub fn get_appropriate_unit(&self, binary_multiples: bool) -> AdjustedByte {
        let bytes = self.bytes;

        if binary_multiples {
            if bytes > n_pib_bytes!() {
                AdjustedByte {
                    value: bytes as f64 / n_pib_bytes!() as f64,
                    unit: ByteUnit::PiB,
                }
            } else if bytes > n_tib_bytes!() {
                AdjustedByte {
                    value: bytes as f64 / n_tib_bytes!() as f64,
                    unit: ByteUnit::TiB,
                }
            } else if bytes > n_gib_bytes!() {
                AdjustedByte {
                    value: bytes as f64 / n_gib_bytes!() as f64,
                    unit: ByteUnit::GiB,
                }
            } else if bytes > n_mib_bytes!() {
                AdjustedByte {
                    value: bytes as f64 / n_mib_bytes!() as f64,
                    unit: ByteUnit::MiB,
                }
            } else if bytes > n_kib_bytes!() {
                AdjustedByte {
                    value: bytes as f64 / n_kib_bytes!() as f64,
                    unit: ByteUnit::KiB,
                }
            } else {
                AdjustedByte {
                    value: bytes as f64,
                    unit: ByteUnit::B,
                }
            }
        } else if bytes > n_pb_bytes!() {
            AdjustedByte {
                value: bytes as f64 / n_pb_bytes!() as f64,
                unit: ByteUnit::PB,
            }
        } else if bytes > n_tb_bytes!() {
            AdjustedByte {
                value: bytes as f64 / n_tb_bytes!() as f64,
                unit: ByteUnit::TB,
            }
        } else if bytes > n_gb_bytes!() {
            AdjustedByte {
                value: bytes as f64 / n_gb_bytes!() as f64,
                unit: ByteUnit::GB,
            }
        } else if bytes > n_mb_bytes!() {
            AdjustedByte {
                value: bytes as f64 / n_mb_bytes!() as f64,
                unit: ByteUnit::MB,
            }
        } else if bytes > n_kb_bytes!() {
            AdjustedByte {
                value: bytes as f64 / n_kb_bytes!() as f64,
                unit: ByteUnit::KB,
            }
        } else {
            AdjustedByte {
                value: bytes as f64,
                unit: ByteUnit::B,
            }
        }
    }

    /// Adjust the unit and value for `Byte` object. **Accuracy** should be taken care of.
    ///
    /// ## Examples
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::{Byte, ByteUnit};
    ///
    /// let byte = Byte::from_str("123KiB").unwrap();
    ///
    /// let adjusted_byte = byte.get_adjusted_unit(ByteUnit::KB);
    ///
    /// assert_eq!(adjusted_byte.to_string(), "125.95 KB");
    /// ```
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::{Byte, ByteUnit};
    ///
    /// let byte = Byte::from_str("50.84 MB").unwrap();
    ///
    /// let adjusted_byte = byte.get_adjusted_unit(ByteUnit::MiB);
    ///
    /// assert_eq!(adjusted_byte.to_string(), "48.48 MiB");
    /// ```
    #[allow(clippy::unnecessary_cast)]
    pub fn get_adjusted_unit(&self, unit: ByteUnit) -> AdjustedByte {
        let bytes = self.bytes;

        let value = match unit {
            ByteUnit::B => bytes as f64,
            ByteUnit::KB => bytes as f64 / n_kb_bytes!() as f64,
            ByteUnit::KiB => bytes as f64 / n_kib_bytes!() as f64,
            ByteUnit::MB => bytes as f64 / n_mb_bytes!() as f64,
            ByteUnit::MiB => bytes as f64 / n_mib_bytes!() as f64,
            ByteUnit::GB => bytes as f64 / n_gb_bytes!() as f64,
            ByteUnit::GiB => bytes as f64 / n_gib_bytes!() as f64,
            ByteUnit::TB => bytes as f64 / n_tb_bytes!() as f64,
            ByteUnit::TiB => bytes as f64 / n_tib_bytes!() as f64,
            ByteUnit::PB => bytes as f64 / n_pb_bytes!() as f64,
            ByteUnit::PiB => bytes as f64 / n_pib_bytes!() as f64,
        };

        AdjustedByte {
            value,
            unit,
        }
    }
}

#[derive(Debug, Clone, Copy)]
/// Generated from the `get_appropriate_unit` and `get_adjusted_unit` methods of a `Byte` object.
pub struct AdjustedByte {
    value: f64,
    unit: ByteUnit,
}

impl PartialEq for AdjustedByte {
    /// Deal with the logical numeric equivalent.
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::{Byte, ByteUnit};
    ///
    /// let byte1 = Byte::from_unit(1024f64, ByteUnit::KiB).unwrap();
    /// let byte2 = Byte::from_unit(1024f64, ByteUnit::KiB).unwrap();
    ///
    /// assert_eq!(byte1.get_appropriate_unit(false), byte2.get_appropriate_unit(true));
    /// ```
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::{Byte, ByteUnit};
    ///
    /// let byte1 = Byte::from_unit(1024f64, ByteUnit::KiB).unwrap();
    /// let byte2 = Byte::from_unit(1f64, ByteUnit::MiB).unwrap();
    ///
    /// assert_eq!(byte1.get_appropriate_unit(true), byte2.get_appropriate_unit(false));
    /// ```
    #[inline]
    fn eq(&self, other: &AdjustedByte) -> bool {
        if self.value == other.value && self.unit == other.unit {
            return true;
        }

        let self_value = get_bytes(self.value, self.unit);

        let other_value = get_bytes(other.value, other.unit);

        self_value == other_value
    }
}

impl Eq for AdjustedByte {}

impl AdjustedByte {
    /// Format the `AdjustedByte` object to string.
    ///
    /// # Examples
    ///
    /// ```
    /// extern crate byte_unit;
    ///
    /// use byte_unit::{Byte, ByteUnit};
    ///
    /// let byte = Byte::from_unit(1555f64, ByteUnit::KB).unwrap();
    ///
    /// let result = byte.get_appropriate_unit(false).format(3);
    ///
    /// assert_eq!(result, "1.555 MB");
    /// ```
    #[inline]
    pub fn format(&self, fractional_digits: usize) -> String {
        format!("{:.*} {}", fractional_digits, self.value, self.unit)
    }

    #[inline]
    pub fn get_value(&self) -> f64 {
        self.value
    }

    #[inline]
    pub fn get_unit(&self) -> ByteUnit {
        self.unit
    }
}

impl Display for AdjustedByte {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        f.write_fmt(format_args!("{:.2} ", self.value))?;
        Display::fmt(&self.unit, f)
    }
}

fn get_bytes(value: f64, unit: ByteUnit) -> u128 {
    match unit {
        ByteUnit::B => value as u128,
        ByteUnit::KB => n_kb_bytes!(value, f64),
        ByteUnit::KiB => n_kib_bytes!(value, f64),
        ByteUnit::MB => n_mb_bytes!(value, f64),
        ByteUnit::MiB => n_mib_bytes!(value, f64),
        ByteUnit::GB => n_gb_bytes!(value, f64),
        ByteUnit::GiB => n_gib_bytes!(value, f64),
        ByteUnit::TB => n_tb_bytes!(value, f64),
        ByteUnit::TiB => n_gib_bytes!(value, f64),
        ByteUnit::PB => n_pb_bytes!(value, f64),
        ByteUnit::PiB => n_pib_bytes!(value, f64),
    }
}