Skip to content

Instantly share code, notes, and snippets.

@caelifer
Last active June 22, 2016 17:34
Show Gist options
  • Save caelifer/51b70fea0363c0168c07e47476542d2d to your computer and use it in GitHub Desktop.
Save caelifer/51b70fea0363c0168c07e47476542d2d to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"unsafe"
)
type T1 struct {
d1 int32
d2 int32
}
type T2 int64
func cmp8bytes(a, b [8]byte) bool {
for i := 0; i < 8; i++ {
if a[i] != b[i] {
return false
}
}
return true
}
func cmp8bytes_s(a, b [8]byte) bool {
t1 := *(*T1)(unsafe.Pointer(&a))
t2 := *(*T1)(unsafe.Pointer(&b))
return t1 == t2
}
func cmp8bytes_ss(a, b [8]byte) bool {
t1 := *(*T2)(unsafe.Pointer(&a))
t2 := *(*T2)(unsafe.Pointer(&b))
return t1 == t2
}
func main() {
for _, t := range []struct {
a [8]byte
b [8]byte
}{
{
[8]byte{1, 2, 3, 4, 5, 6, 7, 8},
[8]byte{1, 2, 3, 4, 5, 6, 7, 8},
},
{
[8]byte{0, 2, 3, 4, 5, 6, 7, 8},
[8]byte{1, 2, 3, 4, 5, 6, 7, 8},
},
} {
if cmp8bytes(t.a, t.b) == cmp8bytes_s(t.a, t.b) {
fmt.Println("cmp8bytes_s works")
}
if cmp8bytes(t.a, t.b) == cmp8bytes_ss(t.a, t.b) {
fmt.Println("cmp8bytes_ss works too!")
}
}
}
@caelifer
Copy link
Author

caelifer commented Apr 19, 2016

Live code - https://play.golang.org/p/wkel3QbUgR

Sample output:

cmp8bytes_s works
cmp8bytes_ss works too!
cmp8bytes_s works
cmp8bytes_ss works too!

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