From f2423bb71467d3107e0b2b317844fede16dcdd15 Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Fri, 7 Aug 2020 13:26:37 -0700 Subject: [PATCH] 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 --- encoding/protojson/well_known_types.go | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/encoding/protojson/well_known_types.go b/encoding/protojson/well_known_types.go index 73b038eb..7a2fde33 100644 --- a/encoding/protojson/well_known_types.go +++ b/encoding/protojson/well_known_types.go @@ -605,14 +605,11 @@ func (e encoder) marshalDuration(m pref.Message) error { } // 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")