mirror of
https://github.com/tailscale/tailscale.git
synced 2026-11-24 02:31:18 -08:00
types/jsonx: add wrapper types for JSON time and duration wire formats
Add DurationNano, DurationUnits, DurationISO8601, TimeUnix, TimeUnixNano, and TimeRFC1123: wrappers around time.Duration and time.Time that marshal to the wire formats that json `format:` struct tag options (format:nano, format:units, and so on) used to produce with github.com/go-json-experiment/json. Go 1.27's encoding/json rejects format tag options outright, and the module moved its support behind a global experimental option that its documentation says will be removed (see golang/go#71631). Struct tags are also only honored by the marshaler that happens to encode the struct, so any stdlib encoding/json call reaching a tagged struct, including generated MarshalJSON methods, breaks under Go 1.27. These types instead carry their wire format with them: they implement both the v1 json.Marshaler/Unmarshaler and the module's MarshalerTo/UnmarshalerFrom interfaces and produce identical bytes under the standard library and the module, on Go 1.26 and Go 1.27. Tests verify byte-for-byte parity against the module's format tag encodings across randomized values. Unmarshal is additionally lenient where the legacy standard library produced a different encoding for the underlying type because it ignored the tags: the Time types also accept RFC 3339 strings and the string-formatted Duration types also accept nanosecond counts, so previously persisted data remains readable. The tailscale corp repo will migrate its format tag uses to these types; this repo has none. Updates #20220 Updates tailscale/corp#45953 Signed-off-by: Brad Fitzpatrick <[email protected]> Change-Id: Iabde575b0228eb782d00e7180044ddd2f01d505e
This commit is contained in:
1 parent
deded79f0e
commit
483e2efcc0
3 files changed
+725
No files matched your search
@@ -1,3 +1,9 @@
|
||||
FormatUnsupported tailscale.com/types/jsonx.*.ISO8601
|
||||
FormatUnsupported tailscale.com/types/jsonx.*.Nano
|
||||
FormatUnsupported tailscale.com/types/jsonx.*.RFC1123
|
||||
FormatUnsupported tailscale.com/types/jsonx.*.Units
|
||||
FormatUnsupported tailscale.com/types/jsonx.*.Unix
|
||||
FormatUnsupported tailscale.com/types/jsonx.*.UnixNano
|
||||
OmitEmptyShouldBeOmitZero tailscale.com/client/web.authResponse.ViewerIdentity
|
||||
OmitEmptyShouldBeOmitZero tailscale.com/cmd/k8s-operator.OwnerRef.Resource
|
||||
OmitEmptyShouldBeOmitZero tailscale.com/cmd/tailscale/cli.apiResponse.Error
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
// Copyright (c) Tailscale Inc & contributors
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
package jsonx
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-json-experiment/json/jsontext"
|
||||
)
|
||||
|
||||
// This file provides wrapper types for time.Time and time.Duration that
|
||||
// marshal to specific JSON wire formats.
|
||||
//
|
||||
// They exist to replace `format:` options in json struct tags (such as
|
||||
// `json:",format:nano"`), which [github.com/go-json-experiment/json]
|
||||
// used to support: Go 1.27's encoding/json rejects such tags outright,
|
||||
// and the module moved its support behind a global experimental option
|
||||
// slated for removal (see golang/go#71631). Unlike struct tags, which
|
||||
// are interpreted only by the marshaler that happens to encode the
|
||||
// struct, these types carry their wire format with them and produce
|
||||
// identical bytes under both the standard library's encoding/json and
|
||||
// the go-json-experiment module, on both Go 1.26 and Go 1.27.
|
||||
//
|
||||
// Each type marshals exactly as the module used to marshal the
|
||||
// corresponding format tag. Where the standard library's legacy
|
||||
// encoding/json produced a different encoding for the underlying type
|
||||
// (because it ignored the format tag), Unmarshal also accepts that
|
||||
// legacy form, so previously persisted data remains readable.
|
||||
|
||||
// DurationNano is a [time.Duration] that marshals as a JSON number of
|
||||
// nanoseconds, like `format:nano` and like the standard library's
|
||||
// encoding of time.Duration.
|
||||
type DurationNano time.Duration
|
||||
|
||||
// Duration returns d as a [time.Duration].
|
||||
func (d DurationNano) Duration() time.Duration { return time.Duration(d) }
|
||||
|
||||
func (d DurationNano) String() string { return time.Duration(d).String() }
|
||||
|
||||
func (d DurationNano) MarshalJSON() ([]byte, error) {
|
||||
return strconv.AppendInt(nil, int64(d), 10), nil
|
||||
}
|
||||
|
||||
func (d *DurationNano) UnmarshalJSON(b []byte) error {
|
||||
n, err := strconv.ParseInt(string(b), 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("jsonx.DurationNano: parsing %q: %w", b, err)
|
||||
}
|
||||
*d = DurationNano(n)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d DurationNano) MarshalJSONTo(enc *jsontext.Encoder) error {
|
||||
b, _ := d.MarshalJSON()
|
||||
return enc.WriteValue(b)
|
||||
}
|
||||
|
||||
func (d *DurationNano) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
|
||||
b, err := dec.ReadValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return d.UnmarshalJSON(b)
|
||||
}
|
||||
|
||||
// DurationUnits is a [time.Duration] that marshals as a JSON string in
|
||||
// Go's duration syntax, such as "1h2m3.5s", like `format:units`.
|
||||
//
|
||||
// Unmarshal also accepts a JSON number of nanoseconds, which is how the
|
||||
// standard library's legacy encoding/json encoded time.Duration.
|
||||
type DurationUnits time.Duration
|
||||
|
||||
// Duration returns d as a [time.Duration].
|
||||
func (d DurationUnits) Duration() time.Duration { return time.Duration(d) }
|
||||
|
||||
func (d DurationUnits) String() string { return time.Duration(d).String() }
|
||||
|
||||
func (d DurationUnits) MarshalJSON() ([]byte, error) {
|
||||
return strconv.AppendQuote(nil, time.Duration(d).String()), nil
|
||||
}
|
||||
|
||||
func (d *DurationUnits) UnmarshalJSON(b []byte) error {
|
||||
if len(b) > 0 && b[0] != '"' {
|
||||
// Legacy form: a JSON number of nanoseconds.
|
||||
n, err := strconv.ParseInt(string(b), 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("jsonx.DurationUnits: parsing %q: %w", b, err)
|
||||
}
|
||||
*d = DurationUnits(n)
|
||||
return nil
|
||||
}
|
||||
s, err := strconv.Unquote(string(b))
|
||||
if err != nil {
|
||||
return fmt.Errorf("jsonx.DurationUnits: parsing %q: %w", b, err)
|
||||
}
|
||||
dur, err := time.ParseDuration(s)
|
||||
if err != nil {
|
||||
return fmt.Errorf("jsonx.DurationUnits: %w", err)
|
||||
}
|
||||
*d = DurationUnits(dur)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d DurationUnits) MarshalJSONTo(enc *jsontext.Encoder) error {
|
||||
b, _ := d.MarshalJSON()
|
||||
return enc.WriteValue(b)
|
||||
}
|
||||
|
||||
func (d *DurationUnits) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
|
||||
b, err := dec.ReadValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return d.UnmarshalJSON(b)
|
||||
}
|
||||
|
||||
// DurationISO8601 is a [time.Duration] that marshals as a JSON string
|
||||
// containing an ISO 8601 duration, such as "PT1H2M3.5S", like
|
||||
// `format:iso8601`. Only the accurate hour, minute, and second
|
||||
// designators are used, matching the module's restricted grammar.
|
||||
//
|
||||
// Unmarshal also accepts a JSON number of nanoseconds, which is how the
|
||||
// standard library's legacy encoding/json encoded time.Duration.
|
||||
type DurationISO8601 time.Duration
|
||||
|
||||
// Duration returns d as a [time.Duration].
|
||||
func (d DurationISO8601) Duration() time.Duration { return time.Duration(d) }
|
||||
|
||||
func (d DurationISO8601) String() string { return time.Duration(d).String() }
|
||||
|
||||
func (d DurationISO8601) MarshalJSON() ([]byte, error) {
|
||||
if d == 0 {
|
||||
return []byte(`"PT0S"`), nil
|
||||
}
|
||||
b := make([]byte, 0, 24)
|
||||
b = append(b, '"')
|
||||
n := uint64(d)
|
||||
if d < 0 {
|
||||
b = append(b, '-')
|
||||
n = uint64(-int64(d))
|
||||
}
|
||||
b = append(b, "PT"...)
|
||||
nsec := n % 1e9
|
||||
n /= 1e9
|
||||
sec := n % 60
|
||||
n /= 60
|
||||
min := n % 60
|
||||
hour := n / 60
|
||||
if hour > 0 {
|
||||
b = append(strconv.AppendUint(b, hour, 10), 'H')
|
||||
}
|
||||
if min > 0 {
|
||||
b = append(strconv.AppendUint(b, min, 10), 'M')
|
||||
}
|
||||
if sec > 0 || nsec > 0 {
|
||||
b = strconv.AppendUint(b, sec, 10)
|
||||
b = appendFrac(b, nsec, 1e9)
|
||||
b = append(b, 'S')
|
||||
}
|
||||
return append(b, '"'), nil
|
||||
}
|
||||
|
||||
func (d *DurationISO8601) UnmarshalJSON(b []byte) error {
|
||||
if len(b) > 0 && b[0] != '"' {
|
||||
// Legacy form: a JSON number of nanoseconds.
|
||||
n, err := strconv.ParseInt(string(b), 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("jsonx.DurationISO8601: parsing %q: %w", b, err)
|
||||
}
|
||||
*d = DurationISO8601(n)
|
||||
return nil
|
||||
}
|
||||
s, err := strconv.Unquote(string(b))
|
||||
if err != nil {
|
||||
return fmt.Errorf("jsonx.DurationISO8601: parsing %q: %w", b, err)
|
||||
}
|
||||
dur, err := parseDurationISO8601(s)
|
||||
if err != nil {
|
||||
return fmt.Errorf("jsonx.DurationISO8601: parsing %q: %w", b, err)
|
||||
}
|
||||
*d = DurationISO8601(dur)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d DurationISO8601) MarshalJSONTo(enc *jsontext.Encoder) error {
|
||||
b, _ := d.MarshalJSON()
|
||||
return enc.WriteValue(b)
|
||||
}
|
||||
|
||||
func (d *DurationISO8601) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
|
||||
b, err := dec.ReadValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return d.UnmarshalJSON(b)
|
||||
}
|
||||
|
||||
// parseDurationISO8601 parses the restricted ISO 8601 duration grammar
|
||||
// produced by DurationISO8601.MarshalJSON: an optional sign, then "PT",
|
||||
// then optional hour, minute, and second fields, where only the second
|
||||
// field may have a fractional component.
|
||||
func parseDurationISO8601(s string) (time.Duration, error) {
|
||||
orig := s
|
||||
neg := false
|
||||
if strings.HasPrefix(s, "-") {
|
||||
neg = true
|
||||
s = s[1:]
|
||||
} else if strings.HasPrefix(s, "+") {
|
||||
s = s[1:]
|
||||
}
|
||||
rest, ok := strings.CutPrefix(s, "PT")
|
||||
if !ok {
|
||||
return 0, errors.New("missing PT prefix")
|
||||
}
|
||||
if rest == "" {
|
||||
return 0, errors.New("empty duration")
|
||||
}
|
||||
var total time.Duration
|
||||
seen := 0 // bitmask of seen designators, to enforce ordering
|
||||
for rest != "" {
|
||||
i := strings.IndexAny(rest, "HMS")
|
||||
if i < 0 {
|
||||
return 0, fmt.Errorf("missing unit designator in %q", orig)
|
||||
}
|
||||
num, unit := rest[:i], rest[i]
|
||||
rest = rest[i+1:]
|
||||
switch unit {
|
||||
case 'H':
|
||||
if seen >= 1 {
|
||||
return 0, errors.New("duplicate or misordered H")
|
||||
}
|
||||
seen = 1
|
||||
n, err := strconv.ParseUint(num, 10, 63)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
total += time.Duration(n) * time.Hour
|
||||
case 'M':
|
||||
if seen >= 2 {
|
||||
return 0, errors.New("duplicate or misordered M")
|
||||
}
|
||||
seen = 2
|
||||
n, err := strconv.ParseUint(num, 10, 63)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
total += time.Duration(n) * time.Minute
|
||||
case 'S':
|
||||
if seen >= 4 {
|
||||
return 0, errors.New("duplicate S")
|
||||
}
|
||||
seen = 4
|
||||
sec, frac, err := parseDecimal(num, 1e9)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
total += time.Duration(sec)*time.Second + time.Duration(frac)
|
||||
}
|
||||
}
|
||||
if neg {
|
||||
total = -total
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
// TimeUnix is a [time.Time] that marshals as a JSON number of seconds
|
||||
// since the Unix epoch, with any sub-second component encoded as a
|
||||
// decimal fraction with insignificant zeros omitted, like
|
||||
// `format:unix`.
|
||||
//
|
||||
// Unmarshal also accepts an RFC 3339 JSON string, which is how the
|
||||
// standard library's legacy encoding/json encoded time.Time.
|
||||
type TimeUnix struct {
|
||||
time.Time
|
||||
}
|
||||
|
||||
func (t TimeUnix) MarshalJSON() ([]byte, error) {
|
||||
b := make([]byte, 0, 24)
|
||||
sec, nsec := t.Unix(), uint64(t.Nanosecond())
|
||||
if sec < 0 && nsec > 0 {
|
||||
// Match the module's encoding of pre-epoch times: negate the
|
||||
// (sec, nsec) pair rather than emitting a negative second count
|
||||
// with a positive fraction.
|
||||
sec, nsec = -(sec + 1), 1e9-nsec
|
||||
b = append(b, '-')
|
||||
}
|
||||
b = strconv.AppendInt(b, sec, 10)
|
||||
b = appendFrac(b, nsec, 1e9)
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (t *TimeUnix) UnmarshalJSON(b []byte) error {
|
||||
if len(b) > 0 && b[0] == '"' {
|
||||
// Legacy form: an RFC 3339 string.
|
||||
return t.Time.UnmarshalJSON(b)
|
||||
}
|
||||
s := string(b)
|
||||
neg := strings.HasPrefix(s, "-")
|
||||
if neg {
|
||||
s = s[1:]
|
||||
}
|
||||
sec, frac, err := parseDecimal(s, 1e9)
|
||||
if err != nil {
|
||||
return fmt.Errorf("jsonx.TimeUnix: parsing %q: %w", b, err)
|
||||
}
|
||||
nsec := int64(frac)
|
||||
if neg {
|
||||
sec, nsec = -sec, -nsec
|
||||
}
|
||||
t.Time = time.Unix(sec, nsec).UTC()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t TimeUnix) MarshalJSONTo(enc *jsontext.Encoder) error {
|
||||
b, _ := t.MarshalJSON()
|
||||
return enc.WriteValue(b)
|
||||
}
|
||||
|
||||
func (t *TimeUnix) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
|
||||
b, err := dec.ReadValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return t.UnmarshalJSON(b)
|
||||
}
|
||||
|
||||
// TimeUnixNano is a [time.Time] that marshals as a JSON number of
|
||||
// nanoseconds since the Unix epoch, like `format:unixnano`.
|
||||
//
|
||||
// It can only represent times in the [time.Time.UnixNano] range
|
||||
// (years 1678 to 2262).
|
||||
//
|
||||
// Unmarshal also accepts an RFC 3339 JSON string, which is how the
|
||||
// standard library's legacy encoding/json encoded time.Time.
|
||||
type TimeUnixNano struct {
|
||||
time.Time
|
||||
}
|
||||
|
||||
func (t TimeUnixNano) MarshalJSON() ([]byte, error) {
|
||||
return strconv.AppendInt(nil, t.UnixNano(), 10), nil
|
||||
}
|
||||
|
||||
func (t *TimeUnixNano) UnmarshalJSON(b []byte) error {
|
||||
if len(b) > 0 && b[0] == '"' {
|
||||
// Legacy form: an RFC 3339 string.
|
||||
return t.Time.UnmarshalJSON(b)
|
||||
}
|
||||
n, err := strconv.ParseInt(string(b), 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("jsonx.TimeUnixNano: parsing %q: %w", b, err)
|
||||
}
|
||||
t.Time = time.Unix(0, n).UTC()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t TimeUnixNano) MarshalJSONTo(enc *jsontext.Encoder) error {
|
||||
b, _ := t.MarshalJSON()
|
||||
return enc.WriteValue(b)
|
||||
}
|
||||
|
||||
func (t *TimeUnixNano) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
|
||||
b, err := dec.ReadValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return t.UnmarshalJSON(b)
|
||||
}
|
||||
|
||||
// TimeRFC1123 is a [time.Time] that marshals as a JSON string in RFC
|
||||
// 1123 format, such as "Mon, 02 Jan 2006 15:04:05 MST", like
|
||||
// `format:RFC1123`.
|
||||
//
|
||||
// Unmarshal also accepts an RFC 3339 JSON string, which is how the
|
||||
// standard library's legacy encoding/json encoded time.Time.
|
||||
type TimeRFC1123 struct {
|
||||
time.Time
|
||||
}
|
||||
|
||||
func (t TimeRFC1123) MarshalJSON() ([]byte, error) {
|
||||
b := make([]byte, 0, len(time.RFC1123)+2)
|
||||
b = append(b, '"')
|
||||
b = t.AppendFormat(b, time.RFC1123)
|
||||
return append(b, '"'), nil
|
||||
}
|
||||
|
||||
func (t *TimeRFC1123) UnmarshalJSON(b []byte) error {
|
||||
s, err := strconv.Unquote(string(b))
|
||||
if err != nil {
|
||||
return fmt.Errorf("jsonx.TimeRFC1123: parsing %q: %w", b, err)
|
||||
}
|
||||
tt, err := time.Parse(time.RFC1123, s)
|
||||
if err != nil {
|
||||
// Legacy form: an RFC 3339 string.
|
||||
if tt3339, err3339 := time.Parse(time.RFC3339Nano, s); err3339 == nil {
|
||||
t.Time = tt3339
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("jsonx.TimeRFC1123: %w", err)
|
||||
}
|
||||
t.Time = tt
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t TimeRFC1123) MarshalJSONTo(enc *jsontext.Encoder) error {
|
||||
b, _ := t.MarshalJSON()
|
||||
return enc.WriteValue(b)
|
||||
}
|
||||
|
||||
func (t *TimeRFC1123) UnmarshalJSONFrom(dec *jsontext.Decoder) error {
|
||||
b, err := dec.ReadValue()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return t.UnmarshalJSON(b)
|
||||
}
|
||||
|
||||
// appendFrac appends the fraction n/max10 as a decimal point followed
|
||||
// by the significant fractional digits, omitting trailing zeros. It
|
||||
// appends nothing if n is zero. max10 must be a power of 10 larger
|
||||
// than n.
|
||||
func appendFrac(b []byte, n, max10 uint64) []byte {
|
||||
if n == 0 {
|
||||
return b
|
||||
}
|
||||
b = append(b, '.')
|
||||
for max10 > 1 {
|
||||
max10 /= 10
|
||||
b = append(b, byte('0'+n/max10))
|
||||
n %= max10
|
||||
}
|
||||
return bytes.TrimRight(b, "0")
|
||||
}
|
||||
|
||||
// parseDecimal parses a non-negative decimal number with an optional
|
||||
// fractional component, returning the whole part and the fraction
|
||||
// scaled to max10 (a power of 10). Fractional digits beyond the
|
||||
// precision of max10 must be zero.
|
||||
func parseDecimal(s string, max10 uint64) (whole int64, frac uint64, err error) {
|
||||
wholeStr, fracStr, hasFrac := strings.Cut(s, ".")
|
||||
whole, err = strconv.ParseInt(wholeStr, 10, 64)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
if !hasFrac {
|
||||
return whole, 0, nil
|
||||
}
|
||||
if fracStr == "" {
|
||||
return 0, 0, errors.New("empty fraction")
|
||||
}
|
||||
scale := max10
|
||||
for _, c := range []byte(fracStr) {
|
||||
if c < '0' || c > '9' {
|
||||
return 0, 0, fmt.Errorf("invalid fraction digit %q", c)
|
||||
}
|
||||
if scale > 1 {
|
||||
scale /= 10
|
||||
frac += uint64(c-'0') * scale
|
||||
} else if c != '0' {
|
||||
return 0, 0, errors.New("fraction exceeds available precision")
|
||||
}
|
||||
}
|
||||
return whole, frac, nil
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
// Copyright (c) Tailscale Inc & contributors
|
||||
// SPDX-License-Identifier: BSD-3-Clause
|
||||
|
||||
package jsonx
|
||||
|
||||
import (
|
||||
jsonv1 "encoding/json"
|
||||
"math/rand/v2"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
jsonv2 "github.com/go-json-experiment/json"
|
||||
)
|
||||
|
||||
// marshalWithFormatTag marshals v with the go-json-experiment module
|
||||
// with support for `format:` json tags enabled, producing the encoding
|
||||
// that these wrapper types must match byte for byte.
|
||||
func marshalWithFormatTag(t *testing.T, v any) []byte {
|
||||
t.Helper()
|
||||
b, err := jsonv2.Marshal(v, jsonv2.ExperimentalSupportFormatTag(true))
|
||||
if err != nil {
|
||||
t.Fatalf("module marshal: %v", err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// interestingDurations returns fixed and random durations covering the
|
||||
// interesting encoding cases.
|
||||
func interestingDurations() []time.Duration {
|
||||
ds := []time.Duration{
|
||||
0,
|
||||
time.Nanosecond,
|
||||
-time.Nanosecond,
|
||||
time.Second,
|
||||
-time.Second,
|
||||
time.Second + 500*time.Millisecond,
|
||||
90*time.Second + 500*time.Millisecond,
|
||||
time.Hour + 2*time.Minute + 3*time.Second,
|
||||
-(time.Hour + 2*time.Minute + 3*time.Second + 4*time.Nanosecond),
|
||||
123456789 * time.Nanosecond,
|
||||
time.Duration(1<<63 - 1),
|
||||
-time.Duration(1<<63 - 1),
|
||||
}
|
||||
for range 100 {
|
||||
ds = append(ds, time.Duration(rand.Int64()-rand.Int64()))
|
||||
}
|
||||
return ds
|
||||
}
|
||||
|
||||
// interestingTimes returns fixed and random times covering the
|
||||
// interesting encoding cases.
|
||||
func interestingTimes() []time.Time {
|
||||
ts := []time.Time{
|
||||
time.Unix(0, 0),
|
||||
time.Unix(1700000000, 0),
|
||||
time.Unix(1700000000, 500000000),
|
||||
time.Unix(1700000000, 123456789),
|
||||
time.Unix(1700000000, 1),
|
||||
time.Unix(-1, 500000000), // pre-epoch with fraction
|
||||
time.Unix(-1700000000, 0),
|
||||
time.Date(2262, 1, 1, 0, 0, 0, 999999999, time.UTC),
|
||||
}
|
||||
for range 100 {
|
||||
ts = append(ts, time.Unix(rand.Int64N(1<<33)-1<<32, rand.Int64N(1e9)))
|
||||
}
|
||||
return ts
|
||||
}
|
||||
|
||||
func TestDurationTypesMatchFormatTags(t *testing.T) {
|
||||
for _, d := range interestingDurations() {
|
||||
type tagged struct {
|
||||
Nano time.Duration `json:"n,format:nano"`
|
||||
Units time.Duration `json:"u,format:units"`
|
||||
ISO8601 time.Duration `json:"i,format:iso8601"`
|
||||
}
|
||||
want := marshalWithFormatTag(t, tagged{d, d, d})
|
||||
|
||||
type wrapped struct {
|
||||
Nano DurationNano `json:"n"`
|
||||
Units DurationUnits `json:"u"`
|
||||
ISO8601 DurationISO8601 `json:"i"`
|
||||
}
|
||||
w := wrapped{DurationNano(d), DurationUnits(d), DurationISO8601(d)}
|
||||
|
||||
gotV1, err := jsonv1.Marshal(w)
|
||||
if err != nil {
|
||||
t.Fatalf("d=%v: v1 marshal: %v", d, err)
|
||||
}
|
||||
gotV2, err := jsonv2.Marshal(w)
|
||||
if err != nil {
|
||||
t.Fatalf("d=%v: v2 marshal: %v", d, err)
|
||||
}
|
||||
if string(gotV1) != string(want) {
|
||||
t.Errorf("d=%v: v1 mismatch:\n got %s\nwant %s", d, gotV1, want)
|
||||
}
|
||||
if string(gotV2) != string(want) {
|
||||
t.Errorf("d=%v: v2 mismatch:\n got %s\nwant %s", d, gotV2, want)
|
||||
}
|
||||
|
||||
var back wrapped
|
||||
if err := jsonv1.Unmarshal(gotV1, &back); err != nil {
|
||||
t.Fatalf("d=%v: unmarshal: %v", d, err)
|
||||
}
|
||||
if back != w {
|
||||
t.Errorf("d=%v: round trip: got %+v, want %+v", d, back, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeTypesMatchFormatTags(t *testing.T) {
|
||||
for _, tt := range interestingTimes() {
|
||||
type tagged struct {
|
||||
Unix time.Time `json:"u,format:unix"`
|
||||
UnixNano time.Time `json:"n,format:unixnano"`
|
||||
RFC1123 time.Time `json:"r,format:RFC1123"`
|
||||
}
|
||||
want := marshalWithFormatTag(t, tagged{tt, tt, tt})
|
||||
|
||||
type wrapped struct {
|
||||
Unix TimeUnix `json:"u"`
|
||||
UnixNano TimeUnixNano `json:"n"`
|
||||
RFC1123 TimeRFC1123 `json:"r"`
|
||||
}
|
||||
w := wrapped{TimeUnix{tt}, TimeUnixNano{tt}, TimeRFC1123{tt}}
|
||||
|
||||
gotV1, err := jsonv1.Marshal(w)
|
||||
if err != nil {
|
||||
t.Fatalf("t=%v: v1 marshal: %v", tt, err)
|
||||
}
|
||||
gotV2, err := jsonv2.Marshal(w)
|
||||
if err != nil {
|
||||
t.Fatalf("t=%v: v2 marshal: %v", tt, err)
|
||||
}
|
||||
if string(gotV1) != string(want) {
|
||||
t.Errorf("t=%v: v1 mismatch:\n got %s\nwant %s", tt, gotV1, want)
|
||||
}
|
||||
if string(gotV2) != string(want) {
|
||||
t.Errorf("t=%v: v2 mismatch:\n got %s\nwant %s", tt, gotV2, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeUnixRoundTrip(t *testing.T) {
|
||||
for _, tt := range interestingTimes() {
|
||||
w := TimeUnix{tt}
|
||||
b, err := jsonv1.Marshal(w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var back TimeUnix
|
||||
if err := jsonv1.Unmarshal(b, &back); err != nil {
|
||||
t.Fatalf("t=%v: unmarshal %s: %v", tt, b, err)
|
||||
}
|
||||
if !back.Equal(tt) {
|
||||
t.Errorf("t=%v: round trip through %s: got %v", tt, b, back.Time)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeUnixNanoRoundTrip(t *testing.T) {
|
||||
for _, tt := range interestingTimes() {
|
||||
w := TimeUnixNano{tt}
|
||||
b, err := jsonv1.Marshal(w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var back TimeUnixNano
|
||||
if err := jsonv1.Unmarshal(b, &back); err != nil {
|
||||
t.Fatalf("t=%v: unmarshal %s: %v", tt, b, err)
|
||||
}
|
||||
if !back.Equal(tt) {
|
||||
t.Errorf("t=%v: round trip through %s: got %v", tt, b, back.Time)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeRFC1123RoundTrip(t *testing.T) {
|
||||
// RFC 1123 has only second precision and needs a UTC zone name to
|
||||
// round trip exactly.
|
||||
tt := time.Date(2026, 8, 1, 12, 34, 56, 0, time.UTC)
|
||||
w := TimeRFC1123{tt}
|
||||
b, err := jsonv1.Marshal(w)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var back TimeRFC1123
|
||||
if err := jsonv1.Unmarshal(b, &back); err != nil {
|
||||
t.Fatalf("unmarshal %s: %v", b, err)
|
||||
}
|
||||
if !back.Equal(tt) {
|
||||
t.Errorf("round trip through %s: got %v, want %v", b, back.Time, tt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyFormsAccepted(t *testing.T) {
|
||||
// Times written by the legacy standard library encoding/json (which
|
||||
// ignored format tags) are RFC 3339 strings; durations are integer
|
||||
// nanosecond counts. Unmarshal must accept both.
|
||||
legacyTime, err := jsonv1.Marshal(time.Unix(1700000000, 500000000).UTC())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var tu TimeUnix
|
||||
if err := jsonv1.Unmarshal(legacyTime, &tu); err != nil {
|
||||
t.Fatalf("TimeUnix legacy %s: %v", legacyTime, err)
|
||||
}
|
||||
var tn TimeUnixNano
|
||||
if err := jsonv1.Unmarshal(legacyTime, &tn); err != nil {
|
||||
t.Fatalf("TimeUnixNano legacy %s: %v", legacyTime, err)
|
||||
}
|
||||
var tr TimeRFC1123
|
||||
if err := jsonv1.Unmarshal(legacyTime, &tr); err != nil {
|
||||
t.Fatalf("TimeRFC1123 legacy %s: %v", legacyTime, err)
|
||||
}
|
||||
want := time.Unix(1700000000, 500000000)
|
||||
for name, got := range map[string]time.Time{"TimeUnix": tu.Time, "TimeUnixNano": tn.Time, "TimeRFC1123": tr.Time} {
|
||||
if !got.Equal(want) {
|
||||
t.Errorf("%s legacy: got %v, want %v", name, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
var du DurationUnits
|
||||
if err := jsonv1.Unmarshal([]byte("90500000000"), &du); err != nil {
|
||||
t.Fatalf("DurationUnits legacy: %v", err)
|
||||
}
|
||||
if du.Duration() != 90*time.Second+500*time.Millisecond {
|
||||
t.Errorf("DurationUnits legacy: got %v", du)
|
||||
}
|
||||
var di DurationISO8601
|
||||
if err := jsonv1.Unmarshal([]byte("90500000000"), &di); err != nil {
|
||||
t.Fatalf("DurationISO8601 legacy: %v", err)
|
||||
}
|
||||
if di.Duration() != 90*time.Second+500*time.Millisecond {
|
||||
t.Errorf("DurationISO8601 legacy: got %v", di)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOmitZero(t *testing.T) {
|
||||
type S struct {
|
||||
D DurationNano `json:"d,omitzero"`
|
||||
T TimeUnix `json:"t,omitzero"`
|
||||
}
|
||||
b, err := jsonv2.Marshal(S{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(b) != "{}" {
|
||||
t.Errorf("omitzero: got %s, want {}", b)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user