stringToDuration function
Parses a duration string ("Xs", "X.Ns") into a
google.protobuf.Duration.
Returns {"seconds": int, "nanos": int}.
Throws FormatException if the string does not end with 's'.
Implementation
Map<String, Object?> stringToDuration(String durationStr) {
if (!durationStr.endsWith('s')) {
throw FormatException('Duration string must end with "s": $durationStr');
}
final body = durationStr.substring(0, durationStr.length - 1);
final negative = body.startsWith('-');
final abs = negative ? body.substring(1) : body;
final dotIndex = abs.indexOf('.');
int seconds;
int nanos;
if (dotIndex == -1) {
seconds = int.parse(abs);
nanos = 0;
} else {
seconds = int.parse(abs.substring(0, dotIndex));
final fracStr = abs.substring(dotIndex + 1).padRight(9, '0');
nanos = int.parse(fracStr.substring(0, 9));
}
if (negative) {
seconds = -seconds;
if (nanos != 0) nanos = -nanos;
}
return {'seconds': seconds, 'nanos': nanos};
}