Documentation
¶
Overview ¶
Package memmapfs provides a memory-mapped file wrapper for absfs with zero-copy I/O.
Example ¶
Example demonstrates basic usage of memmapfs for reading a file.
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/absfs/memmapfs"
"github.com/absfs/osfs"
)
func main() {
// Create a temporary test file
tmpDir, _ := os.MkdirTemp("", "memmapfs-example")
defer os.RemoveAll(tmpDir)
tmpFile := filepath.Join(tmpDir, "test.txt")
content := "Hello, memory-mapped filesystem!"
os.WriteFile(tmpFile, []byte(content), 0644)
// Create the underlying OS filesystem
osFS, err := osfs.NewFS()
if err != nil {
log.Fatal(err)
}
// Wrap it with memmapfs
mfs := memmapfs.New(osFS, memmapfs.DefaultConfig())
// Open a file - it will be memory-mapped automatically
file, err := mfs.Open(tmpFile)
if err != nil {
log.Fatal(err)
}
defer file.Close()
// Read from the memory-mapped file
data := make([]byte, len(content))
n, err := file.Read(data)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Read %d bytes: %s\n", n, string(data))
}
Output: Read 32 bytes: Hello, memory-mapped filesystem!
Index ¶
- Constants
- Variables
- type Config
- type MappedFile
- func (mf *MappedFile) Advise(advice int) error
- func (mf *MappedFile) AdviseDontNeed() error
- func (mf *MappedFile) AdviseFree() error
- func (mf *MappedFile) AdviseHugePage() error
- func (mf *MappedFile) AdviseNoHugePage() error
- func (mf *MappedFile) AdviseRandom() error
- func (mf *MappedFile) AdviseRemove() error
- func (mf *MappedFile) AdviseSequential() error
- func (mf *MappedFile) AdviseWillNeed() error
- func (mf *MappedFile) Close() error
- func (mf *MappedFile) Data() []byte
- func (mf *MappedFile) DisableSIGBUSProtection()
- func (mf *MappedFile) EnableSIGBUSProtection()
- func (mf *MappedFile) Name() string
- func (mf *MappedFile) Read(p []byte) (int, error)
- func (mf *MappedFile) ReadAt(p []byte, off int64) (int, error)
- func (mf *MappedFile) ReadDir(n int) ([]fs.DirEntry, error)
- func (mf *MappedFile) Readdir(n int) ([]os.FileInfo, error)
- func (mf *MappedFile) Readdirnames(n int) ([]string, error)
- func (mf *MappedFile) RemapAfterTruncation() error
- func (mf *MappedFile) Seek(offset int64, whence int) (int64, error)
- func (mf *MappedFile) Stat() (fs.FileInfo, error)
- func (mf *MappedFile) Sync() error
- func (mf *MappedFile) Truncate(size int64) error
- func (mf *MappedFile) Write(p []byte) (int, error)
- func (mf *MappedFile) WriteAt(p []byte, off int64) (int, error)
- func (mf *MappedFile) WriteString(s string) (int, error)
- type MappingMode
- type MemMapFS
- func (mfs *MemMapFS) Chdir(dir string) error
- func (mfs *MemMapFS) Chmod(name string, mode os.FileMode) error
- func (mfs *MemMapFS) Chown(name string, uid, gid int) error
- func (mfs *MemMapFS) Chtimes(name string, atime, mtime time.Time) error
- func (mfs *MemMapFS) Create(name string) (absfs.File, error)
- func (mfs *MemMapFS) Getwd() (string, error)
- func (mfs *MemMapFS) Mkdir(name string, perm os.FileMode) error
- func (mfs *MemMapFS) MkdirAll(name string, perm os.FileMode) error
- func (mfs *MemMapFS) Open(name string) (absfs.File, error)
- func (mfs *MemMapFS) OpenFile(name string, flag int, perm os.FileMode) (absfs.File, error)
- func (mfs *MemMapFS) ReadDir(name string) ([]fs.DirEntry, error)
- func (mfs *MemMapFS) ReadFile(name string) ([]byte, error)
- func (mfs *MemMapFS) Remove(name string) error
- func (mfs *MemMapFS) RemoveAll(name string) error
- func (mfs *MemMapFS) Rename(oldname, newname string) error
- func (mfs *MemMapFS) Stat(name string) (os.FileInfo, error)
- func (mfs *MemMapFS) Sub(dir string) (fs.FS, error)
- func (mfs *MemMapFS) TempDir() string
- func (mfs *MemMapFS) Truncate(name string, size int64) error
- type SIGBUSHandler
- type SharedMemory
- type SharedMemoryConfig
- type SyncMode
Examples ¶
- Package
- Config (MemoryOptimized)
- Config (PerformanceTuning)
- MappedFile (AccessPatterns)
- MappedFile (HugePages)
- MappedFile (WindowedSeek)
- MappedFile.Data
- MappedFile.ReadAt
- MappedFile.Seek
- New (CustomConfig)
- New (WindowedMapping)
- New (WindowedWrite)
- SIGBUSHandler
- SharedMemory (Basic)
- SharedMemory (Cleanup)
- SharedMemory (Ipc)
Constants ¶
const ( // DefaultWindowSize is the default window size for large files (1 GB) DefaultWindowSize = 1 << 30 // 1 GB )
Variables ¶
var ( ErrNotMapped = errors.New("file is not memory-mapped") ErrInvalidOffset = errors.New("invalid offset") ErrInvalidWhence = errors.New("invalid whence") ErrWriteToReadOnlyMap = errors.New("cannot write to read-only mapping") ErrSIGBUS = errors.New("SIGBUS signal received: possible file truncation or I/O error") )
Common errors
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// Mode specifies the mapping mode (read-only, read-write, copy-on-write)
Mode MappingMode
// SyncMode specifies when to sync dirty pages to disk
SyncMode SyncMode
// SyncInterval is the interval for periodic sync (only used with SyncPeriodic)
SyncInterval time.Duration
// MapFullFile determines whether to map the entire file at once
// If false, WindowSize is used for windowed mapping
MapFullFile bool
// WindowSize specifies the size of the mapping window for large files
// Only used when MapFullFile is false. If 0, defaults to 1GB.
WindowSize int64
// Preload hints that pages should be loaded immediately
Preload bool
// PreloadAsync performs preload asynchronously
PreloadAsync bool
// PopulatePages uses MAP_POPULATE to eagerly load pages (Linux-specific)
// This prefaults page tables, loading file contents into RAM immediately
// More aggressive than Preload which uses madvise hints
PopulatePages bool
// UseHugePages attempts to use huge pages (MAP_HUGETLB on Linux)
// Requires system configuration and may fail if huge pages unavailable
// Can significantly improve TLB performance for large files
UseHugePages bool
}
Config holds configuration for the memory-mapped filesystem.
Example (MemoryOptimized) ¶
ExampleConfig_memoryOptimized demonstrates memory-optimized configuration.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/absfs/memmapfs"
"github.com/absfs/osfs"
)
func main() {
tmpDir, _ := os.MkdirTemp("", "memmapfs-example")
defer os.RemoveAll(tmpDir)
tmpFile := filepath.Join(tmpDir, "large.dat")
data := make([]byte, 100*1024*1024) // 100MB
os.WriteFile(tmpFile, data, 0644)
osFS, _ := osfs.NewFS()
// Configuration optimized for low memory usage
memOptConfig := &memmapfs.Config{
Mode: memmapfs.ModeReadOnly,
SyncMode: memmapfs.SyncNever,
PopulatePages: false, // Don't preload
MapFullFile: false, // Use windowing
WindowSize: 10 * 1024 * 1024, // 10MB window
Preload: false,
}
mfs := memmapfs.New(osFS, memOptConfig)
file, _ := mfs.Open(tmpFile)
defer file.Close()
// Hint: sequential access to help OS optimize
if mf, ok := file.(*memmapfs.MappedFile); ok {
mf.AdviseSequential()
}
fmt.Printf("File opened with memory-optimized configuration\n")
}
Output: File opened with memory-optimized configuration
Example (PerformanceTuning) ¶
ExampleConfig_performanceTuning demonstrates performance tuning options.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/absfs/memmapfs"
"github.com/absfs/osfs"
)
func main() {
tmpDir, _ := os.MkdirTemp("", "memmapfs-example")
defer os.RemoveAll(tmpDir)
tmpFile := filepath.Join(tmpDir, "data.bin")
data := make([]byte, 5*1024*1024) // 5MB
os.WriteFile(tmpFile, data, 0644)
osFS, _ := osfs.NewFS()
// Configuration for maximum performance (database-like workload)
highPerfConfig := &memmapfs.Config{
Mode: memmapfs.ModeReadWrite,
SyncMode: memmapfs.SyncLazy, // Sync only on close
PopulatePages: true, // Eagerly load all pages
MapFullFile: true, // Map entire file
Preload: false, // PopulatePages is more aggressive
}
mfs := memmapfs.New(osFS, highPerfConfig)
file, _ := mfs.OpenFile(tmpFile, os.O_RDWR, 0644)
defer file.Close()
// Access pattern hints for further optimization
if mf, ok := file.(*memmapfs.MappedFile); ok {
// Hint: random access pattern
mf.AdviseRandom()
}
fmt.Printf("File opened with high-performance configuration\n")
}
Output: File opened with high-performance configuration
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns a configuration suitable for most use cases.
type MappedFile ¶
type MappedFile struct {
// contains filtered or unexported fields
}
MappedFile represents a memory-mapped file.
Example (AccessPatterns) ¶
ExampleMappedFile_accessPatterns demonstrates access pattern optimization.
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/absfs/memmapfs"
"github.com/absfs/osfs"
)
func main() {
tmpDir, _ := os.MkdirTemp("", "memmapfs-example")
defer os.RemoveAll(tmpDir)
tmpFile := filepath.Join(tmpDir, "data.bin")
data := make([]byte, 10*1024*1024) // 10MB
os.WriteFile(tmpFile, data, 0644)
osFS, _ := osfs.NewFS()
mfs := memmapfs.New(osFS, memmapfs.DefaultConfig())
file, _ := mfs.Open(tmpFile)
defer file.Close()
mf, _ := file.(*memmapfs.MappedFile)
// Example 1: Sequential scan
mf.AdviseSequential() // OS can readahead aggressively
buf := make([]byte, 4096)
for i := 0; i < 100; i++ {
file.Read(buf)
}
// Example 2: Random access
file.Seek(0, io.SeekStart)
mf.AdviseRandom() // OS disables readahead
offsets := []int64{1000, 50000, 10000, 80000}
for _, offset := range offsets {
file.ReadAt(buf, offset)
}
// Example 3: Done with data
mf.AdviseDontNeed() // Allow OS to reclaim pages
fmt.Printf("Applied access pattern hints\n")
}
Output: Applied access pattern hints
Example (HugePages) ¶
ExampleMappedFile_hugePages demonstrates using huge pages for large files.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/absfs/memmapfs"
"github.com/absfs/osfs"
)
func main() {
tmpDir, _ := os.MkdirTemp("", "memmapfs-example")
defer os.RemoveAll(tmpDir)
tmpFile := filepath.Join(tmpDir, "huge.dat")
// Create file >= 2MB (typical huge page size)
data := make([]byte, 4*1024*1024) // 4MB
os.WriteFile(tmpFile, data, 0644)
osFS, _ := osfs.NewFS()
// Try to use huge pages for better TLB performance
hugePagesConfig := &memmapfs.Config{
Mode: memmapfs.ModeReadOnly,
UseHugePages: true, // Request huge pages (Linux-specific)
PopulatePages: true, // Preload for immediate access
}
mfs := memmapfs.New(osFS, hugePagesConfig)
file, _ := mfs.Open(tmpFile)
if file != nil {
defer file.Close()
// Further hint to use transparent huge pages
if mf, ok := file.(*memmapfs.MappedFile); ok {
mf.AdviseHugePage()
}
fmt.Printf("File opened with huge pages support\n")
} else {
fmt.Printf("Huge pages not available (requires system configuration)\n")
}
}
Output: File opened with huge pages support
Example (WindowedSeek) ¶
ExampleMappedFile_windowedSeek demonstrates seeking across windows.
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/absfs/memmapfs"
"github.com/absfs/osfs"
)
func main() {
// Create a large test file
tmpDir, _ := os.MkdirTemp("", "memmapfs-example")
defer os.RemoveAll(tmpDir)
tmpFile := filepath.Join(tmpDir, "large.dat")
largeData := make([]byte, 10*1024*1024)
for i := range largeData {
largeData[i] = byte(i % 256)
}
os.WriteFile(tmpFile, largeData, 0644)
// Configure windowed mapping
config := &memmapfs.Config{
Mode: memmapfs.ModeReadOnly,
SyncMode: memmapfs.SyncNever,
MapFullFile: false,
WindowSize: 2 * 1024 * 1024,
}
osFS, _ := osfs.NewFS()
mfs := memmapfs.New(osFS, config)
file, _ := mfs.Open(tmpFile)
defer file.Close()
// Seek to different positions - window will slide automatically
offsets := []int64{0, 5 * 1024 * 1024, 9 * 1024 * 1024}
for _, offset := range offsets {
file.Seek(offset, io.SeekStart)
buf := make([]byte, 10)
n, _ := file.Read(buf)
fmt.Printf("At offset %d: read %d bytes\n", offset, n)
}
}
Output: At offset 0: read 10 bytes At offset 5242880: read 10 bytes At offset 9437184: read 10 bytes
func (*MappedFile) Advise ¶
func (mf *MappedFile) Advise(advice int) error
Advise provides access pattern hints to the kernel. This is a utility function for advanced use cases.
func (*MappedFile) AdviseDontNeed ¶
func (mf *MappedFile) AdviseDontNeed() error
AdviseDontNeed hints that the pages won't be needed soon and can be evicted.
func (*MappedFile) AdviseFree ¶
func (mf *MappedFile) AdviseFree() error
AdviseFree hints that the pages can be freed (Linux 4.5+). This allows the kernel to reclaim memory without writing dirty pages. Use with caution - data will be lost!
func (*MappedFile) AdviseHugePage ¶
func (mf *MappedFile) AdviseHugePage() error
AdviseHugePage hints that the kernel should use transparent huge pages (Linux). This can improve TLB performance for large files. Requires transparent huge pages to be enabled in the kernel.
func (*MappedFile) AdviseNoHugePage ¶
func (mf *MappedFile) AdviseNoHugePage() error
AdviseNoHugePage hints that the kernel should not use transparent huge pages.
func (*MappedFile) AdviseRandom ¶
func (mf *MappedFile) AdviseRandom() error
AdviseRandom hints that the file will be accessed randomly.
func (*MappedFile) AdviseRemove ¶
func (mf *MappedFile) AdviseRemove() error
AdviseRemove hints that pages will not be accessed in the near future (Linux). Similar to DontNeed but doesn't free immediately.
func (*MappedFile) AdviseSequential ¶
func (mf *MappedFile) AdviseSequential() error
AdviseSequential hints that the file will be accessed sequentially.
func (*MappedFile) AdviseWillNeed ¶
func (mf *MappedFile) AdviseWillNeed() error
AdviseWillNeed hints that the pages will be needed soon.
func (*MappedFile) Close ¶
func (mf *MappedFile) Close() error
Close unmaps the memory and closes the underlying file.
func (*MappedFile) Data ¶
func (mf *MappedFile) Data() []byte
Data returns a direct slice to the mapped memory. Use with caution - this provides direct access to the mapped region. For read-only mappings, modifications will cause a panic.
Example ¶
ExampleMappedFile_Data demonstrates direct access to mapped memory.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/absfs/memmapfs"
"github.com/absfs/osfs"
)
func main() {
// Create a test file
tmpDir, _ := os.MkdirTemp("", "memmapfs-example")
defer os.RemoveAll(tmpDir)
tmpFile := filepath.Join(tmpDir, "data.txt")
content := "Direct memory access!"
os.WriteFile(tmpFile, []byte(content), 0644)
// Setup memmapfs
osFS, _ := osfs.NewFS()
mfs := memmapfs.New(osFS, memmapfs.DefaultConfig())
file, _ := mfs.Open(tmpFile)
defer file.Close()
// Get direct access to mapped memory (zero-copy)
mf := file.(*memmapfs.MappedFile)
data := mf.Data()
fmt.Printf("Direct access: %s\n", string(data))
}
Output: Direct access: Direct memory access!
func (*MappedFile) DisableSIGBUSProtection ¶
func (mf *MappedFile) DisableSIGBUSProtection()
DisableSIGBUSProtection disables SIGBUS monitoring for a mapped file.
func (*MappedFile) EnableSIGBUSProtection ¶
func (mf *MappedFile) EnableSIGBUSProtection()
EnableSIGBUSProtection enables SIGBUS monitoring for a mapped file. This should be called after opening a file if you want protection.
func (*MappedFile) Read ¶
func (mf *MappedFile) Read(p []byte) (int, error)
Read reads data from the mapped memory.
func (*MappedFile) ReadAt ¶
func (mf *MappedFile) ReadAt(p []byte, off int64) (int, error)
ReadAt reads data at a specific offset without changing the file position.
Example ¶
ExampleMappedFile_ReadAt demonstrates random access reading.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/absfs/memmapfs"
"github.com/absfs/osfs"
)
func main() {
// Create a test file
tmpDir, _ := os.MkdirTemp("", "memmapfs-example")
defer os.RemoveAll(tmpDir)
tmpFile := filepath.Join(tmpDir, "data.bin")
content := "0123456789ABCDEF"
os.WriteFile(tmpFile, []byte(content), 0644)
// Setup memmapfs
osFS, _ := osfs.NewFS()
mfs := memmapfs.New(osFS, memmapfs.DefaultConfig())
file, _ := mfs.Open(tmpFile)
defer file.Close()
// Read from specific offset without seeking
buf := make([]byte, 6)
n, _ := file.ReadAt(buf, 10) // Read "ABCDEF" starting at offset 10
fmt.Printf("Read %d bytes from offset 10: %s\n", n, string(buf))
}
Output: Read 6 bytes from offset 10: ABCDEF
func (*MappedFile) ReadDir ¶
func (mf *MappedFile) ReadDir(n int) ([]fs.DirEntry, error)
ReadDir reads the contents of the directory and returns a slice of DirEntry values.
func (*MappedFile) Readdir ¶
func (mf *MappedFile) Readdir(n int) ([]os.FileInfo, error)
Readdir reads directory contents.
func (*MappedFile) Readdirnames ¶
func (mf *MappedFile) Readdirnames(n int) ([]string, error)
Readdirnames reads directory entry names.
func (*MappedFile) RemapAfterTruncation ¶
func (mf *MappedFile) RemapAfterTruncation() error
RemapAfterTruncation attempts to remap the file after detecting truncation. This can be called from a SIGBUS handler to recover from truncation.
func (*MappedFile) Seek ¶
func (mf *MappedFile) Seek(offset int64, whence int) (int64, error)
Seek sets the file position for the next Read or Write.
Example ¶
ExampleMappedFile_Seek demonstrates seeking within a memory-mapped file.
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/absfs/memmapfs"
"github.com/absfs/osfs"
)
func main() {
// Create a test file
tmpDir, _ := os.MkdirTemp("", "memmapfs-example")
defer os.RemoveAll(tmpDir)
tmpFile := filepath.Join(tmpDir, "data.txt")
content := "Hello, World!"
os.WriteFile(tmpFile, []byte(content), 0644)
// Setup memmapfs
osFS, _ := osfs.NewFS()
mfs := memmapfs.New(osFS, memmapfs.DefaultConfig())
file, _ := mfs.Open(tmpFile)
defer file.Close()
// Seek to offset 7
file.Seek(7, io.SeekStart)
// Read from new position
buf := make([]byte, 6)
n, _ := file.Read(buf)
fmt.Printf("After seeking to 7, read %d bytes: %s\n", n, string(buf))
}
Output: After seeking to 7, read 6 bytes: World!
func (*MappedFile) Sync ¶
func (mf *MappedFile) Sync() error
Sync synchronizes the file's in-memory state with storage. For mapped files, this syncs dirty pages to disk.
func (*MappedFile) Truncate ¶
func (mf *MappedFile) Truncate(size int64) error
Truncate changes the size of the file. For mapped files, this is not supported in Phase 1.
func (*MappedFile) Write ¶
func (mf *MappedFile) Write(p []byte) (int, error)
Write writes data to the mapped memory.
func (*MappedFile) WriteAt ¶
func (mf *MappedFile) WriteAt(p []byte, off int64) (int, error)
WriteAt writes data at a specific offset.
func (*MappedFile) WriteString ¶
func (mf *MappedFile) WriteString(s string) (int, error)
WriteString writes a string to the file.
type MappingMode ¶
type MappingMode int
MappingMode defines how files should be memory-mapped.
const ( // ModeReadOnly maps files as read-only (PROT_READ, MAP_PRIVATE/MAP_SHARED) ModeReadOnly MappingMode = iota // ModeReadWrite maps files as read-write (PROT_READ|PROT_WRITE, MAP_SHARED) ModeReadWrite // ModeCopyOnWrite maps files as copy-on-write (PROT_READ|PROT_WRITE, MAP_PRIVATE) ModeCopyOnWrite )
type MemMapFS ¶
type MemMapFS struct {
// contains filtered or unexported fields
}
MemMapFS wraps an existing filesystem and provides memory-mapped file access.
func New ¶
func New(underlying absfs.FileSystem, config *Config) *MemMapFS
New creates a new memory-mapped filesystem wrapper. The underlying filesystem is typically osfs.NewFS() or another absfs.FileSystem implementation.
Example (CustomConfig) ¶
ExampleNew_customConfig demonstrates using a custom configuration.
package main
import (
"fmt"
"github.com/absfs/memmapfs"
"github.com/absfs/osfs"
)
func main() {
// Create custom configuration
config := &memmapfs.Config{
Mode: memmapfs.ModeReadOnly,
SyncMode: memmapfs.SyncNever,
Preload: false, // Don't preload pages
}
osFS, _ := osfs.NewFS()
mfs := memmapfs.New(osFS, config)
// Use mfs for file operations...
fmt.Printf("Created memmapfs with custom config\n")
_ = mfs
}
Output: Created memmapfs with custom config
Example (WindowedMapping) ¶
ExampleNew_windowedMapping demonstrates using windowed mapping for large files.
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/absfs/memmapfs"
"github.com/absfs/osfs"
)
func main() {
// Create a large test file
tmpDir, _ := os.MkdirTemp("", "memmapfs-example")
defer os.RemoveAll(tmpDir)
tmpFile := filepath.Join(tmpDir, "large.dat")
// Create a 10MB file
largeData := make([]byte, 10*1024*1024)
for i := range largeData {
largeData[i] = byte(i % 256)
}
os.WriteFile(tmpFile, largeData, 0644)
// Configure windowed mapping with 2MB window
config := &memmapfs.Config{
Mode: memmapfs.ModeReadOnly,
SyncMode: memmapfs.SyncNever,
MapFullFile: false, // Use windowed mapping
WindowSize: 2 * 1024 * 1024, // 2MB window
}
osFS, _ := osfs.NewFS()
mfs := memmapfs.New(osFS, config)
// Open large file - only 2MB will be mapped at a time
file, _ := mfs.Open(tmpFile)
defer file.Close()
// Sequential reading automatically slides the window
buf := make([]byte, 4096)
totalRead := 0
for {
n, err := file.Read(buf)
totalRead += n
if err == io.EOF {
break
}
}
fmt.Printf("Read %d bytes from large file using windowed mapping\n", totalRead)
}
Output: Read 10485760 bytes from large file using windowed mapping
Example (WindowedWrite) ¶
ExampleNew_windowedWrite demonstrates writing with windowed mapping.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/absfs/memmapfs"
"github.com/absfs/osfs"
)
func main() {
// Create a test file
tmpDir, _ := os.MkdirTemp("", "memmapfs-example")
defer os.RemoveAll(tmpDir)
tmpFile := filepath.Join(tmpDir, "output.dat")
// Create initial file
data := make([]byte, 5*1024*1024) // 5MB
os.WriteFile(tmpFile, data, 0644)
// Configure windowed mapping for writing
config := &memmapfs.Config{
Mode: memmapfs.ModeReadWrite,
SyncMode: memmapfs.SyncImmediate,
MapFullFile: false,
WindowSize: 1 * 1024 * 1024, // 1MB window
}
osFS, _ := osfs.NewFS()
mfs := memmapfs.New(osFS, config)
file, _ := mfs.OpenFile(tmpFile, os.O_RDWR, 0644)
defer file.Close()
// Write to different positions - window will slide
pattern := []byte("WINDOW")
offsets := []int64{0, 2 * 1024 * 1024, 4 * 1024 * 1024}
for _, offset := range offsets {
file.WriteAt(pattern, offset)
}
fmt.Printf("Wrote to %d positions using windowed mapping\n", len(offsets))
}
Output: Wrote to 3 positions using windowed mapping
func (*MemMapFS) Create ¶
Create creates a new file. For Phase 1, this delegates to the underlying filesystem.
func (*MemMapFS) Open ¶
Open opens a file for reading and maps it into memory. For Phase 1, only read operations are supported.
func (*MemMapFS) OpenFile ¶
OpenFile opens a file with specified flags and permissions. For Phase 1, only read-only mode is fully supported.
func (*MemMapFS) ReadDir ¶
ReadDir reads the named directory and returns a list of directory entries.
type SIGBUSHandler ¶
type SIGBUSHandler struct {
// contains filtered or unexported fields
}
SIGBUSHandler manages SIGBUS signal handling for memory-mapped files. SIGBUS can occur when: - File is truncated while mapped - I/O error occurs reading from disk - Accessing beyond mapped region
Example ¶
ExampleSIGBUSHandler demonstrates SIGBUS protection.
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/absfs/memmapfs"
"github.com/absfs/osfs"
)
func main() {
tmpDir, _ := os.MkdirTemp("", "memmapfs-example")
defer os.RemoveAll(tmpDir)
tmpFile := filepath.Join(tmpDir, "protected.dat")
data := make([]byte, 1024)
os.WriteFile(tmpFile, data, 0644)
osFS, _ := osfs.NewFS()
mfs := memmapfs.New(osFS, memmapfs.DefaultConfig())
file, _ := mfs.Open(tmpFile)
mf := file.(*memmapfs.MappedFile)
// Enable SIGBUS protection
mf.EnableSIGBUSProtection()
// Register a recovery handler
handler := memmapfs.GetSIGBUSHandler()
handler.OnSIGBUS(func(mappedFile *memmapfs.MappedFile, err error) {
fmt.Printf("SIGBUS detected, attempting recovery...\n")
// Attempt to remap after truncation
mappedFile.RemapAfterTruncation()
})
// Use the file...
// If the file is truncated externally, the handler will be called
mf.DisableSIGBUSProtection()
file.Close()
fmt.Printf("SIGBUS protection enabled\n")
}
Output: SIGBUS protection enabled
func GetSIGBUSHandler ¶
func GetSIGBUSHandler() *SIGBUSHandler
GetSIGBUSHandler returns the global SIGBUS handler instance.
func (*SIGBUSHandler) Disable ¶
func (h *SIGBUSHandler) Disable()
Disable stops monitoring for SIGBUS signals.
func (*SIGBUSHandler) Enable ¶
func (h *SIGBUSHandler) Enable()
Enable starts monitoring for SIGBUS signals.
func (*SIGBUSHandler) OnSIGBUS ¶
func (h *SIGBUSHandler) OnSIGBUS(handler func(*MappedFile, error))
OnSIGBUS registers a handler function called when SIGBUS occurs.
func (*SIGBUSHandler) Register ¶
func (h *SIGBUSHandler) Register(mf *MappedFile)
Register adds a mapped file to the monitored set.
func (*SIGBUSHandler) Unregister ¶
func (h *SIGBUSHandler) Unregister(mf *MappedFile)
Unregister removes a mapped file from the monitored set.
type SharedMemory ¶
type SharedMemory struct {
// contains filtered or unexported fields
}
SharedMemory provides utilities for inter-process communication via memory-mapped files.
func CreateSharedMemory ¶
func CreateSharedMemory(config *SharedMemoryConfig) (*SharedMemory, error)
CreateSharedMemory creates a new shared memory region. The file will be created if it doesn't exist.
func OpenSharedMemory ¶
func OpenSharedMemory(path string, writable bool) (*SharedMemory, error)
OpenSharedMemory opens an existing shared memory region.
func (*SharedMemory) Close ¶
func (sm *SharedMemory) Close() error
Close closes the shared memory region. The underlying file remains on disk and can be reopened.
func (*SharedMemory) Data ¶
func (sm *SharedMemory) Data() []byte
Data returns a direct slice to the shared memory region. CAUTION: Concurrent access from multiple processes requires synchronization.
func (*SharedMemory) MappedFile ¶
func (sm *SharedMemory) MappedFile() *MappedFile
MappedFile returns the underlying MappedFile for advanced operations.
func (*SharedMemory) Path ¶
func (sm *SharedMemory) Path() string
Path returns the filesystem path to the shared memory file.
func (*SharedMemory) Remove ¶
func (sm *SharedMemory) Remove() error
Remove closes and deletes the shared memory file.
func (*SharedMemory) Size ¶
func (sm *SharedMemory) Size() int64
Size returns the size of the shared memory region.
func (*SharedMemory) Sync ¶
func (sm *SharedMemory) Sync() error
Sync synchronizes the shared memory to disk.
type SharedMemoryConfig ¶
type SharedMemoryConfig struct {
Path string
Size int64
Mode MappingMode
SyncMode SyncMode
SyncInterval int
Permissions os.FileMode
PopulatePages bool
}
SharedMemoryConfig configures shared memory creation.