toTimeoutString function

String toTimeoutString(
  1. Duration duration
)

Convert timeout to grpc-timeout header string format.

Implementation

// Mostly inspired by grpc-java implementation.
// TODO(jakobr): Modify to match grpc/core implementation instead.
String toTimeoutString(Duration duration) {
  const cutoff = 100000;
  final timeout = duration.inMicroseconds;
  if (timeout < 0) {
    // Smallest possible timeout.
    return '1n';
  } else if (timeout < cutoff) {
    return '${timeout}u';
  } else if (timeout < cutoff * 1000) {
    return '${timeout ~/ 1000}m';
  } else if (timeout < cutoff * 1000 * 1000) {
    return '${timeout ~/ 1000000}S';
  } else if (timeout < cutoff * 1000 * 1000 * 60) {
    return '${timeout ~/ 60000000}M';
  } else {
    return '${timeout ~/ 3600000000}H';
  }
}