gotosocial/vendor/github.com/tdewolff/parse/v2/binary_unix.go
kim 78defcd916 [chore] bump dependencies (#4406)
- codeberg.org/gruf/go-ffmpreg: v0.6.9 -> v0.6.10
- github.com/ncruces/go-sqlite3: v0.27.1 -> v0.28.0
- github.com/stretchr/testify: v1.10.0 -> v1.11.1
- github.com/tdewolff/minify/v2 v2.23.11 -> v2.24.2
- go.opentelemetry.io/otel{,/*}: v1.37.0 -> v1.38.0
- go.opentelemetry.io/contrib/*: v0.62.0 -> v0.63.0

Reviewed-on: https://codeberg.org/superseriousbusiness/gotosocial/pulls/4406
Co-authored-by: kim <grufwub@gmail.com>
Co-committed-by: kim <grufwub@gmail.com>
2025-09-04 15:29:27 +02:00

95 lines
2.1 KiB
Go

//go:build unix
package parse
import (
"errors"
"fmt"
"os"
"runtime"
"syscall"
)
type binaryReaderMmap struct {
data []byte
size int64
}
func newBinaryReaderMmap(filename string) (*binaryReaderMmap, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return nil, err
}
size := info.Size()
if size == 0 {
// Treat (size == 0) as a special case, avoiding the syscall, since
// "man 2 mmap" says "the length... must be greater than 0".
//
// As we do not call syscall.Mmap, there is no need to call
// runtime.SetFinalizer to enforce a balancing syscall.Munmap.
return &binaryReaderMmap{
data: make([]byte, 0),
}, nil
} else if size < 0 {
return nil, fmt.Errorf("mmap: file %s has negative size", filename)
} else if size != int64(int(size)) {
return nil, fmt.Errorf("mmap: file %s is too large", filename)
}
data, err := syscall.Mmap(int(f.Fd()), 0, int(size), syscall.PROT_READ, syscall.MAP_SHARED)
if err != nil {
return nil, err
}
r := &binaryReaderMmap{data, size}
runtime.SetFinalizer(r, (*binaryReaderMmap).Close)
return r, nil
}
// Close closes the reader.
func (r *binaryReaderMmap) Close() error {
if r.data == nil {
return nil
} else if len(r.data) == 0 {
r.data = nil
return nil
}
data := r.data
r.data = nil
runtime.SetFinalizer(r, nil)
return syscall.Munmap(data)
}
// Len returns the length of the underlying memory-mapped file.
func (r *binaryReaderMmap) Len() int64 {
return r.size
}
func (r *binaryReaderMmap) Bytes(b []byte, n, off int64) ([]byte, error) {
if r.data == nil {
return nil, errors.New("mmap: closed")
} else if off < 0 || n < 0 || int64(len(r.data)) < off || int64(len(r.data))-off < n {
return nil, fmt.Errorf("mmap: invalid range %d--%d", off, off+n)
}
data := r.data[off : off+n : off+n]
if b == nil {
return data, nil
}
copy(b, data)
return b, nil
}
func NewBinaryReaderMmap(filename string) (*BinaryReader, error) {
f, err := newBinaryReaderMmap(filename)
if err != nil {
return nil, err
}
return NewBinaryReader(f), nil
}