1
0
mirror of https://github.com/golang/go synced 2024-11-15 09:01:06 -07:00

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.
This commit is contained in:
aimuz 2024-04-14 16:35:42 +08:00
parent 519f6a00e4
commit c031bb5663
No known key found for this signature in database
GPG Key ID: 63C3DC9FBA22D9D7

View File

@ -4,7 +4,10 @@
package bzip2 package bzip2
import "sort" import (
"cmp"
"slices"
)
// A huffmanTree is a binary tree which is navigated, bit-by-bit to reach a // A huffmanTree is a binary tree which is navigated, bit-by-bit to reach a
// symbol. // symbol.
@ -100,17 +103,11 @@ func newHuffmanTree(lengths []uint8) (huffmanTree, error) {
pairs[i].length = length pairs[i].length = length
} }
sort.Slice(pairs, func(i, j int) bool { slices.SortFunc(pairs, func(a, b huffmanSymbolLengthPair) int {
if pairs[i].length < pairs[j].length { if c := cmp.Compare(a.length, b.length); c != 0 {
return true return c
} }
if pairs[i].length > pairs[j].length { return cmp.Compare(a.value, b.value)
return false
}
if pairs[i].value < pairs[j].value {
return true
}
return false
}) })
// Now we assign codes to the symbols, starting with the longest code. // Now we assign codes to the symbols, starting with the longest code.
@ -135,8 +132,8 @@ func newHuffmanTree(lengths []uint8) (huffmanTree, error) {
// Now we can sort by the code so that the left half of each branch are // Now we can sort by the code so that the left half of each branch are
// grouped together, recursively. // grouped together, recursively.
sort.Slice(codes, func(i, j int) bool { slices.SortFunc(codes, func(a, b huffmanCode) int {
return codes[i].code < codes[j].code return cmp.Compare(a.code, b.code)
}) })
t.nodes = make([]huffmanNode, len(codes)) t.nodes = make([]huffmanNode, len(codes))