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
#![warn(
    anonymous_parameters,
    bare_trait_objects,
    missing_debug_implementations,
    missing_docs,
    trivial_casts,
    trivial_numeric_casts,
    unused_extern_crates,
    unused_import_braces,
    unused_qualifications,
    unused_results,
    variant_size_differences
)]
#![forbid(unsafe_code)]

//! The `human_size` crate represents sizes for humans.
//!
//! The main type is [`SpecificSize`], which (as the name might suggests)
//! represents a size in specific multiple. Alternatively [`Size`] can be used
//! to represent a size with a generic multiple (not defined at compile type).
//!
//! [`SpecificSize`]: struct.SpecificSize.html
//! [`Size`]: type.Size.html
//!
//! # Example
//!
//! Below is small example that parses a size from a string and prints it.
//!
//! ```
//! # extern crate human_size;
//! # fn main() {
//! use human_size::{Size, SpecificSize, Kilobyte};
//!
//! let size1: Size = "10000 B".parse().unwrap();
//! assert_eq!(size1.to_string(), "10000 B");
//!
//! // Or using a specific multiple.
//! let size2: SpecificSize<Kilobyte> = "10000 B".parse().unwrap();
//! assert_eq!(size2.to_string(), "10 kB");
//!
//! // Generic and specific sizes can be compared.
//! assert_eq!(size1, size2);
//! # }
//! ```
//!
//! # Notes
//!
//! Internally `f64` is used to represent the size, so when comparing sizes with
//! different multiples be wary of rounding errors related to usage of floating
//! point numbers.

use std::cmp::Ordering;
use std::error::Error;
use std::fmt;
use std::str::FromStr;

pub mod multiples;

pub use multiples::*;

/// Size with a generic [`Multiple`].
///
/// # Notes
///
/// The size of `Size` is 16 bytes, but using a specific multiple, e.g.
/// `SpecificSize<Byte>`, requires only 8 bytes.
///
/// [`Multiple`]: trait.Multiple.html
pub type Size = SpecificSize<Any>;

/// `SpecificSize` represents a size in bytes with a multiple.
///
/// `SpecificSize` can be created using the `new` function, or parsed from a
/// string using the [`FromStr`] trait.
///
/// ```
/// # extern crate human_size;
/// # fn main() {
/// use human_size::{SpecificSize, Size, Byte, Any};
///
/// let size1 = SpecificSize::new(1000, Byte).unwrap();
/// assert_eq!(size1.to_string(), "1000 B");
///
/// // `Size` is a type alias for `SpecificSize<Any>`.
/// let size2: Size = "1 kB".parse().unwrap();
/// assert_eq!(size2.to_string(), "1 kB");
///
/// // Even though the multiples are different we can still compare them.
/// assert_eq!(size1, size2);
/// # }
/// ```
///
/// Creating a `SpecificSize` with a specific [`Multiple`], e.g. [`Kilobyte`],
/// only uses 8 bytes. Using the generic mulitple, i.e. [`Any`], it can
/// represent all multiples but requires an extra 8 bytes for a total of 16
/// bytes.
///
/// ```
/// # extern crate human_size;
/// # fn main() {
/// use std::mem;
///
/// use human_size::{SpecificSize, Size, Byte, Any};
///
/// assert_eq!(mem::size_of::<SpecificSize<Byte>>(), 8);
/// assert_eq!(mem::size_of::<Size>(), 16);
/// # }
/// ```
///
/// # Notes
///
/// When comparing sizes with one another it is to possible compare different
/// multiples, see the first example above. However due to a lack of precision
/// in floating point numbers equality ignores a difference less then
/// `0.00000001`, after applying the multiple. See the `PartialEq`
/// implementation (via \[src\] to the right) for details.
///
/// The same is true for converting to and from multiples, here again the lack
/// of precision of floating points can be a cause of bugs.
///
/// [`FromStr`]: https://doc.rust-lang.org/nightly/core/str/trait.FromStr.html
/// [`Multiple`]: trait.Multiple.html
/// [`Kilobyte`]: multiples/struct.Kilobyte.html
/// [`Any`]: multiples/enum.Any.html
#[derive(Copy, Clone, Debug)]
pub struct SpecificSize<M = Any> {
    value: f64,
    multiple: M,
}

impl<M: Multiple> SpecificSize<M> {
    /// Create a new `SpecificSize` with the given value and multiple. If the
    /// `value` is [not normal] this will return an error, however zero is
    /// allowed. If the `value` is normal the result can be safely unwraped.
    ///
    /// ```
    /// # extern crate human_size;
    /// # fn main() {
    /// use std::f64;
    /// use human_size::{SpecificSize, Kilobyte, InvalidValueError};
    ///
    /// let size = SpecificSize::new(100, Kilobyte).unwrap();
    /// assert_eq!(size.to_string(), "100 kB");
    ///
    /// let res = SpecificSize::new(f64::NAN, Kilobyte);
    /// assert_eq!(res, Err(InvalidValueError)); // NAN is not a valid number.
    /// # }
    /// ```
    ///
    /// [not normal]: https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.is_normal
    pub fn new<V>(value: V, multiple: M) -> Result<SpecificSize<M>, InvalidValueError>
    where
        V: Into<f64>,
    {
        let value = value.into();
        if is_valid_value(value) {
            Ok(SpecificSize { value, multiple })
        } else {
            Err(InvalidValueError)
        }
    }

