forked from thatguystone/cog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unsafec.go
32 lines (28 loc) · 986 Bytes
/
unsafec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Package unsafec makes unsafe even more unsafe.
package unsafec
import (
"reflect"
"unsafe"
)
// String turns a byte slice into a string. This is unsafe as it leaves
// a string mutable. Don't use this if you will EVER modify the underlying
// byte slice.
//
// From: https://github.com/golang/go/issues/2632#issuecomment-66061057
//
// As bradfitz says, "As a medium-term hack, I showed they could do... But I
// felt bad even pointing that out."
//
// Until golang can optimize this case, sadness everywhere.
func String(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
// Bytes is the opposite String. This is unsafe as it leaves a string mutable.
// Don't not, under any circumstances, modify the returned byte slice.
// Seriously, if you do, unicorns will die, kittens will commit suicide, and
// puppies will maul you.
func Bytes(s string) []byte {
sh := *((*reflect.SliceHeader)(unsafe.Pointer(&s)))
sh.Cap = sh.Len
return *(*[]byte)(unsafe.Pointer(&sh))
}