Coverage for wasmtime/_wat2wasm.py: 100%

23 statements  

« prev     ^ index     » next       coverage.py v7.11.3, created at 2025-12-01 19:40 +0000

1import ctypes 

2 

3from . import _ffi as ffi 

4from wasmtime import WasmtimeError 

5import typing 

6 

7 

8def wat2wasm(wat: typing.Union[str, bytes]) -> bytearray: 

9 """ 

10 Converts the [WebAssembly Text format][wat] to the binary format. 

11 

12 This function is intended to be a convenience function for local 

13 development and you likely don't want to use it extensively in production. 

14 It's much faster to parse and compile the binary format than it is to 

15 process the text format. 

16 

17 Takes a `str` as input, raises an error if it fails to parse, and returns 

18 a `bytes` if conversion/parsing was successful. 

19 

20 >>> wat2wasm('(module)') 

21 bytearray(b'\\x00asm\\x01\\x00\\x00\\x00') 

22 

23 [wat]: https://webassembly.github.io/spec/core/text/index.html 

24 """ 

25 

26 if isinstance(wat, str): 

27 wat = wat.encode('utf8') 

28 wat_buffer = ctypes.create_string_buffer(wat) 

29 wasm = ffi.wasm_byte_vec_t() 

30 error = ffi.wasmtime_wat2wasm(wat_buffer, len(wat), ctypes.byref(wasm)) 

31 if error: 

32 raise WasmtimeError._from_ptr(error) 

33 else: 

34 ret = ffi.to_bytes(wasm) 

35 ffi.wasm_byte_vec_delete(ctypes.byref(wasm)) 

36 return ret 

37 

38def _to_wasm(wasm: typing.Union[str, bytes, bytearray]) -> typing.Union[bytes, bytearray]: 

39 # If this looks like a string, parse it as the text format. Note that 

40 # in python 2 strings and bytes are basically the same, so we skip this 

41 # if the first byte in the string is 0, meaning this is actually a wasm 

42 # module. 

43 if isinstance(wasm, str) and len(wasm) > 0 and ord(wasm[0]) != 0: 

44 wasm = wat2wasm(wasm) 

45 if isinstance(wasm, bytes) and len(wasm) > 0 and wasm[0] != 0: 

46 wasm = wat2wasm(wasm) 

47 

48 if not isinstance(wasm, (bytes, bytearray)): 

49 raise TypeError("expected wasm bytes") 

50 return wasm