Skip to content

Commit

Permalink
feat: support java null encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
ahaostudy authored and root committed Nov 25, 2023
1 parent 6c40744 commit 5d34775
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
31 changes: 29 additions & 2 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ type Encoder struct {
classInfoList []*ClassInfo
buffer []byte
refMap map[unsafe.Pointer]_refElem
config *EncoderConfig
}

// classIndex find the index of the given java name in encoder class info list.
Expand All @@ -49,12 +50,32 @@ func (e *Encoder) classIndex(javaName string) int {
}

// NewEncoder generate an encoder instance
func NewEncoder() *Encoder {
func NewEncoder(opts ...EncoderOption) *Encoder {
buffer := make([]byte, 64)
config := &EncoderConfig{}
for _, opt := range opts {
opt(config)
}

return &Encoder{
buffer: buffer[:0],
refMap: make(map[unsafe.Pointer]_refElem, 7),
config: config,
}
}

// EncoderConfig config for encoder
type EncoderConfig struct {
JavaNullCompatible bool
}

// EncoderOption inject configuration into encoder
type EncoderOption func(*EncoderConfig)

// WithJavaNullCompatible configuring java null compatible for encoder
func WithJavaNullCompatible() EncoderOption {
return func(config *EncoderConfig) {
config.JavaNullCompatible = true
}
}

Expand Down Expand Up @@ -94,7 +115,13 @@ func (e *Encoder) Append(buf []byte) {

// Encode If @v can not be encoded, the return value is nil. At present only struct may can not be encoded.
func (e *Encoder) Encode(v interface{}) error {
if v == nil {
if e.config.JavaNullCompatible {
vv := reflect.ValueOf(v)
if vv.Kind() == reflect.Ptr && vv.IsNil() {
e.buffer = EncNull(e.buffer)
return nil
}
} else if v == nil {
e.buffer = EncNull(e.buffer)
return nil
}
Expand Down
14 changes: 13 additions & 1 deletion null_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,18 @@ func TestNull(t *testing.T) {
testDecodeFramework(t, "replyNull", nil)
}

func TestNulEncode(t *testing.T) {
func TestNullEncode(t *testing.T) {
testJavaDecode(t, "argNull", nil)
}

func TestNullCompatibleEncode(t *testing.T) {
e := NewEncoder(
WithJavaNullCompatible(),
)
var null *int = nil
e.Encode(null)
if e.Buffer() == nil {
t.Fail()
}
assertEqual([]byte("N"), e.buffer, t)
}

0 comments on commit 5d34775

Please sign in to comment.