1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Type conversions for Scan.
16 // convertAssign copies to dest the value in src, converting it if possible.
17 // An error is returned if the copy would result in loss of information.
18 // dest should be a pointer type.
19 func convertAssign(dest, src interface{}) os.Error {
20 // Common cases, without reflect. Fall through.
21 switch s := src.(type) {
23 switch d := dest.(type) {
29 switch d := dest.(type) {
39 sv := reflect.ValueOf(src)
41 switch d := dest.(type) {
45 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
46 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
47 reflect.Float32, reflect.Float64:
48 *d = fmt.Sprintf("%v", src)
53 if scanner, ok := dest.(ScannerInto); ok {
54 return scanner.ScanInto(src)
57 dpv := reflect.ValueOf(dest)
58 if dpv.Kind() != reflect.Ptr {
59 return os.NewError("destination not a pointer")
62 dv := reflect.Indirect(dpv)
63 if dv.Kind() == sv.Kind() {
69 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
70 if s, ok := asString(src); ok {
71 i64, err := strconv.Atoi64(s)
73 return fmt.Errorf("converting string %q to a %s: %v", s, dv.Kind(), err)
75 if dv.OverflowInt(i64) {
76 return fmt.Errorf("string %q overflows %s", s, dv.Kind())
81 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
82 if s, ok := asString(src); ok {
83 u64, err := strconv.Atoui64(s)
85 return fmt.Errorf("converting string %q to a %s: %v", s, dv.Kind(), err)
87 if dv.OverflowUint(u64) {
88 return fmt.Errorf("string %q overflows %s", s, dv.Kind())
95 return fmt.Errorf("unsupported driver -> Scan pair: %T -> %T", src, dest)
98 func asString(src interface{}) (s string, ok bool) {
99 switch v := src.(type) {
103 return string(v), true