Commit 38e74922 authored by Eric Myhre's avatar Eric Myhre

Handle byte slices in fluent.Reflect.

parent 295aef09
......@@ -160,6 +160,8 @@ func (rcfg Reflector) ReflectIntoAssembler(na ipld.NodeAssembler, i interface{})
return la.Finish()
case string:
return na.AssignString(x)
case []byte:
return na.AssignBytes(x)
case int:
return na.AssignInt(x)
case nil:
......@@ -170,14 +172,18 @@ func (rcfg Reflector) ReflectIntoAssembler(na ipld.NodeAssembler, i interface{})
switch rv.Kind() {
case reflect.Bool:
return na.AssignBool(rv.Bool())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return na.AssignInt(int(rv.Int()))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return na.AssignInt(int(rv.Uint()))
case reflect.Float32, reflect.Float64:
return na.AssignFloat(rv.Float())
case reflect.String:
return na.AssignString(rv.String())
case reflect.Slice, reflect.Array:
if rv.Type().Elem().Kind() == reflect.Uint8 { // byte slices are a special case
return na.AssignBytes(rv.Bytes())
}
l := rv.Len()
la, err := na.BeginList(l)
if err != nil {
......
......@@ -114,4 +114,41 @@ func TestReflect(t *testing.T) {
Wish(t, n.ReprKind(), ShouldEqual, ipld.ReprKind_Map)
Wish(t, must.String(must.Node(n.LookupByString("wow"))), ShouldEqual, "wee")
})
t.Run("Bytes", func(t *testing.T) {
n, err := fluent.Reflect(basicnode.Prototype.Any, []byte{0x1, 0x2, 0x3})
Wish(t, err, ShouldEqual, nil)
Wish(t, n.ReprKind(), ShouldEqual, ipld.ReprKind_Bytes)
b, err := n.AsBytes()
Wish(t, err, ShouldEqual, nil)
Wish(t, b, ShouldEqual, []byte{0x1, 0x2, 0x3})
})
t.Run("NamedBytes", func(t *testing.T) {
type Foo []byte
type Bar struct {
Z Foo
}
n, err := fluent.Reflect(basicnode.Prototype.Any, Bar{[]byte{0x1, 0x2, 0x3}})
Wish(t, err, ShouldEqual, nil)
Wish(t, n.ReprKind(), ShouldEqual, ipld.ReprKind_Map)
n, err = n.LookupByString("Z")
Wish(t, err, ShouldEqual, nil)
Wish(t, n.ReprKind(), ShouldEqual, ipld.ReprKind_Bytes)
b, err := n.AsBytes()
Wish(t, err, ShouldEqual, nil)
Wish(t, b, ShouldEqual, []byte{0x1, 0x2, 0x3})
})
t.Run("InterfaceContainingBytes", func(t *testing.T) {
type Zaz struct {
Z interface{}
}
n, err := fluent.Reflect(basicnode.Prototype.Any, Zaz{[]byte{0x1, 0x2, 0x3}})
Wish(t, err, ShouldEqual, nil)
Wish(t, n.ReprKind(), ShouldEqual, ipld.ReprKind_Map)
n, err = n.LookupByString("Z")
Wish(t, err, ShouldEqual, nil)
Wish(t, n.ReprKind(), ShouldEqual, ipld.ReprKind_Bytes)
b, err := n.AsBytes()
Wish(t, err, ShouldEqual, nil)
Wish(t, b, ShouldEqual, []byte{0x1, 0x2, 0x3})
})
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment