Coverage for tests/codegen/generated/export_resources/intrinsics.py: 21%

29 statements  

« prev     ^ index     » next       coverage.py v7.6.12, created at 2025-02-20 16:25 +0000

1import ctypes 

2from typing import Any, Tuple 

3import wasmtime 

4 

5 

6def _encode_utf8(val: str, realloc: wasmtime.Func, mem: wasmtime.Memory, store: wasmtime.Storelike) -> Tuple[int, int]: 

7 bytes = val.encode('utf8') 

8 ptr = realloc(store, 0, 0, 1, len(bytes)) 

9 assert(isinstance(ptr, int)) 

10 ptr = ptr & 0xffffffff 

11 if ptr + len(bytes) > mem.data_len(store): 

12 raise IndexError('string out of bounds') 

13 base = mem.data_ptr(store) 

14 base = ctypes.POINTER(ctypes.c_ubyte)( 

15 ctypes.c_ubyte.from_address(ctypes.addressof(base.contents) + ptr) 

16 ) 

17 ctypes.memmove(base, bytes, len(bytes)) 

18 return (ptr, len(bytes)) 

19 

20 

21def _load(ty: Any, mem: wasmtime.Memory, store: wasmtime.Storelike, base: int, offset: int) -> Any: 

22 ptr = (base & 0xffffffff) + offset 

23 if ptr + ctypes.sizeof(ty) > mem.data_len(store): 

24 raise IndexError('out-of-bounds store') 

25 raw_base = mem.data_ptr(store) 

26 c_ptr = ctypes.POINTER(ty)( 

27 ty.from_address(ctypes.addressof(raw_base.contents) + ptr) 

28 ) 

29 return c_ptr[0] 

30 

31 

32def _decode_utf8(mem: wasmtime.Memory, store: wasmtime.Storelike, ptr: int, len: int) -> str: 

33 ptr = ptr & 0xffffffff 

34 len = len & 0xffffffff 

35 if ptr + len > mem.data_len(store): 

36 raise IndexError('string out of bounds') 

37 base = mem.data_ptr(store) 

38 base = ctypes.POINTER(ctypes.c_ubyte)( 

39 ctypes.c_ubyte.from_address(ctypes.addressof(base.contents) + ptr) 

40 ) 

41 return ctypes.string_at(base, len).decode('utf-8') 

42