| 1 |
use super::RelativeDuration; |
| 2 |
use chrono::Duration; |
| 3 |
use std::{convert::TryInto, fmt::Write}; |
| 4 |
|
| 5 |
fn dhmsn_to_duration( |
| 6 |
days: i64, |
| 7 |
hours: i64, |
| 8 |
minutes: i64, |
| 9 |
seconds: i64, |
| 10 |
nanos: u32, |
| 11 |
) -> Option<Duration> { |
| 12 |
Duration::new( |
| 13 |
days.checked_mul(24)? |
| 14 |
.checked_add(hours)? |
| 15 |
.checked_mul(60)? |
| 16 |
.checked_add(minutes)? |
| 17 |
.checked_mul(60)? |
| 18 |
.checked_add(seconds)?, |
| 19 |
nanos, |
| 20 |
) |
| 21 |
} |
| 22 |
|
| 23 |
fn get_terminated<T: std::str::FromStr + From<i32>>( |
| 24 |
input: &str, |
| 25 |
terminator: char, |
| 26 |
) -> Result<(&str, T), String> { |
| 27 |
if let Some((int_string, remainder)) = input.split_once(terminator) { |
| 28 |
let int = int_string.parse::<T>().map_err(|_| { |
| 29 |
format!( |
| 30 |
"{} is not a valid {}", |
| 31 |
int_string, |
| 32 |
std::any::type_name::<T>() |
| 33 |
) |
| 34 |
})?; |
| 35 |
Ok((remainder, int)) |
| 36 |
} else { |
| 37 |
Ok((input, 0.into())) |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
fn get_terminated_decimal(input: &str, terminator: char) -> Result<(&str, i64, u32), String> { |
| 42 |
if let Some((decimal_string, remainder)) = input.split_once(terminator) { |
| 43 |
let (int_string, fraction_string) = decimal_string.split_once('.').unwrap_or_else(|| { |
| 44 |
decimal_string |
| 45 |
// if no '.' was found, look for ',', as both are valid decimal separators in iso 8601 |
| 46 |
.split_once(',') |
| 47 |
// if neither is found take the whole string as the integer part, with no fraction |
| 48 |
.unwrap_or((decimal_string, "")) |
| 49 |
}); |
| 50 |
|
| 51 |
let int = int_string |
| 52 |
.parse::<i64>() |
| 53 |
.map_err(|_| format!("{} is not a valid i64", int_string))?; |
| 54 |
|
| 55 |
let fraction = if fraction_string.is_empty() { |
| 56 |
0 |
| 57 |
} else { |
| 58 |
fraction_string |
| 59 |
.chars() |
| 60 |
// right pad with zeros |
| 61 |
.chain(std::iter::repeat('0')) |
| 62 |
// truncate to 9 chars, since we only support nanosecond resolution |
| 63 |
.take(9) |
| 64 |
.collect::<String>() |
| 65 |
.parse::<u32>() |
| 66 |
.map_err(|_| format!("{} is not a valid u32", fraction_string))? |
| 67 |
}; |
| 68 |
|
| 69 |
// special handling for case of nonzero nanoseconds on a negative duration |
| 70 |
if decimal_string.starts_with('-') && fraction != 0 { |
| 71 |
Ok(( |
| 72 |
remainder, |
| 73 |
int - 1, |
| 74 |
(-(fraction as i32) + 1_000_000_000).try_into().unwrap(), |
| 75 |
)) |
| 76 |
} else { |
| 77 |
Ok((remainder, int, fraction)) |
| 78 |
} |
| 79 |
} else { |
| 80 |
Ok((input, 0, 0)) |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
fn parse_datespec(datespec: &str) -> Result<(i32, i32, i64), String> { |
| 85 |
let (remainder, years) = get_terminated::<i32>(datespec, 'Y')?; |
| 86 |
let (remainder, months) = get_terminated::<i32>(remainder, 'M')?; |
| 87 |
let (remainder, weeks) = get_terminated::<i64>(remainder, 'W')?; |
| 88 |
let (remainder, days) = get_terminated::<i64>(remainder, 'D')?; |
| 89 |
|
| 90 |
if !remainder.is_empty() { |
| 91 |
Err(format!( |
| 92 |
"trailing characters: {} in datespec: {}", |
| 93 |
remainder, datespec |
| 94 |
)) |
| 95 |
} else { |
| 96 |
Ok(( |
| 97 |
years, |
| 98 |
months, |
| 99 |
weeks |
| 100 |
.checked_mul(7) |
| 101 |
.and_then(|x| x.checked_add(days)) |
| 102 |
.ok_or_else(|| "integer overflow on constructing duration".to_string())?, |
| 103 |
)) |
| 104 |
} |
| 105 |
} |
| 106 |
|
| 107 |
fn parse_timespec(timespec: &str) -> Result<(i64, i64, i64, u32), String> { |
| 108 |
let (remainder, hours) = get_terminated::<i64>(timespec, 'H')?; |
| 109 |
let (remainder, mins) = get_terminated::<i64>(remainder, 'M')?; |
| 110 |
let (remainder, secs, nanos) = get_terminated_decimal(remainder, 'S')?; |
| 111 |
|
| 112 |
if !remainder.is_empty() { |
| 113 |
Err(format!( |
| 114 |
"trailing characters: {} in timespec: {}", |
| 115 |
remainder, timespec |
| 116 |
)) |
| 117 |
} else { |
| 118 |
Ok((hours, mins, secs, nanos)) |
| 119 |
} |
| 120 |
} |
| 121 |
|
| 122 |
impl RelativeDuration { |
| 123 |
/// Parses an [ISO 8601 duration string](https://en.wikipedia.org/wiki/ISO_8601#Durations) into |
| 124 |
/// a [`RelativeDuration`] value. |
| 125 |
/// |
| 126 |
/// This supports only duration strings with integer values (i.e `"P1Y"` but not `"P0.5Y"` or |
| 127 |
/// `"P0,5Y"`), as fractional values cannot be unambiguously represented as a |
| 128 |
/// [`RelativeDuration`]. The one exception to this is the seconds field, where the fractional |
| 129 |
/// part is truncated to 9 digits, and parsed as nanoseconds. |
| 130 |
/// |
| 131 |
/// # Errors |
| 132 |
/// |
| 133 |
/// - Invalid duration string input |
| 134 |
/// - Fractional values (apart from seconds) in duration string |
| 135 |
/// |
| 136 |
/// # Example |
| 137 |
/// |
| 138 |
/// ``` |
| 139 |
/// use chronoutil::RelativeDuration; |
| 140 |
/// |
| 141 |
/// assert_eq!( |
| 142 |
/// RelativeDuration::parse_from_iso8601("P1Y").unwrap(), |
| 143 |
/// RelativeDuration::years(1), |
| 144 |
/// ); |
| 145 |
/// ``` |
| 146 |
pub fn parse_from_iso8601(input: &str) -> Result<RelativeDuration, String> { |
| 147 |
let input = input |
| 148 |
.strip_prefix('P') |
| 149 |
.ok_or_else(|| "duration was not prefixed with P".to_string())?; |
| 150 |
|
| 151 |
let (datespec, timespec) = input.split_once('T').unwrap_or((input, "")); |
| 152 |
|
| 153 |
let (years, months, days) = parse_datespec(datespec)?; |
| 154 |
let (hours, mins, secs, nanos) = parse_timespec(timespec)?; |
| 155 |
|
| 156 |
Ok(RelativeDuration::months( |
| 157 |
years |
| 158 |
.checked_mul(12) |
| 159 |
.and_then(|x| x.checked_add(months)) |
| 160 |
.ok_or_else(|| "integer overflow on constructing duration".to_string())?, |
| 161 |
) |
| 162 |
.with_duration( |
| 163 |
dhmsn_to_duration(days, hours, mins, secs, nanos) |
| 164 |
.ok_or_else(|| "integer overflow on constructing duration".to_string())?, |
| 165 |
)) |
| 166 |
} |
| 167 |
|
| 168 |
/// Formats a [`RelativeDuration`] value into an |
| 169 |
/// [ISO 8601 duration string](https://en.wikipedia.org/wiki/ISO_8601#Durations). |
| 170 |
/// |
| 171 |
/// # Example |
| 172 |
/// |
| 173 |
/// ``` |
| 174 |
/// use chronoutil::RelativeDuration; |
| 175 |
/// |
| 176 |
/// assert_eq!( |
| 177 |
/// RelativeDuration::years(1).format_to_iso8601(), |
| 178 |
/// "P1Y", |
| 179 |
/// ); |
| 180 |
/// ``` |
| 181 |
pub fn format_to_iso8601(&self) -> String { |
| 182 |
let years = self.months as i64 / 12; |
| 183 |
let months = self.months as i64 % 12; |
| 184 |
|
| 185 |
let duration_seconds = self.duration.num_seconds(); |
| 186 |
|
| 187 |
let days = duration_seconds / (24 * 60 * 60); |
| 188 |
let mut remaining_seconds = duration_seconds % (24 * 60 * 60); |
| 189 |
|
| 190 |
let hours = remaining_seconds / (60 * 60); |
| 191 |
remaining_seconds %= 60 * 60; |
| 192 |
|
| 193 |
let minutes = remaining_seconds / 60; |
| 194 |
remaining_seconds %= 60; |
| 195 |
|
| 196 |
let subsec_nanos = self.duration.subsec_nanos(); |
| 197 |
|
| 198 |
// This awkward handling is needed to represent nanoseconds as a fraction of seconds, |
| 199 |
// instead of independently, since it must have no sign, and will affect the sign for |
| 200 |
// seconds. This would be simpler if we could get the Duration.secs and Duration.nanos |
| 201 |
// directly, but unfortunately chrono only offers Duration::num_seconds and |
| 202 |
// Duration::subsec_nanos, both of which apply transformations before returning... |
| 203 |
let (seconds, nanos, push_minus) = if remaining_seconds > 0 && subsec_nanos < 0 { |
| 204 |
(remaining_seconds - 1, subsec_nanos + 1_000_000_000, false) |
| 205 |
} else if remaining_seconds < 0 && subsec_nanos > 0 { |
| 206 |
(remaining_seconds + 1, -subsec_nanos + 1_000_000_000, false) |
| 207 |
} else if remaining_seconds <= 0 && subsec_nanos < 0 { |
| 208 |
(remaining_seconds, -subsec_nanos, remaining_seconds == 0) |
| 209 |
} else { |
| 210 |
(remaining_seconds, subsec_nanos, false) |
| 211 |
}; |
| 212 |
|
| 213 |
let mut out = String::new(); |
| 214 |
|
| 215 |
out.push('P'); |
| 216 |
|
| 217 |
[years, months, days] |
| 218 |
.iter() |
| 219 |
.zip(['Y', 'M', 'D']) |
| 220 |
.filter(|x| *x.0 != 0) |
| 221 |
.fold(&mut out, |out, x| { |
| 222 |
let _ = write!(out, "{}{}", x.0, x.1); |
| 223 |
out |
| 224 |
}); |
| 225 |
|
| 226 |
if [hours, minutes, seconds, nanos as i64] |
| 227 |
.iter() |
| 228 |
.any(|x| *x != 0) |
| 229 |
{ |
| 230 |
out.push('T'); |
| 231 |
} |
| 232 |
|
| 233 |
[hours, minutes] |
| 234 |
.iter() |
| 235 |
.zip(['H', 'M']) |
| 236 |
.filter(|x| *x.0 != 0) |
| 237 |
.fold(&mut out, |out, x| { |
| 238 |
let _ = write!(out, "{}{}", x.0, x.1); |
| 239 |
out |
| 240 |
}); |
| 241 |
|
| 242 |
if push_minus { |
| 243 |
out.push('-'); |
| 244 |
} |
| 245 |
|
| 246 |
if seconds != 0 || nanos != 0 { |
| 247 |
let _ = write!(out, "{}", seconds); |
| 248 |
|
| 249 |
if nanos != 0 { |
| 250 |
let nanos_str_raw = format!("{:0>9}", nanos); |
| 251 |
let nanos_str_trimmed = nanos_str_raw.trim_end_matches('0'); |
| 252 |
out.push('.'); |
| 253 |
out.push_str(nanos_str_trimmed); |
| 254 |
} |
| 255 |
|
| 256 |
out.push('S'); |
| 257 |
} |
| 258 |
|
| 259 |
out |
| 260 |
} |
| 261 |
} |
| 262 |
|
| 263 |
#[cfg(test)] |
| 264 |
mod tests { |
| 265 |
use proptest::prelude::*; |
| 266 |
|
| 267 |
use super::*; |
| 268 |
|
| 269 |
#[test] |
| 270 |
fn test_parse_duration() { |
| 271 |
[ |
| 272 |
( |
| 273 |
"P1YT1S", |
| 274 |
RelativeDuration::months(12).with_duration(Duration::seconds(1)), |
| 275 |
), |
| 276 |
( |
| 277 |
"P2Y2M2DT2H2M2S", |
| 278 |
RelativeDuration::months(2 * 12 + 2) |
| 279 |
.with_duration(dhmsn_to_duration(2, 2, 2, 2, 0).unwrap()), |
| 280 |
), |
| 281 |
( |
| 282 |
"P1M", |
| 283 |
RelativeDuration::months(1).with_duration(Duration::zero()), |
| 284 |
), |
| 285 |
("PT10M", RelativeDuration::minutes(10)), |
| 286 |
("P-1M", RelativeDuration::months(-1)), |
| 287 |
("P1W1D", RelativeDuration::days(8)), |
| 288 |
( |
| 289 |
"P1Y-10M-1W3DT3H-6M-1S", |
| 290 |
RelativeDuration::months(2) |
| 291 |
.with_duration(dhmsn_to_duration(-4, 3, -6, -1, 0).unwrap()), |
| 292 |
), |
| 293 |
("P-23M", RelativeDuration::months(-23)), |
| 294 |
("PT0.0000000010S", RelativeDuration::nanoseconds(1)), |
| 295 |
("PT0.1S", RelativeDuration::nanoseconds(100_000_000)), |
| 296 |
( |
| 297 |
"PT-0.999999999S", |
| 298 |
RelativeDuration::years(0) |
| 299 |
.with_duration(dhmsn_to_duration(0, 0, 0, -1, 1).unwrap()), |
| 300 |
), |
| 301 |
] |
| 302 |
.iter() |
| 303 |
.for_each(|(input, expected)| { |
| 304 |
assert_eq!( |
| 305 |
RelativeDuration::parse_from_iso8601(input).unwrap(), |
| 306 |
*expected |
| 307 |
) |
| 308 |
}) |
| 309 |
} |
| 310 |
|
| 311 |
#[test] |
| 312 |
fn test_format_duration() { |
| 313 |
[ |
| 314 |
( |
| 315 |
RelativeDuration::months(12).with_duration(Duration::seconds(1)), |
| 316 |
"P1YT1S", |
| 317 |
), |
| 318 |
( |
| 319 |
RelativeDuration::months(2 * 12 + 2) |
| 320 |
.with_duration(dhmsn_to_duration(2, 2, 2, 2, 0).unwrap()), |
| 321 |
"P2Y2M2DT2H2M2S", |
| 322 |
), |
| 323 |
( |
| 324 |
RelativeDuration::months(1).with_duration(Duration::zero()), |
| 325 |
"P1M", |
| 326 |
), |
| 327 |
(RelativeDuration::minutes(10), "PT10M"), |
| 328 |
(RelativeDuration::months(-1), "P-1M"), |
| 329 |
(RelativeDuration::months(-23), "P-1Y-11M"), |
| 330 |
(RelativeDuration::nanoseconds(1), "PT0.000000001S"), |
| 331 |
(RelativeDuration::nanoseconds(100_000_000), "PT0.1S"), |
| 332 |
( |
| 333 |
RelativeDuration::years(0) |
| 334 |
.with_duration(dhmsn_to_duration(0, 0, 0, -1, 1).unwrap()), |
| 335 |
"PT-0.999999999S", |
| 336 |
), |
| 337 |
] |
| 338 |
.iter() |
| 339 |
.for_each(|(input, expected)| assert_eq!(input.format_to_iso8601(), *expected)) |
| 340 |
} |
| 341 |
|
| 342 |
proptest! { |
| 343 |
#[test] |
| 344 |
fn proptest_format_and_back( |
| 345 |
months in prop::num::i32::ANY, |
| 346 |
secs in (i64::MIN/1000)..(i64::MAX/1000), |
| 347 |
nanos in 0u32..1_000_000_000 |
| 348 |
) { |
| 349 |
let d = RelativeDuration::months(months).with_duration(Duration::new(secs, nanos).unwrap()); |
| 350 |
prop_assert_eq!(d, RelativeDuration::parse_from_iso8601(&(d.format_to_iso8601())).unwrap()); |
| 351 |
} |
| 352 |
|
| 353 |
#[test] |
| 354 |
fn proptest_parse_and_back( |
| 355 |
s in r"P(?:[1-9][0-9]{0,7}Y)?(?:(?:[1-9]|1[0-1])M)?(?:(?:[1-9]|[1-2][0-9])D)?(?:T(?:(?:[1-9]|1[0-9]|2[0-3])H)(?:(?:[1-9]|[1-5][0-9])M)(?:(?:(?:[1-9]|[1-5][0-9])|(?:(?:[0-9]|[1-5][0-9])\.[0-9]{0,8}[1-9]))S))?", |
| 356 |
) { |
| 357 |
prop_assert_eq!(s.clone(), RelativeDuration::parse_from_iso8601(&s).unwrap().format_to_iso8601()); |
| 358 |
} |
| 359 |
|
| 360 |
#[test] |
| 361 |
fn proptest_parse_doesnt_panic(s in r"//PC*") { |
| 362 |
let _ = RelativeDuration::parse_from_iso8601(&s); |
| 363 |
} |
| 364 |
} |
| 365 |
} |