Convert converts the value to given scalar type.
(from Val, toID TypeID)
| 94 | |
| 95 | // Convert converts the value to given scalar type. |
| 96 | func Convert(from Val, toID TypeID) (Val, error) { |
| 97 | to := Val{Tid: toID} |
| 98 | |
| 99 | // sanity: we expect a value |
| 100 | data, ok := from.Value.([]byte) |
| 101 | if !ok { |
| 102 | return to, errors.Errorf("invalid data to convert to %s", toID.Name()) |
| 103 | } |
| 104 | |
| 105 | fromID := from.Tid |
| 106 | res := &to.Value |
| 107 | |
| 108 | // Convert from-type to to-type and store in the result interface. |
| 109 | switch fromID { |
| 110 | case BinaryID: |
| 111 | { |
| 112 | // Unmarshal from Binary to type interfaces. |
| 113 | switch toID { |
| 114 | case BinaryID: |
| 115 | *res = data |
| 116 | case StringID, DefaultID: |
| 117 | // We never modify from Val, so this should be safe. |
| 118 | *res = *(*string)(unsafe.Pointer(&data)) |
| 119 | case IntID: |
| 120 | if len(data) < 8 { |
| 121 | return to, errors.Errorf("invalid data for int64 %v", data) |
| 122 | } |
| 123 | *res = int64(binary.LittleEndian.Uint64(data)) |
| 124 | case FloatID: |
| 125 | if len(data) < 8 { |
| 126 | return to, errors.Errorf("invalid data for float %v", data) |
| 127 | } |
| 128 | i := binary.LittleEndian.Uint64(data) |
| 129 | *res = math.Float64frombits(i) |
| 130 | case BigFloatID: |
| 131 | var b big.Float |
| 132 | b.SetPrec(BigFloatPrecision) |
| 133 | if err := b.UnmarshalText(data); err != nil { |
| 134 | return to, err |
| 135 | } |
| 136 | *res = b |
| 137 | case BoolID: |
| 138 | if len(data) == 0 || data[0] == 0 { |
| 139 | *res = false |
| 140 | return to, nil |
| 141 | } else if data[0] == 1 { |
| 142 | *res = true |
| 143 | return to, nil |
| 144 | } |
| 145 | return to, errors.Errorf("invalid value for bool %v", data[0]) |
| 146 | case DateTimeID: |
| 147 | var t time.Time |
| 148 | if err := t.UnmarshalBinary(data); err != nil { |
| 149 | return to, err |
| 150 | } |
| 151 | *res = t |
| 152 | case GeoID: |
| 153 | w, err := wkb.Unmarshal(data) |