Module wasmtime.component

Classes

class Bool
Expand source code
@dataclass
class Bool(ValType):
    def add_classes(self, s: Set[type]) -> None:
        s.add(bool)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if not isinstance(val, bool):
            raise TypeError("expected bool for Bool type")
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_BOOL
        ptr.contents.of.boolean = val

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_BOOL.value)
        return bool(c.of.boolean)

Bool()

Ancestors

  • wasmtime.component._types.ValType

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(bool)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_BOOL.value)
    return bool(c.of.boolean)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if not isinstance(val, bool):
        raise TypeError("expected bool for Bool type")
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_BOOL
    ptr.contents.of.boolean = val

Converts val to this type and stores it in ptr

class BorrowType (ty: wasmtime.component._resource_type.ResourceType)
Expand source code
@dataclass
class BorrowType(ValType):
    ty: ResourceType

    def add_classes(self, s: Set[type]) -> None:
        s.add(ResourceAny)
        s.add(ResourceHost)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if isinstance(val, ResourceAny):
            ptr.contents.kind = ffi.WASMTIME_COMPONENT_RESOURCE
            ptr.contents.of.resource = ffi.wasmtime_component_resource_any_clone(val.ptr())
        elif isinstance(val, ResourceHost):
            ptr.contents.kind = ffi.WASMTIME_COMPONENT_RESOURCE
            ptr.contents.of.resource = val.to_any(store)._consume()
        else:
            raise TypeError("expected ResourceAny or ResourceHost for Own type")

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_RESOURCE.value)
        return ResourceAny._from_ptr(ffi.take_pointer(c.of, 'resource'))

BorrowType(ty: wasmtime.component._resource_type.ResourceType)

Ancestors

  • wasmtime.component._types.ValType

Instance variables

var ty : wasmtime.component._resource_type.ResourceType

The type of the None singleton.

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(ResourceAny)
    s.add(ResourceHost)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_RESOURCE.value)
    return ResourceAny._from_ptr(ffi.take_pointer(c.of, 'resource'))

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if isinstance(val, ResourceAny):
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_RESOURCE
        ptr.contents.of.resource = ffi.wasmtime_component_resource_any_clone(val.ptr())
    elif isinstance(val, ResourceHost):
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_RESOURCE
        ptr.contents.of.resource = val.to_any(store)._consume()
    else:
        raise TypeError("expected ResourceAny or ResourceHost for Own type")

Converts val to this type and stores it in ptr

class Char
Expand source code
@dataclass
class Char(ValType):
    def add_classes(self, s: Set[type]) -> None:
        s.add(str)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if not isinstance(val, str) or len(val) != 1:
            raise TypeError("expected single-character string for Char type")
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_CHAR
        ptr.contents.of.character = ord(val)

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_CHAR.value)
        return chr(c.of.character)

Char()

Ancestors

  • wasmtime.component._types.ValType

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(str)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_CHAR.value)
    return chr(c.of.character)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if not isinstance(val, str) or len(val) != 1:
        raise TypeError("expected single-character string for Char type")
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_CHAR
    ptr.contents.of.character = ord(val)

Converts val to this type and stores it in ptr

class Component (engine: wasmtime._engine.Engine, wasm: str | bytes | bytearray)
Expand source code
class Component(Managed["ctypes._Pointer[ffi.wasmtime_component_t]"]):

    @classmethod
    def from_file(cls, engine: Engine, path: typing.Union[str, bytes, PathLike]) -> "Component":
        """
        Compiles and creates a new `Component` by reading the file at `path` and
        then delegating to the `Component` constructor.
        """

        with open(path, "rb") as f:
            contents = f.read()
        return cls(engine, contents)

    def __init__(self, engine: Engine, wasm: typing.Union[str, bytes, bytearray]):
        if not isinstance(engine, Engine):
            raise TypeError("expected an Engine")

        wasm = _to_wasm(wasm)

        # TODO: can the copy be avoided here? I can't for the life of me
        # figure this out.
        binary = (ctypes.c_uint8 * len(wasm)).from_buffer_copy(wasm)
        ptr = ctypes.POINTER(ffi.wasmtime_component_t)()
        error = ffi.wasmtime_component_new(engine.ptr(), binary, len(wasm), ctypes.byref(ptr))
        if error:
            raise WasmtimeError._from_ptr(error)
        self._set_ptr(ptr)

    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_t]") -> None:
        ffi.wasmtime_component_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_t]") -> "Component":
        if not isinstance(ptr, ctypes.POINTER(ffi.wasmtime_component_t)):
            raise TypeError("wrong pointer type")
        ty: "Component" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    @classmethod
    def deserialize(cls, engine: Engine, encoded: typing.Union[bytes, bytearray]) -> 'Component':
        """
        Deserializes bytes previously created by `Component.serialize`.

        This constructor for `Component` will deserialize bytes previously created
        by a serialized component. This will only succeed if the bytes were
        previously created by the same version of `wasmtime` as well as the
        same configuration within `Engine`.
        """

        if not isinstance(encoded, (bytes, bytearray)):
            raise TypeError("expected bytes")

        ptr = ctypes.POINTER(ffi.wasmtime_component_t)()

        # TODO: can the copy be avoided here? I can't for the life of me
        # figure this out.
        error = ffi.wasmtime_component_deserialize(
            engine.ptr(),
            (ctypes.c_uint8 * len(encoded)).from_buffer_copy(encoded),
            len(encoded),
            ctypes.byref(ptr))
        if error:
            raise WasmtimeError._from_ptr(error)
        return cls._from_ptr(ptr)

    @classmethod
    def deserialize_file(cls, engine: Engine, path: str) -> 'Component':
        """
        Deserializes bytes previously created by `Component.serialize` that are
        stored in a file on the filesystem.

        Otherwise this function is the same as `Component.deserialize`.
        """

        ptr = ctypes.POINTER(ffi.wasmtime_component_t)()
        path_bytes = path.encode('utf-8')
        error = ffi.wasmtime_component_deserialize_file(
            engine.ptr(),
            path_bytes,
            ctypes.byref(ptr))
        if error:
            raise WasmtimeError._from_ptr(error)
        return cls._from_ptr(ptr)

    def serialize(self) -> bytearray:
        """
        Serializes this component to a binary representation.

        This method will serialize this component to an in-memory byte array
        which can be cached and later passed to `Component.deserialize` to
        recreate this component.
        """
        raw = ffi.wasm_byte_vec_t()
        err = ffi.wasmtime_component_serialize(self.ptr(), ctypes.byref(raw))
        if err:
            raise WasmtimeError._from_ptr(err)
        ret = ffi.to_bytes(raw)
        ffi.wasm_byte_vec_delete(ctypes.byref(raw))
        return ret

    def get_export_index(self, name: str, instance : typing.Optional[ExportIndex] = None) -> typing.Optional[ExportIndex]:
        """
        Gets an `ExportIndex` from this component pointing to a specific item
        in this component.

        The returned `ExportIndex` can later be used to lookup exports on an
        instance or it can be used to lookup further indexes if it points to an
        instance for example.
        """
        name_bytes = name.encode('utf-8')
        name_buf = ctypes.create_string_buffer(name_bytes)
        ret = ffi.wasmtime_component_get_export_index(
            self.ptr(),
            instance.ptr() if instance is not None else None,
            name_buf,
            len(name_bytes))
        if not ret:
            return None
        return ExportIndex._from_ptr(ret)

    @property
    def type(self) -> ComponentType:
        """
        Returns the `ComponentType` corresponding to this component.
        """
        ptr = ffi.wasmtime_component_type(self.ptr())
        return ComponentType._from_ptr(ptr)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Static methods

def deserialize(engine: wasmtime._engine.Engine, encoded: bytearray | bytes) ‑> wasmtime.component._component.Component

Deserializes bytes previously created by Component.serialize().

This constructor for Component will deserialize bytes previously created by a serialized component. This will only succeed if the bytes were previously created by the same version of wasmtime as well as the same configuration within Engine.

def deserialize_file(engine: wasmtime._engine.Engine, path: str) ‑> wasmtime.component._component.Component

Deserializes bytes previously created by Component.serialize() that are stored in a file on the filesystem.

Otherwise this function is the same as Component.deserialize().

def from_file(engine: wasmtime._engine.Engine, path: str | bytes | os.PathLike) ‑> wasmtime.component._component.Component

Compiles and creates a new Component by reading the file at path and then delegating to the Component constructor.

Instance variables

prop type : wasmtime.component._types.ComponentType
Expand source code
@property
def type(self) -> ComponentType:
    """
    Returns the `ComponentType` corresponding to this component.
    """
    ptr = ffi.wasmtime_component_type(self.ptr())
    return ComponentType._from_ptr(ptr)

Returns the ComponentType corresponding to this component.

Methods

def get_export_index(self,
name: str,
instance: wasmtime.component._component.ExportIndex | None = None) ‑> wasmtime.component._component.ExportIndex | None
Expand source code
def get_export_index(self, name: str, instance : typing.Optional[ExportIndex] = None) -> typing.Optional[ExportIndex]:
    """
    Gets an `ExportIndex` from this component pointing to a specific item
    in this component.

    The returned `ExportIndex` can later be used to lookup exports on an
    instance or it can be used to lookup further indexes if it points to an
    instance for example.
    """
    name_bytes = name.encode('utf-8')
    name_buf = ctypes.create_string_buffer(name_bytes)
    ret = ffi.wasmtime_component_get_export_index(
        self.ptr(),
        instance.ptr() if instance is not None else None,
        name_buf,
        len(name_bytes))
    if not ret:
        return None
    return ExportIndex._from_ptr(ret)

Gets an ExportIndex from this component pointing to a specific item in this component.

The returned ExportIndex can later be used to lookup exports on an instance or it can be used to lookup further indexes if it points to an instance for example.

def serialize(self) ‑> bytearray
Expand source code
def serialize(self) -> bytearray:
    """
    Serializes this component to a binary representation.

    This method will serialize this component to an in-memory byte array
    which can be cached and later passed to `Component.deserialize` to
    recreate this component.
    """
    raw = ffi.wasm_byte_vec_t()
    err = ffi.wasmtime_component_serialize(self.ptr(), ctypes.byref(raw))
    if err:
        raise WasmtimeError._from_ptr(err)
    ret = ffi.to_bytes(raw)
    ffi.wasm_byte_vec_delete(ctypes.byref(raw))
    return ret

Serializes this component to a binary representation.

This method will serialize this component to an in-memory byte array which can be cached and later passed to Component.deserialize() to recreate this component.

class ComponentInstanceType
Expand source code
class ComponentInstanceType(Managed["ctypes._Pointer[ffi.wasmtime_component_instance_type_t]"]):
    def __init__(self) -> None:
        raise WasmtimeError("Cannot directly construct a `ComponentInstanceType`")

    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_instance_type_t]") -> None:
        ffi.wasmtime_component_instance_type_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_instance_type_t]") -> "ComponentInstanceType":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_instance_type_t)):
            raise TypeError("wrong pointer type")
        ty: "ComponentInstanceType" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    def exports(self, engine: Engine) -> Dict[str, "ComponentItem"]:
        """
        Returns a dictionary of the exports of this component instance type.
        """
        n = ffi.wasmtime_component_instance_type_export_count(self.ptr(), engine.ptr())
        items = {}
        for i in range(n):
            name_ptr = ctypes.POINTER(ctypes.c_char)()
            name_len = ctypes.c_size_t()
            item = ffi.wasmtime_component_item_t()
            found = ffi.wasmtime_component_instance_type_export_nth(self.ptr(),
                                                           engine.ptr(),
                                                           i,
                                                           byref(name_ptr),
                                                           byref(name_len),
                                                           byref(item))
            name = ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
            items[name] = component_item_from_ptr(item)
            assert(found)
        return items

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Methods

