wasi-module-sdk-go/mem/unmanaged.go

59 lines
1.3 KiB
Go
Raw Normal View History

2023-05-08 13:21:31 +00:00
package mem
2023-05-24 20:11:05 +00:00
import (
"sync"
"unsafe"
)
2023-05-13 15:46:09 +00:00
2023-05-24 20:11:05 +00:00
var (
alivePointers = map[uintptr][]byte{}
pointersLock sync.Mutex
)
2023-05-08 13:21:31 +00:00
2023-05-13 15:46:09 +00:00
func DataToManagedPtr(data []byte) (ptr uint32, size uint32) {
uptr := unsafe.Pointer(unsafe.SliceData(data))
return uint32(uintptr(uptr)), uint32(len(data))
}
func DataToUnmanagedPtr(data []byte) (uint32, uint32) {
2023-05-24 20:11:05 +00:00
pointersLock.Lock()
defer pointersLock.Unlock()
buf := make([]byte, len(data))
copy(buf, data)
ptr := &buf[0]
unsafePtr := uintptr(unsafe.Pointer(ptr))
alivePointers[unsafePtr] = buf
return uint32(unsafePtr), uint32(len(data))
2023-05-08 13:21:31 +00:00
}
func DataFromPtr(ptr, size uint32) []byte {
p := unsafe.Pointer(uintptr(ptr))
return unsafe.Slice((*byte)(p), int(size))
}
func PtrToData(ptr uint32, size uint32) []byte {
return unsafe.Slice((*byte)(unsafe.Pointer(uintptr(ptr))), size)
}
2023-05-13 15:46:09 +00:00
func UnifyPtrSize(ptr, size uint32) uint64 {
return (uint64(ptr) << uint64(32)) | uint64(size)
}
func UnifiedPtrToSizePtr(uint64ptr uint64) (ptr uint32, size uint32) {
return uint32(uint64ptr >> 32), uint32(uint64ptr)
}
2023-05-24 20:11:05 +00:00
2023-06-29 19:55:40 +00:00
//export allocate
2023-05-24 20:11:05 +00:00
func Allocate(size uint32) uintptr {
pointersLock.Lock()
defer pointersLock.Unlock()
buf := make([]byte, size)
unsafePtr := uintptr(unsafe.Pointer(unsafe.SliceData(buf)))
alivePointers[unsafePtr] = buf
return unsafePtr
}