2019-05-01 09:23:05 +00:00
|
|
|
package builtin
|
|
|
|
|
2019-05-01 13:14:49 +00:00
|
|
|
import (
|
2019-05-03 18:09:04 +00:00
|
|
|
"encoding/json"
|
2019-05-01 13:14:49 +00:00
|
|
|
|
|
|
|
"git.xdrm.io/go/aicra/typecheck"
|
|
|
|
)
|
2019-05-01 09:23:05 +00:00
|
|
|
|
|
|
|
// Float64 checks if a value is a float64
|
|
|
|
type Float64 struct{}
|
|
|
|
|
|
|
|
// NewFloat64 returns a bare number type checker
|
|
|
|
func NewFloat64() *Float64 {
|
|
|
|
return &Float64{}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Checker returns the checker function
|
2019-05-02 20:15:03 +00:00
|
|
|
func (Float64) Checker(typeName string) typecheck.CheckerFunc {
|
2019-05-01 09:23:05 +00:00
|
|
|
// nothing if type not handled
|
|
|
|
if typeName != "float64" && typeName != "float" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return func(value interface{}) bool {
|
2019-05-02 20:15:03 +00:00
|
|
|
_, isFloat := readFloat(value)
|
|
|
|
return isFloat
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// readFloat tries to read a serialized float and returns whether it succeeded.
|
|
|
|
func readFloat(value interface{}) (float64, 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 string:
|
2019-05-03 18:09:04 +00:00
|
|
|
num := json.Number(cast)
|
|
|
|
floatVal, err := num.Float64()
|
2019-05-02 20:15:03 +00:00
|
|
|
return floatVal, err == nil
|
|
|
|
|
2019-11-18 15:17:02 +00:00
|
|
|
case []byte:
|
|
|
|
num := json.Number(cast)
|
|
|
|
floatVal, err := num.Float64()
|
|
|
|
return floatVal, err == nil
|
|
|
|
|
2019-05-02 20:15:03 +00:00
|
|
|
// unknown type
|
|
|
|
default:
|
|
|
|
return 0, false
|
|
|
|
|
2019-05-01 09:23:05 +00:00
|
|
|
}
|
|
|
|
}
|