forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
casts.go
38 lines (33 loc) · 921 Bytes
/
casts.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Copyright 2016 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package topdown
import (
"encoding/json"
"strconv"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/topdown/builtins"
)
func builtinToNumber(a ast.Value) (ast.Value, error) {
switch a := a.(type) {
case ast.Null:
return ast.Number("0"), nil
case ast.Boolean:
if a {
return ast.Number("1"), nil
}
return ast.Number("0"), nil
case ast.Number:
return a, nil
case ast.String:
_, err := strconv.ParseFloat(string(a), 64)
if err != nil {
return nil, err
}
return ast.Number(json.Number(a)), nil
}
return nil, builtins.NewOperandTypeErr(1, a, ast.NullTypeName, ast.BooleanTypeName, ast.NumberTypeName, ast.StringTypeName)
}
func init() {
RegisterFunctionalBuiltin1(ast.ToNumber.Name, builtinToNumber)
}