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:(ast) nill Node can marshal to null #685

Merged
merged 1 commit into from
Aug 6, 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
6 changes: 4 additions & 2 deletions ast/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,10 @@ import (
// Hack: this is used for both checking space and cause firendly compile errors in 32-bit arch.
const _Sonic_Not_Support_32Bit_Arch__Checking_32Bit_Arch_Here = (1 << ' ') | (1 << '\t') | (1 << '\r') | (1 << '\n')

var bytesNull = []byte("null")

const (
bytesNull = "null"
strNull = "null"
bytesTrue = "true"
bytesFalse = "false"
bytesObject = "{}"
Expand Down Expand Up @@ -64,7 +66,7 @@ func decodeNull(src string, pos int) (ret int) {
if ret > len(src) {
return -int(types.ERR_EOF)
}
if src[pos:ret] == bytesNull {
if src[pos:ret] == strNull {
return ret
} else {
return -int(types.ERR_INVALID_CHAR)
Expand Down
6 changes: 5 additions & 1 deletion ast/encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@ func quoteString(e *[]byte, s string) {
var bytesPool = sync.Pool{}

func (self *Node) MarshalJSON() ([]byte, error) {
if self == nil {
return bytesNull, nil
}

buf := newBuffer()
err := self.encode(buf)
if err != nil {
Expand Down Expand Up @@ -159,7 +163,7 @@ func (self *Node) encodeRaw(buf *[]byte) error {
}

func (self *Node) encodeNull(buf *[]byte) error {
*buf = append(*buf, bytesNull...)
*buf = append(*buf, strNull...)
return nil
}

Expand Down
16 changes: 16 additions & 0 deletions ast/encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,23 @@ func TestEncodeValue(t *testing.T) {
}
}

func BenchmarkNil(b *testing.B) {
for i:=0; i<b.N; i++ {
null := (*Node)(nil)
_, _ = null.MarshalJSON()
}
}

func TestEncodeNode(t *testing.T) {
null := (*Node)(nil)
js, err := null.MarshalJSON()
if err != nil {
t.Fatal(err)
}
if string(js) != "null" {
t.Fatal(string(js))
}

data := `{"a":[{},[],-0.1,true,false,null,""],"b":0,"c":true,"d":false,"e":null,"g":""}`
root, e := NewSearcher(data).GetByPath()
if e != nil {
Expand Down
Loading