2
0

Simplify []byte scanning

This commit is contained in:
Jack Christensen
2017-03-18 14:42:36 -05:00
parent df8f8e17cf
commit d516894475
2 changed files with 35 additions and 2 deletions
+10
View File
@@ -49,6 +49,16 @@ func (src *Text) AssignTo(dst interface{}) error {
return fmt.Errorf("cannot assign %v to %T", src, dst)
}
*v = src.String
case *[]byte:
switch src.Status {
case Present:
*v = make([]byte, len(src.String))
copy(*v, src.String)
case Null:
*v = nil
default:
return fmt.Errorf("unknown status")
}
default:
if v := reflect.ValueOf(dst); v.Kind() == reflect.Ptr {
el := v.Elem()
+25 -2
View File
@@ -1,6 +1,7 @@
package pgtype_test
import (
"bytes"
"reflect"
"testing"
@@ -44,7 +45,7 @@ func TestTextAssignTo(t *testing.T) {
var s string
var ps *string
simpleTests := []struct {
stringTests := []struct {
src pgtype.Text
dst interface{}
expected interface{}
@@ -53,7 +54,7 @@ func TestTextAssignTo(t *testing.T) {
{src: pgtype.Text{Status: pgtype.Null}, dst: &ps, expected: ((*string)(nil))},
}
for i, tt := range simpleTests {
for i, tt := range stringTests {
err := tt.src.AssignTo(tt.dst)
if err != nil {
t.Errorf("%d: %v", i, err)
@@ -64,6 +65,28 @@ func TestTextAssignTo(t *testing.T) {
}
}
var buf []byte
bytesTests := []struct {
src pgtype.Text
dst *[]byte
expected []byte
}{
{src: pgtype.Text{String: "foo", Status: pgtype.Present}, dst: &buf, expected: []byte("foo")},
{src: pgtype.Text{Status: pgtype.Null}, dst: &buf, expected: nil},
}
for i, tt := range bytesTests {
err := tt.src.AssignTo(tt.dst)
if err != nil {
t.Errorf("%d: %v", i, err)
}
if bytes.Compare(*tt.dst, tt.expected) != 0 {
t.Errorf("%d: expected %v to assign %v, but result was %v", i, tt.src, tt.expected, tt.dst)
}
}
pointerAllocTests := []struct {
src pgtype.Text
dst interface{}