def exports(self, engine: wasmtime._engine.Engine) ‑> Dict[str, wasmtime.component._types.ComponentType | wasmtime.component._types.ModuleType | wasmtime.component._types.ComponentInstanceType | wasmtime.component._resource_type.ResourceType | wasmtime.component._types.ValType | wasmtime.component._types.FuncType]
Expand source code
def exports(self, engine: Engine) -> Dict[str, "ComponentItem"]:
    """
    Returns a dictionary of the exports of this component instance type.
    """
    n = ffi.wasmtime_component_instance_type_export_count(self.ptr(), engine.ptr())
    items = {}
    for i in range(n):
        name_ptr = ctypes.POINTER(ctypes.c_char)()
        name_len = ctypes.c_size_t()
        item = ffi.wasmtime_component_item_t()
        found = ffi.wasmtime_component_instance_type_export_nth(self.ptr(),
                                                       engine.ptr(),
                                                       i,
                                                       byref(name_ptr),
                                                       byref(name_len),
                                                       byref(item))
        name = ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
        items[name] = component_item_from_ptr(item)
        assert(found)
    return items

Returns a dictionary of the exports of this component instance type.

class ComponentType
Expand source code
class ComponentType(Managed["ctypes._Pointer[ffi.wasmtime_component_type_t]"]):
    def __init__(self) -> None:
        raise WasmtimeError("Cannot directly construct a `ComponentType`")

    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_type_t]") -> None:
        ffi.wasmtime_component_type_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_type_t]") -> "ComponentType":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_type_t)):
            raise TypeError("wrong pointer type")
        ty: "ComponentType" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    def imports(self, engine: Engine) -> Dict[str, "ComponentItem"]:
        """
        Returns a dictionary of the imports of this component type.
        """
        n = ffi.wasmtime_component_type_import_count(self.ptr(), engine.ptr())
        items = {}
        for i in range(n):
            name_ptr = ctypes.POINTER(ctypes.c_char)()
            name_len = ctypes.c_size_t()
            item = ffi.wasmtime_component_item_t()
            found = ffi.wasmtime_component_type_import_nth(self.ptr(),
                                                           engine.ptr(),
                                                           i,
                                                           byref(name_ptr),
                                                           byref(name_len),
                                                           byref(item))
            assert(found)
            name = ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
            items[name] = component_item_from_ptr(item)
        return items

    def exports(self, engine: Engine) -> Dict[str, "ComponentItem"]:
        """
        Returns a dictionary of the exports of this component type.
        """
        n = ffi.wasmtime_component_type_export_count(self.ptr(), engine.ptr())
        items = {}
        for i in range(n):
            name_ptr = ctypes.POINTER(ctypes.c_char)()
            name_len = ctypes.c_size_t()
            item = ffi.wasmtime_component_item_t()
            found = ffi.wasmtime_component_type_export_nth(self.ptr(),
                                                           engine.ptr(),
                                                           i,
                                                           byref(name_ptr),
                                                           byref(name_len),
                                                           byref(item))
            assert(found)
            name = ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
            items[name] = component_item_from_ptr(item)
        return items

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Methods

def exports(self, engine: wasmtime._engine.Engine) ‑> Dict[str, wasmtime.component._types.ComponentType | wasmtime.component._types.ModuleType | wasmtime.component._types.ComponentInstanceType | wasmtime.component._resource_type.ResourceType | wasmtime.component._types.ValType | wasmtime.component._types.FuncType]
Expand source code
def exports(self, engine: Engine) -> Dict[str, "ComponentItem"]:
    """
    Returns a dictionary of the exports of this component type.
    """
    n = ffi.wasmtime_component_type_export_count(self.ptr(), engine.ptr())
    items = {}
    for i in range(n):
        name_ptr = ctypes.POINTER(ctypes.c_char)()
        name_len = ctypes.c_size_t()
        item = ffi.wasmtime_component_item_t()
        found = ffi.wasmtime_component_type_export_nth(self.ptr(),
                                                       engine.ptr(),
                                                       i,
                                                       byref(name_ptr),
                                                       byref(name_len),
                                                       byref(item))
        assert(found)
        name = ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
        items[name] = component_item_from_ptr(item)
    return items

Returns a dictionary of the exports of this component type.

def imports(self, engine: wasmtime._engine.Engine) ‑> Dict[str, wasmtime.component._types.ComponentType | wasmtime.component._types.ModuleType | wasmtime.component._types.ComponentInstanceType | wasmtime.component._resource_type.ResourceType | wasmtime.component._types.ValType | wasmtime.component._types.FuncType]
Expand source code
def imports(self, engine: Engine) -> Dict[str, "ComponentItem"]:
    """
    Returns a dictionary of the imports of this component type.
    """
    n = ffi.wasmtime_component_type_import_count(self.ptr(), engine.ptr())
    items = {}
    for i in range(n):
        name_ptr = ctypes.POINTER(ctypes.c_char)()
        name_len = ctypes.c_size_t()
        item = ffi.wasmtime_component_item_t()
        found = ffi.wasmtime_component_type_import_nth(self.ptr(),
                                                       engine.ptr(),
                                                       i,
                                                       byref(name_ptr),
                                                       byref(name_len),
                                                       byref(item))
        assert(found)
        name = ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
        items[name] = component_item_from_ptr(item)
    return items

Returns a dictionary of the imports of this component type.

class EnumType
Expand source code
class EnumType(Managed["ctypes._Pointer[ffi.wasmtime_component_enum_type_t]"], ValType):
    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_enum_type_t]") -> None:
        ffi.wasmtime_component_enum_type_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_enum_type_t]") -> "EnumType":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_enum_type_t)):
            raise TypeError("wrong pointer type")
        ty: "EnumType" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    @property
    def names_count(self) -> int:
        """
        Returns the numter of names of this enum type.
        """
        return ffi.wasmtime_component_enum_type_names_count(self.ptr())

    def name(self, n: int) -> Optional[str]:
        """
        Returns the nth name of this enum type.
        """
        name_ptr = ctypes.POINTER(ctypes.c_char)()
        name_len = ctypes.c_size_t()
        found = ffi.wasmtime_component_enum_type_names_nth(self.ptr(),
                                                           n,
                                                           byref(name_ptr),
                                                           byref(name_len))
        if found:
            return ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
        return None

    @property
    def names(self) -> List[str]:
        """
        Returns the names of this enum type.
        """
        items = []
        for i in range(self.names_count):
            name = self.name(i)
            assert(name is not None)
            items.append(name)
        return items

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, EnumType):
            return False
        return ffi.wasmtime_component_enum_type_equal(self.ptr(), other.ptr())

    def add_classes(self, s: Set[type]) -> None:
        s.add(str)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if isinstance(val, str):
            ptr.contents.kind = ffi.WASMTIME_COMPONENT_ENUM
            ptr.contents.of.enumeration = ffi.str_to_capi(val)
        else:
            raise TypeError("expected str type")

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_ENUM.value)
        ret = ffi.to_str(c.of.enumeration)
        ffi.wasm_byte_vec_delete(byref(c.of.enumeration))
        return ret

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic
  • wasmtime.component._types.ValType

Instance variables

prop names : List[str]
Expand source code
@property
def names(self) -> List[str]:
    """
    Returns the names of this enum type.
    """
    items = []
    for i in range(self.names_count):
        name = self.name(i)
        assert(name is not None)
        items.append(name)
    return items

Returns the names of this enum type.

prop names_count : int
Expand source code
@property
def names_count(self) -> int:
    """
    Returns the numter of names of this enum type.
    """
    return ffi.wasmtime_component_enum_type_names_count(self.ptr())

Returns the numter of names of this enum type.

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(str)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_ENUM.value)
    ret = ffi.to_str(c.of.enumeration)
    ffi.wasm_byte_vec_delete(byref(c.of.enumeration))
    return ret

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if isinstance(val, str):
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_ENUM
        ptr.contents.of.enumeration = ffi.str_to_capi(val)
    else:
        raise TypeError("expected str type")

Converts val to this type and stores it in ptr

def name(self, n: int) ‑> str | None
Expand source code
def name(self, n: int) -> Optional[str]:
    """
    Returns the nth name of this enum type.
    """
    name_ptr = ctypes.POINTER(ctypes.c_char)()
    name_len = ctypes.c_size_t()
    found = ffi.wasmtime_component_enum_type_names_nth(self.ptr(),
                                                       n,
                                                       byref(name_ptr),
                                                       byref(name_len))
    if found:
        return ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
    return None

Returns the nth name of this enum type.

class ErrorContext
Expand source code
@dataclass
class ErrorContext(ValType):
    def add_classes(self, s: Set[type]) -> None:
        raise NotImplementedError("ErrorContext conversion not implemented yet")

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        raise NotImplementedError("ErrorContext conversion not implemented yet")

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        raise NotImplementedError("ErrorContext conversion not implemented yet")

ErrorContext()

Ancestors

  • wasmtime.component._types.ValType

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    raise NotImplementedError("ErrorContext conversion not implemented yet")

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    raise NotImplementedError("ErrorContext conversion not implemented yet")

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    raise NotImplementedError("ErrorContext conversion not implemented yet")

Converts val to this type and stores it in ptr

class ExportIndex
Expand source code
class ExportIndex(Managed["ctypes._Pointer[ffi.wasmtime_component_export_index_t]"]):

    def __init__(self) -> None:
        raise WasmtimeError("Cannot directly construct an `ExportIndex`")

    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_export_index_t]") -> None:
        ffi.wasmtime_component_export_index_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_export_index_t]") -> "ExportIndex":
        if not isinstance(ptr, ctypes.POINTER(ffi.wasmtime_component_export_index_t)):
            raise TypeError("wrong pointer type")
        ty: "ExportIndex" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic
class F32
Expand source code
@dataclass
class F32(ValType):
    def add_classes(self, s: Set[type]) -> None:
        s.add(float)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if not isinstance(val, float):
            raise TypeError("expected float for F32 type")
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_F32
        ptr.contents.of.f32 = val

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_F32.value)
        return float(c.of.f32)

F32()

Ancestors

  • wasmtime.component._types.ValType

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(float)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_F32.value)
    return float(c.of.f32)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if not isinstance(val, float):
        raise TypeError("expected float for F32 type")
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_F32
    ptr.contents.of.f32 = val

Converts val to this type and stores it in ptr

class F64
Expand source code
@dataclass
class F64(ValType):
    def add_classes(self, s: Set[type]) -> None:
        s.add(float)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if not isinstance(val, float):
            raise TypeError("expected float for F64 type")
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_F64
        ptr.contents.of.f64 = val

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_F64.value)
        return float(c.of.f64)

F64()

Ancestors

  • wasmtime.component._types.ValType

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(float)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_F64.value)
    return float(c.of.f64)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if not isinstance(val, float):
        raise TypeError("expected float for F64 type")
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_F64
    ptr.contents.of.f64 = val

Converts val to this type and stores it in ptr

class FlagsType
Expand source code
class FlagsType(Managed["ctypes._Pointer[ffi.wasmtime_component_flags_type_t]"], ValType):
    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_flags_type_t]") -> None:
        ffi.wasmtime_component_flags_type_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_flags_type_t]") -> "FlagsType":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_flags_type_t)):
            raise TypeError("wrong pointer type")
        ty: "FlagsType" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    @property
    def names(self) -> List[str]:
        """
        Returns the names of this flags type.
        """
        n = ffi.wasmtime_component_flags_type_names_count(self.ptr())
        items = []
        for i in range(n):
            name_ptr = ctypes.POINTER(ctypes.c_char)()
            name_len = ctypes.c_size_t()
            found = ffi.wasmtime_component_flags_type_names_nth(self.ptr(),
                                                                i,
                                                                byref(name_ptr),
                                                                byref(name_len))
            assert(found)
            name = ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
            items.append(name)
        return items

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, FlagsType):
            return False
        return ffi.wasmtime_component_flags_type_equal(self.ptr(), other.ptr())

    def add_classes(self, s: Set[type]) -> None:
        s.add(set)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if not isinstance(val, set):
            raise TypeError("expected set type for Flags type")
        for s in val:
            if not isinstance(s, str):
                raise TypeError("expected set of strings for Flags type")

        raw = ffi.wasmtime_component_valflags_t()
        ffi.wasmtime_component_valflags_new_uninit(raw, len(val))
        for i, s in enumerate(val):
            raw.data[i] = ffi.str_to_capi(s)
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_FLAGS
        ptr.contents.of.flags = raw

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_FLAGS.value)
        result = set()
        for i in range(c.of.flags.size):
            s = ffi.to_str(c.of.flags.data[i])
            result.add(s)
        ffi.wasmtime_component_valflags_delete(byref(c.of.flags))
        return result

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic
  • wasmtime.component._types.ValType

