Skip to content

Commit

Permalink
feat:(ast) nill Node can marshal to null (#685)
Browse files Browse the repository at this point in the history
  • Loading branch information
AsterDY authored Aug 6, 2024
1 parent 10a00a9 commit 1a0c001
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
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

0 comments on commit 1a0c001

Please sign in to comment.