Skip to content

Commit b107d95

Browse files
aimuzgopherbot
authored andcommitted
compress/bzip2: simplify Huffman tree construction
This change simplifies the construction of the Huffman tree in the bzip2 package by replacing custom sort logic with the more concise and idiomatic use of "slices" and "cmp" packages. Change-Id: I2a8aef146b54b9433038b133d2cc8856ba077c72 GitHub-Last-Rev: c031bb5 GitHub-Pull-Request: #66817 Reviewed-on: https://go-review.googlesource.com/c/go/+/578438 Reviewed-by: Ian Lance Taylor <[email protected]> Auto-Submit: Ian Lance Taylor <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Cherry Mui <[email protected]>
1 parent f7f56de commit b107d95

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

src/compress/bzip2/huffman.go

+10-13
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44

55
package bzip2
66

7-
import "sort"
7+
import (
8+
"cmp"
9+
"slices"
10+
)
811

912
// A huffmanTree is a binary tree which is navigated, bit-by-bit to reach a
1013
// symbol.
@@ -100,17 +103,11 @@ func newHuffmanTree(lengths []uint8) (huffmanTree, error) {
100103
pairs[i].length = length
101104
}
102105

103-
sort.Slice(pairs, func(i, j int) bool {
104-
if pairs[i].length < pairs[j].length {
105-
return true
106+
slices.SortFunc(pairs, func(a, b huffmanSymbolLengthPair) int {
107+
if c := cmp.Compare(a.length, b.length); c != 0 {
108+
return c
106109
}
107-
if pairs[i].length > pairs[j].length {
108-
return false
109-
}
110-
if pairs[i].value < pairs[j].value {
111-
return true
112-
}
113-
return false
110+
return cmp.Compare(a.value, b.value)
114111
})
115112

116113
// Now we assign codes to the symbols, starting with the longest code.
@@ -135,8 +132,8 @@ func newHuffmanTree(lengths []uint8) (huffmanTree, error) {
135132

136133
// Now we can sort by the code so that the left half of each branch are
137134
// grouped together, recursively.
138-
sort.Slice(codes, func(i, j int) bool {
139-
return codes[i].code < codes[j].code
135+
slices.SortFunc(codes, func(a, b huffmanCode) int {
136+
return cmp.Compare(a.code, b.code)
140137
})
141138

142139
t.nodes = make([]huffmanNode, len(codes))

0 commit comments

Comments
 (0)