Skip to content

Commit

Permalink
Optimize code validator to not use regexp
Browse files Browse the repository at this point in the history
  • Loading branch information
Jacalz committed Jan 15, 2024
1 parent 9e1a8cc commit a3c6d92
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 3 deletions.
40 changes: 37 additions & 3 deletions internal/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,62 @@ import (
"errors"
"os"
"path/filepath"
"regexp"
"strings"

"fyne.io/fyne/v2"
)

//lint:ignore ST1005 The error is not printed to a terminal as usual but displayed to the user in the ui.
var errInvalidCode = errors.New("Invalid code. Must begin with a number followed by groups of letters, separated with \"-\".")
var codeRegexp = regexp.MustCompile(`^\d+(-(\w|\d)+)+$`)

// CodeValidator provides a validator for wormhole codes.
func CodeValidator(input string) error {
if input == "" {
return nil // We don't want empty entry to report an error.
}

if !codeRegexp.MatchString(input) {
next := strings.IndexByte(input, '-')
if next == -1 {
return errInvalidCode
}

mailbox := strings.IndexFunc(input[:next], runeIsNotNumerical)
if mailbox != -1 {
return errInvalidCode
}

input = input[next+1:]
if input == "" {
return errInvalidCode
}

for input != "" {
next = strings.IndexByte(input, '-')
if next == -1 {
next += len(input)
} else if next == len(input)-1 || next == 0 {
return errInvalidCode
}

invalidChars := strings.IndexFunc(input[:next], runeIsNotAlphaNumerical)
if invalidChars != -1 {
return errInvalidCode
}

input = input[next+1:]
}

return nil
}

func runeIsNotAlphaNumerical(r rune) bool {
return (r < '0' || r > '9') && (r < 'a' || r > 'z') && (r < 'A' || r > 'Z')
}

func runeIsNotNumerical(r rune) bool {
return r < '0' || r > '9'
}

// UserDownloadsFolder returns the downloads folder corresponding to the current user.
func UserDownloadsFolder() string {
dir, err := os.UserHomeDir()
Expand Down
27 changes: 27 additions & 0 deletions internal/util/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@ import (
"github.com/stretchr/testify/assert"
)

var globalValidationError error

func BenchmarkCodeValidator(b *testing.B) {
local := error(nil)

for i := 0; i < b.N; i++ {
local = CodeValidator("125-upset-universe-mistake")
}

globalValidationError = local
}

func TestCodeValidator(t *testing.T) {
validate := CodeValidator

Expand All @@ -17,6 +29,21 @@ func TestCodeValidator(t *testing.T) {
valid = validate("invalid-code")
assert.Error(t, valid)

valid = validate("IOI-")
assert.Error(t, valid)

valid = validate("126-")
assert.Error(t, valid)

valid = validate("126--almost--valid")
assert.Error(t, valid)

valid = validate("126-almost--valid")
assert.Error(t, valid)

valid = validate("126-almost-valid--")
assert.Error(t, valid)

valid = validate("15")
assert.Error(t, valid)

Expand Down

0 comments on commit a3c6d92

Please sign in to comment.