Formats a [`Duration`] into a string. String returns a string representing the duration in the form "72h3m0.5s". Leading zero units are omitted. As a special case, durations less than one second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure that the leading digit is non-zero. The zero duration formats as 0s. This is a direct port of the Go version of the time.Duration(0).St
(d: &Duration)
| 98 | /// |
| 99 | /// This is a direct port of the Go version of the time.Duration(0).String() function. |
| 100 | pub fn format_duration(d: &Duration) -> String { |
| 101 | let buf = &mut [0u8; 32]; |
| 102 | let mut w = buf.len(); |
| 103 | |
| 104 | let mut neg = false; |
| 105 | let mut u = d |
| 106 | .num_nanoseconds() |
| 107 | .map(|n| { |
| 108 | if n < 0 { |
| 109 | neg = true; |
| 110 | } |
| 111 | n as u64 |
| 112 | }) |
| 113 | .unwrap_or_else(|| { |
| 114 | let s = d.num_seconds(); |
| 115 | if s < 0 { |
| 116 | neg = true; |
| 117 | } |
| 118 | s as u64 * SECOND |
| 119 | }); |
| 120 | |
| 121 | if u < SECOND { |
| 122 | // Special case: if duration is smaller than a second, |
| 123 | // use smaller units, like 1.2ms |
| 124 | let mut _prec = 0; |
| 125 | w -= 1; |
| 126 | buf[w] = b's'; |
| 127 | w -= 1; |
| 128 | |
| 129 | if u == 0 { |
| 130 | return "0s".to_string(); |
| 131 | } else if u < MICROSECOND { |
| 132 | _prec = 0; |
| 133 | buf[w] = b'n'; |
| 134 | } else if u < MILLISECOND { |
| 135 | _prec = 3; |
| 136 | // U+00B5 'µ' micro sign == 0xC2 0xB5 |
| 137 | buf[w] = 0xB5; |
| 138 | w -= 1; |
| 139 | buf[w] = 0xC2; |
| 140 | } else { |
| 141 | _prec = 6; |
| 142 | buf[w] = b'm'; |
| 143 | } |
| 144 | (w, u) = format_float(&mut buf[..w], u, _prec); |
| 145 | w = format_int(&mut buf[..w], u); |
| 146 | } else { |
| 147 | w -= 1; |
| 148 | buf[w] = b's'; |
| 149 | (w, u) = format_float(&mut buf[..w], u, 9); |
| 150 | |
| 151 | // u is now integer number of seconds |
| 152 | w = format_int(&mut buf[..w], u % 60); |
| 153 | u /= 60; |
| 154 | |
| 155 | // u is now integer number of minutes |
| 156 | if u > 0 { |
| 157 | w -= 1; |
no test coverage detected