From e8836d6d46a6f463171eb2fb09b0a8bcc6e9e40c Mon Sep 17 00:00:00 2001 From: "duanyi.aster" Date: Tue, 6 Aug 2024 15:04:10 +0800 Subject: [PATCH] feat:(ast) nill Node can marshal to `null` --- ast/decode.go | 6 ++++-- ast/encode.go | 6 +++++- ast/encode_test.go | 16 ++++++++++++++++ 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/ast/decode.go b/ast/decode.go index 2593d4fc4..6690d513e 100644 --- a/ast/decode.go +++ b/ast/decode.go @@ -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 = "{}" @@ -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) diff --git a/ast/encode.go b/ast/encode.go index 345f91fe8..eae0bd258 100644 --- a/ast/encode.go +++ b/ast/encode.go @@ -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 { @@ -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 } diff --git a/ast/encode_test.go b/ast/encode_test.go index 45446ebd7..67cdb90d2 100644 --- a/ast/encode_test.go +++ b/ast/encode_test.go @@ -120,7 +120,23 @@ func TestEncodeValue(t *testing.T) { } } +func BenchmarkNil(b *testing.B) { + for i:=0; i