Skip to content

Commit

Permalink
Fix infinite loop on single match
Browse files Browse the repository at this point in the history
If there's a single entry in the collection of matches, our huffman
implementation will return an empty label. That results in an infinite
loop when rendering because we attempt to match empy input to an empty
label.

Resolve this by handling the single match case separately.

Fixes #38
  • Loading branch information
abhinav committed Sep 8, 2021
1 parent 3561e26 commit 88db35f
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Change default action to `tmux load-buffer -`. This eliminates risk of
hitting ARG_MAX with `set-buffer`--however unlikely that was.

### Fixed
- ([#38]): Fix infinite loop when there's a single match.

([#38]): https://github.com/abhinav/tmux-fastcopy/issues/38

## 0.4.0 - 2021-09-06
Highlight: The minimum required version of Tmux was lowered to 3.0.

Expand Down
7 changes: 6 additions & 1 deletion internal/huffman/huffman.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,13 @@ func Label(alphabetSize int, freqs []int) (labels [][]int) {
panic("alphabet must have at least two elements")
}

if len(freqs) == 0 {
switch len(freqs) {
case 0:
return nil
case 1:
// special-case: If there's only one item, create a single
// letter alabel.
return [][]int{{0}}
}

// Fill the heap with leaf nodes for the user-provided elements.
Expand Down
13 changes: 13 additions & 0 deletions internal/huffman/huffman_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@ func TestLabel(t *testing.T) {
alphabet *alphabet
items []item
}{
{
alphabet: _ab,
},
{
alphabet: _ab,
items: []item{
{1, "a"},
},
},
{
alphabet: _ab,
items: []item{
Expand Down Expand Up @@ -149,6 +158,10 @@ func assertLabelInvariants(t *testing.T, numItems int, labels []string) bool {
// 2) There must be no duplicates.
var seen []string
for _, label := range labels {
if !assert.NotEmpty(t, label, "label with %d items must not be empty", numItems) {
return false
}

if !assert.NotContains(t, seen, label, "duplicate label %q", label) {
return false
}
Expand Down

0 comments on commit 88db35f

Please sign in to comment.