Skip to content

Commit

Permalink
feat(enc.b64): ensure compat with stdlib
Browse files Browse the repository at this point in the history
  • Loading branch information
ernado committed Nov 5, 2021
1 parent bd32fe4 commit 6792720
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 8 deletions.
3 changes: 1 addition & 2 deletions enc_b64.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,10 @@ import "encoding/base64"
//
// Same as encoding/json, base64.StdEncoding or RFC 4648.
func (e *Encoder) Base64(data []byte) {
if len(data) == 0 {
if data == nil {
e.Null()
return
}

e.byte('"')
encodedLen := base64.StdEncoding.EncodedLen(len(data))
start := len(e.buf)
Expand Down
17 changes: 13 additions & 4 deletions enc_b64_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,19 @@ func TestEncoder_Base64(t *testing.T) {
requireCompat(t, e.Bytes(), s)
}
})
t.Run("Zero", func(t *testing.T) {
var e Encoder
e.Base64([]byte{})
require.Equal(t, `null`, e.String())
t.Run("Zeroes", func(t *testing.T) {
t.Run("Nil", func(t *testing.T) {
v := []byte(nil)
var e Encoder
e.Base64(v)
requireCompat(t, e.Bytes(), v)
})
t.Run("ZeroLen", func(t *testing.T) {
v := make([]byte, 0)
var e Encoder
e.Base64(v)
requireCompat(t, e.Bytes(), v)
})
})
}

Expand Down
4 changes: 2 additions & 2 deletions jx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ import (
)

// requireCompat fails if `encoding/json` will encode v differently than exp.
func requireCompat(t testing.TB, exp []byte, v interface{}) {
func requireCompat(t testing.TB, got []byte, v interface{}) {
t.Helper()
buf, err := json.Marshal(v)
require.NoError(t, err)
require.Equal(t, exp, buf)
require.Equal(t, buf, got)
}

func TestPutEncoder(t *testing.T) {
Expand Down

0 comments on commit 6792720

Please sign in to comment.