1package experimental
2
3import (
4 "context"
5
6 "github.com/tetratelabs/wazero/internal/expctxkeys"
7)
8
9// MemoryAllocator is a memory allocation hook,
10// invoked to create a LinearMemory.
11type MemoryAllocator interface {
12 // Allocate should create a new LinearMemory with the given specification:
13 // cap is the suggested initial capacity for the backing []byte,
14 // and max the maximum length that will ever be requested.
15 //
16 // Notes:
17 // - To back a shared memory, the address of the backing []byte cannot
18 // change. This is checked at runtime. Implementations should document
19 // if the returned LinearMemory meets this requirement.
20 Allocate(cap, max uint64) LinearMemory
21}
22
23// MemoryAllocatorFunc is a convenience for defining inlining a MemoryAllocator.
24type MemoryAllocatorFunc func(cap, max uint64) LinearMemory
25
26// Allocate implements MemoryAllocator.Allocate.
27func (f MemoryAllocatorFunc) Allocate(cap, max uint64) LinearMemory {
28 return f(cap, max)
29}
30
31// LinearMemory is an expandable []byte that backs a Wasm linear memory.
32type LinearMemory interface {
33 // Reallocates the linear memory to size bytes in length.
34 //
35 // Notes:
36 // - To back a shared memory, Reallocate can't change the address of the
37 // backing []byte (only its length/capacity may change).
38 // - Reallocate may return nil if fails to grow the LinearMemory. This
39 // condition may or may not be handled gracefully by the Wasm module.
40 Reallocate(size uint64) []byte
41 // Free the backing memory buffer.
42 Free()
43}
44
45// WithMemoryAllocator registers the given MemoryAllocator into the given
46// context.Context. The context must be passed when initializing a module.
47func WithMemoryAllocator(ctx context.Context, allocator MemoryAllocator) context.Context {
48 if allocator != nil {
49 return context.WithValue(ctx, expctxkeys.MemoryAllocatorKey{}, allocator)
50 }
51 return ctx
52}