From: aimuz Date: Sun, 14 Apr 2024 08:45:12 +0000 (+0000) Subject: compress/bzip2: simplify Huffman tree construction X-Git-Tag: go1.23rc1~619 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=b107d95b9a66bfe7150fd4f2915e9bb876a6999a;p=gostls13.git 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: c031bb56635552205c12b87add5f4337a7def74f GitHub-Pull-Request: golang/go#66817 Reviewed-on: https://go-review.googlesource.com/c/go/+/578438 Reviewed-by: Ian Lance Taylor Auto-Submit: Ian Lance Taylor LUCI-TryBot-Result: Go LUCI Reviewed-by: Cherry Mui --- diff --git a/src/compress/bzip2/huffman.go b/src/compress/bzip2/huffman.go index 447fc4d851..9dffc34bc3 100644 --- a/src/compress/bzip2/huffman.go +++ b/src/compress/bzip2/huffman.go @@ -4,7 +4,10 @@ package bzip2 -import "sort" +import ( + "cmp" + "slices" +) // A huffmanTree is a binary tree which is navigated, bit-by-bit to reach a // symbol. @@ -100,17 +103,11 @@ func newHuffmanTree(lengths []uint8) (huffmanTree, error) { pairs[i].length = length } - sort.Slice(pairs, func(i, j int) bool { - if pairs[i].length < pairs[j].length { - return true + slices.SortFunc(pairs, func(a, b huffmanSymbolLengthPair) int { + if c := cmp.Compare(a.length, b.length); c != 0 { + return c } - if pairs[i].length > pairs[j].length { - return false - } - if pairs[i].value < pairs[j].value { - return true - } - return false + return cmp.Compare(a.value, b.value) }) // 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 // grouped together, recursively. - sort.Slice(codes, func(i, j int) bool { - return codes[i].code < codes[j].code + slices.SortFunc(codes, func(a, b huffmanCode) int { + return cmp.Compare(a.code, b.code) }) t.nodes = make([]huffmanNode, len(codes))