syscall: copy only read bytes in js/wasm

CopyBytesToGo in Read and Pread copies the entire buffer instead of
only the n bytes actually returned by the read call. This is wasteful,
especially for small files where os.ReadFile uses a 512-byte buffer
but only a few bytes are read.

Copy only the bytes that were read, and skip the copy entirely when
zero bytes are returned.

Fixes #53566

Change-Id: I3109db5e8afe4f5ea53c9c0aa2724ff60e883ec1
Reviewed-on: https://go-review.googlesource.com/c/go/+/767680
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Reviewed-by: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>
Reviewed-by: Hyang-Ah Hana Kim <hyangah@gmail.com>
This commit is contained in:
iamrajiv 2026-04-16 11:29:36 +05:30 committed by Cherry Mui
parent 0e9a844b0d
commit 17bd5ab8c6

View file

@ -421,9 +421,11 @@ func Read(fd int, b []byte) (int, error) {
if err != nil {
return 0, err
}
js.CopyBytesToGo(b, buf)
n2 := n.Int()
if n2 > 0 {
js.CopyBytesToGo(b[:n2], buf)
}
f.pos += int64(n2)
return n2, err
}
@ -465,8 +467,11 @@ func Pread(fd int, b []byte, offset int64) (int, error) {
if err != nil {
return 0, err
}
js.CopyBytesToGo(b, buf)
return n.Int(), nil
n2 := n.Int()
if n2 > 0 {
js.CopyBytesToGo(b[:n2], buf)
}
return n2, nil
}
func Pwrite(fd int, b []byte, offset int64) (int, error) {