Skip to content

Use mmap in ReadAll if possible #2122

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion excelize.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ func (f *File) checkOpenReaderOptions() error {
// OpenReader read data stream from io.Reader and return a populated
// spreadsheet file.
func OpenReader(r io.Reader, opts ...Options) (*File, error) {
b, err := io.ReadAll(r)
b, err := readAll(r)
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion lib.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ func (f *File) readBytes(name string) []byte {
if err != nil {
return content
}
content, _ = io.ReadAll(file)
content, _ = readAll(file)
f.Pkg.Store(name, content)
_ = file.Close()
return content
Expand Down
37 changes: 37 additions & 0 deletions lib_nonwindows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//go:build !windows

// Copyright 2025 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.

package excelize

import (
"io"
"os"
"runtime"
"syscall"
)

// readAll is like io.ReadAll, but uses mmap if possible.
func readAll(r io.Reader) ([]byte, error) {
if fder, ok := r.(interface {
Fd() uintptr
Stat() (os.FileInfo, error)
}); ok {
if fi, err := fder.Stat(); err == nil {
if b, err := syscall.Mmap(
int(fder.Fd()),
0, int(fi.Size()),
syscall.PROT_READ,
syscall.MAP_PRIVATE|syscall.MAP_POPULATE,
); err == nil {
runtime.SetFinalizer(&b, func(_ any) error {
return syscall.Munmap(b)
})
return b, nil
}
}
}
return io.ReadAll(r)
}
16 changes: 16 additions & 0 deletions lib_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//go:build windows

// Copyright 2025 The excelize Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.

package excelize

import (
"io"
)

// readAll is like io.ReadAll, but uses mmap if possible.
func readAll(r io.Reader) ([]byte, error) {
return io.ReadAll(r)
}
Loading