2023-04-11 10:27:36 +02:00

79 lines
2.2 KiB
Python

from typing import TextIO, Union
from phasmplatform.common import valuetype
from phasmplatform.common.router import BaseRouter
from phasmplatform.common.method import MethodCall
from phasmplatform.common.value import Value
from phasmplatform.common.valuetype import ValueType
class RunnerInterface:
__slots__ = ('router', )
def do_call(self, call: MethodCall) -> None:
raise NotImplementedError
class BaseRunner(RunnerInterface):
__slots__ = ('router', )
router: BaseRouter
def __init__(self, router: BaseRouter) -> None:
self.router = router
def alloc_bytes(self, data: bytes) -> int:
"""
Calls upon stdlib.types.__alloc_bytes__ to allocate a bytes object
"""
raise NotImplementedError
def read_bytes(self, ptr: int) -> bytes:
"""
Reads a byte object allocated by stdlib.types.__alloc_bytes__
"""
raise NotImplementedError
def value_to_wasm(self, val: Value) -> Union[None, int, float]:
if val.value_type is valuetype.bytes:
assert isinstance(val.data, bytes) # type hint
return self.alloc_bytes(val.data)
raise NotImplementedError(val)
def value_from_wasm(self, value_type: ValueType, val: Union[None, int, float]) -> Value:
if value_type is valuetype.none:
assert val is None # type hint
return Value(value_type, None)
if value_type is valuetype.bytes:
assert isinstance(val, int) # type hint
return Value(value_type, self.read_bytes(val))
raise NotImplementedError(value_type, val)
def log_bytes(self, msg_ptr: int) -> None:
print('LOG: ' + self.read_bytes(msg_ptr).decode())
def dump_memory(textio: TextIO, mem: bytes) -> None:
line_width = 16
prev_line = None
skip = False
for idx in range(0, len(mem), line_width):
line = ''
for idx2 in range(0, line_width):
line += f'{mem[idx + idx2]:02X}'
if idx2 % 2 == 1:
line += ' '
if prev_line == line:
if not skip:
textio.write('**\n')
skip = True
else:
textio.write(f'{idx:08x} {line}\n')
prev_line = line