Skip to content

Commit 63dd353

Browse files
committed
Add TryFrom to convert from Varargs to tuples
godot-rust#886
1 parent e17c456 commit 63dd353

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

gdnative-core/src/export/method.rs

+54
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,60 @@ impl<'a> Iterator for Varargs<'a> {
415415
}
416416
}
417417

418+
// Return a second token.
419+
macro_rules! replace_expr {
420+
($_t:tt $sub:expr) => {
421+
$sub
422+
};
423+
}
424+
425+
// Count parameters.
426+
macro_rules! count_tts {
427+
($($tts:tt)*) => {
428+
0usize $(+ replace_expr!($tts 1usize))*
429+
};
430+
}
431+
432+
// Convert from Varargs to tuples, implement traits.
433+
macro_rules! varargs_into_tuple {
434+
($($params:ident),*) => {
435+
impl<'a, $($params: FromVariant),*> std::convert::TryFrom<Varargs<'a>> for ($($params,)*) {
436+
type Error = VarargsError;
437+
438+
#[inline]
439+
fn try_from(args: Varargs<'a>) -> Result<Self, Self::Error> {
440+
const EXPECTED: usize = count_tts!($($params)*);
441+
args.check_length(EXPECTED)?;
442+
let mut i: usize = 0;
443+
#[allow(unused_variables, unused_mut)]
444+
let mut inc = || {
445+
let ret = i;
446+
i += 1;
447+
ret
448+
};
449+
Ok((
450+
$(args.get::<$params>(inc())?,)*
451+
))
452+
}
453+
}
454+
};
455+
}
456+
457+
// Define up to the length supported by standard library.
458+
varargs_into_tuple!();
459+
varargs_into_tuple!(A);
460+
varargs_into_tuple!(A, B);
461+
varargs_into_tuple!(A, B, C);
462+
varargs_into_tuple!(A, B, C, D);
463+
varargs_into_tuple!(A, B, C, D, E);
464+
varargs_into_tuple!(A, B, C, D, E, F);
465+
varargs_into_tuple!(A, B, C, D, E, F, G);
466+
varargs_into_tuple!(A, B, C, D, E, F, G, H);
467+
varargs_into_tuple!(A, B, C, D, E, F, G, H, I);
468+
varargs_into_tuple!(A, B, C, D, E, F, G, H, I, J);
469+
varargs_into_tuple!(A, B, C, D, E, F, G, H, I, J, K);
470+
varargs_into_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
471+
418472
/// All possible error types for convert from Varargs.
419473
#[derive(Debug)]
420474
pub enum VarargsError {

0 commit comments

Comments
 (0)