Coverage for wasmtime/_wat2wasm.py: 100%

15 statements  

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

1from . import _ffi as ffi 

2from ctypes import * 

3from wasmtime import WasmtimeError 

4import typing 

5 

6 

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

8 """ 

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

10 

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

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

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

14 process the text format. 

15 

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

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

18 

19 >>> wat2wasm('(module)') 

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

21 

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

23 """ 

24 

25 if isinstance(wat, str): 

26 wat = wat.encode('utf8') 

27 wat_buffer = create_string_buffer(wat) 

28 wasm = ffi.wasm_byte_vec_t() 

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

30 if error: 

31 raise WasmtimeError._from_ptr(error) 

32 else: 

33 ret = ffi.to_bytes(wasm) 

34 ffi.wasm_byte_vec_delete(byref(wasm)) 

35 return ret