Skip to content

Commit

Permalink
Check that the alphabet does not contain multibyte characters
Browse files Browse the repository at this point in the history
  • Loading branch information
peterhellberg committed Sep 6, 2023
1 parent 27a0d2c commit 833eb66
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
10 changes: 10 additions & 0 deletions alphabet_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ import (
"testing"
)

func TestMultibyteAlphabet(t *testing.T) {
_, err := New(Options{
Alphabet: "ë1092",
})

if err != errAlphabetMultibyte {
t.Fatalf("unexpected error: %v", err)
}
}

func TestAlphabetSimple(t *testing.T) {
numbers := []uint64{1, 2, 3}
id := "4d9fd2"
Expand Down
19 changes: 16 additions & 3 deletions sqids.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ const (

var defaultBlocklist []string = newDefaultBlocklist()

// Alphabet validation errors
var (
errAlphabetMultibyte = errors.New("alphabet must not contain any multibyte characters")
errAlphabetTooShort = errors.New("alphabet length must be at least 5")
errAlphabetNotUniqueChars = errors.New("alphabet must contain unique characters")
errAlphabetMinLength = errors.New("alphabet minimum length")
)

// Options for a custom instance of Sqids
type Options struct {
Alphabet string
Expand Down Expand Up @@ -59,19 +67,24 @@ func validatedOptions(o Options) (Options, error) {
o.Alphabet = defaultAlphabet
}

// check that the alphabet does not contain multibyte characters
if len(o.Alphabet) != len([]rune(o.Alphabet)) {
return Options{}, errAlphabetMultibyte
}

// check the length of the alphabet
if len(o.Alphabet) < minAlphabetLength {
return Options{}, errors.New("alphabet length must be at least 5")
return Options{}, errAlphabetTooShort
}

// check that the alphabet has only unique characters
if !hasUniqueChars(o.Alphabet) {
return Options{}, errors.New("alphabet must contain unique characters")
return Options{}, errAlphabetNotUniqueChars
}

// test min length (type [might be lang-specific] + min length + max length)
if o.MinLength < int(minUint64Value) || o.MinLength > len(o.Alphabet) {
return Options{}, fmt.Errorf("minimum length has to be between %d and %d", minUint64Value, len(o.Alphabet))
return Options{}, fmt.Errorf("%w has to be between %d and %d", errAlphabetMinLength, minUint64Value, len(o.Alphabet))
}

o.Blocklist = filterBlocklist(o.Alphabet, o.Blocklist)
Expand Down

0 comments on commit 833eb66

Please sign in to comment.