slice_go113_unsafe.go raw

   1  // Copyright 2023 The gVisor Authors.
   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  //go:build go1.13 && !go1.20
  16  // +build go1.13,!go1.20
  17  
  18  // TODO(go.dev/issue/8422): Remove this once Go 1.19 is no longer supported,
  19  // and update callers to use unsafe.Slice directly.
  20  
  21  package gohacks
  22  
  23  import (
  24  	"unsafe"
  25  )
  26  
  27  // sliceHeader is equivalent to reflect.SliceHeader, but represents the pointer
  28  // to the underlying array as unsafe.Pointer rather than uintptr, allowing
  29  // sliceHeaders to be directly converted to slice objects.
  30  type sliceHeader struct {
  31  	Data unsafe.Pointer
  32  	Len  int
  33  	Cap  int
  34  }
  35  
  36  // Slice returns a slice whose underlying array starts at ptr an which length
  37  // and capacity are len.
  38  func Slice[T any](ptr *T, length int) []T {
  39  	var s []T
  40  	hdr := (*sliceHeader)(unsafe.Pointer(&s))
  41  	hdr.Data = unsafe.Pointer(ptr)
  42  	hdr.Len = length
  43  	hdr.Cap = length
  44  	return s
  45  }
  46