Skip to main content

Function

Struct Function 

Source
pub struct Function { /* private fields */ }
Expand description

A type-erased callable that works across languages.

A Function takes AnyView arguments and returns an Any. Make one from a Rust closure with from_typed, look one up by name with get_global, and call it with call_tuple or call_packed. into_typed_fn! turns it back into a typed closure.

§Examples

use tvm_ffi::{Function, Result};

let add = Function::from_typed(|x: i64, y: i64| -> Result<i64> { Ok(x + y) });
let sum = i64::try_from(add.call_tuple((1_i64, 2_i64))?)?;
assert_eq!(sum, 3);

A Function may be called from any thread, so a Rust callback must be Send + Sync; a callback holding an Rc is rejected. A function written in another language is as thread-safe as its implementation.

ⓘ
use std::rc::Rc;
let count = Rc::new(0_i64);
tvm_ffi::Function::from_typed(move || -> tvm_ffi::Result<i64> { Ok(*count) });

Implementations§

Source§

impl Function

Source

pub fn call_packed(&self, packed_args: &[AnyView<'_>]) -> Result<Any>

Call the function with the arguments packed_args.

§Arguments
  • packed_args - The arguments, one AnyView each.
§Returns

The function’s result.

§Errors

Returns the error that the function raises.

use tvm_ffi::{AnyView, Function, Result};
let add = Function::from_typed(|x: i64, y: i64| -> Result<i64> { Ok(x + y) });
let result = add.call_packed(&[AnyView::from(&1_i64), AnyView::from(&2_i64)])?;
assert_eq!(i64::try_from(result)?, 3);

See also Function.

Source

pub fn call_tuple(&self, tuple_args: impl PackedCallArgs) -> Result<Any>

Call the function with the arguments in the tuple tuple_args.

An element may be a value or a reference to one; a reference passes an object without retaining it, and a &str or &[u8] passes as a String or Bytes.

§Arguments
  • tuple_args - The arguments, as a tuple such as (1_i64, &array).
§Returns

The function’s result.

§Errors

Returns the error that the function raises.

See also Function.

Source

pub fn get_global(name: &str) -> Result<Function>

Look up the global function registered as name.

§Arguments
  • name - The name of the function, such as "my_ext.double".
§Returns

The global function.

§Errors

Returns a ValueError if no function is registered as name, as C++ Function::GetGlobalRequired. Probe with .ok() where a missing function is expected.

use tvm_ffi::Function;
let double = Function::from_typed(|x: i64| -> tvm_ffi::Result<i64> { Ok(x * 2) });
Function::register_global("my_ext.double", double)?;
let double = Function::get_global("my_ext.double")?;
assert_eq!(i64::try_from(double.call_tuple((21_i64,))?)?, 42);

See also register_global_typed.

Source

pub fn register_global(name: &str, func: Function) -> Result<()>

Register a function as a global function, which every language can then look up by name.

The function’s metadata records only that it is a function, with no parameter types. Use Function::register_global_typed to record the parameter and return types of a typed function, and a doc string.

§Arguments
  • name - The name of the function.
  • func - The function to register.
§Returns

Ok(()) once the function is registered.

§Errors

Returns an error if the registration fails.

See also get_global.

Source

pub fn register_global_typed<F, I, O>( name: &str, func: F, doc: &str, ) -> Result<()>
where F: AsPackedCallable<I, O> + Send + Sync + 'static,

Register a typed function as a global function, with a doc string.

The function’s metadata records its type schema, the parameter and return types, which tvm_ffi.get_global_func_metadata and the stub generator read. An empty doc records no doc string.

§Arguments
  • name - The name of the function.
  • func - The typed function to register, as for Function::from_typed.
  • doc - The doc string of the function.
§Returns

Ok(()) once the function is registered.

§Errors

Returns an error if the registration fails.

use tvm_ffi::{Function, Result};
let add = |x: i64, y: i64| -> Result<i64> { Ok(x + y) };
Function::register_global_typed("my_ext.add", add, "Add two integers.")?;

See also get_global.

Source

pub fn from_packed<F>(func: F) -> Self
where F: Fn(&[AnyView<'_>]) -> Result<Any> + Send + Sync + 'static,

Construct a function from a packed function, which takes its arguments as a slice.

Use it for a variable number of arguments; otherwise from_typed converts the arguments for you. Report errors by returning them. A panic in func is caught and raised to the caller as an InternalError, but panicking is discouraged.

§Arguments
  • func - The packed function, of signature Fn(&[AnyView]) -> Result<Any>.
§Returns

The function.

use tvm_ffi::{Any, AnyView, Function, Result};
let count = Function::from_packed(|args: &[AnyView]| -> Result<Any> {
    Ok(Any::from(args.len() as i64))
});
assert_eq!(i64::try_from(count.call_tuple((1_i64, true))?)?, 2);

See also Function.

Source

pub fn from_typed<F, I, O>(func: F) -> Self
where F: AsPackedCallable<I, O> + Send + Sync + 'static,

Construct a function from a typed function.

Each argument is converted to its parameter type, and a mismatch raises a TypeError to the caller. Report errors by returning them. A panic in func is caught and raised to the caller as an InternalError, but panicking is discouraged.

§Arguments
  • func - The typed function, an AsPackedCallable such as Fn(T0, T1, ...) -> Result<O>; each parameter is an AnyCompatible type, a TensorView or an RValueRef<T>.
§Returns

The function.

use tvm_ffi::{Function, Result};
let scale = Function::from_typed(|x: f64, factor: f64| -> Result<f64> { Ok(x * factor) });
assert_eq!(f64::try_from(scale.call_tuple((2.0_f64, 1.5_f64))?)?, 3.0);

See also Function.

Source

pub unsafe fn from_extern_c( handle: *mut c_void, safe_call: TVMFFISafeCallType, deleter: Option<unsafe extern "C" fn(*mut c_void)>, ) -> Result<Self>

Wrap a C callback as a Function.

§Safety

handle (may be null) is the state safe_call receives; deleter frees it when the Function drops. All three must be safe to use from any thread.

§Errors

Returns an error if the runtime cannot allocate the function. The function then does not take handle: deleter is not called, and the caller still owns handle.

Trait Implementations§

Source§

impl AsRef<Function> for Function

Source§

fn as_ref(&self) -> &Self

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<ObjectRef> for Function

Source§

fn as_ref(&self) -> &ObjectRef

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for Function

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Function

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Function

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl DowncastRefFromAny for Function

Source§

unsafe fn downcast_ref_from_any(cell: &TVMFFIAny) -> Option<&Self>

Borrow cell as Self when it holds one. Read more
Source§

impl From<&Function> for Function

Source§

fn from(value: &Function) -> Self

Converts to this type from the input type.
Source§

impl From<&Function> for ObjectRef

Source§

fn from(value: &Function) -> Self

Converts to this type from the input type.
Source§

impl From<Function> for ObjectRef

Source§

fn from(value: Function) -> Self

Converts to this type from the input type.
Source§

impl IntoArg<Function> for Function

Source§

type Output = Function

T when owned, &T when borrowed.
Source§

fn into_arg(self) -> Function

Convert into a T or a &T.
Source§

fn into_owned(self) -> Function

Convert into an owned T, cloning only a borrowed value.
Source§

impl<'a> IntoArg<Function> for &'a Function

Source§

type Output = &'a Function

T when owned, &T when borrowed.
Source§

fn into_arg(self) -> &'a Function

Convert into a T or a &T.
Source§

fn into_owned(self) -> Function

Convert into an owned T, cloning only a borrowed value.
Source§

impl IntoArg<ObjectRef> for Function

Source§

type Output = ObjectRef

T when owned, &T when borrowed.
Source§

fn into_arg(self) -> ObjectRef

Convert into a T or a &T.
Source§

fn into_owned(self) -> ObjectRef

Convert into an owned T, cloning only a borrowed value.
Source§

impl<'a> IntoArg<ObjectRef> for &'a Function

Source§

type Output = &'a ObjectRef

T when owned, &T when borrowed.
Source§

fn into_arg(self) -> &'a ObjectRef

Convert into a T or a &T.
Source§

fn into_owned(self) -> ObjectRef

Convert into an owned T, cloning only a borrowed value.
Source§

impl ObjectRefAnyCompatible for Function

Source§

fn extra_check(obj: &Self::ContainerType) -> bool

Whether obj, an instance of ContainerType, is a value of Self. Every strict and converting cast checks it, after the object type.
Source§

fn convert_fallback(value: AnyView<'_>) -> Option<Self>

Convert a value that is not a Self object, such as an integer that stands for a constant; None rejects it. Only converting casts (TryFrom<Any>, typed function arguments) call it; downcast_ref, downcast and match_any! never do.
Source§

fn custom_type_str() -> String

The type name in conversion errors and type schemas; by default the object’s type key. See AnyCompatible::type_str.
Source§

fn custom_mismatch_type_info(value: AnyView<'_>) -> String

The name of the mismatched value in conversion errors; by default its runtime type key. See AnyCompatible::get_mismatch_type_info.
Source§

impl ObjectRefCore for Function

Source§

type ContainerType = FunctionObj

The object type the reference points to.
Source§

fn data(this: &Self) -> &ObjectArc<Self::ContainerType>

Borrow the object’s handle.
Source§

fn into_data(this: Self) -> ObjectArc<Self::ContainerType>

Take the object’s handle.
Source§

unsafe fn from_data(data: ObjectArc<Self::ContainerType>) -> Self

Make a reference from the object’s handle. Read more
Source§

fn same_as<Other: ObjectRefCore>(&self, other: &Other) -> bool

Whether two references point to the same object.
Source§

fn type_key(&self) -> &'static str

The registered type key of the object’s runtime type, such as "ffi.Array", as C++ ObjectRef::GetTypeKey.
Source§

fn is<T: AnyCompatible>(&self) -> bool

Whether the reference is a T as is, such as a subtype or a container whose elements are checked too, by the strict check of downcast, without a reference count change. See also crate::Any::is.
Source§

fn downcast_ref<T: DowncastRefFromObject>(&self) -> Option<&T>

Borrow the underlying object as T when it is one. Read more
Source§

fn downcast<B>(self) -> Result<B, Self>
where B: ObjectRefCore,

Take self as B, a subtype or a container such as Array<i64> whose elements are checked too, when its object is one, without copying it. On a mismatch the reference is returned unchanged. Read more
Source§

impl PackedCallArg for Function

Source§

type Holder = Function

What keeps the argument alive during the call.
Source§

fn into_packed_arg(self) -> Function

Source§

fn as_packed_arg(holder: &Self::Holder) -> AnyView<'_>

Source§

impl<'a> PackedCallArg for &'a Function

Source§

type Holder = &'a Function

What keeps the argument alive during the call.
Source§

fn into_packed_arg(self) -> &'a Function

Source§

fn as_packed_arg(holder: &Self::Holder) -> AnyView<'_>

Source§

impl Send for Function

Source§

impl Sync for Function

Source§

impl<'a> TryFrom<&'a Any> for Function

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(value: &'a Any) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<&ObjectRef> for Function

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(value: &ObjectRef) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<Any> for Function

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(value: Any) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<'a> TryFrom<AnyView<'a>> for Function

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(value: AnyView<'a>) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<ObjectRef> for Function

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(value: ObjectRef) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TypeSubsumes<Function> for ObjectRef

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> AnyCompatible for T

Source§

const MATCH_ANY_EXACT: bool = const MATCH_ANY_EXACT: bool = <T as ObjectRefAnyCompatible>::MATCH_ANY_EXACT && <T::ContainerType as ObjectCore>::TYPE_FINAL;

Source§

fn match_any_exact_type_index() -> i32

Source§

unsafe fn is_undefined(field: *const T) -> bool

Whether field, which holds a value of this type or all-zero bytes, holds all-zero bytes that are no value of this type, as a null object reference, a string of type index None or a zero device type: a field that a creator left undefined for reflection to set. An undefined field is no value; a nullable reference is Option<T>, whose None is a defined value. Read more
Source§

unsafe fn copy_to_any_view(src: &T, data: &mut TVMFFIAny)

Write a cell that borrows src into data. Read more
Source§

unsafe fn move_to_any(src: T, data: &mut TVMFFIAny)

Write a cell that owns src into data. Read more
Source§

unsafe fn check_any_strict(data: &TVMFFIAny) -> bool

Whether data holds a Self as is, without conversion. Read more
Source§

unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> T

Copy a Self out of a cell that holds one, retaining any object. Read more
Source§

unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> T

Move a Self out of an owning cell that holds one. Read more
Source§

unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<T, ()>

Convert data into a Self by the FFI rules, such as an integer into a float; Err if it does not convert. Read more
Source§

fn get_mismatch_type_info(data: &TVMFFIAny) -> String

The name of the mismatched value data in conversion errors; by default its runtime type key.
Source§

fn type_str() -> String

The type name in conversion errors and type schemas, such as int, ffi.String or Array<int>.
Source§

fn type_schema() -> String

The type schema of the type: the JSON object that describes it, which the type schemas of functions and fields embed. Read more
Source§

fn to_any(&self) -> Any

Borrow self into an owned Any, increfing object-backed values. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> ContainerElement for T
where T: AnyCompatible,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> TypeSubsumes<T> for T
where T: ?Sized,