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
//! Human-readable time features.
use std::fmt;
use std::time::Duration;
#[cfg(feature="chrono")]
use chrono;

use crate::scalar;

const MIN_SECS: f64 = 60.0;
const HOUR_SECS: f64 = MIN_SECS * 60.0;
const DAY_SECS: f64 = HOUR_SECS * 24.0;
const WEEK_SECS: f64 = DAY_SECS * 7.0;

/// Human-displayable durations (from [Duration]).
///
/// There are two settings to tweak on a displayable duration:
///
/// - Whether it is full (“3 hours 2 minutes 3.42 seconds”) or compact (“2h2m3.42s”)
/// - How many components are displayed (e.g. with 3 parts, “5d3h2m” will omit seconds)
///
/// The default is compact display with 3 parts.
pub struct HumanDuration {
  seconds: f64,
  compact: bool,
  parts: i32,
}

impl From<Duration> for HumanDuration {
  fn from(d: Duration) -> HumanDuration {
    HumanDuration::new_from_secs(d.as_secs_f64())
  }
}

#[cfg(feature="chrono")]
impl From<chrono::Duration> for HumanDuration {
  fn from(d: chrono::Duration) -> HumanDuration {
    seconds(d.num_milliseconds() as f64 * 0.001)
  }
}

impl HumanDuration {
  /// Create a new readable duration from seconds.
  pub fn new_from_secs(seconds: f64) -> HumanDuration {
    HumanDuration {
      seconds,
      compact: true,
      parts: 3
    }
  }

  /// Set whether display is compact.
  pub fn compact(self, compact: bool) -> HumanDuration {
    HumanDuration {
      compact,
      ..self
    }
  }

  /// Set the number of parts to display (0 for all).
  pub fn parts(self, parts: i32) -> HumanDuration {
    HumanDuration {
      parts,
      ..self
    }
  }
}

/// Make a duration displayable.
pub fn duration<D: Into<HumanDuration>>(dur: D) -> HumanDuration {
  dur.into()
}

/// Create a duration from seconds.
pub fn seconds(secs: f64) -> HumanDuration {
  HumanDuration::new_from_secs(secs)
}

impl fmt::Display for HumanDuration {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    if self.seconds.abs() < MIN_SECS {
      return write!(f, "{}", scalar(self.seconds).suffix("s").space(!self.compact));
    }

    let mut pw = PartWriter::new(f, self);

    if pw.keep_going() && self.seconds > WEEK_SECS {
      let weeks = self.seconds / WEEK_SECS;
      pw.put_part(weeks, 0, "w", "weeks")?;
    }

    if pw.keep_going() && self.seconds > DAY_SECS {
      let days = self.seconds % WEEK_SECS / DAY_SECS;
      pw.put_part(days, 0, "d", "days")?;
    }

    if pw.keep_going() && self.seconds > HOUR_SECS {
      let hours = self.seconds % DAY_SECS / HOUR_SECS;
      pw.put_part(hours, 0, "h", "hours")?;
    }

    if pw.keep_going() && self.seconds > MIN_SECS {
      let mins = self.seconds % HOUR_SECS / MIN_SECS;
      pw.put_part(mins, 0, "m", "minutes")?;
    }

    if pw.keep_going() {
      let secs = self.seconds % MIN_SECS;
      pw.put_part(secs, 2, "s", "seconds")?;
    }

    Ok(())
  }
}

struct PartWriter<'a, 'b> {
  fmt: &'a mut fmt::Formatter<'b>,
  parts: i32,
  written: i32,
  compact: bool
}

impl <'a, 'b> PartWriter<'a, 'b> {
  fn new(fmt: &'a mut fmt::Formatter<'b>, dur: &HumanDuration) -> PartWriter<'a, 'b> {
    PartWriter {
      fmt, parts: dur.parts, written: 0, compact: dur.compact
    }
  }

  fn keep_going(&self) -> bool {
    self.parts <= 0 || self.written < self.parts
  }

  fn put_part(&mut self, val: f64, prec: usize, short: &'static str, long: &'static str) -> fmt::Result {
    let v = if prec == 0 {
      val.floor()
    } else {
      val
    };
    if self.written > 0 && !self.compact {
      self.fmt.write_str(" ")?;
    }
    write!(self.fmt, "{:.*}", prec, v)?;
    if self.compact {
      self.fmt.write_str(short)?;
    } else {
      write!(self.fmt, " {}", long)?;
    }
    self.written += 1;
    Ok(())
  }
}

#[test]
fn test_ms() {
  let ms = seconds(0.324);
  assert_eq!(ms.to_string().as_str(), "324.0ms");
}

#[test]
fn test_seconds() {
  let d = seconds(5.29314);
  assert_eq!(d.to_string().as_str(), "5.293s");
}


#[test]
fn test_hms() {
  let d = seconds(5.0 * 3600.0 + 32.0 * 60.0 + 10.5);
  assert_eq!(d.to_string().as_str(), "5h32m10.50s");
}


#[test]
fn test_hm() {
  let d = seconds(5.0 * 3600.0 + 32.0 * 60.0 + 10.5).parts(2);
  assert_eq!(d.to_string().as_str(), "5h32m");
}


#[test]
fn test_hms_full() {
  let d = seconds(5.0 * 3600.0 + 32.0 * 60.0 + 10.5).compact(false);
  assert_eq!(d.to_string().as_str(), "5 hours 32 minutes 10.50 seconds");
}

#[cfg(feature="chrono")]
#[test]
fn test_chrono() {
  let dur = chrono::Duration::seconds(1042) + chrono::Duration::milliseconds(314);
  let d = duration(dur);
  assert_eq!(d.to_string().as_str(), "17m22.31s");
}