encoding/protojson: simplify Duration formatting
Simplify the implementation by reducing the number of branches.
Change-Id: I6e2ffee0fc2d77f7e2a70f76e03d081f4fc0e99d
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/247459
Reviewed-by: Herbie Ong <herbie@google.com>
diff --git a/encoding/protojson/well_known_types.go b/encoding/protojson/well_known_types.go
index 73b038e..7a2fde3 100644
--- a/encoding/protojson/well_known_types.go
+++ b/encoding/protojson/well_known_types.go
@@ -605,14 +605,11 @@
}
// Generated output always contains 0, 3, 6, or 9 fractional digits,
// depending on required precision, followed by the suffix "s".
- f := "%d.%09d"
- if nanos < 0 {
- nanos = -nanos
- if secs == 0 {
- f = "-%d.%09d"
- }
+ var sign string
+ if secs < 0 || nanos < 0 {
+ sign, secs, nanos = "-", -1*secs, -1*nanos
}
- x := fmt.Sprintf(f, secs, nanos)
+ x := fmt.Sprintf("%s%d.%09d", sign, secs, nanos)
x = strings.TrimSuffix(x, "000")
x = strings.TrimSuffix(x, "000")
x = strings.TrimSuffix(x, ".000")