v8.run/go/exp@v0.0.26-0.20230226010534-afcdbd3f782d/util/noescape/noescape.go (about)

     1  package noescape
     2  
     3  import (
     4  	"io"
     5  	"reflect"
     6  	"unsafe"
     7  )
     8  
     9  //nolint:staticcheck,unsafeptr
    10  func NoEscape(p unsafe.Pointer) unsafe.Pointer {
    11  	return unsafe.Pointer(uintptr(p) ^ 0)
    12  }
    13  
    14  //nolint:unsafeptr
    15  func Bytes(p *[]byte) []byte {
    16  	data := NoEscape(unsafe.Pointer((*reflect.SliceHeader)(NoEscape(unsafe.Pointer(p))).Data))
    17  	sh := reflect.SliceHeader{Data: uintptr(data), Len: len(*p), Cap: cap(*p)}
    18  	return *(*[]byte)(unsafe.Pointer(&sh))
    19  }
    20  
    21  type blackholestruct struct {
    22  	b     bool
    23  	bytes []byte
    24  }
    25  
    26  var blackhole = &blackholestruct{}
    27  
    28  //go:noinline
    29  func (b *blackholestruct) Write(p []byte) (n int, err error) {
    30  	return len(p), nil
    31  }
    32  
    33  //go:noinline
    34  func (b *blackholestruct) Read(p []byte) (n int, err error) {
    35  	if b.b && len(b.bytes) > 0 {
    36  		b.bytes[0] = 0
    37  	}
    38  	return len(p), nil
    39  }
    40  
    41  var blackholeIO io.ReadWriter = blackhole
    42  
    43  //go:noinline
    44  func EscapeBytes(p []byte) {
    45  	blackhole.b = true
    46  	if blackhole.b {
    47  		blackhole.bytes = p
    48  	}
    49  	blackhole.b = false
    50  }
    51  
    52  func Write(w io.Writer, p []byte) (n int, err error) {
    53  	return w.Write(Bytes(&p))
    54  }
    55  
    56  func Read(r io.Reader, p []byte) (n int, err error) {
    57  	return r.Read(Bytes(&p))
    58  }
    59  
    60  func ReadAtLeast(r io.Reader, p []byte, min int) (n int, err error) {
    61  	return io.ReadAtLeast(r, Bytes(&p), min)
    62  }
    63  
    64  func ReadFull(r io.Reader, p []byte) (n int, err error) {
    65  	return io.ReadFull(r, Bytes(&p))
    66  }