Skip to content

Commit

Permalink
codec: use stdlib time.Time encoding
Browse files Browse the repository at this point in the history
The new json encoder has different behavior for encoding zero time.Time
values. This change forces the Marshal method to be called, which gets
back the previous behavior (always produce a string) at the cost of
doing an allocation.

Closes #1231

Signed-off-by: Hank Donnay <hdonnay@redhat.com>
  • Loading branch information
hdonnay committed Apr 9, 2021
1 parent 60f9684 commit d5cac13
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
4 changes: 4 additions & 0 deletions internal/codec/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ func init() {
// This is documented to cause "smart buffering".
jsonHandle.WriterBufferSize = 4096
jsonHandle.ReaderBufferSize = 4096
// Force calling time.Time's Marshal function. This causes an allocation on
// every time.Time value, but is the same behavior as the stdlib json
// encoder. If we decide nulls are OK, this should get removed.
jsonHandle.TimeNotBuiltin = true
}

// Encoder and decoder pools, to reuse if possible.
Expand Down
27 changes: 27 additions & 0 deletions internal/codec/codec_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package codec

import (
"bytes"
"encoding/json"
"fmt"
"os"
"strings"
"testing"
"time"

"github.com/google/go-cmp/cmp"
)
Expand Down Expand Up @@ -72,3 +74,28 @@ func BenchmarkDecodeStdlib(b *testing.B) {
}
}
}

func TestTimeNotNull(t *testing.T) {
type s struct {
Time time.Time
}
var b bytes.Buffer
enc := GetEncoder(&b)
defer PutEncoder(enc)

// Example encoding of a populated time:
if err := enc.Encode(s{Time: time.Unix(0, 0).UTC()}); err != nil {
t.Error(err)
}
t.Log(b.String())
b.Reset()

// Now encode a zero time and make sure it's a string.
if err := enc.Encode(s{}); err != nil {
t.Error(err)
}
t.Log(b.String())
if strings.Contains(b.String(), "null") {
t.Error("wanted non-null encoding")
}
}

0 comments on commit d5cac13

Please sign in to comment.