Instance variables

prop names : List[str]
Expand source code
@property
def names(self) -> List[str]:
    """
    Returns the names of this flags type.
    """
    n = ffi.wasmtime_component_flags_type_names_count(self.ptr())
    items = []
    for i in range(n):
        name_ptr = ctypes.POINTER(ctypes.c_char)()
        name_len = ctypes.c_size_t()
        found = ffi.wasmtime_component_flags_type_names_nth(self.ptr(),
                                                            i,
                                                            byref(name_ptr),
                                                            byref(name_len))
        assert(found)
        name = ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
        items.append(name)
    return items

Returns the names of this flags type.

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(set)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_FLAGS.value)
    result = set()
    for i in range(c.of.flags.size):
        s = ffi.to_str(c.of.flags.data[i])
        result.add(s)
    ffi.wasmtime_component_valflags_delete(byref(c.of.flags))
    return result

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if not isinstance(val, set):
        raise TypeError("expected set type for Flags type")
    for s in val:
        if not isinstance(s, str):
            raise TypeError("expected set of strings for Flags type")

    raw = ffi.wasmtime_component_valflags_t()
    ffi.wasmtime_component_valflags_new_uninit(raw, len(val))
    for i, s in enumerate(val):
        raw.data[i] = ffi.str_to_capi(s)
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_FLAGS
    ptr.contents.of.flags = raw

Converts val to this type and stores it in ptr

class Func
Expand source code
class Func:
    _func: ffi.wasmtime_component_func_t

    def __init__(self) -> None:
        raise WasmtimeError("Cannot directly construct a `Func`")

    @classmethod
    def _from_raw(cls, func: ffi.wasmtime_component_func_t) -> "Func":
        ty: "Func" = cls.__new__(cls)
        ty._func = func
        return ty

    def __call__(self, store: Storelike, *params: Any) -> Any:
        fty = self.type(store)
        param_tys = fty.params
        result_ty = fty.result
        if len(params) != len(param_tys):
            raise TypeError("wrong number of parameters provided: given %s, expected %s" %
                                (len(params), len(param_tys)))
        param_capi = (ffi.wasmtime_component_val_t * len(params))()
        n = 0
        try:
            for (_name, ty), val in zip(param_tys, params):
                ty.convert_to_c(store, val, pointer(param_capi[n]))
                n += 1
            result_space = None
            result_capi = None
            result_len = 0
            if result_ty is not None:
                result_space = ffi.wasmtime_component_val_t()
                result_capi = byref(result_space)
                result_len = 1

            def run() -> 'ctypes._Pointer[ffi.wasmtime_error_t]':
                return ffi.wasmtime_component_func_call(byref(self._func),
                                                        store._context(),
                                                        param_capi,
                                                        n,
                                                        result_capi,
                                                        result_len)
            enter_wasm(run)

            if result_space is None:
                return None
            assert(result_ty is not None)
            return result_ty.convert_from_c(result_space)

        finally:
            for i in range(n):
                ffi.wasmtime_component_val_delete(byref(param_capi[i]))


    def post_return(self, store: Storelike) -> None:
        """
        Performs any necessary post-return operations for this function.
        """
        def run() -> 'ctypes._Pointer[ffi.wasmtime_error_t]':
            return ffi.wasmtime_component_func_post_return(byref(self._func), store._context())
        enter_wasm(run)

    def type(self, store: Storelike) -> FuncType:
        """
        Returns the type of this function.
        """
        ptr = ffi.wasmtime_component_func_type(byref(self._func), store._context())
        return FuncType._from_ptr(ptr)

Methods

def post_return(self, store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext)
Expand source code
def post_return(self, store: Storelike) -> None:
    """
    Performs any necessary post-return operations for this function.
    """
    def run() -> 'ctypes._Pointer[ffi.wasmtime_error_t]':
        return ffi.wasmtime_component_func_post_return(byref(self._func), store._context())
    enter_wasm(run)

Performs any necessary post-return operations for this function.

def type(self, store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> wasmtime.component._types.FuncType
Expand source code
def type(self, store: Storelike) -> FuncType:
    """
    Returns the type of this function.
    """
    ptr = ffi.wasmtime_component_func_type(byref(self._func), store._context())
    return FuncType._from_ptr(ptr)

Returns the type of this function.

class FuncType
Expand source code
class FuncType(Managed["ctypes._Pointer[ffi.wasmtime_component_func_type_t]"]):
    _owner: Any

    def __init__(self) -> None:
        raise WasmtimeError("Cannot directly construct a `FuncType`")

    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_func_type_t]") -> None:
        if self._owner is None:
            ffi.wasmtime_component_func_type_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_func_type_t]", owner: Any = None) -> "FuncType":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_func_type_t)):
            raise TypeError("wrong pointer type")
        ty: "FuncType" = cls.__new__(cls)
        ty._set_ptr(ptr)
        ty._owner = owner
        return ty

    @property
    def params(self) -> List[Tuple[str, 'ValType']]:
        """
        Returns the parameter types of this component function type.
        """
        n = ffi.wasmtime_component_func_type_param_count(self.ptr())
        items = []
        for i in range(n):
            name_ptr = ctypes.POINTER(ctypes.c_char)()
            name_len = ctypes.c_size_t()
            valtype_ptr = ffi.wasmtime_component_valtype_t()
            found = ffi.wasmtime_component_func_type_param_nth(self.ptr(),
                                                               i,
                                                               byref(name_ptr),
                                                               byref(name_len),
                                                               byref(valtype_ptr))
            assert(found)
            name = ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
            valtype = valtype_from_ptr(valtype_ptr)
            items.append((name, valtype))
        return items

    @property
    def result(self) -> Optional['ValType']:
        """
        Returns the result type of this component function type, if any.
        """
        valtype_ptr = ffi.wasmtime_component_valtype_t()
        has_result = ffi.wasmtime_component_func_type_result(self.ptr(), byref(valtype_ptr))
        if not has_result:
            return None
        return valtype_from_ptr(valtype_ptr)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Instance variables

prop params : List[Tuple[str, ValType]]
Expand source code
@property
def params(self) -> List[Tuple[str, 'ValType']]:
    """
    Returns the parameter types of this component function type.
    """
    n = ffi.wasmtime_component_func_type_param_count(self.ptr())
    items = []
    for i in range(n):
        name_ptr = ctypes.POINTER(ctypes.c_char)()
        name_len = ctypes.c_size_t()
        valtype_ptr = ffi.wasmtime_component_valtype_t()
        found = ffi.wasmtime_component_func_type_param_nth(self.ptr(),
                                                           i,
                                                           byref(name_ptr),
                                                           byref(name_len),
                                                           byref(valtype_ptr))
        assert(found)
        name = ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
        valtype = valtype_from_ptr(valtype_ptr)
        items.append((name, valtype))
    return items

Returns the parameter types of this component function type.

prop resultValType | None
Expand source code
@property
def result(self) -> Optional['ValType']:
    """
    Returns the result type of this component function type, if any.
    """
    valtype_ptr = ffi.wasmtime_component_valtype_t()
    has_result = ffi.wasmtime_component_func_type_result(self.ptr(), byref(valtype_ptr))
    if not has_result:
        return None
    return valtype_from_ptr(valtype_ptr)

Returns the result type of this component function type, if any.

class FutureType
Expand source code
class FutureType(Managed["ctypes._Pointer[ffi.wasmtime_component_future_type_t]"], ValType):
    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_future_type_t]") -> None:
        ffi.wasmtime_component_future_type_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_future_type_t]") -> "FutureType":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_future_type_t)):
            raise TypeError("wrong pointer type")
        ty: "FutureType" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    @property
    def payload(self) -> 'ValType':
        """
        Returns the payload type of this future type.
        """
        valtype_ptr = ffi.wasmtime_component_valtype_t()
        ffi.wasmtime_component_future_type_ty(self.ptr(), byref(valtype_ptr))
        return valtype_from_ptr(valtype_ptr)

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, FutureType):
            return False
        return ffi.wasmtime_component_future_type_equal(self.ptr(), other.ptr())

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        raise NotImplementedError("Future conversion not implemented yet")

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        raise NotImplementedError("conversion not implemented yet")

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic
  • wasmtime.component._types.ValType

Instance variables

prop payloadValType
Expand source code
@property
def payload(self) -> 'ValType':
    """
    Returns the payload type of this future type.
    """
    valtype_ptr = ffi.wasmtime_component_valtype_t()
    ffi.wasmtime_component_future_type_ty(self.ptr(), byref(valtype_ptr))
    return valtype_from_ptr(valtype_ptr)

Returns the payload type of this future type.

Methods

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    raise NotImplementedError("conversion not implemented yet")

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    raise NotImplementedError("Future conversion not implemented yet")

Converts val to this type and stores it in ptr

class Instance
Expand source code
class Instance:
    _instance: ffi.wasmtime_component_instance_t

    def __init__(self) -> None:
        raise WasmtimeError("Cannot directly construct an `Instance`")

    @classmethod
    def _from_raw(cls, instance: ffi.wasmtime_component_instance_t) -> "Instance":
        ty: "Instance" = cls.__new__(cls)
        ty._instance = instance
        return ty

    def get_export_index(self, store: Storelike, name: str, instance: Optional[ExportIndex] = None) -> Optional[ExportIndex]:
        """
        Retrieves the export index for the export named `name` from this
        component instance.

        If `instance` is provided then the export is looked up within that
        nested instance.

        Returns `None` if no such export exists otherwise returns the export
        index.
        """
        name_bytes = name.encode('utf-8')
        name_buf = ctypes.create_string_buffer(name_bytes)

        ptr = ffi.wasmtime_component_instance_get_export_index(
            byref(self._instance),
            store._context(),
            instance.ptr() if instance is not None else None,
            name_buf,
            len(name_bytes))
        if ptr:
            return ExportIndex._from_ptr(ptr)
        return None

    def get_func(self, store: Storelike, index: Union[ExportIndex, str]) -> Optional[Func]:
        """
        Retrieves the function export for the given export index.

        Returns `None` if the export index does not correspond to a function
        export and otherwise returns the function.
        """
        if isinstance(index, str):
            ei = self.get_export_index(store, index)
            if ei is None:
                return None
            index = ei

        raw = ffi.wasmtime_component_func_t()
        found = ffi.wasmtime_component_instance_get_func(
            byref(self._instance),
            store._context(),
            index.ptr(),
            byref(raw))
        if found:
            return Func._from_raw(raw)
        return None

Methods

def get_export_index(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
name: str,
instance: wasmtime.component._component.ExportIndex | None = None) ‑> wasmtime.component._component.ExportIndex | None
Expand source code
def get_export_index(self, store: Storelike, name: str, instance: Optional[ExportIndex] = None) -> Optional[ExportIndex]:
    """
    Retrieves the export index for the export named `name` from this
    component instance.

    If `instance` is provided then the export is looked up within that
    nested instance.

    Returns `None` if no such export exists otherwise returns the export
    index.
    """
    name_bytes = name.encode('utf-8')
    name_buf = ctypes.create_string_buffer(name_bytes)

    ptr = ffi.wasmtime_component_instance_get_export_index(
        byref(self._instance),
        store._context(),
        instance.ptr() if instance is not None else None,
        name_buf,
        len(name_bytes))
    if ptr:
        return ExportIndex._from_ptr(ptr)
    return None

Retrieves the export index for the export named name from this component instance.

If instance is provided then the export is looked up within that nested instance.

Returns None if no such export exists otherwise returns the export index.

def get_func(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
index: wasmtime.component._component.ExportIndex | str) ‑> wasmtime.component._func.Func | None
Expand source code
def get_func(self, store: Storelike, index: Union[ExportIndex, str]) -> Optional[Func]:
    """
    Retrieves the function export for the given export index.

    Returns `None` if the export index does not correspond to a function
    export and otherwise returns the function.
    """
    if isinstance(index, str):
        ei = self.get_export_index(store, index)
        if ei is None:
            return None
        index = ei

    raw = ffi.wasmtime_component_func_t()
    found = ffi.wasmtime_component_instance_get_func(
        byref(self._instance),
        store._context(),
        index.ptr(),
        byref(raw))
    if found:
        return Func._from_raw(raw)
    return None

Retrieves the function export for the given export index.

Returns None if the export index does not correspond to a function export and otherwise returns the function.

class Linker (engine: wasmtime._engine.Engine)
Expand source code
class Linker(Managed["ctypes._Pointer[ffi.wasmtime_component_linker_t]"]):
    engine: Engine
    locked: bool

    def __init__(self, engine: Engine):
        """
        Creates a new linker ready to instantiate modules within the store
        provided.
        """
        self._set_ptr(ffi.wasmtime_component_linker_new(engine.ptr()))
        self.engine = engine
        self.locked = False

    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_linker_t]") -> None:
        self._assert_not_locked()
        ffi.wasmtime_component_linker_delete(ptr)

    @setter_property
    def allow_shadowing(self, allow: bool) -> None:
        """
        Configures whether definitions are allowed to shadow one another within
        this linker
        """
        self._assert_not_locked()
        ffi.wasmtime_component_linker_allow_shadowing(self.ptr(), allow)

    def _assert_not_locked(self) -> None:
        if self.locked:
            raise WasmtimeError("cannot use linker while it's in use by other instances")

    def root(self) -> "LinkerInstance":
        """
        Returns the root instance used to defined new items in this linker.

        While this root instance is alive this linker cannot be used for any
        other operations. Until the returned object is destroyed this linker is
        considered "locked".

        It's recommended to bind the return value in a `with` block to
        automatically dispose of it when it's done.
        """
        self._assert_not_locked()
        ptr = ffi.wasmtime_component_linker_root(self.ptr())
        return LinkerInstance._from_ptr(ptr, self)

    def add_wasip2(self) -> None:
        """
        Adds the WASIp2 API definitions, from Wasmtime, in this linker.
        """
        self._assert_not_locked()
        err = ffi.wasmtime_component_linker_add_wasip2(self.ptr())
        if err:
            raise WasmtimeError._from_ptr(err)

    def instantiate(self, store: Storelike, component: Component) -> Instance:
        """
        Instantiates the given component using this linker within the provided
        store.

        Returns the instantiated `Instance` on success.
        """
        self._assert_not_locked()
        instance = ffi.wasmtime_component_instance_t()
        err = ffi.wasmtime_component_linker_instantiate(
            self.ptr(),
            store._context(),
            component.ptr(),
            byref(instance))
        if err:
            raise WasmtimeError._from_ptr(err)
        return Instance._from_raw(instance)

    def define_unknown_imports_as_traps(self, component: Component) -> None:
        """
        Configures this linker to define any unknown imports of `component` as
        traps which will error when invoked.
        """
        self._assert_not_locked()
        err = ffi.wasmtime_component_linker_define_unknown_imports_as_traps(
            self.ptr(),
            component.ptr())
        if err:
            raise WasmtimeError._from_ptr(err)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Creates a new linker ready to instantiate modules within the store provided.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Class variables

var engine : wasmtime._engine.Engine

The type of the None singleton.

var locked : bool

The type of the None singleton.

Instance variables

prop allow_shadowing
Expand source code
@setter_property
def allow_shadowing(self, allow: bool) -> None:
    """
    Configures whether definitions are allowed to shadow one another within
    this linker
    """
    self._assert_not_locked()
    ffi.wasmtime_component_linker_allow_shadowing(self.ptr(), allow)

Configures whether definitions are allowed to shadow one another within this linker

    Note that this field can only be set, it cannot be read

Methods

def add_wasip2(self) ‑> None
Expand source code
def add_wasip2(self) -> None:
    """
    Adds the WASIp2 API definitions, from Wasmtime, in this linker.
    """
    self._assert_not_locked()
    err = ffi.wasmtime_component_linker_add_wasip2(self.ptr())
    if err:
        raise WasmtimeError._from_ptr(err)

Adds the WASIp2 API definitions, from Wasmtime, in this linker.

def define_unknown_imports_as_traps(self, component: wasmtime.component._component.Component) ‑> None
Expand source code
def define_unknown_imports_as_traps(self, component: Component) -> None:
    """
    Configures this linker to define any unknown imports of `component` as
    traps which will error when invoked.
    """
    self._assert_not_locked()
    err = ffi.wasmtime_component_linker_define_unknown_imports_as_traps(
        self.ptr(),
        component.ptr())
    if err:
        raise WasmtimeError._from_ptr(err)

Configures this linker to define any unknown imports of component as traps which will error when invoked.

def instantiate(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
component: wasmtime.component._component.Component) ‑> wasmtime.component._instance.Instance
Expand source code
def instantiate(self, store: Storelike, component: Component) -> Instance:
    """
    Instantiates the given component using this linker within the provided
    store.

    Returns the instantiated `Instance` on success.
    """
    self._assert_not_locked()
    instance = ffi.wasmtime_component_instance_t()
    err = ffi.wasmtime_component_linker_instantiate(
        self.ptr(),
        store._context(),
        component.ptr(),
        byref(instance))
    if err:
        raise WasmtimeError._from_ptr(err)
    return Instance._from_raw(instance)

Instantiates the given component using this linker within the provided store.

Returns the instantiated Instance on success.

def root(self) ‑> wasmtime.component._linker.LinkerInstance
Expand source code
def root(self) -> "LinkerInstance":
    """
    Returns the root instance used to defined new items in this linker.

    While this root instance is alive this linker cannot be used for any
    other operations. Until the returned object is destroyed this linker is
    considered "locked".

    It's recommended to bind the return value in a `with` block to
    automatically dispose of it when it's done.
    """
    self._assert_not_locked()
    ptr = ffi.wasmtime_component_linker_root(self.ptr())
    return LinkerInstance._from_ptr(ptr, self)

Returns the root instance used to defined new items in this linker.

While this root instance is alive this linker cannot be used for any other operations. Until the returned object is destroyed this linker is considered "locked".

It's recommended to bind the return value in a with block to automatically dispose of it when it's done.

class LinkerInstance
Expand source code
class LinkerInstance(Managed["ctypes._Pointer[ffi.wasmtime_component_linker_instance_t]"]):
    parent: Union[LinkerInstanceParent, None]
    locked: bool

    def __init__(self) -> None:
        raise WasmtimeError("Cannot directly construct a `LinkerInstance`")

    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_linker_instance_t]") -> None:
        self._assert_not_locked()
        ffi.wasmtime_component_linker_instance_delete(ptr)
        assert(self.parent is not None)
        assert(self.parent.locked)
        self.parent.locked = False
        self.parent = None

    def _assert_not_locked(self) -> None:
        if self.locked:
            raise WasmtimeError("cannot use linker instance while it's in use by other instances")

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_linker_instance_t]", parent: LinkerInstanceParent) -> "LinkerInstance":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_linker_instance_t)):
            raise TypeError("wrong pointer type")
        ty: "LinkerInstance" = cls.__new__(cls)
        ty._set_ptr(ptr)
        ty.parent = parent
        ty.locked = False
        assert(not parent.locked)
        parent.locked = True
        return ty


    def add_instance(self, name: str) -> "LinkerInstance":
        """
        Adds a new instance to this linker instance under the given name.

        Returns a new `LinkerInstance` which can be used to define further
        items.

        While the returned instance is alive this linker instance cannot be
        used for other operations. Until the returned object is destroyed this
        linker instance is considered "locked".

        It's recommended to bind the return value in a `with` block to
        automatically dispose of it when it's done.
        """
        self._assert_not_locked()
        name_bytes = name.encode('utf-8')
        name_buf = create_string_buffer(name_bytes)
        ptr = POINTER(ffi.wasmtime_component_linker_instance_t)()
        err = ffi.wasmtime_component_linker_instance_add_instance(self.ptr(),
                                                                  name_buf,
                                                                  len(name_bytes),
                                                                  byref(ptr))
        if err:
            raise WasmtimeError._from_ptr(err)
        return LinkerInstance._from_ptr(ptr, self)

    def add_module(self, name: str, module: Module) -> None:
        """
        Adds a new module to this linker instance under the given name.
        """
        self._assert_not_locked()
        name_bytes = name.encode('utf-8')
        name_buf = create_string_buffer(name_bytes)
        err = ffi.wasmtime_component_linker_instance_add_module(self.ptr(),
                                                                name_buf,
                                                                len(name_bytes),
                                                                module.ptr())
        if err:
            raise WasmtimeError._from_ptr(err)

    def add_resource(self, name: str, ty: ResourceType, dtor: ResourceDtor) -> None:
        """
        Defines a the resource type `ty` under `name`

        When a value of this resource is destroyed then `dtor` is invoked.
        """
        self._assert_not_locked()
        name_bytes = name.encode('utf-8')
        name_buf = create_string_buffer(name_bytes)
        idx = RESOURCE_DTORS.allocate(dtor)
        err = ffi.wasmtime_component_linker_instance_add_resource(self.ptr(),
                                                                  name_buf,
                                                                  len(name_bytes),
                                                                  ty.ptr(),
                                                                  resource_dtor_impl,
                                                                  idx,
                                                                  resource_dtor_finalize)
        if err:
            raise WasmtimeError._from_ptr(err)

    def add_func(self, name: str, func: UserFunc) -> None:
        self._assert_not_locked()
        name_bytes = name.encode('utf-8')
        name_buf = create_string_buffer(name_bytes)
        idx = FUNCTIONS.allocate(func)
        err = ffi.wasmtime_component_linker_instance_add_func(self.ptr(),
                                                              name_buf,
                                                              len(name_bytes),
                                                              func_impl,
                                                              idx,
                                                              func_finalize)
        if err:
            raise WasmtimeError._from_ptr(err)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Class variables

var locked : bool

The type of the None singleton.

var parent : wasmtime.component._linker.Linker | wasmtime.component._linker.LinkerInstance | None

The type of the None singleton.

Methods

def add_func(self, name: str, func: Callable[..., Any | None]) ‑> None
Expand source code
def add_func(self, name: str, func: UserFunc) -> None:
    self._assert_not_locked()
    name_bytes = name.encode('utf-8')
    name_buf = create_string_buffer(name_bytes)
    idx = FUNCTIONS.allocate(func)
    err = ffi.wasmtime_component_linker_instance_add_func(self.ptr(),
                                                          name_buf,
                                                          len(name_bytes),
                                                          func_impl,
                                                          idx,
                                                          func_finalize)
    if err:
        raise WasmtimeError._from_ptr(err)
def add_instance(self, name: str) ‑> wasmtime.component._linker.LinkerInstance
Expand source code
def add_instance(self, name: str) -> "LinkerInstance":
    """
    Adds a new instance to this linker instance under the given name.

    Returns a new `LinkerInstance` which can be used to define further
    items.

    While the returned instance is alive this linker instance cannot be
    used for other operations. Until the returned object is destroyed this
    linker instance is considered "locked".

    It's recommended to bind the return value in a `with` block to
    automatically dispose of it when it's done.
    """
    self._assert_not_locked()
    name_bytes = name.encode('utf-8')
    name_buf = create_string_buffer(name_bytes)
    ptr = POINTER(ffi.wasmtime_component_linker_instance_t)()
    err = ffi.wasmtime_component_linker_instance_add_instance(self.ptr(),
                                                              name_buf,
                                                              len(name_bytes),
                                                              byref(ptr))
    if err:
        raise WasmtimeError._from_ptr(err)
    return LinkerInstance._from_ptr(ptr, self)

Adds a new instance to this linker instance under the given name.

Returns a new LinkerInstance which can be used to define further items.

While the returned instance is alive this linker instance cannot be used for other operations. Until the returned object is destroyed this linker instance is considered "locked".

It's recommended to bind the return value in a with block to automatically dispose of it when it's done.

def add_module(self, name: str, module: wasmtime._module.Module) ‑> None
Expand source code
def add_module(self, name: str, module: Module) -> None:
    """
    Adds a new module to this linker instance under the given name.
    """
    self._assert_not_locked()
    name_bytes = name.encode('utf-8')
    name_buf = create_string_buffer(name_bytes)
    err = ffi.wasmtime_component_linker_instance_add_module(self.ptr(),
                                                            name_buf,
                                                            len(name_bytes),
                                                            module.ptr())
    if err:
        raise WasmtimeError._from_ptr(err)

Adds a new module to this linker instance under the given name.

def add_resource(self,
name: str,
ty: wasmtime.component._resource_type.ResourceType,
dtor: Callable[[wasmtime._store.StoreContext, int], None]) ‑> None
Expand source code
def add_resource(self, name: str, ty: ResourceType, dtor: ResourceDtor) -> None:
    """
    Defines a the resource type `ty` under `name`

    When a value of this resource is destroyed then `dtor` is invoked.
    """
    self._assert_not_locked()
    name_bytes = name.encode('utf-8')
    name_buf = create_string_buffer(name_bytes)
    idx = RESOURCE_DTORS.allocate(dtor)
    err = ffi.wasmtime_component_linker_instance_add_resource(self.ptr(),
                                                              name_buf,
                                                              len(name_bytes),
                                                              ty.ptr(),
                                                              resource_dtor_impl,
                                                              idx,
                                                              resource_dtor_finalize)
    if err:
        raise WasmtimeError._from_ptr(err)

Defines a the resource type ty under name

When a value of this resource is destroyed then dtor is invoked.

class ListType
Expand source code
class ListType(Managed["ctypes._Pointer[ffi.wasmtime_component_list_type_t]"], ValType):
    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_list_type_t]") -> None:
        ffi.wasmtime_component_list_type_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_list_type_t]") -> "ListType":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_list_type_t)):
            raise TypeError("wrong pointer type")
        ty: "ListType" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    @property
    def element(self) -> 'ValType':
        """
        Returns the element type of this list type.
        """
        valtype_ptr = ffi.wasmtime_component_valtype_t()
        ffi.wasmtime_component_list_type_element(self.ptr(), byref(valtype_ptr))
        return valtype_from_ptr(valtype_ptr)

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, ListType):
            return False
        return ffi.wasmtime_component_list_type_equal(self.ptr(), other.ptr())

    def _is_bytes(self) -> bool:
        return isinstance(self.element, U8)

    def add_classes(self, s: Set[type]) -> None:
        if self._is_bytes():
            s.add(bytes)
        else:
            s.add(list)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        element = self.element
        if self._is_bytes():
            if not isinstance(val, bytes):
                raise TypeError("expected bytes value")
        else:
            if not isinstance(val, list):
                raise TypeError("expected list value")
        assert(isinstance(val, (bytes, list))) # here for mypy
        raw = ffi.wasmtime_component_vallist_t()
        ffi.wasmtime_component_vallist_new_uninit(raw, len(val))
        i = 0
        cleanup = True
        try:
            for e in val:
                element.convert_to_c(store, e, ctypes.pointer(raw.data[i]))
                i += 1
            ptr.contents.kind = ffi.WASMTIME_COMPONENT_LIST
            ptr.contents.of.list = raw
            cleanup = False
        finally:
            if cleanup:
                for j in range(i, len(val)):
                    raw.data[j].kind = ffi.WASMTIME_COMPONENT_BOOL
                    raw.data[j].of.boolean = False
                ffi.wasmtime_component_vallist_delete(byref(raw))


    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_LIST.value)
        try:
            ret = []
            element = self.element
            for i in range(c.of.record.size):
                raw_field = c.of.tuple.data[i]
                ret.append(element.convert_from_c(raw_field))
                raw_field.kind = ffi.WASMTIME_COMPONENT_BOOL
                raw_field.of.boolean = False
            if self._is_bytes():
                return bytes(ret)
            return ret
        finally:
            ffi.wasmtime_component_valtuple_delete(byref(c.of.tuple))

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic
  • wasmtime.component._types.ValType

Instance variables

prop elementValType
Expand source code
@property
def element(self) -> 'ValType':
    """
    Returns the element type of this list type.
    """
    valtype_ptr = ffi.wasmtime_component_valtype_t()
    ffi.wasmtime_component_list_type_element(self.ptr(), byref(valtype_ptr))
    return valtype_from_ptr(valtype_ptr)

Returns the element type of this list type.

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    if self._is_bytes():
        s.add(bytes)
    else:
        s.add(list)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_LIST.value)
    try:
        ret = []
        element = self.element
        for i in range(c.of.record.size):
            raw_field = c.of.tuple.data[i]
            ret.append(element.convert_from_c(raw_field))
            raw_field.kind = ffi.WASMTIME_COMPONENT_BOOL
            raw_field.of.boolean = False
        if self._is_bytes():
            return bytes(ret)
        return ret
    finally:
        ffi.wasmtime_component_valtuple_delete(byref(c.of.tuple))

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    element = self.element
    if self._is_bytes():
        if not isinstance(val, bytes):
            raise TypeError("expected bytes value")
    else:
        if not isinstance(val, list):
            raise TypeError("expected list value")
    assert(isinstance(val, (bytes, list))) # here for mypy
    raw = ffi.wasmtime_component_vallist_t()
    ffi.wasmtime_component_vallist_new_uninit(raw, len(val))
    i = 0
    cleanup = True
    try:
        for e in val:
            element.convert_to_c(store, e, ctypes.pointer(raw.data[i]))
            i += 1
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_LIST
        ptr.contents.of.list = raw
        cleanup = False
    finally:
        if cleanup:
            for j in range(i, len(val)):
                raw.data[j].kind = ffi.WASMTIME_COMPONENT_BOOL
                raw.data[j].of.boolean = False
            ffi.wasmtime_component_vallist_delete(byref(raw))

Converts val to this type and stores it in ptr

class ModuleType
Expand source code
class ModuleType(Managed["ctypes._Pointer[ffi.wasmtime_module_type_t]"]):
    def __init__(self) -> None:
        raise WasmtimeError("Cannot directly construct a `ModuleType`")

    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_module_type_t]") -> None:
        ffi.wasmtime_module_type_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_module_type_t]") -> "ModuleType":
        if not isinstance(ptr, POINTER(ffi.wasmtime_module_type_t)):
            raise TypeError("wrong pointer type")
        ty: "ModuleType" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    def imports(self, engine: Engine) -> List[ImportType]:
        """
        Returns a list of the imports of this module type.
        """
        n = ffi.wasmtime_module_type_import_count(self.ptr(), engine.ptr())
        items = []
        for i in range(n):
            item = ffi.wasmtime_module_type_import_nth(self.ptr(),
                                                       engine.ptr(),
                                                       i)
            items.append(ImportType._from_ptr(item))
        return items

    def exports(self, engine: Engine) -> List[ExportType]:
        """
        Returns a list of the exports of this module type.
        """
        n = ffi.wasmtime_module_type_export_count(self.ptr(), engine.ptr())
        items = []
        for i in range(n):
            item = ffi.wasmtime_module_type_export_nth(self.ptr(),
                                                       engine.ptr(),
                                                       i)
            items.append(ExportType._from_ptr(item))
        return items

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Methods

def exports(self, engine: wasmtime._engine.Engine) ‑> List[wasmtime._types.ExportType]
Expand source code
def exports(self, engine: Engine) -> List[ExportType]:
    """
    Returns a list of the exports of this module type.
    """
    n = ffi.wasmtime_module_type_export_count(self.ptr(), engine.ptr())
    items = []
    for i in range(n):
        item = ffi.wasmtime_module_type_export_nth(self.ptr(),
                                                   engine.ptr(),
                                                   i)
        items.append(ExportType._from_ptr(item))
    return items

Returns a list of the exports of this module type.

def imports(self, engine: wasmtime._engine.Engine) ‑> List[wasmtime._types.ImportType]
Expand source code
def imports(self, engine: Engine) -> List[ImportType]:
    """
    Returns a list of the imports of this module type.
    """
    n = ffi.wasmtime_module_type_import_count(self.ptr(), engine.ptr())
    items = []
    for i in range(n):
        item = ffi.wasmtime_module_type_import_nth(self.ptr(),
                                                   engine.ptr(),
                                                   i)
        items.append(ImportType._from_ptr(item))
    return items

Returns a list of the imports of this module type.

class OptionType
Expand source code
class OptionType(Managed["ctypes._Pointer[ffi.wasmtime_component_option_type_t]"], ValType, VariantLikeType):
    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_option_type_t]") -> None:
        ffi.wasmtime_component_option_type_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_option_type_t]") -> "OptionType":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_option_type_t)):
            raise TypeError("wrong pointer type")
        ty: "OptionType" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    @property
    def payload(self) -> 'ValType':
        """
        Returns the payload type of this option type.
        """
        valtype_ptr = ffi.wasmtime_component_valtype_t()
        ffi.wasmtime_component_option_type_ty(self.ptr(), byref(valtype_ptr))
        return valtype_from_ptr(valtype_ptr)

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, OptionType):
            return False
        return ffi.wasmtime_component_option_type_equal(self.ptr(), other.ptr())

    def _cases(self) -> List[Tuple[str, Optional['ValType']]]:
        return [('none', None), ('some', self.payload)]

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        _, raw = self._lower(store, val)
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_OPTION
        ptr.contents.of.option = raw

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_OPTION.value)
        if c.of.option:
            tag = 'some'
        else:
            tag = 'none'
        return self._lift(tag, c.of.option)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic
  • wasmtime.component._types.ValType
  • wasmtime.component._types.VariantLikeType

Instance variables

prop payloadValType
Expand source code
@property
def payload(self) -> 'ValType':
    """
    Returns the payload type of this option type.
    """
    valtype_ptr = ffi.wasmtime_component_valtype_t()
    ffi.wasmtime_component_option_type_ty(self.ptr(), byref(valtype_ptr))
    return valtype_from_ptr(valtype_ptr)

Returns the payload type of this option type.

Methods

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_OPTION.value)
    if c.of.option:
        tag = 'some'
    else:
        tag = 'none'
    return self._lift(tag, c.of.option)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    _, raw = self._lower(store, val)
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_OPTION
    ptr.contents.of.option = raw

Converts val to this type and stores it in ptr

class OwnType (ty: wasmtime.component._resource_type.ResourceType)
Expand source code
@dataclass
class OwnType(ValType):
    ty: ResourceType

    def add_classes(self, s: Set[type]) -> None:
        s.add(ResourceAny)
        s.add(ResourceHost)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if isinstance(val, ResourceAny):
            ptr.contents.kind = ffi.WASMTIME_COMPONENT_RESOURCE
            ptr.contents.of.resource = val._consume()
        elif isinstance(val, ResourceHost):
            ptr.contents.kind = ffi.WASMTIME_COMPONENT_RESOURCE
            ptr.contents.of.resource = val.to_any(store)._consume()
        else:
            raise TypeError("expected ResourceAny or ResourceHost for Own type")

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_RESOURCE.value)
        return ResourceAny._from_ptr(ffi.take_pointer(c.of, 'resource'))

OwnType(ty: wasmtime.component._resource_type.ResourceType)

Ancestors

  • wasmtime.component._types.ValType

Instance variables

var ty : wasmtime.component._resource_type.ResourceType

The type of the None singleton.

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(ResourceAny)
    s.add(ResourceHost)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_RESOURCE.value)
    return ResourceAny._from_ptr(ffi.take_pointer(c.of, 'resource'))

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if isinstance(val, ResourceAny):
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_RESOURCE
        ptr.contents.of.resource = val._consume()
    elif isinstance(val, ResourceHost):
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_RESOURCE
        ptr.contents.of.resource = val.to_any(store)._consume()
    else:
        raise TypeError("expected ResourceAny or ResourceHost for Own type")

Converts val to this type and stores it in ptr

class Record
Expand source code
class Record:
    def __eq__(self, other: Any) -> bool:
        for key, value in self.__dict__.items():
            if not hasattr(other, key) or getattr(other, key) != value:
                return False
        return True
class RecordType
Expand source code
class RecordType(Managed["ctypes._Pointer[ffi.wasmtime_component_record_type_t]"], ValType):
    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_record_type_t]") -> None:
        ffi.wasmtime_component_record_type_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_record_type_t]") -> "RecordType":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_record_type_t)):
            raise TypeError("wrong pointer type")
        ty: "RecordType" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    @property
    def fields(self) -> List[Tuple[str, 'ValType']]:
        """
        Returns the fields of this record type.
        """
        n = ffi.wasmtime_component_record_type_field_count(self.ptr())
        items = []
        for i in range(n):
            name_ptr = ctypes.POINTER(ctypes.c_char)()
            name_len = ctypes.c_size_t()
            valtype_ptr = ffi.wasmtime_component_valtype_t()
            found = ffi.wasmtime_component_record_type_field_nth(self.ptr(),
                                                                 i,
                                                                 byref(name_ptr),
                                                                 byref(name_len),
                                                                 byref(valtype_ptr))
            assert(found)
            name = ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
            valtype = valtype_from_ptr(valtype_ptr)
            items.append((name, valtype))
        return items

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, RecordType):
            return False
        return ffi.wasmtime_component_record_type_equal(self.ptr(), other.ptr())

    def add_classes(self, s: Set[type]) -> None:
        s.add(Record)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        fields = self.fields
        raw = ffi.wasmtime_component_valrecord_t()
        ffi.wasmtime_component_valrecord_new_uninit(raw, len(fields))
        i = 0
        cleanup = True
        try:
            for name, ty in fields:
                ty.convert_to_c(store, getattr(val, name), ctypes.pointer(raw.data[i].val))
                raw.data[i].name = ffi.str_to_capi(name)
                i += 1
            ptr.contents.kind = ffi.WASMTIME_COMPONENT_RECORD
            ptr.contents.of.record = raw
            cleanup = False
        finally:
            if cleanup:
                for j in range(i, len(fields)):
                    raw.data[j].val.kind = ffi.WASMTIME_COMPONENT_BOOL
                    raw.data[j].val.of.boolean = False
                ffi.wasmtime_component_valrecord_delete(byref(raw))


    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_RECORD.value)
        try:
            ret = Record()
            fields = self.fields
            for i, (name, ty) in zip(range(c.of.record.size), fields):
                raw_field = c.of.record.data[i]
                raw_name = ffi.to_str(raw_field.name)
                assert(raw_name == name)
                val = ty.convert_from_c(raw_field.val)
                setattr(ret, name, val)
                raw_field.val.kind = ffi.WASMTIME_COMPONENT_BOOL
                raw_field.val.of.boolean = False
            return ret
        finally:
            ffi.wasmtime_component_valrecord_delete(c.of.record)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic
  • wasmtime.component._types.ValType

Instance variables

prop fields : List[Tuple[str, ValType]]
Expand source code
@property
def fields(self) -> List[Tuple[str, 'ValType']]:
    """
    Returns the fields of this record type.
    """
    n = ffi.wasmtime_component_record_type_field_count(self.ptr())
    items = []
    for i in range(n):
        name_ptr = ctypes.POINTER(ctypes.c_char)()
        name_len = ctypes.c_size_t()
        valtype_ptr = ffi.wasmtime_component_valtype_t()
        found = ffi.wasmtime_component_record_type_field_nth(self.ptr(),
                                                             i,
                                                             byref(name_ptr),
                                                             byref(name_len),
                                                             byref(valtype_ptr))
        assert(found)
        name = ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
        valtype = valtype_from_ptr(valtype_ptr)
        items.append((name, valtype))
    return items

Returns the fields of this record type.

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(Record)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_RECORD.value)
    try:
        ret = Record()
        fields = self.fields
        for i, (name, ty) in zip(range(c.of.record.size), fields):
            raw_field = c.of.record.data[i]
            raw_name = ffi.to_str(raw_field.name)
            assert(raw_name == name)
            val = ty.convert_from_c(raw_field.val)
            setattr(ret, name, val)
            raw_field.val.kind = ffi.WASMTIME_COMPONENT_BOOL
            raw_field.val.of.boolean = False
        return ret
    finally:
        ffi.wasmtime_component_valrecord_delete(c.of.record)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    fields = self.fields
    raw = ffi.wasmtime_component_valrecord_t()
    ffi.wasmtime_component_valrecord_new_uninit(raw, len(fields))
    i = 0
    cleanup = True
    try:
        for name, ty in fields:
            ty.convert_to_c(store, getattr(val, name), ctypes.pointer(raw.data[i].val))
            raw.data[i].name = ffi.str_to_capi(name)
            i += 1
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_RECORD
        ptr.contents.of.record = raw
        cleanup = False
    finally:
        if cleanup:
            for j in range(i, len(fields)):
                raw.data[j].val.kind = ffi.WASMTIME_COMPONENT_BOOL
                raw.data[j].val.of.boolean = False
            ffi.wasmtime_component_valrecord_delete(byref(raw))

Converts val to this type and stores it in ptr

class ResourceAny
Expand source code
class ResourceAny(Managed["ctypes._Pointer[ffi.wasmtime_component_resource_any_t]"]):
    def __init__(self) -> None:
        raise WasmtimeError("Cannot directly construct a `ResourceAny`")

    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_resource_any_t]") -> None:
        ffi.wasmtime_component_resource_any_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_resource_any_t]") -> "ResourceAny":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_resource_any_t)):
            raise TypeError("wrong pointer type")
        ty: "ResourceAny" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    @property
    def type(self) -> ResourceType:
        """
        Returns the `ResourceType` of this `ResourceAny`.
        """
        ptr = ffi.wasmtime_component_resource_any_type(self.ptr())
        return ResourceType._from_ptr(ptr)

    @property
    def owned(self) -> bool:
        """
        Returns whether this `ResourceAny` is an `own` resource or a `borrow`
        resource.
        """
        return ffi.wasmtime_component_resource_any_owned(self.ptr())

    def drop(self, store: Storelike) -> None:
        """
        Runs the WebAssembly-defined destructor, if any, for this resource.

        This is required to be called to clean up state information in the
        store about this resource. This may execute WebAssembly code if the
        resource is a guest-owned resource with a defined destructor.
        """
        def run() -> 'ctypes._Pointer[ffi.wasmtime_error_t]':
            return ffi.wasmtime_component_resource_any_drop(store._context(), self.ptr())
        enter_wasm(run)

    def to_host(self, store: Storelike) -> "ResourceHost":
        """
        Attempts to downcast this `ResourceAny` to a `ResourceHost`.

        This will raise a `WasmtimeError` if this `ResourceAny` is not
        actually a host-defined resource.
        """
        ptr = POINTER(ffi.wasmtime_component_resource_host_t)()
        error = ffi.wasmtime_component_resource_any_to_host(store._context(), self.ptr(), byref(ptr))
        if error:
            raise WasmtimeError._from_ptr(error)
        return ResourceHost._from_ptr(ptr)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Instance variables

prop owned : bool
Expand source code
@property
def owned(self) -> bool:
    """
    Returns whether this `ResourceAny` is an `own` resource or a `borrow`
    resource.
    """
    return ffi.wasmtime_component_resource_any_owned(self.ptr())

Returns whether this ResourceAny is an own resource or a borrow resource.

prop type : wasmtime.component._resource_type.ResourceType
Expand source code
@property
def type(self) -> ResourceType:
    """
    Returns the `ResourceType` of this `ResourceAny`.
    """
    ptr = ffi.wasmtime_component_resource_any_type(self.ptr())
    return ResourceType._from_ptr(ptr)

Returns the ResourceType of this ResourceAny.

Methods

def drop(self, store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext)
Expand source code
def drop(self, store: Storelike) -> None:
    """
    Runs the WebAssembly-defined destructor, if any, for this resource.

    This is required to be called to clean up state information in the
    store about this resource. This may execute WebAssembly code if the
    resource is a guest-owned resource with a defined destructor.
    """
    def run() -> 'ctypes._Pointer[ffi.wasmtime_error_t]':
        return ffi.wasmtime_component_resource_any_drop(store._context(), self.ptr())
    enter_wasm(run)

Runs the WebAssembly-defined destructor, if any, for this resource.

This is required to be called to clean up state information in the store about this resource. This may execute WebAssembly code if the resource is a guest-owned resource with a defined destructor.

def to_host(self, store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> ResourceHost
Expand source code
def to_host(self, store: Storelike) -> "ResourceHost":
    """
    Attempts to downcast this `ResourceAny` to a `ResourceHost`.

    This will raise a `WasmtimeError` if this `ResourceAny` is not
    actually a host-defined resource.
    """
    ptr = POINTER(ffi.wasmtime_component_resource_host_t)()
    error = ffi.wasmtime_component_resource_any_to_host(store._context(), self.ptr(), byref(ptr))
    if error:
        raise WasmtimeError._from_ptr(error)
    return ResourceHost._from_ptr(ptr)

Attempts to downcast this ResourceAny to a ResourceHost.

This will raise a WasmtimeError if this ResourceAny is not actually a host-defined resource.

class ResourceHost
Expand source code
class ResourceHost(Managed["ctypes._Pointer[ffi.wasmtime_component_resource_host_t]"]):
    def __init__(self) -> None:
        raise WasmtimeError("Cannot directly construct a `ResourceHost`")

    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_resource_host_t]") -> None:
        ffi.wasmtime_component_resource_host_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_resource_host_t]") -> "ResourceHost":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_resource_host_t)):
            raise TypeError("wrong pointer type")
        ty: "ResourceHost" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    @classmethod
    def own(cls, rep: int, ty: int) -> "ResourceHost":
        ptr = ffi.wasmtime_component_resource_host_new(True, rep, ty)
        return cls._from_ptr(ptr)

    @classmethod
    def borrow(cls, rep: int, ty: int) -> "ResourceHost":
        ptr = ffi.wasmtime_component_resource_host_new(False, rep, ty)
        return cls._from_ptr(ptr)

    @property
    def rep(self) -> int:
        """
        Returns the integer representation associated with this host resource.
        """
        return ffi.wasmtime_component_resource_host_rep(self.ptr())

    @property
    def type(self) -> int:
        """
        Returns the integer type identifier associated with this host resource.
        """
        return ffi.wasmtime_component_resource_host_type(self.ptr())

    @property
    def owned(self) -> bool:
        """
        Returns whether this `ResourceHost` is an `own` resource or a `borrow`
        resource.
        """
        return ffi.wasmtime_component_resource_host_owned(self.ptr())

    def to_any(self, store: Storelike) -> ResourceAny:
        """
        Upcasts this `ResourceHost` to a `ResourceAny`.
        """
        ptr = POINTER(ffi.wasmtime_component_resource_any_t)()
        error = ffi.wasmtime_component_resource_host_to_any(store._context(), self.ptr(), byref(ptr))
        if error:
            raise WasmtimeError._from_ptr(error)
        return ResourceAny._from_ptr(ptr)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Static methods

def borrow(rep: int, ty: int) ‑> wasmtime.component._resources.ResourceHost
def own(rep: int, ty: int) ‑> wasmtime.component._resources.ResourceHost

Instance variables

prop owned : bool
Expand source code
@property
def owned(self) -> bool:
    """
    Returns whether this `ResourceHost` is an `own` resource or a `borrow`
    resource.
    """
    return ffi.wasmtime_component_resource_host_owned(self.ptr())

Returns whether this ResourceHost is an own resource or a borrow resource.

prop rep : int
Expand source code
@property
def rep(self) -> int:
    """
    Returns the integer representation associated with this host resource.
    """
    return ffi.wasmtime_component_resource_host_rep(self.ptr())

Returns the integer representation associated with this host resource.

prop type : int
Expand source code
@property
def type(self) -> int:
    """
    Returns the integer type identifier associated with this host resource.
    """
    return ffi.wasmtime_component_resource_host_type(self.ptr())

Returns the integer type identifier associated with this host resource.

Methods

def to_any(self, store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext) ‑> wasmtime.component._resources.ResourceAny
Expand source code
def to_any(self, store: Storelike) -> ResourceAny:
    """
    Upcasts this `ResourceHost` to a `ResourceAny`.
    """
    ptr = POINTER(ffi.wasmtime_component_resource_any_t)()
    error = ffi.wasmtime_component_resource_host_to_any(store._context(), self.ptr(), byref(ptr))
    if error:
        raise WasmtimeError._from_ptr(error)
    return ResourceAny._from_ptr(ptr)

Upcasts this ResourceHost to a ResourceAny.

class ResourceType
Expand source code
class ResourceType(Managed["ctypes._Pointer[ffi.wasmtime_component_resource_type_t]"]):
    def __init__(self) -> None:
        raise WasmtimeError("Cannot directly construct a `ResourceType`")

    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_resource_type_t]") -> None:
        ffi.wasmtime_component_resource_type_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_resource_type_t]") -> "ResourceType":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_resource_type_t)):
            raise TypeError("wrong pointer type")
        ty: "ResourceType" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    @classmethod
    def host(cls, val: int) -> "ResourceType":
        """
        Creates a new `ResourceType` representing a host-defined resource
        identified by the integer identifier `val` given.
        """
        ptr = ffi.wasmtime_component_resource_type_new_host(val)
        return cls._from_ptr(ptr)

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, ResourceType):
            return False
        return ffi.wasmtime_component_resource_type_equal(self.ptr(), other.ptr())

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic

Static methods

def host(val: int) ‑> wasmtime.component._resource_type.ResourceType

Creates a new ResourceType representing a host-defined resource identified by the integer identifier val given.

class ResultType
Expand source code
class ResultType(Managed["ctypes._Pointer[ffi.wasmtime_component_result_type_t]"], ValType, VariantLikeType):
    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_result_type_t]") -> None:
        ffi.wasmtime_component_result_type_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_result_type_t]") -> "ResultType":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_result_type_t)):
            raise TypeError("wrong pointer type")
        ty: "ResultType" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    @property
    def ok(self) -> Optional['ValType']:
        """
        Returns the ok type of this result type, if any.
        """
        valtype_ptr = ffi.wasmtime_component_valtype_t()
        has_ok = ffi.wasmtime_component_result_type_ok(self.ptr(), byref(valtype_ptr))
        if not has_ok:
            return None
        return valtype_from_ptr(valtype_ptr)

    @property
    def err(self) -> Optional['ValType']:
        """
        Returns the err type of this result type, if any.
        """
        valtype_ptr = ffi.wasmtime_component_valtype_t()
        has_err = ffi.wasmtime_component_result_type_err(self.ptr(), byref(valtype_ptr))
        if not has_err:
            return None
        return valtype_from_ptr(valtype_ptr)

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, ResultType):
            return False
        return ffi.wasmtime_component_result_type_equal(self.ptr(), other.ptr())

    def _cases(self) -> List[Tuple[str, Optional['ValType']]]:
        return [('ok', self.ok), ('err', self.err)]

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        name, raw = self._lower(store, val)
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_RESULT
        ptr.contents.of.result.is_ok = name == 'ok'
        ptr.contents.of.result.val = raw

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_RESULT.value)
        if c.of.result.is_ok:
            tag = 'ok'
        else:
            tag = 'err'
        return self._lift(tag, c.of.result.val)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic
  • wasmtime.component._types.ValType
  • wasmtime.component._types.VariantLikeType

Instance variables

prop errValType | None
Expand source code
@property
def err(self) -> Optional['ValType']:
    """
    Returns the err type of this result type, if any.
    """
    valtype_ptr = ffi.wasmtime_component_valtype_t()
    has_err = ffi.wasmtime_component_result_type_err(self.ptr(), byref(valtype_ptr))
    if not has_err:
        return None
    return valtype_from_ptr(valtype_ptr)

Returns the err type of this result type, if any.

prop okValType | None
Expand source code
@property
def ok(self) -> Optional['ValType']:
    """
    Returns the ok type of this result type, if any.
    """
    valtype_ptr = ffi.wasmtime_component_valtype_t()
    has_ok = ffi.wasmtime_component_result_type_ok(self.ptr(), byref(valtype_ptr))
    if not has_ok:
        return None
    return valtype_from_ptr(valtype_ptr)

Returns the ok type of this result type, if any.

Methods

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_RESULT.value)
    if c.of.result.is_ok:
        tag = 'ok'
    else:
        tag = 'err'
    return self._lift(tag, c.of.result.val)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    name, raw = self._lower(store, val)
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_RESULT
    ptr.contents.of.result.is_ok = name == 'ok'
    ptr.contents.of.result.val = raw

Converts val to this type and stores it in ptr

class S16
Expand source code
@dataclass
class S16(ValType):
    def add_classes(self, s: Set[type]) -> None:
        s.add(int)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if not isinstance(val, int):
            raise TypeError("expected int for S16 type")
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_S16
        ptr.contents.of.s16 = val

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_S16.value)
        return int(c.of.s16)

S16()

Ancestors

  • wasmtime.component._types.ValType

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(int)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_S16.value)
    return int(c.of.s16)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if not isinstance(val, int):
        raise TypeError("expected int for S16 type")
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_S16
    ptr.contents.of.s16 = val

Converts val to this type and stores it in ptr

class S32
Expand source code
@dataclass
class S32(ValType):
    def add_classes(self, s: Set[type]) -> None:
        s.add(int)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if not isinstance(val, int):
            raise TypeError("expected int for S32 type")
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_S32
        ptr.contents.of.s32 = val

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_S32.value)
        return int(c.of.s32)

S32()

Ancestors

  • wasmtime.component._types.ValType

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(int)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_S32.value)
    return int(c.of.s32)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if not isinstance(val, int):
        raise TypeError("expected int for S32 type")
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_S32
    ptr.contents.of.s32 = val

Converts val to this type and stores it in ptr

class S64
Expand source code
@dataclass
class S64(ValType):
    def add_classes(self, s: Set[type]) -> None:
        s.add(int)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if not isinstance(val, int):
            raise TypeError("expected int for S64 type")
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_S64
        ptr.contents.of.s64 = val

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_S64.value)
        return int(c.of.s64)

S64()

Ancestors

  • wasmtime.component._types.ValType

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(int)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_S64.value)
    return int(c.of.s64)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if not isinstance(val, int):
        raise TypeError("expected int for S64 type")
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_S64
    ptr.contents.of.s64 = val

Converts val to this type and stores it in ptr

class S8
Expand source code
@dataclass
class S8(ValType):
    def add_classes(self, s: Set[type]) -> None:
        s.add(int)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if not isinstance(val, int):
            raise TypeError("expected int for S8 type")
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_S8
        ptr.contents.of.s8 = val

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_S8.value)
        return int(c.of.s8)

S8()

Ancestors

  • wasmtime.component._types.ValType

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(int)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_S8.value)
    return int(c.of.s8)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if not isinstance(val, int):
        raise TypeError("expected int for S8 type")
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_S8
    ptr.contents.of.s8 = val

Converts val to this type and stores it in ptr

class StreamType
Expand source code
class StreamType(Managed["ctypes._Pointer[ffi.wasmtime_component_stream_type_t]"], ValType):
    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_stream_type_t]") -> None:
        ffi.wasmtime_component_stream_type_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_stream_type_t]") -> "StreamType":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_stream_type_t)):
            raise TypeError("wrong pointer type")
        ty: "StreamType" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    @property
    def payload(self) -> 'ValType':
        """
        Returns the payload type of this stream type.
        """
        valtype_ptr = ffi.wasmtime_component_valtype_t()
        ffi.wasmtime_component_stream_type_ty(self.ptr(), byref(valtype_ptr))
        return valtype_from_ptr(valtype_ptr)

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, StreamType):
            return False
        return ffi.wasmtime_component_stream_type_equal(self.ptr(), other.ptr())

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        raise NotImplementedError("Stream conversion not implemented yet")

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        raise NotImplementedError("conversion not implemented yet")

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic
  • wasmtime.component._types.ValType

Instance variables

prop payloadValType
Expand source code
@property
def payload(self) -> 'ValType':
    """
    Returns the payload type of this stream type.
    """
    valtype_ptr = ffi.wasmtime_component_valtype_t()
    ffi.wasmtime_component_stream_type_ty(self.ptr(), byref(valtype_ptr))
    return valtype_from_ptr(valtype_ptr)

Returns the payload type of this stream type.

Methods

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    raise NotImplementedError("conversion not implemented yet")

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    raise NotImplementedError("Stream conversion not implemented yet")

Converts val to this type and stores it in ptr

class String
Expand source code
@dataclass
class String(ValType):
    def add_classes(self, s: Set[type]) -> None:
        s.add(str)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if not isinstance(val, str):
            raise TypeError("expected string type")
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_STRING
        ptr.contents.of.string = ffi.str_to_capi(val)

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_STRING.value)
        ret = ffi.to_str(c.of.string)
        ffi.wasm_byte_vec_delete(byref(c.of.string))
        return ret

String()

Ancestors

  • wasmtime.component._types.ValType

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(str)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_STRING.value)
    ret = ffi.to_str(c.of.string)
    ffi.wasm_byte_vec_delete(byref(c.of.string))
    return ret

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if not isinstance(val, str):
        raise TypeError("expected string type")
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_STRING
    ptr.contents.of.string = ffi.str_to_capi(val)

Converts val to this type and stores it in ptr

class TupleType
Expand source code
class TupleType(Managed["ctypes._Pointer[ffi.wasmtime_component_tuple_type_t]"], ValType):
    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_tuple_type_t]") -> None:
        ffi.wasmtime_component_tuple_type_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_tuple_type_t]") -> "TupleType":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_tuple_type_t)):
            raise TypeError("wrong pointer type")
        ty: "TupleType" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    @property
    def elements(self) -> List['ValType']:
        """
        Returns the element types of this tuple type.
        """
        n = ffi.wasmtime_component_tuple_type_types_count(self.ptr())
        items = []
        for i in range(n):
            valtype_ptr = ffi.wasmtime_component_valtype_t()
            found = ffi.wasmtime_component_tuple_type_types_nth(self.ptr(),
                                                                i,
                                                                byref(valtype_ptr))
            assert(found)
            valtype = valtype_from_ptr(valtype_ptr)
            items.append(valtype)
        return items

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, TupleType):
            return False
        return ffi.wasmtime_component_tuple_type_equal(self.ptr(), other.ptr())

    def add_classes(self, s: Set[type]) -> None:
        s.add(tuple)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        elements = self.elements
        if not isinstance(val, tuple):
            raise TypeError("expected tuple type")
        if len(val) != len(elements):
            raise TypeError("tuple length mismatch")
        raw = ffi.wasmtime_component_valtuple_t()
        ffi.wasmtime_component_valtuple_new_uninit(raw, len(elements))
        i = 0
        cleanup = True
        try:
            for ty, element in zip(elements, val):
                ty.convert_to_c(store, element, ctypes.pointer(raw.data[i]))
                i += 1
            ptr.contents.kind = ffi.WASMTIME_COMPONENT_TUPLE
            ptr.contents.of.tuple = raw
            cleanup = False
        finally:
            if cleanup:
                for j in range(i, len(elements)):
                    raw.data[j].kind = ffi.WASMTIME_COMPONENT_BOOL
                    raw.data[j].of.boolean = False
                ffi.wasmtime_component_valtuple_delete(byref(raw))


    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_TUPLE.value)
        try:
            ret: List[Any] = []
            for i, ty in zip(range(c.of.record.size), self.elements):
                raw_field = c.of.tuple.data[i]
                ret.append(ty.convert_from_c(raw_field))
                raw_field.kind = ffi.WASMTIME_COMPONENT_BOOL
                raw_field.of.boolean = False
            return tuple(ret)
        finally:
            ffi.wasmtime_component_valtuple_delete(byref(c.of.tuple))

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic
  • wasmtime.component._types.ValType

