open-vault/vendor/github.com/ugorji/go/codec/helper_unsafe.go

50 lines
1.1 KiB
Go
Raw Normal View History

2015-06-29 21:50:55 +00:00
//+build unsafe
// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
2015-08-19 01:12:51 +00:00
// Use of this source code is governed by a MIT license found in the LICENSE file.
2015-06-29 21:50:55 +00:00
package codec
import (
"unsafe"
)
// This file has unsafe variants of some helper methods.
type unsafeString struct {
Data uintptr
Len int
}
2016-04-26 00:18:04 +00:00
type unsafeSlice struct {
2015-06-29 21:50:55 +00:00
Data uintptr
Len int
Cap int
}
// stringView returns a view of the []byte as a string.
// In unsafe mode, it doesn't incur allocation and copying caused by conversion.
// In regular safe mode, it is an allocation and copy.
func stringView(v []byte) string {
2015-10-07 20:10:00 +00:00
if len(v) == 0 {
return ""
}
2016-04-26 00:18:04 +00:00
bx := (*unsafeSlice)(unsafe.Pointer(&v))
sx := unsafeString{bx.Data, bx.Len}
return *(*string)(unsafe.Pointer(&sx))
2015-06-29 21:50:55 +00:00
}
// bytesView returns a view of the string as a []byte.
// In unsafe mode, it doesn't incur allocation and copying caused by conversion.
// In regular safe mode, it is an allocation and copy.
func bytesView(v string) []byte {
2015-10-07 20:10:00 +00:00
if len(v) == 0 {
return zeroByteSlice
}
2016-04-26 00:18:04 +00:00
sx := (*unsafeString)(unsafe.Pointer(&v))
bx := unsafeSlice{sx.Data, sx.Len, sx.Len}
return *(*[]byte)(unsafe.Pointer(&bx))
2015-06-29 21:50:55 +00:00
}