From 8ccde101426c9b296deb205af2d8b6ac7eaad99d Mon Sep 17 00:00:00 2001 From: Oleg Kovalov Date: Fri, 8 Dec 2023 18:05:46 +0100 Subject: [PATCH] Encode more integer types (#24) --- encode.go | 10 ++++++++-- encode_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/encode.go b/encode.go index defa04b..33d9c95 100644 --- a/encode.go +++ b/encode.go @@ -190,16 +190,22 @@ func (enc *Encoder) writeValue(ename string, v reflect.Value) (int, error) { case reflect.String: count += enc.writeElem(TypeString, ename) count += enc.writeString(v.String()) - case reflect.Int32: + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32: count += enc.writeElem(TypeInt32, ename) count += enc.writeInt32(int32(v.Int())) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32: + count += enc.writeElem(TypeInt32, ename) + count += enc.writeInt32(int32(v.Uint())) + case reflect.Uint64: + count += enc.writeElem(TypeInt64, ename) + count += enc.writeInt64(int64(v.Uint())) case reflect.Int64: count += enc.writeElem(TypeInt64, ename) count += enc.writeInt64(int64(v.Int())) case reflect.Bool: count += enc.writeElem(TypeBool, ename) count += enc.writeBool(v.Bool()) - case reflect.Float64: + case reflect.Float32, reflect.Float64: count += enc.writeElem(TypeDouble, ename) count += enc.writeInt64(int64(math.Float64bits(v.Float()))) diff --git a/encode_test.go b/encode_test.go index 43042a1..cb257cb 100644 --- a/encode_test.go +++ b/encode_test.go @@ -5,6 +5,34 @@ import ( "testing" ) +func TestEncode(t *testing.T) { + var buf bytes.Buffer + enc := NewEncoder(&buf) + + var err error + var arr A + + arr = A{ + bool(true), + int(123), + int8(123), + int16(123), + int32(123), + int64(123), + uint(123), + uint8(123), + uint16(123), + uint32(123), + uint64(123), + float32(123), + float64(123), + } + err = enc.Encode(arr) + mustOk(t, err) + wantBytes(t, buf.Bytes(), "70000000083000011031007b0000001032007b0000001033007b0000001034007b0000001235007b000000000000001036007b0000001037007b0000001038007b0000001039007b000000123130007b00000000000000013131000000000000c05e40013132000000000000c05e4000") + buf.Reset() +} + func TestEncodeA(t *testing.T) { var buf bytes.Buffer enc := NewEncoder(&buf)