Skip to content

Commit

Permalink
topdown: Added a new string reverse function
Browse files Browse the repository at this point in the history
ast: Updated the builtins list

partially fixes open-policy-agent#3736

Signed-off-by: Olamide Omolola <omololaolamidex@gmail.com>
  • Loading branch information
olamiko committed Nov 13, 2021
1 parent 6f903b2 commit a1eece5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
12 changes: 12 additions & 0 deletions ast/builtins.go
Expand Up @@ -128,6 +128,7 @@ var DefaultBuiltins = [...]*Builtin{
TrimSuffix,
TrimSpace,
Sprintf,
Reverse,

// Numbers
NumbersRange,
Expand Down Expand Up @@ -1085,6 +1086,17 @@ var Sprintf = &Builtin{
),
}

// Reverse returns the given string, reversed.
var Reverse = &Builtin{
Name: "reverse",
Decl: types.NewFunction(
types.Args(
types.S,
),
types.S,
),
}

/**
* Numbers
*/
Expand Down
24 changes: 24 additions & 0 deletions topdown/strings.go
Expand Up @@ -412,6 +412,29 @@ func builtinSprintf(a, b ast.Value) (ast.Value, error) {
return ast.String(fmt.Sprintf(string(s), args...)), nil
}

func builtinReverse(bctx BuiltinContext, operands []*ast.Term, iter func(*ast.Term) error) error {
s, err := builtins.StringOperand(operands[0].Value, 1)
if err != nil {
return err
}

sRunes := []rune(string(s))
length := len(sRunes)
reversedRunes := make([]rune, length)
index := 0

for index < length {
reversedRunes[index] = sRunes[length-index-1]
index++
}

var reversedString ast.String
reversedString = ast.String(sRunes)

return iter(ast.StringTerm(reversedString.String()))

}

func init() {
RegisterFunctionalBuiltin2(ast.FormatInt.Name, builtinFormatInt)
RegisterFunctionalBuiltin2(ast.Concat.Name, builtinConcat)
Expand All @@ -432,4 +455,5 @@ func init() {
RegisterFunctionalBuiltin2(ast.TrimSuffix.Name, builtinTrimSuffix)
RegisterFunctionalBuiltin1(ast.TrimSpace.Name, builtinTrimSpace)
RegisterFunctionalBuiltin2(ast.Sprintf.Name, builtinSprintf)
RegisterBuiltinFunc(ast.Reverse.Name, builtinReverse)
}

0 comments on commit a1eece5

Please sign in to comment.