v2 / vlib / builtin / wasm / builtin.v
119 lines · 108 sloc · 2.37 KB · d559a62cfe3f3de0a5ca1e59f14e622960e3917b
Raw
1module builtin
2
3// vwasm_heap_base returns the base address of the heap.
4pub fn vwasm_heap_base() voidptr {
5 mut rval := unsafe { nil }
6 asm wasm {
7 global.get __heap_base
8 local.set rval
9 ; =r (rval)
10 }
11 return rval
12}
13
14// vwasm_heap_size returns the size of the main wasm memory in pages.
15// Analogous to the `memory.size` instruction.
16pub fn vwasm_memory_size() int {
17 mut rval := 0
18 asm wasm {
19 memory.size
20 local.set rval
21 ; =r (rval)
22 }
23 return rval
24}
25
26// vwasm_memory_grow grows the main wasm memory by `size` pages.
27// Analogous to the `memory.grow` instruction.
28pub fn vwasm_memory_grow(size int) int {
29 mut rval := 0
30 asm wasm {
31 local.get size
32 memory.grow
33 local.set rval
34 ; =r (rval)
35 ; r (size)
36 }
37 return rval
38}
39
40// vcalloc dynamically allocates a zeroed `n` bytes block of memory on the heap.
41// vcalloc returns a `byteptr` pointing to the memory address of the allocated space.
42// vcalloc checks for negative values given in `n`.
43@[unsafe]
44pub fn vcalloc(n isize) &u8 {
45 if n <= 0 {
46 $if no_imports ? {
47 return unsafe { nil }
48 } $else {
49 panic('valloc(n <= 0)')
50 }
51 }
52
53 res := unsafe { malloc(n) }
54
55 asm wasm {
56 local.get res
57 i32.const 0x0
58 local.get n
59 memory.fill
60 ; ; r (res)
61 r (n)
62 }
63
64 return res
65}
66
67// isnil returns true if an object is nil (only for C objects).
68@[inline]
69pub fn isnil(v voidptr) bool {
70 return v == 0
71}
72
73// vmemcpy copies n bytes from memory area src to memory area dest.
74// The memory areas **CAN** overlap. vmemcpy returns a pointer to `dest`.
75@[unsafe]
76pub fn vmemcpy(dest voidptr, const_src voidptr, n isize) voidptr {
77 asm wasm {
78 local.get dest
79 local.get const_src
80 local.get n
81 memory.copy
82 ; ; r (dest)
83 r (const_src)
84 r (n)
85 }
86 return dest
87}
88
89// vmemmove copies n bytes from memory area src to memory area dest.
90// The memory areas **CAN** overlap. vmemmove returns a pointer to `dest`.
91@[unsafe]
92pub fn vmemmove(dest voidptr, const_src voidptr, n isize) voidptr {
93 asm wasm {
94 local.get dest
95 local.get const_src
96 local.get n
97 memory.copy
98 ; ; r (dest)
99 r (const_src)
100 r (n)
101 }
102 return dest
103}
104
105// vmemset fills the first `n` bytes of the memory area pointed to by `s`,
106// with the constant byte `c`. It returns a pointer to the memory area `s`.
107@[unsafe]
108pub fn vmemset(s voidptr, c int, n isize) voidptr {
109 asm wasm {
110 local.get s
111 local.get c
112 local.get n
113 memory.fill
114 ; ; r (s)
115 r (c)
116 r (n)
117 }
118 return s
119}
120