Skip to content

Commit

Permalink
Implement string-lenght-limit like the game
Browse files Browse the repository at this point in the history
  • Loading branch information
dbaumgarten committed Aug 21, 2021
1 parent 776f1b8 commit e53ccd4
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
11 changes: 10 additions & 1 deletion pkg/vm/operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ package vm
import (
"fmt"
"strings"
"unicode/utf8"

"github.com/dbaumgarten/yodk/pkg/number"
)

const MaxStringLenght = 1024

// RunUnaryOperation executes the given operation with the given argument and returns the result
func RunUnaryOperation(arg *Variable, operator string) (*Variable, error) {
var result Variable
Expand Down Expand Up @@ -178,7 +181,13 @@ func RunBinaryOperation(arg1 *Variable, arg2 *Variable, operator string) (*Varia
if arg1.IsString() {
switch operator {
case "+":
endResult.Value = arg1.String() + arg2.String()
value := arg1.String() + arg2.String()
size := utf8.RuneCountInString(value)
if size > MaxStringLenght {
runes := []rune(value)
value = string(runes[:1024])
}
endResult.Value = value
break
case "-":
lastIndex := strings.LastIndex(arg1.String(), arg2.String())
Expand Down
14 changes: 11 additions & 3 deletions pkg/vm/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"strings"
"sync"
"unicode/utf8"

"github.com/dbaumgarten/yodk/pkg/number"
"github.com/dbaumgarten/yodk/pkg/parser"
Expand Down Expand Up @@ -708,13 +709,20 @@ func (v *VM) runDeref(d *ast.Dereference) (*Variable, error) {
case "":
return oldval, nil
case "++":
newval.Value = oldval.String() + " "
if len(oldval.String()) < MaxStringLenght {
newval.Value = oldval.String() + " "
}
break
case "--":
if len(oldval.String()) == 0 {
str := oldval.String()
if len(str) == 0 {
return nil, RuntimeError{fmt.Errorf("String in variable '%s' is already empty", d.Variable), d}
}
newval.Value = string([]rune(oldval.String())[:len(oldval.String())-1])
r, size := utf8.DecodeLastRuneInString(str)
if r == utf8.RuneError && (size == 0 || size == 1) {
size = 0
}
newval.Value = str[:len(str)-size]
break
default:
return nil, RuntimeError{fmt.Errorf("Unknown operator '%s'", d.Operator), d}
Expand Down

0 comments on commit e53ccd4

Please sign in to comment.