Instance variables

prop elements : List[ValType]
Expand source code
@property
def elements(self) -> List['ValType']:
    """
    Returns the element types of this tuple type.
    """
    n = ffi.wasmtime_component_tuple_type_types_count(self.ptr())
    items = []
    for i in range(n):
        valtype_ptr = ffi.wasmtime_component_valtype_t()
        found = ffi.wasmtime_component_tuple_type_types_nth(self.ptr(),
                                                            i,
                                                            byref(valtype_ptr))
        assert(found)
        valtype = valtype_from_ptr(valtype_ptr)
        items.append(valtype)
    return items

Returns the element types of this tuple type.

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(tuple)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_TUPLE.value)
    try:
        ret: List[Any] = []
        for i, ty in zip(range(c.of.record.size), self.elements):
            raw_field = c.of.tuple.data[i]
            ret.append(ty.convert_from_c(raw_field))
            raw_field.kind = ffi.WASMTIME_COMPONENT_BOOL
            raw_field.of.boolean = False
        return tuple(ret)
    finally:
        ffi.wasmtime_component_valtuple_delete(byref(c.of.tuple))

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    elements = self.elements
    if not isinstance(val, tuple):
        raise TypeError("expected tuple type")
    if len(val) != len(elements):
        raise TypeError("tuple length mismatch")
    raw = ffi.wasmtime_component_valtuple_t()
    ffi.wasmtime_component_valtuple_new_uninit(raw, len(elements))
    i = 0
    cleanup = True
    try:
        for ty, element in zip(elements, val):
            ty.convert_to_c(store, element, ctypes.pointer(raw.data[i]))
            i += 1
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_TUPLE
        ptr.contents.of.tuple = raw
        cleanup = False
    finally:
        if cleanup:
            for j in range(i, len(elements)):
                raw.data[j].kind = ffi.WASMTIME_COMPONENT_BOOL
                raw.data[j].of.boolean = False
            ffi.wasmtime_component_valtuple_delete(byref(raw))

Converts val to this type and stores it in ptr

class U16
Expand source code
@dataclass
class U16(ValType):
    def add_classes(self, s: Set[type]) -> None:
        s.add(int)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if not isinstance(val, int):
            raise TypeError("expected int for U16 type")
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_U16
        ptr.contents.of.u16 = val

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_U16.value)
        return int(c.of.u16)

U16()

Ancestors

  • wasmtime.component._types.ValType

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(int)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_U16.value)
    return int(c.of.u16)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if not isinstance(val, int):
        raise TypeError("expected int for U16 type")
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_U16
    ptr.contents.of.u16 = val

Converts val to this type and stores it in ptr

class U32
Expand source code
@dataclass
class U32(ValType):
    def add_classes(self, s: Set[type]) -> None:
        s.add(int)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if not isinstance(val, int):
            raise TypeError("expected int for U32 type")
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_U32
        ptr.contents.of.u32 = val

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_U32.value)
        return int(c.of.u32)

U32()

Ancestors

  • wasmtime.component._types.ValType

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(int)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_U32.value)
    return int(c.of.u32)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if not isinstance(val, int):
        raise TypeError("expected int for U32 type")
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_U32
    ptr.contents.of.u32 = val

Converts val to this type and stores it in ptr

class U64
Expand source code
@dataclass
class U64(ValType):
    def add_classes(self, s: Set[type]) -> None:
        s.add(int)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if not isinstance(val, int):
            raise TypeError("expected int for U64 type")
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_U64
        ptr.contents.of.u64 = val

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_U64.value)
        return int(c.of.u64)

U64()

Ancestors

  • wasmtime.component._types.ValType

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(int)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_U64.value)
    return int(c.of.u64)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if not isinstance(val, int):
        raise TypeError("expected int for U64 type")
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_U64
    ptr.contents.of.u64 = val

Converts val to this type and stores it in ptr

class U8
Expand source code
@dataclass
class U8(ValType):
    def add_classes(self, s: Set[type]) -> None:
        s.add(int)

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        if not isinstance(val, int):
            raise TypeError("expected int for U8 type")
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_U8
        ptr.contents.of.u8 = val

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_U8.value)
        return int(c.of.u8)

U8()

Ancestors

  • wasmtime.component._types.ValType

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
def add_classes(self, s: Set[type]) -> None:
    s.add(int)

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_U8.value)
    return int(c.of.u8)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    if not isinstance(val, int):
        raise TypeError("expected int for U8 type")
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_U8
    ptr.contents.of.u8 = val

Converts val to this type and stores it in ptr

class ValType
Expand source code
class ValType:
    @abstractmethod
    def add_classes(self, s: Set[type]) -> None:
        """
        Returns the python class that is created by `convert_from_c` and
        accepted by `convert_to_c`
        """
        pass

    @abstractmethod
    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        """
        Converts `val` to this type and stores it in `ptr`
        """
        pass

    @abstractmethod
    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        """
        Converts `val` to Python
        """
        pass

Subclasses

  • wasmtime.component._types.Bool
  • wasmtime.component._types.BorrowType
  • wasmtime.component._types.Char
  • wasmtime.component._types.EnumType
  • wasmtime.component._types.ErrorContext
  • wasmtime.component._types.F32
  • wasmtime.component._types.F64
  • wasmtime.component._types.FlagsType
  • wasmtime.component._types.FutureType
  • wasmtime.component._types.ListType
  • wasmtime.component._types.OptionType
  • wasmtime.component._types.OwnType
  • wasmtime.component._types.RecordType
  • wasmtime.component._types.ResultType
  • wasmtime.component._types.S16
  • wasmtime.component._types.S32
  • wasmtime.component._types.S64
  • wasmtime.component._types.S8
  • wasmtime.component._types.StreamType
  • wasmtime.component._types.String
  • wasmtime.component._types.TupleType
  • wasmtime.component._types.U16
  • wasmtime.component._types.U32
  • wasmtime.component._types.U64
  • wasmtime.component._types.U8
  • wasmtime.component._types.VariantType

Methods

def add_classes(self, s: Set[type]) ‑> None
Expand source code
@abstractmethod
def add_classes(self, s: Set[type]) -> None:
    """
    Returns the python class that is created by `convert_from_c` and
    accepted by `convert_to_c`
    """
    pass

Returns the python class that is created by convert_from_c and accepted by convert_to_c

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
@abstractmethod
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    """
    Converts `val` to Python
    """
    pass

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
@abstractmethod
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    """
    Converts `val` to this type and stores it in `ptr`
    """
    pass

Converts val to this type and stores it in ptr

class Variant (tag: str, payload: Any | None = None)
Expand source code
@dataclass
class Variant:
    tag: str
    payload: Optional[Any] = None

Variant(tag: str, payload: Any | None = None)

Instance variables

var payload : Any | None

The type of the None singleton.

var tag : str

The type of the None singleton.

class VariantType
Expand source code
class VariantType(Managed["ctypes._Pointer[ffi.wasmtime_component_variant_type_t]"], ValType, VariantLikeType):
    def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_component_variant_type_t]") -> None:
        ffi.wasmtime_component_variant_type_delete(ptr)

    @classmethod
    def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_component_variant_type_t]") -> "VariantType":
        if not isinstance(ptr, POINTER(ffi.wasmtime_component_variant_type_t)):
            raise TypeError("wrong pointer type")
        ty: "VariantType" = cls.__new__(cls)
        ty._set_ptr(ptr)
        return ty

    @property
    def cases(self) -> List[Tuple[str, Optional['ValType']]]:
        """
        Returns the cases of this variant type.
        """
        n = ffi.wasmtime_component_variant_type_case_count(self.ptr())
        items = []
        for i in range(n):
            name_ptr = ctypes.POINTER(ctypes.c_char)()
            name_len = ctypes.c_size_t()
            has_payload = ctypes.c_bool()
            valtype_ptr = ffi.wasmtime_component_valtype_t()
            found = ffi.wasmtime_component_variant_type_case_nth(self.ptr(),
                                                                 i,
                                                                 byref(name_ptr),
                                                                 byref(name_len),
                                                                 byref(has_payload),
                                                                 byref(valtype_ptr))
            assert(found)
            name = ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
            if has_payload.value:
                valtype = valtype_from_ptr(valtype_ptr)
            else:
                valtype = None
            items.append((name, valtype))
        return items

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, VariantType):
            return False
        return ffi.wasmtime_component_variant_type_equal(self.ptr(), other.ptr())

    def _cases(self) -> List[Tuple[str, Optional['ValType']]]:
        return self.cases

    def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
        name, raw = self._lower(store, val)
        ptr.contents.kind = ffi.WASMTIME_COMPONENT_VARIANT
        ptr.contents.of.variant.discriminant = ffi.str_to_capi(name)
        ptr.contents.of.variant.val = raw

    def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
        assert(c.kind == ffi.WASMTIME_COMPONENT_VARIANT.value)
        tag = ffi.to_str(c.of.variant.discriminant)
        ffi.wasm_byte_vec_delete(byref(c.of.variant.discriminant))
        return self._lift(tag, c.of.variant.val)

Abstract base class for types which contain an owned pointer in the C FFI layer.

Not exported directly from this package.

Ancestors

  • wasmtime._managed.Managed
  • typing.Generic
  • wasmtime.component._types.ValType
  • wasmtime.component._types.VariantLikeType

Instance variables

prop cases : List[Tuple[str, ValType | None]]
Expand source code
@property
def cases(self) -> List[Tuple[str, Optional['ValType']]]:
    """
    Returns the cases of this variant type.
    """
    n = ffi.wasmtime_component_variant_type_case_count(self.ptr())
    items = []
    for i in range(n):
        name_ptr = ctypes.POINTER(ctypes.c_char)()
        name_len = ctypes.c_size_t()
        has_payload = ctypes.c_bool()
        valtype_ptr = ffi.wasmtime_component_valtype_t()
        found = ffi.wasmtime_component_variant_type_case_nth(self.ptr(),
                                                             i,
                                                             byref(name_ptr),
                                                             byref(name_len),
                                                             byref(has_payload),
                                                             byref(valtype_ptr))
        assert(found)
        name = ctypes.string_at(name_ptr, name_len.value).decode('utf-8')
        if has_payload.value:
            valtype = valtype_from_ptr(valtype_ptr)
        else:
            valtype = None
        items.append((name, valtype))
    return items

Returns the cases of this variant type.

Methods

def convert_from_c(self, c: ffi.wasmtime_component_val_t) ‑> Any
Expand source code
def convert_from_c(self, c: 'ffi.wasmtime_component_val_t') -> Any:
    assert(c.kind == ffi.WASMTIME_COMPONENT_VARIANT.value)
    tag = ffi.to_str(c.of.variant.discriminant)
    ffi.wasm_byte_vec_delete(byref(c.of.variant.discriminant))
    return self._lift(tag, c.of.variant.val)

Converts val to Python

def convert_to_c(self,
store: wasmtime._store.Store | Caller | wasmtime._store.StoreContext,
val: Any,
ptr: ctypes._Pointer[ffi.wasmtime_component_val_t])
Expand source code
def convert_to_c(self, store: Storelike, val: Any, ptr: 'ctypes._Pointer[ffi.wasmtime_component_val_t]') -> None:
    name, raw = self._lower(store, val)
    ptr.contents.kind = ffi.WASMTIME_COMPONENT_VARIANT
    ptr.contents.of.variant.discriminant = ffi.str_to_capi(name)
    ptr.contents.of.variant.val = raw

Converts val to this type and stores it in ptr