    /// Conversion between sizes with different multiples.
    ///
    /// This allows a size with one multiple to be converted into a size with
    /// another multiple.
    ///
    /// ```
    /// # extern crate human_size;
    /// # fn main() {
    /// use human_size::{SpecificSize, Byte, Kilobyte};
    ///
    /// let size = SpecificSize::new(1, Kilobyte).unwrap();
    /// let size2: SpecificSize<Byte> = size.into();
    ///
    /// assert_eq!(size, size2);
    /// assert_eq!(size.to_string(), "1 kB");
    /// assert_eq!(size2.to_string(), "1000 B");
    /// # }
    /// ```
    ///
    /// # Notes
    ///
    /// Normally this would be done by implementing the `From` or `Into` trait.
    /// However currently this is not possible due to the blanket implementation
    /// in the standard library. Maybe once specialisation is available this can
    /// be resolved.
    pub fn into<M2>(self) -> SpecificSize<M2>
    where
        M2: Multiple,
    {
        let (value, any) = M::into_any(self);
        M2::from_any(value, any)
    }

    /// Returns the size in current the multiple.
    ///
    /// ```
    /// # extern crate human_size;
    /// # fn main() {
    /// use human_size::{SpecificSize, Kilobyte};
    ///
    /// let size = SpecificSize::new(1, Kilobyte).unwrap();
    ///
    /// assert_eq!(size.value(), 1.0);
    /// # }
    /// ```
    pub fn value(self) -> f64 {
        self.value
    }

    /// Returns the multiple.
    ///
    /// ```
    /// # extern crate human_size;
    /// # fn main() {
    /// use human_size::{SpecificSize, Any, Kilobyte};
    ///
    /// let size1 = SpecificSize::new(1, Kilobyte).unwrap();
    /// let size2 = SpecificSize::new(1, Any::Kilobyte).unwrap();
    ///
    /// assert_eq!(size1.multiple(), Kilobyte);
    /// assert_eq!(size2.multiple(), Any::Kilobyte);
    /// # }
    /// ```
    pub fn multiple(self) -> M {
        self.multiple
    }

    /// Returns the size as bytes.
    ///
    /// # Notes
    ///
    /// Be careful of truncation for large file size.
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate human_size;
    /// # fn main() {
    /// use human_size::{SpecificSize, Any, Kilobyte};
    ///
    /// let size1 = SpecificSize::new(1, Kilobyte).unwrap();
    /// let size2 = SpecificSize::new(8, Any::Kilobyte).unwrap();
    ///
    /// assert_eq!(size1.to_bytes(), 1000);
    /// assert_eq!(size2.to_bytes(), 8000);
    /// # }
    /// ```
    pub fn to_bytes(self) -> u64 {
        let (value, any) = M::into_any(self);
        Byte::from_any(value, any).value as u64
    }
}

/// Check if the provided `value` is valid.
fn is_valid_value(value: f64) -> bool {
    use std::num::FpCategory::*;
    matches!(value.classify(), Normal | Zero)
}

impl<M: Multiple> FromStr for SpecificSize<M> {
    type Err = ParsingError;

    fn from_str(input: &str) -> Result<SpecificSize<M>, Self::Err> {
        let input = input.trim();
        if input.is_empty() {
            return Err(ParsingError::EmptyInput);
        }

        let multiple_index = input
            .chars()
            .position(|c| !(c.is_numeric() || c == '.'))
            .ok_or(ParsingError::MissingMultiple)?;
        if multiple_index == 0 {
            return Err(ParsingError::MissingValue);
        }

        let (value, multiple) = &input.split_at(multiple_index);
        let value = value.parse().map_err(|_| ParsingError::InvalidValue)?;

        if is_valid_value(value) {
            let multiple = multiple.trim().parse()?;
            Ok(M::from_any(value, multiple))
        } else {
            Err(ParsingError::InvalidValue)
        }
    }
}

#[cfg(feature = "serde")]
impl<'de, M> serde::Deserialize<'de> for SpecificSize<M>
where
    M: Multiple,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use std::marker::PhantomData;

        use serde::de::{Error, Visitor};

        struct SpecificSizeVisitor<M>(PhantomData<M>);

        impl<'de, M: Multiple> Visitor<'de> for SpecificSizeVisitor<M> {
            type Value = SpecificSize<M>;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("size")
            }

            fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
            where
                E: Error,
            {
                s.parse().map_err(Error::custom)
            }
        }

        deserializer.deserialize_str(SpecificSizeVisitor(PhantomData))
    }
}

#[cfg(feature = "serde")]
impl<M> serde::Serialize for SpecificSize<M>
where
    M: Multiple + fmt::Display,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        // NOTE: this is not the best method as this allocates a string that get
        // dropped after using it. We could try to use the
        // `serialize_display_bounded_length` macro from serde.
        serializer.serialize_str(&*self.to_string())
    }
}

