2020-03-14 15:13:38 +00:00
|
|
|
package builtin
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2020-03-28 17:48:27 +00:00
|
|
|
"reflect"
|
2020-03-14 15:13:38 +00:00
|
|
|
|
2020-03-16 08:20:00 +00:00
|
|
|
"git.xdrm.io/go/aicra/datatype"
|
2020-03-14 15:13:38 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// FloatDataType is what its name tells
|
|
|
|
type FloatDataType struct{}
|
|
|
|
|
2020-03-28 18:11:23 +00:00
|
|
|
// Type returns the type of data
|
|
|
|
func (FloatDataType) Type() reflect.Type {
|
|
|
|
return reflect.TypeOf(float64(0))
|
2020-03-28 17:48:27 +00:00
|
|
|
}
|
|
|
|
|
2020-03-14 15:13:38 +00:00
|
|
|
// Build returns the validator
|
2020-03-22 15:50:10 +00:00
|
|
|
func (FloatDataType) Build(typeName string, registry ...datatype.T) datatype.Validator {
|
2020-03-14 15:13:38 +00:00
|
|
|
// nothing if type not handled
|
|
|
|
if typeName != "float64" && typeName != "float" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return func(value interface{}) (interface{}, bool) {
|
|
|
|
switch cast := value.(type) {
|
|
|
|
|
|
|
|
case int:
|
|
|
|
return float64(cast), true
|
|
|
|
|
|
|
|
case uint:
|
|
|
|
return float64(cast), true
|
|
|
|
|
|
|
|
case float64:
|
|
|
|
return cast, true
|
|
|
|
|
|
|
|
// serialized string -> try to convert to float
|
|
|
|
case []byte:
|
|
|
|
num := json.Number(cast)
|
|
|
|
floatVal, err := num.Float64()
|
|
|
|
return floatVal, err == nil
|
|
|
|
|
|
|
|
case string:
|
|
|
|
num := json.Number(cast)
|
|
|
|
floatVal, err := num.Float64()
|
|
|
|
return floatVal, err == nil
|
|
|
|
|
|
|
|
// unknown type
|
|
|
|
default:
|
|
|
|
return 0, false
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|