]> Cypherpunks repositories - gostls13.git/commitdiff
compress/bzip2: simplify Huffman tree construction
authoraimuz <mr.imuz@gmail.com>
Sun, 14 Apr 2024 08:45:12 +0000 (08:45 +0000)
committerGopher Robot <gobot@golang.org>
Mon, 15 Apr 2024 17:44:37 +0000 (17:44 +0000)
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 <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
src/compress/bzip2/huffman.go

index 447fc4d8510ce117086f49049285e57922fc35c5..9dffc34bc3ee961c0c2b5abfca6b4787012b5dc1 100644 (file)
@@ -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))