1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use crate::{FromValue, ToValue, Value, VmError, VmErrorKind};

/// A helper type to deserialize arrays with different interior types.
///
/// This implements [FromValue], allowing it to be used as a return value from
/// a virtual machine.
///
/// [FromValue]: crate::FromValue
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct VecTuple<T>(pub T);

impl<T> VecTuple<T>
where
    Self: ToValue,
{
    /// Construct a new vector tuple for serializing values.
    pub fn new(inner: T) -> Self {
        Self(inner)
    }
}

macro_rules! impl_from_value_tuple_vec {
    () => {
    };

    ({$ty:ident, $value:ident, $count:expr}, $({$rest_ty:ident, $rest_value:ident, $rest_count:expr},)*) => {
        impl_from_value_tuple_vec!{@impl $count, {$ty, $value, $count}, $({$rest_ty, $rest_value, $rest_count},)*}
        impl_from_value_tuple_vec!{$({$rest_ty, $rest_value, $rest_count},)*}
    };

    (@impl $count:expr, $({$ty:ident, $value:ident, $ignore_count:expr},)*) => {
        impl<$($ty,)*> FromValue for VecTuple<($($ty,)*)>
        where
            $($ty: FromValue,)*
        {
            fn from_value(value: Value) -> Result<Self, VmError> {
                let vec = value.into_vec()?;
                let vec = vec.take()?;

                if vec.len() != $count {
                    return Err(VmError::from(VmErrorKind::ExpectedTupleLength {
                        actual: vec.len(),
                        expected: $count,
                    }));
                }

                #[allow(unused_mut, unused_variables)]
                let mut it = vec.into_iter();

                $(
                    let $value: $ty = match it.next() {
                        Some(value) => <$ty>::from_value(value)?,
                        None => {
                            return Err(VmError::from(VmErrorKind::IterationError));
                        },
                    };
                )*

                Ok(VecTuple(($($value,)*)))
            }
        }

        impl<$($ty,)*> ToValue for VecTuple<($($ty,)*)>
        where
            $($ty: ToValue,)*
        {
            fn to_value(self) -> Result<Value, VmError> {
                let ($($value,)*) = self.0;
                let vec = vec![$($value.to_value()?,)*];
                Ok(Value::vec(vec))
            }
        }
    };
}

repeat_macro!(impl_from_value_tuple_vec);