github.com/tetratelabs/tinymem@v0.1.0/tinymem.go (about)

     1  // Package tinymem contains WebAssembly functions for memory allocation.
     2  //
     3  // Note: If you are only interested in exporting functions to the host, blank
     4  // import this package like so:
     5  //
     6  //	import _ github.com/tetratelabs/tinymem
     7  package tinymem
     8  
     9  import (
    10  	"unsafe"
    11  )
    12  
    13  // PtrToString returns a string from WebAssembly compatible numeric types
    14  // representing its pointer and length.
    15  func PtrToString(ptr uintptr, size uint32) string {
    16  	// Get a slice view of the underlying bytes in the stream.
    17  	s := unsafe.Slice((*byte)(unsafe.Pointer(ptr)), size)
    18  	return *(*string)(unsafe.Pointer(&s))
    19  }
    20  
    21  // StringToPtr returns a pointer and size pair for the given string in a way
    22  // compatible with WebAssembly numeric types.
    23  func StringToPtr(s string) (uintptr, uint32) {
    24  	buf := []byte(s)
    25  	ptr := &buf[0]
    26  	unsafePtr := uintptr(unsafe.Pointer(ptr))
    27  	return unsafePtr, uint32(len(buf))
    28  }