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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
|
use std::any::TypeId;
use std::mem::{transmute_copy, ManuallyDrop};
use paste::paste;
use seq_macro::seq;
use util_macros::sub;
/// Used to append a element to a tuple type.
pub trait With<OtherElem>
{
type With;
}
/// Used to make all elements of a tuple type wrapped in [`Option`].
pub trait IntoInOptions
{
type InOptions: WithOptionElements;
fn into_in_options(self) -> Self::InOptions;
}
/// A tuple with all elements wrapped in [`Option`].
pub trait WithOptionElements
{
fn take<Element: 'static>(&mut self) -> TakeOptionElementResult<Element>;
}
/// Using the type system, reduces the elements of a tuple to a single one. Each element
/// determines itself how it is handled.
pub trait Reduce<Operation>
{
type Out;
}
pub trait ReduceElement<Accumulator, Operation>
{
type Return;
}
/// The result of trying to [`take`] a element from a implementation of
/// [`WithOptionElements`].
///
/// [`take`]: WithOptionElements::take
pub enum TakeOptionElementResult<Element>
{
/// The element was succesfully taken.
Found(Element),
/// The element is not a element of the tuple.
NotFound,
/// The element has already been taken
AlreadyTaken,
}
macro_rules! tuple_reduce_elem_tuple {
(overflow) => {
()
};
($index: tt) => {
paste! {
[<Elem $index>]::Return
}
};
}
macro_rules! impl_tuple_traits {
($cnt: tt) => {
seq!(I in 0..$cnt {
impl<OtherElem, #(Elem~I,)*> With<OtherElem> for (#(Elem~I,)*)
{
type With = (#(Elem~I,)* OtherElem,);
}
impl<#(Element~I: 'static,)*> IntoInOptions for (#(Element~I,)*)
{
type InOptions = (#(Option<Element~I>,)*);
fn into_in_options(self) -> Self::InOptions
{
#![allow(clippy::unused_unit)]
(#(Some(self.I),)*)
}
}
impl<#(Element~I: 'static,)*> WithOptionElements for (#(Option<Element~I>,)*)
{
fn take<Element: 'static>(&mut self)
-> TakeOptionElementResult<Element>
{
#(
if TypeId::of::<Element~I>() == TypeId::of::<Element>() {
let input = match self.I.take() {
Some(input) => ManuallyDrop::new(input),
None => {
return TakeOptionElementResult::AlreadyTaken;
}
};
return TakeOptionElementResult::Found(
// SAFETY: It can be transmuted safely since it is the
// same type and the type is 'static
unsafe { transmute_copy(&input) }
);
}
)*
TakeOptionElementResult::NotFound
}
}
paste! {
impl<Operation, #(Elem~I,)*> Reduce<Operation> for (#(Elem~I,)*)
where
#(
Elem~I: ReduceElement<
sub!(I - 1, tuple_reduce_elem_tuple), Operation
>,
)*
{
type Out = sub!($cnt - 1, tuple_reduce_elem_tuple);
}
}
});
};
}
seq!(N in 0..16 {
impl_tuple_traits!(N);
});
|