Debian Codegraph @

dependency/hack/hack.go

raw symbols SCIP
1 /*
2 Copyright 2017 Google Inc.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 // Package hack gives you some efficient functionality at the cost of
18 // breaking some Go rules.
19 package hack
20
21 import (
22 "reflect"
23 "unsafe"
24 )
25
26 // StringArena lets you consolidate allocations for a group of strings
27 // that have similar life length
28 type StringArena struct {
29 buf []byte
30 str string
31 }
32
33 // NewStringArena creates an arena of the specified size.
34 func NewStringArena(size int) *StringArena {
35 sa := &StringArena{buf: make([]byte, 0, size)}
36 pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&sa.buf))
37 pstring := (*reflect.StringHeader)(unsafe.Pointer(&sa.str))
38 pstring.Data = pbytes.Data
39 pstring.Len = pbytes.Cap
40 return sa
41 }
42
43 // NewString copies a byte slice into the arena and returns it as a string.
44 // If the arena is full, it returns a traditional go string.
45 func (sa *StringArena) NewString(b []byte) string {
46 if len(b) == 0 {
47 return ""
48 }
49 if len(sa.buf)+len(b) > cap(sa.buf) {
50 return string(b)
51 }
52 start := len(sa.buf)
53 sa.buf = append(sa.buf, b...)
54 return sa.str[start : start+len(b)]
55 }
56
57 // SpaceLeft returns the amount of space left in the arena.
58 func (sa *StringArena) SpaceLeft() int {
59 return cap(sa.buf) - len(sa.buf)
60 }
61
62 // String force casts a []byte to a string.
63 // USE AT YOUR OWN RISK
64 func String(b []byte) (s string) {
65 if len(b) == 0 {
66 return ""
67 }
68 pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
69 pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
70 pstring.Data = pbytes.Data
71 pstring.Len = pbytes.Len
72 return
73 }
74
75 // StringPointer returns &s[0], which is not allowed in go
76 func StringPointer(s string) unsafe.Pointer {
77 pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
78 return unsafe.Pointer(pstring.Data)
79 }