-
-
Save cbluth/72cdb91420d5b14e10ee18067e6028f7 to your computer and use it in GitHub Desktop.
sort byte slices in Golang without needing to fmt as string. useful for Set hashes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"log" | |
"sort" | |
) | |
// implement `Interface` in sort package. | |
type sortByteArrays [][]byte | |
func (b sortByteArrays) Len() int { | |
return len(b) | |
} | |
func (b sortByteArrays) Less(i, j int) bool { | |
// bytes package already implements Comparable for []byte. | |
switch bytes.Compare(b[i], b[j]) { | |
case -1: | |
return true | |
case 0, 1: | |
return false | |
default: | |
log.Panic("not fail-able with `bytes.Comparable` bounded [-1, 1].") | |
return false | |
} | |
} | |
func (b sortByteArrays) Swap(i, j int) { | |
b[j], b[i] = b[i], b[j] | |
} | |
// Public | |
func SortByteArrays(src [][]byte) [][]byte { | |
sorted := sortByteArrays(src) | |
sort.Sort(sorted) | |
return sorted | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment