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

Better fix for TakeWhileBetween fuzz failure #23

Merged
merged 1 commit into from
Feb 2, 2024
Merged
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: 5 additions & 8 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -288,21 +288,18 @@ func TakeWhileBetween(lower, upper int, predicate func(r rune) bool) Parser[stri
return "", "", errors.New("TakeWhileBetween: predicate never returned true")
}

index := -1 // Index of last char for which predicate returns true
index := 0 // Index of last char for which predicate returns true
for pos, char := range input {
if !predicate(char) {
break
}
// Add the byte width of the char in question because the next char is the
// first one where predicate(char) == false, that's where we want to cut
// the string
index = pos + utf8.RuneLen(char)
}

// This is *extremely* rare and I only found it with fuzz testing! I'm still not entirely
// sure why this can happen, but this is a best stab at explaining the error
if index == -1 {
return "", "", errors.New("TakeWhileBetween: invalid utf-8 byte split")
runeLen := utf8.RuneLen(char)
if runeLen != -1 {
index = pos + utf8.RuneLen(char)
}
}

// If we have an index, our job now is to return whichever is longest out of
Expand Down
4 changes: 2 additions & 2 deletions parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -687,15 +687,15 @@ func TestTakeWhileBetween(t *testing.T) {
err: "",
},
{
name: "fuzz failure",
name: "fuzz failure", // Now correctly handled!
input: "\U0001925e0",
lower: 9,
upper: 83,
predicate: unicode.IsGraphic,
value: "",
remainder: "",
wantErr: true,
err: "TakeWhileBetween: invalid utf-8 byte split",
err: "TakeWhileBetween: predicate matched only 0 chars (), below lower limit (9)",
},
{
name: "nil predicate",
Expand Down
Loading