Coverage for tests/bindgen/generated/bare_funcs/intrinsics.py: 25%

40 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 _clamp(i: int, min: int, max: int) -> int: 

7 if i < min or i > max: 

8 raise OverflowError(f'must be between {min} and {max}') 

9 return i 

10 

11 

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

13 bytes = val.encode('utf8') 

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

15 assert(isinstance(ptr, int)) 

16 ptr = ptr & 0xffffffff 

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

18 raise IndexError('string out of bounds') 

19 base = mem.data_ptr(store) 

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

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

22 ) 

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

24 return (ptr, len(bytes)) 

25 

26 

27def _store(ty: Any, mem: wasmtime.Memory, store: wasmtime.Storelike, base: int, offset: int, val: Any) -> None: 

28 ptr = (base & 0xffffffff) + offset 

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

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

31 raw_base = mem.data_ptr(store) 

32 c_ptr = ctypes.POINTER(ty)( 

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

34 ) 

35 c_ptr[0] = val 

36 

37 

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

39 ptr = (base & 0xffffffff) + offset 

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

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

42 raw_base = mem.data_ptr(store) 

43 c_ptr = ctypes.POINTER(ty)( 

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

45 ) 

46 return c_ptr[0] 

47 

48 

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

50 ptr = ptr & 0xffffffff 

51 len = len & 0xffffffff 

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

53 raise IndexError('string out of bounds') 

54 base = mem.data_ptr(store) 

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

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

57 ) 

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

59