github.com/vanus-labs/vanus/lib@v0.0.0-20231221070800-1334a7b9605e/bytes/unsafe.go (about)

     1  // Copyright 2023 Linkall 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 bytes
    16  
    17  import (
    18  	// standard libraries.
    19  	"reflect"
    20  	"unsafe"
    21  )
    22  
    23  func UnsafeFromString(s string) []byte {
    24  	hdr := (*reflect.StringHeader)(unsafe.Pointer(&s))
    25  	return unsafe.Slice((*byte)(unsafe.Pointer(hdr.Data)), hdr.Len)
    26  }
    27  
    28  func UnsafeToString(b []byte) string {
    29  	// hdr := (*reflect.StringHeader)(unsafe.Pointer(&b))
    30  	// return *(*string)(unsafe.Pointer(hdr))
    31  	return *(*string)(unsafe.Pointer(&b))
    32  }
    33  
    34  // UnsafeSlice implements the same functionality as `s[lo:hi]`, but without bounds check.
    35  func UnsafeSlice[T []byte | string](s T, lo int, hi int) []byte {
    36  	hdr := (*reflect.StringHeader)(unsafe.Pointer(&s))
    37  	p := unsafe.Add(unsafe.Pointer(hdr.Data), lo)
    38  	return unsafe.Slice((*byte)(p), hi-lo)
    39  }
    40  
    41  // UnsafeAt implements the same functionality as `s[pos]`, but without bounds check.
    42  func UnsafeAt[T []byte | string](s T, pos int) byte {
    43  	hdr := (*reflect.StringHeader)(unsafe.Pointer(&s))
    44  	p := unsafe.Add(unsafe.Pointer(hdr.Data), pos)
    45  	return *(*byte)(p)
    46  }