Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Forked from schmohlio/sortByteSlice.go
Created September 5, 2018 17:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeoncross/997d07ed56eaced8871b8c7720c38310 to your computer and use it in GitHub Desktop.
Save xeoncross/997d07ed56eaced8871b8c7720c38310 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
}
@xeoncross
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment