mirror of
https://github.com/protocolbuffers/protobuf-go.git
synced 2025-01-17 01:12:51 +00:00
internal/msgfmt: fix formatting of negative Duration
If the seconds is zero, but the nanoseconds are negative, there should still be a leading negative sign. Change-Id: Ia72a26bc3455a80e572b6bf2ff41395381f811c7 Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/247457 Reviewed-by: Herbie Ong <herbie@google.com> Reviewed-by: Damien Neil <dneil@google.com>
This commit is contained in:
parent
f2423bb714
commit
e96d591a68
@ -10,7 +10,6 @@ package msgfmt
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"math"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strconv"
|
||||
@ -130,12 +129,16 @@ func appendKnownMessage(b []byte, m protoreflect.Message) []byte {
|
||||
return append(b, x+"Z"...)
|
||||
|
||||
case genid.Duration_message_fullname:
|
||||
sign := ""
|
||||
secs := m.Get(fds.ByNumber(genid.Duration_Seconds_field_number)).Int()
|
||||
nanos := m.Get(fds.ByNumber(genid.Duration_Nanos_field_number)).Int()
|
||||
if nanos <= -1e9 || nanos >= 1e9 || (secs > 0 && nanos < 0) || (secs < 0 && nanos > 0) {
|
||||
return nil
|
||||
}
|
||||
x := fmt.Sprintf("%d.%09d", secs, int64(math.Abs(float64(nanos))))
|
||||
if secs < 0 || nanos < 0 {
|
||||
sign, secs, nanos = "-", -1*secs, -1*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")
|
||||
|
@ -199,6 +199,11 @@ func TestFormat(t *testing.T) {
|
||||
OptDuration: &durpb.Duration{Seconds: -1257894123, Nanos: -456789},
|
||||
},
|
||||
want: `{opt_duration:-1257894123.000456789s}`,
|
||||
}, {
|
||||
in: &textpb.KnownTypes{
|
||||
OptDuration: &durpb.Duration{Seconds: 0, Nanos: -1},
|
||||
},
|
||||
want: `{opt_duration:-0.000000001s}`,
|
||||
}, {
|
||||
in: &textpb.KnownTypes{
|
||||
OptBool: &wpb.BoolValue{},
|
||||
|
Loading…
Reference in New Issue
Block a user