github.com/bytedance/gopkg@v0.0.0-20240514070511-01b2cbcf35e1/internal/hack/hack.go (about)

     1  // Copyright 2021 ByteDance Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package hack
    16  
    17  import (
    18  	"reflect"
    19  	"unsafe"
    20  )
    21  
    22  // StringToBytes converts a string to a byte slice.
    23  //
    24  // This is a shallow copy, means that the returned byte slice reuse
    25  // the underlying array in string, so you can't change the returned
    26  // byte slice in any situations.
    27  func StringToBytes(s string) (b []byte) {
    28  	bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
    29  	sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
    30  	bh.Data = sh.Data
    31  	bh.Len = sh.Len
    32  	bh.Cap = sh.Len
    33  	return b
    34  }
    35  
    36  // BytesToString converts a byte slice to a string.
    37  //
    38  // This is a shallow copy, means that the returned string reuse the
    39  // underlying array in byte slice, it's your responsibility to keep
    40  // the input byte slice survive until you don't access the string anymore.
    41  func BytesToString(b []byte) string {
    42  	return *(*string)(unsafe.Pointer(&b))
    43  }