File: helper_unsafe.go

package info (click to toggle)
golang-github-ugorji-go-codec 0.0~git20151130.0.357a44b-1~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 1,520 kB
  • sloc: sh: 209; python: 94; makefile: 10
file content (45 lines) | stat: -rw-r--r-- 1,109 bytes parent folder | download | duplicates (2)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
//+build unsafe

// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.

package codec

import (
	"unsafe"
)

// This file has unsafe variants of some helper methods.

type unsafeString struct {
	Data uintptr
	Len  int
}

type unsafeBytes struct {
	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 {
	if len(v) == 0 {
		return ""
	}
	x := unsafeString{uintptr(unsafe.Pointer(&v[0])), len(v)}
	return *(*string)(unsafe.Pointer(&x))
}

// 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 {
	if len(v) == 0 {
		return zeroByteSlice
	}
	x := unsafeBytes{uintptr(unsafe.Pointer(&v)), len(v), len(v)}
	return *(*[]byte)(unsafe.Pointer(&x))
}