github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/internal/unsafeheader/unsafeheader.go (about)

     1  // Copyright 2020 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package unsafeheader contains header declarations copied from Go's runtime.
     6  package unsafeheader
     7  
     8  import (
     9  	"unsafe"
    10  )
    11  
    12  // SliceHeader is the runtime representation of a slice.
    13  //
    14  // Unlike reflect.SliceHeader, its Data field is sufficient to guarantee the
    15  // data it references will not be garbage collected.
    16  type SliceHeader struct {
    17  	Data unsafe.Pointer
    18  	Len  int
    19  	Cap  int
    20  }
    21  
    22  // SliceData returns a pointer to the underlying array of the argument
    23  // slice.
    24  //   - If len(slice) == 0, it returns nil.
    25  //   - Otherwise, it returns the underlying pointer.
    26  func SliceData[T any](slice []T) unsafe.Pointer {
    27  	if len(slice) == 0 {
    28  		return nil
    29  	}
    30  	return (*SliceHeader)(unsafe.Pointer(&slice)).Data
    31  }
    32  
    33  // StringHeader is the runtime representation of a string.
    34  //
    35  // Unlike reflect.StringHeader, its Data field is sufficient to guarantee the
    36  // data it references will not be garbage collected.
    37  type StringHeader struct {
    38  	Data unsafe.Pointer
    39  	Len  int
    40  }
    41  
    42  // StringData returns a pointer to the underlying bytes of str.
    43  //   - If str == "", it returns nil.
    44  //   - Otherwise, it returns the underlying pointer.
    45  func StringData(str string) unsafe.Pointer {
    46  	if str == "" {
    47  		return nil
    48  	}
    49  	return (*StringHeader)(unsafe.Pointer(&str)).Data
    50  }
    51  
    52  // Eface is the header for an empty interface{} value.
    53  // It is a copy type of [runtime.eface].
    54  type Eface struct {
    55  	RType unsafe.Pointer // *rtype
    56  	Word  unsafe.Pointer // data pointer
    57  }
    58  
    59  // Iface is the header of a non-empty interface value.
    60  // It is a copy type of [runtime.iface].
    61  type Iface struct {
    62  	Tab  unsafe.Pointer // *itab
    63  	Data unsafe.Pointer
    64  }