Skip to content

Instantly share code, notes, and snippets.

@cbluth
Forked from schmohlio/sortByteSlice.go
Created March 9, 2020 10:49
Show Gist options
  • Save cbluth/72cdb91420d5b14e10ee18067e6028f7 to your computer and use it in GitHub Desktop.
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
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