github.com/team-ide/go-dialect@v1.9.20/vitess/hack/hack.go (about) 1 /* 2 Copyright 2019 The Vitess Authors. 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 // String force casts a []byte to a string. 27 // USE AT YOUR OWN RISK 28 func String(b []byte) (s string) { 29 if len(b) == 0 { 30 return "" 31 } 32 return *(*string)(unsafe.Pointer(&b)) 33 } 34 35 // StringPointer returns &s[0], which is not allowed in go 36 func StringPointer(s string) unsafe.Pointer { 37 pstring := (*reflect.StringHeader)(unsafe.Pointer(&s)) 38 return unsafe.Pointer(pstring.Data) 39 } 40 41 // StringBytes returns the underlying bytes for a string. Modifying this byte slice 42 // will lead to undefined behavior. 43 func StringBytes(s string) []byte { 44 var b []byte 45 hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b)) 46 hdr.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data 47 hdr.Cap = len(s) 48 hdr.Len = len(s) 49 return b 50 } 51 52 // StringClone returns a newly allocated copy of the string that doesn't share 53 // its underlying memory storage. 54 func StringClone(s string) string { 55 b := make([]byte, len(s)) 56 copy(b, s) 57 return *(*string)(unsafe.Pointer(&b)) 58 }