Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add hexadecimal support for tonumber() #22585

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion lang/funcs/conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/convert"
"github.com/zclconf/go-cty/cty/function"
"github.com/zclconf/go-cty/cty/gocty"
)

// MakeToFunc constructs a "to..." function, like "tostring", which converts
Expand Down Expand Up @@ -54,6 +55,17 @@ func MakeToFunc(wantTy cty.Type) function.Function {
return wantTy, nil
},
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {

// handle 0x prefixed hex strings for tonumber()
gotTy := args[0].Type()
if gotTy == cty.String && wantTy == cty.Number && !args[0].IsNull() &&
len(args[0].AsString()) > 2 && args[0].AsString()[:2] == "0x" {
hexInt, err := strconv.ParseInt(args[0].AsString()[2:], 16, 64)
if err == nil {
// instead of failing up here, allow conversion attempt to proceed and errors are caught below.
args[0], _ = gocty.ToCtyValue(hexInt, cty.Number)
}
}
// We didn't set "AllowUnknown" on our argument, so it is guaranteed
// to be known here but may still be null.
ret, err := convert.Convert(args[0], retType)
Expand All @@ -63,7 +75,6 @@ func MakeToFunc(wantTy cty.Type) function.Function {
// asks to convert the string "a" to bool then we'll
// optimistically permit it during type checking but fail here
// once we note that the value isn't either "true" or "false".
gotTy := args[0].Type()
switch {
case gotTy == cty.String && wantTy == cty.Bool:
what := "string"
Expand Down
6 changes: 6 additions & 0 deletions lang/funcs/conversion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ func TestTo(t *testing.T) {
Want cty.Value
Err string
}{
{
cty.StringVal("0x99"),
cty.Number,
cty.NumberIntVal(153),
``,
},
{
cty.StringVal("a"),
cty.String,
Expand Down