Simplify call_fn API, no need to pass &mut references.

This commit is contained in:
Stephen Chung
2020-03-10 14:09:05 +08:00
parent 711cd9bb1c
commit f3bcb2a10d
4 changed files with 61 additions and 38 deletions

View File

@@ -1,35 +1,29 @@
//! Helper module which defines `FnArgs` to make function calling easier.
use crate::any::{Any, Variant};
use crate::any::{Any, Dynamic};
/// Trait that represent arguments to a function call.
pub trait FuncArgs<'a> {
/// Convert to a `Vec` of `Variant` arguments.
fn into_vec(self) -> Vec<&'a mut Variant>;
pub trait FuncArgs {
/// Convert to a `Vec` of `Dynamic` arguments.
fn into_vec(self) -> Vec<Dynamic>;
}
impl<'a> FuncArgs<'a> for Vec<&'a mut Variant> {
fn into_vec(self) -> Self {
self
}
}
impl<'a, T: Any> FuncArgs<'a> for &'a mut Vec<T> {
fn into_vec(self) -> Vec<&'a mut Variant> {
self.iter_mut().map(|x| x as &mut Variant).collect()
impl<T: Any> FuncArgs for &mut Vec<T> {
fn into_vec(self) -> Vec<Dynamic> {
self.iter_mut().map(|x| x.into_dynamic()).collect()
}
}
macro_rules! impl_args {
($($p:ident),*) => {
impl<'a, $($p: Any + Clone),*> FuncArgs<'a> for ($(&'a mut $p,)*)
impl<$($p: Any + Clone),*> FuncArgs for ($($p,)*)
{
fn into_vec(self) -> Vec<&'a mut Variant> {
fn into_vec(self) -> Vec<Dynamic> {
let ($($p,)*) = self;
#[allow(unused_variables, unused_mut)]
let mut v = Vec::new();
$(v.push($p as &mut Variant);)*
$(v.push($p.into_dynamic());)*
v
}
@@ -45,4 +39,4 @@ macro_rules! impl_args {
}
#[cfg_attr(rustfmt, rustfmt_skip)]
impl_args!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S);
impl_args!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T);