duration method
a number with a unit: 500ms, 30s, 5m, 2h, 1d.
A plain number is seconds: 300 is 5 minutes.
Implementation
Duration? duration(String key) {
String? value = raw(key);
if (value == null) return null;
RegExpMatch? match = _durationPattern.firstMatch(value.toLowerCase());
if (match == null) {
return _invalid(key, 'a Duration (like 500ms, 30s, 5m, 2h, 1d)');
}
int microseconds = switch (match.group(2)) {
'ms' => Duration.microsecondsPerMillisecond,
'm' => Duration.microsecondsPerMinute,
'h' => Duration.microsecondsPerHour,
'd' => Duration.microsecondsPerDay,
_ => Duration.microsecondsPerSecond,
};
int? amount = int.tryParse(match.group(1)!);
// too big for an int, or for a Duration
if (amount == null || amount > _maxInt ~/ microseconds) {
return _invalid(key, 'a Duration that is not too big');
}
return Duration(microseconds: amount * microseconds);
}