Skip to content

Commit

Permalink
Fix loading of numbers. (#3)
Browse files Browse the repository at this point in the history
The javascript firestore sdks can convert automatically between integer and floating types.
This updates the loading code to convert between ints and floats.
Based on https://github.com/googleapis/google-cloud-go/blob/27b5416a80e6a65ee9eebda55f06def51b9b7b88/firestore/from_value.go#L119
  • Loading branch information
ribrdb authored Jun 1, 2020
1 parent 27f753c commit 7941af9
Showing 1 changed file with 27 additions and 7 deletions.
34 changes: 27 additions & 7 deletions load.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,18 @@ func (l *propertyLoader) load(codec *structCodec, structValue reflect.Value, p P
func setVal(v reflect.Value, pValue interface{}) string {
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
x, ok := pValue.(int64)
if !ok && pValue != nil {
var x int64
switch pv := pValue.(type) {
case int64:
x = pv
case float64:
x = int64(pv)
if float64(x) != pv {
return fmt.Sprintf("float %f does not fit into %s", pv, v.Type())
}
case nil:
x = 0
default:
return typeMismatchReason(pValue, v)
}
if v.OverflowInt(x) {
Expand All @@ -177,14 +187,24 @@ func setVal(v reflect.Value, pValue interface{}) string {
}
}
case reflect.Float32, reflect.Float64:
x, ok := pValue.(float64)
if !ok && pValue != nil {
var f float64
switch x := pValue.(type) {
case float64:
f = x
case int64:
f = float64(x)
if int64(f) != x {
return fmt.Sprintf("value %v overflows struct field of type %v", x, v.Type())
}
case nil:
f = 0
default:
return typeMismatchReason(pValue, v)
}
if v.OverflowFloat(x) {
return fmt.Sprintf("value %v overflows struct field of type %v", x, v.Type())
if v.OverflowFloat(f) {
return fmt.Sprintf("value %v overflows struct field of type %v", f, v.Type())
}
v.SetFloat(x)
v.SetFloat(f)
case reflect.Ptr:
x, ok := pValue.(*Key)
if !ok && pValue != nil {
Expand Down

0 comments on commit 7941af9

Please sign in to comment.