Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for JSON null value #14

Merged
merged 1 commit into from
Oct 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions codec.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package udecimal

import (
"bytes"
"database/sql"
"database/sql/driver"
"encoding"
Expand Down Expand Up @@ -236,13 +237,21 @@ func (d Decimal) MarshalJSON() ([]byte, error) {
return []byte(`"` + d.stringBigInt(true) + `"`), nil
}

// nullValue represents the JSON null value.
var nullValue = []byte("null")

// UnmarshalJSON implements the [json.Unmarshaler] interface.
func (d *Decimal) UnmarshalJSON(data []byte) error {
// Remove quotes if they exist.
if len(data) >= 2 && data[0] == '"' && data[len(data)-1] == '"' {
data = data[1 : len(data)-1]
}

// null value.
if bytes.Equal(data, nullValue) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The bytes.Equal function is optimized for performance and will perform much better than bytes.Compare.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm good with this. Just add benchmark here for reference

goos: linux
goarch: amd64
cpu: Intel(R) Core(TM) i9-14900HX
BenchmarkByteEqual-32    	1000000000	         0.1213 ns/op	       0 B/op	       0 allocs/op
BenchmarkByteCmp-32    	247671904	         4.825 ns/op	       0 B/op	       0 allocs/op

return nil
}

return d.UnmarshalText(data)
}

Expand Down
7 changes: 7 additions & 0 deletions codec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,13 @@ func TestUnmarshalJSON(t *testing.T) {
}
}

func TestUnmarshalJSONNull(t *testing.T) {
var test Test
err := json.Unmarshal([]byte(`{"price": null}`), &test)
require.NoError(t, err)
require.True(t, test.Test.IsZero())
}

func TestMarshalBinary(t *testing.T) {
testcases := []struct {
in string
Expand Down