Fixed capacity virtual memory.

This commit is contained in:
Nuno Cruces
2024-05-20 14:34:24 +01:00
parent d23bdcd225
commit 53eef1510f
8 changed files with 53 additions and 23 deletions

View File

@@ -0,0 +1,9 @@
//go:build !(unix || windows) || sqlite3_nosys
package util
import "github.com/tetratelabs/wazero/experimental"
func virtualAlloc(cap, max uint64) experimental.LinearMemory {
return sliceAlloc(cap, max)
}

View File

@@ -0,0 +1,25 @@
//go:build !(darwin || linux) || !(amd64 || arm64 || riscv64) || sqlite3_noshm || sqlite3_nosys
package util
import "github.com/tetratelabs/wazero/experimental"
func sliceAlloc(cap, max uint64) experimental.LinearMemory {
return &sliceBuffer{make([]byte, cap), max}
}
type sliceBuffer struct {
buf []byte
max uint64
}
func (b *sliceBuffer) Free() {}
func (b *sliceBuffer) Reallocate(size uint64) []byte {
if cap := uint64(cap(b.buf)); size > cap {
b.buf = append(b.buf[:cap], make([]byte, size-cap)...)
} else {
b.buf = b.buf[:size]
}
return b.buf
}

View File

@@ -9,7 +9,7 @@ import (
"golang.org/x/sys/unix"
)
func newAllocator(cap, max uint64) experimental.LinearMemory {
func virtualAlloc(cap, max uint64) experimental.LinearMemory {
// Round up to the page size.
rnd := uint64(unix.Getpagesize() - 1)
max = (max + rnd) &^ rnd

View File

@@ -11,7 +11,7 @@ import (
"golang.org/x/sys/windows"
)
func newAllocator(cap, max uint64) experimental.LinearMemory {
func virtualAlloc(cap, max uint64) experimental.LinearMemory {
// Round up to the page size.
rnd := uint64(windows.Getpagesize() - 1)
max = (max + rnd) &^ rnd

View File

@@ -14,7 +14,7 @@ import (
func withAllocator(ctx context.Context) context.Context {
return experimental.WithMemoryAllocator(ctx,
experimental.MemoryAllocatorFunc(newAllocator))
experimental.MemoryAllocatorFunc(virtualAlloc))
}
type mmapState struct {

View File

@@ -1,11 +1,21 @@
//go:build !(darwin || linux || windows) || !(amd64 || arm64 || riscv64) || sqlite3_noshm || sqlite3_nosys
//go:build !(darwin || linux) || !(amd64 || arm64 || riscv64) || sqlite3_noshm || sqlite3_nosys
package util
import "context"
import (
"context"
"github.com/tetratelabs/wazero/experimental"
)
type mmapState struct{}
func withAllocator(ctx context.Context) context.Context {
return ctx
return experimental.WithMemoryAllocator(ctx,
experimental.MemoryAllocatorFunc(func(cap, max uint64) experimental.LinearMemory {
if cap == max {
return virtualAlloc(cap, max)
}
return sliceAlloc(cap, max)
}))
}

View File

@@ -1,16 +0,0 @@
//go:build (amd64 || arm64) && !(sqlite3_noshm || sqlite3_nosys)
package util
import (
"context"
"github.com/tetratelabs/wazero/experimental"
)
type mmapState struct{}
func withAllocator(ctx context.Context) context.Context {
return experimental.WithMemoryAllocator(ctx,
experimental.MemoryAllocatorFunc(newAllocator))
}