/*
TODO: Needs specialisation.
impl<M1: Multiple, M2: Multiple> From<SpecificSize<M2>> for SpecificSize<M1> {
    fn from(size: SpecificSize<M2>) -> Self {
        let (value, any) = M2::into_any(size);
        M1::from_any(value, any)
    }
}
*/

/*
TODO: Enable to specialisation for the same M.
impl<M> PartialEq for SpecificSize<M> {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}
*/

/// The allowed margin to consider two floats still equal, after applying the
/// multiple. Keep in sync with the Notes section of `SpecificSize`.
const CMP_MARGIN: f64 = 0.000_000_01;

impl<LM, RM> PartialEq<SpecificSize<RM>> for SpecificSize<LM>
where
    LM: Multiple + Copy,
    RM: Multiple + Copy,
{
    fn eq(&self, other: &SpecificSize<RM>) -> bool {
        // Ah... floating points...
        // To negate the loss in accuracy we check if the difference between the
        // values is really low and consider that the same.
        let (left, right) = into_same_multiples(*self, *other);
        let diff = left - right;
        diff.abs() < CMP_MARGIN
    }
}

impl<M> Eq for SpecificSize<M> where M: Multiple + Copy {}

/*
TODO: Enable to specialisation for the same M.
impl<M> PartialOrd for SpecificSize<M> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.value.partial_cmp(&other.value)
    }
}
*/

impl<LM, RM> PartialOrd<SpecificSize<RM>> for SpecificSize<LM>
where
    LM: Multiple + Copy,
    RM: Multiple + Copy,
{
    fn partial_cmp(&self, other: &SpecificSize<RM>) -> Option<Ordering> {
        let (left, right) = into_same_multiples(*self, *other);
        left.partial_cmp(&right)
    }
}

/// Convert the provided `left` and `right` sizes into the same multiples,
/// returning the values. For example if left is `1 Kilobyte`, and right is
/// `1000 Byte`, it will return `(1, 1)` (in the multiple of Kilobyte).
fn into_same_multiples<LM, RM>(left: SpecificSize<LM>, right: SpecificSize<RM>) -> (f64, f64)
where
    LM: Multiple,
    RM: Multiple,
{
    let (left_value, left_multiple) = LM::into_any(left);
    let (right_value, right_multiple) = RM::into_any(right);
    let multiply = left_multiple.multiple_of_bytes() / right_multiple.multiple_of_bytes();
    (left_value * multiply, right_value)
}

impl<M: fmt::Display> fmt::Display for SpecificSize<M> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(precision) = f.precision() {
            write!(f, "{:.*} {}", precision, self.value, self.multiple)
        } else {
            write!(f, "{} {}", self.value, self.multiple)
        }
    }
}

/// Trait to convert a [`SpecificSize`] to and from different multiples.
///
/// [`SpecificSize`]: struct.SpecificSize.html
pub trait Multiple: Sized {
    /// Create a new [`SpecificSize`] from a `value` and `multiple`, the
    /// provided `value` must always valid (see [`SpecificSize::new`]).
    ///
    /// [`SpecificSize`]: struct.SpecificSize.html
    /// [`SpecificSize::new`]: struct.SpecificSize.html#method.new
    fn from_any(value: f64, multiple: Any) -> SpecificSize<Self>;

    /// The opposite of `from_any`, converting self into the value and the
    /// generic multiple.
    fn into_any(size: SpecificSize<Self>) -> (f64, Any);
}

/// The error returned when trying to create a new [`SpecificSize`] with an
/// invalid value.
///
/// [`SpecificSize`]: struct.SpecificSize.html
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct InvalidValueError;

impl fmt::Display for InvalidValueError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        ParsingError::InvalidValue.fmt(f)
    }
}

impl Error for InvalidValueError {}

/// The error returned when trying to parse a [`SpecificSize`], using the
/// [`FromStr`] trait.
///
/// [`SpecificSize`]: struct.SpecificSize.html
/// [`FromStr`]: https://doc.rust-lang.org/nightly/core/str/trait.FromStr.html
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ParsingError {
    /// The provided string is empty, i.e. "".
    EmptyInput,
    /// The provided string is missing a value, e.g. "B".
    MissingValue,
    /// The value is invalid, see [`SpecificSize::new`].
    ///
    /// [`SpecificSize::new`]: struct.SpecificSize.html#method.new
    InvalidValue,
    /// The value is missing the multiple of bytes, e.g. "100".
    MissingMultiple,
    /// The multiple in the string is invalid, e.g. "100 invalid".
    InvalidMultiple,
}

impl fmt::Display for ParsingError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad(match *self {
            ParsingError::EmptyInput => "input is empty",
            ParsingError::MissingValue => "no value",
            ParsingError::InvalidValue => "invalid value",
            ParsingError::MissingMultiple => "no multiple",
            ParsingError::InvalidMultiple => "invalid multiple",
        })
    }
}

impl Error for ParsingError {}