Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use the same noescape that the Go standard library in ioutilx #7749

Merged
merged 1 commit into from
Feb 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions sdks/go/pkg/beam/core/util/ioutilx/read.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,10 @@ func ReadN(r io.Reader, n int) ([]byte, error) {
// Intended for use with small, fixed sized, stack allocated buffers that have
// no business being allocated to the heap.
// If the io.Reader somehow retains the passed in []byte, then this should not
// be used, and ReadN prefered.
// be used, and ReadN preferred.
func ReadNBufUnsafe(r io.Reader, b []byte) error {
// Use with unsafe readers at your own peril.
p := uintptr(unsafe.Pointer(&b))
ret := *(*[]byte)(unsafe.Pointer(p))
// Use with parameter retaining readers at your own peril.
ret := *(*[]byte)(noescape(unsafe.Pointer(&b)))
index := 0
n := len(ret)
for {
Expand All @@ -77,9 +76,20 @@ func ReadNBufUnsafe(r io.Reader, b []byte) error {
// Intended for use with small, fixed sized, stack allocated buffers that have
// no business being allocated to the heap.
// If the io.Reader somehow retains the passed in []byte, then this should not
// be used, and ReadN prefered.
// be used, and ReadN preferred.
func ReadUnsafe(r io.Reader, b []byte) (int, error) {
p := uintptr(unsafe.Pointer(&b))
ret := *(*[]byte)(unsafe.Pointer(p))
ret := *(*[]byte)(noescape(unsafe.Pointer(&b)))
return r.Read(ret)
}

// noescape hides a pointer from escape analysis. noescape is
// the identity function but escape analysis doesn't think the
// output depends on the input. noescape is inlined and currently
// compiles down to zero instructions.
// USE CAREFULLY!
// This was copied from the runtime; see issues 23382 and 7921.
//go:nosplit
func noescape(p unsafe.Pointer) unsafe.Pointer {
x := uintptr(p)
return unsafe.Pointer(x ^ 0)
}
3 changes: 1 addition & 2 deletions sdks/go/pkg/beam/core/util/ioutilx/write.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import (
// to the stack. Use with caution, and only when you're certain
// the writer doesn't retain the passed in byte buffer.
func WriteUnsafe(w io.Writer, b []byte) (int, error) {
p := uintptr(unsafe.Pointer(&b))
ret := *(*[]byte)(unsafe.Pointer(p))
ret := *(*[]byte)(noescape(unsafe.Pointer(&b)))
return w.Write(ret)
}