Timeout.parse constructor
- String timeout
Parse the timeout from a user-provided string.
This supports the following formats:
-
Number "x"
, which produces a relative timeout with the given scale factor. -
(Number ("d" | "h" | "m" | "s" | "ms" | "us") (" ")?)+
, which produces an absolute timeout with the duration given by the sum of the given units. -
"none"
, which produces Timeout.none.
Throws a FormatException if timeout
is not in a valid format
Implementation
factory Timeout.parse(String timeout) {
var scanner = StringScanner(timeout);
// First check for the string "none".
if (scanner.scan('none')) {
scanner.expectDone();
return Timeout.none;
}
// Scan a number. This will be either a time unit or a scale factor.
scanner.expect(_untilUnit, name: 'number');
var number = double.parse(scanner.lastMatch![0]!);
// A number followed by "x" is a scale factor.
if (scanner.scan('x') || scanner.scan('X')) {
scanner.expectDone();
return Timeout.factor(number);
}
// Parse time units until none are left. The condition is in the middle of
// the loop because we've already parsed the first number.
var microseconds = 0.0;
while (true) {
scanner.expect(_unit, name: 'unit');
microseconds += _microsecondsFor(number, scanner.lastMatch![0]!);
scanner.scan(_whitespace);
// Scan the next number, if it's available.
if (!scanner.scan(_untilUnit)) break;
number = double.parse(scanner.lastMatch![0]!);
}
scanner.expectDone();
return Timeout(Duration(microseconds: microseconds.round()));
}