pk.Ary support pointer of slice for WriteTo() #98

This commit is contained in:
Tnze
2021-04-02 09:29:51 +08:00
parent c4c4ebeda8
commit c6255de745
2 changed files with 28 additions and 1 deletions

View File

@ -25,6 +25,9 @@ type Ary struct {
func (a Ary) WriteTo(r io.Writer) (n int64, err error) {
array := reflect.ValueOf(a.Ary)
for array.Kind() == reflect.Ptr {
array = array.Elem()
}
for i := 0; i < array.Len(); i++ {
elem := array.Index(i)
nn, err := elem.Interface().(FieldEncoder).WriteTo(r)
@ -54,7 +57,13 @@ func (a Ary) length() int {
func (a Ary) ReadFrom(r io.Reader) (n int64, err error) {
length := a.length()
array := reflect.ValueOf(a.Ary).Elem()
array := reflect.ValueOf(a.Ary)
for array.Kind() == reflect.Ptr {
array = array.Elem()
}
if !array.CanAddr() {
panic(errors.New("the Ary is not addressable"))
}
if array.Cap() < length {
array.Set(reflect.MakeSlice(array.Type(), length, length))
}

View File

@ -93,6 +93,24 @@ func TestAry_WriteTo(t *testing.T) {
}
}
func TestAry_WriteTo_pointer(t *testing.T) {
var buf bytes.Buffer
want := []byte{
0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x02,
0x00, 0x00, 0x00, 0x03,
}
data := pk.Ary{Ary: &[]pk.Int{1, 2, 3}}
_, err := data.WriteTo(&buf)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(buf.Bytes(), want) {
t.Fatalf("Ary encoding error: got %#v, want %#v", buf.Bytes(), want)
}
}
func ExampleOpt_ReadFrom() {
var has pk.Boolean