durationToString function
Converts a google.protobuf.Duration to its canonical string form.
A Duration contains "seconds" (int64) and optional "nanos" (int32,
same sign as seconds or zero, absolute value in [0, 999999999]).
Output: "1.000340012s", "-0.500s", "0s".
Negative durations have a leading - and both seconds and nanos share
the sign.
Implementation
String durationToString(Map<String, Object?> duration) {
final seconds = _toInt(duration['seconds'] ?? 0);
final nanos = _toInt(duration['nanos'] ?? 0);
if (nanos == 0) {
return '${seconds}s';
}
// Determine sign: the canonical form has a single leading '-' when the
// overall duration is negative.
final negative = seconds < 0 || (seconds == 0 && nanos < 0);
final absSeconds = seconds.abs();
final absNanos = nanos.abs();
final nanoStr = absNanos.toString().padLeft(9, '0');
// Trim trailing zeros.
String fractional = nanoStr;
while (fractional.length > 1 && fractional.endsWith('0')) {
fractional = fractional.substring(0, fractional.length - 1);
}
final sign = negative ? '-' : '';
return '$sign$absSeconds.${fractional}s';
}