github.com/vedadiyan/sqlparser@v1.0.0/pkg/hack/hack.go (about)

     1  //go:build gc && !wasm
     2  
     3  /*
     4  Copyright 2019 The Vitess Authors.
     5  
     6  Licensed under the Apache License, Version 2.0 (the "License");
     7  you may not use this file except in compliance with the License.
     8  You may obtain a copy of the License at
     9  
    10      http://www.apache.org/licenses/LICENSE-2.0
    11  
    12  Unless required by applicable law or agreed to in writing, software
    13  distributed under the License is distributed on an "AS IS" BASIS,
    14  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    15  See the License for the specific language governing permissions and
    16  limitations under the License.
    17  */
    18  
    19  // Package hack gives you some efficient functionality at the cost of
    20  // breaking some Go rules.
    21  package hack
    22  
    23  import (
    24  	"reflect"
    25  	"unsafe"
    26  )
    27  
    28  // String force casts a []byte to a string.
    29  // USE AT YOUR OWN RISK
    30  func String(b []byte) (s string) {
    31  	if len(b) == 0 {
    32  		return ""
    33  	}
    34  	return *(*string)(unsafe.Pointer(&b))
    35  }
    36  
    37  // StringBytes returns the underlying bytes for a string. Modifying this byte slice
    38  // will lead to undefined behavior.
    39  func StringBytes(s string) []byte {
    40  	var b []byte
    41  	hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b))
    42  	hdr.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data
    43  	hdr.Cap = len(s)
    44  	hdr.Len = len(s)
    45  	return b
    46  }