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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
use {
core::str,
proc_macro2::{Ident, Literal, Span},
quote::quote,
std::io::{Result, Write},
};
/// Generate `SchemaWrite` and `SchemaRead` implementations for tuples up to the given arity.
#[allow(clippy::arithmetic_side_effects)]
pub fn generate(arity: usize, mut out: impl Write) -> Result<()> {
// Avoid single item tuples and avoid running out of alphabet.
assert!(arity > 1 && arity <= 26, "arity must be > 1 and <= 26");
for arity in 2..=arity {
let mut alpha = 'A'..='Z';
let params: Vec<_> = (0..arity)
.map(|_| {
let char_byte = [alpha.next().unwrap() as u8];
let str = unsafe { str::from_utf8_unchecked(&char_byte) };
Ident::new(str, Span::call_site())
})
.collect();
let idxs: Vec<_> = (0..arity).map(Literal::usize_unsuffixed).collect();
// The generic tuple (A, B, C, ...)
let params_tuple = quote! { ( #(#params),* ) };
let size_impl = {
let parts = params.iter().zip(&idxs).map(
|(ident, i)| quote!( <#ident as crate::SchemaWrite<Cfg>>::size_of(&value.#i)? ),
);
quote!(#(#parts)+*)
};
let write_impl = params
.iter()
.zip(&idxs)
.map(|(ident, i)| quote!( <#ident as crate::SchemaWrite<Cfg>>::write(writer.by_ref(), &value.#i)?; ))
.collect::<Vec<_>>();
let read_impl = params
.iter()
.zip(&idxs)
.enumerate()
.map(|(i, (ident, index))| {
let init_count = if i == arity - 1 {
quote! {}
} else {
quote! { *init_count += 1; }
};
quote! {
<#ident as crate::SchemaRead<'de, Cfg>>::read(
reader.by_ref(),
unsafe { &mut *(&raw mut (*dst_ptr).#index).cast() }
)?;
#init_count
}
})
.collect::<Vec<_>>();
let write_static_size = params.iter().map(|ident| {
quote! { <#ident as crate::SchemaWrite<Cfg>>::TYPE_META }
});
let read_static_size = params.iter().map(|ident| {
quote! { <#ident as crate::SchemaRead<'de, Cfg>>::TYPE_META }
});
// Tuples don't have guaranteed layout, so we never mark them as zero-copy.
let static_size_impl_write = quote! {
TypeMeta::join_types([#(#write_static_size),*]).keep_zero_copy(false)
};
let static_size_impl_read = quote! {
TypeMeta::join_types([#(#read_static_size),*]).keep_zero_copy(false)
};
let drop_arms = (0..arity).map(|init_count| {
if init_count == 0 {
// Nothing initialized.
return quote!(0u8 => {});
}
// Generate code to drop already initialized fields in reverse order.
let drops = idxs[..init_count].iter().rev().map(|i| {
quote! { unsafe { core::ptr::drop_in_place(&raw mut (*dst_ptr).#i); } }
});
let cnt = init_count as u8;
quote!(#cnt => { #(#drops)* })
});
let stream = quote! {
unsafe impl<Cfg: crate::config::ConfigCore, #(#params),*> crate::SchemaWrite<Cfg> for #params_tuple
where
#(#params: crate::SchemaWrite<Cfg>,)*
#(#params::Src: Sized,)*
{
type Src = (#(#params::Src),*);
const TYPE_META: TypeMeta = #static_size_impl_write;
#[inline]
#[allow(clippy::arithmetic_side_effects)]
fn size_of(value: &Self::Src) -> crate::WriteResult<usize> {
if let TypeMeta::Static { size, .. } = <Self as crate::SchemaWrite<Cfg>>::TYPE_META {
Ok(size)
} else {
Ok(#size_impl)
}
}
#[inline]
fn write(mut writer: impl crate::io::Writer, value: &Self::Src) -> crate::WriteResult<()>
{
use crate::io::Writer;
if let TypeMeta::Static { size, .. } = Self::TYPE_META {
// SAFETY: `size` is the serialized size of the tuple, which is the sum
// of the serialized sizes of the members.
// Calling `write` on each field will write exactly `size` bytes,
// fully initializing the trusted window.
let mut writer = unsafe { writer.as_trusted_for(size) }?;
#(#write_impl)*
writer.finish()?;
} else {
#(#write_impl)*
}
Ok(())
}
}
unsafe impl<'de, Cfg: crate::config::ConfigCore, #(#params),*> crate::SchemaRead<'de, Cfg> for #params_tuple
where
#(#params: crate::SchemaRead<'de, Cfg>,)*
{
type Dst = (#(#params::Dst),*);
const TYPE_META: TypeMeta = #static_size_impl_read;
#[inline]
#[allow(clippy::arithmetic_side_effects, clippy::type_complexity)]
fn read(
mut reader: impl crate::io::Reader<'de>,
dst: &mut core::mem::MaybeUninit<Self::Dst>
) -> crate::ReadResult<()>
{
use crate::io::Reader;
let dst_ptr = dst.as_mut_ptr();
struct DropGuard<#(#params),*> {
init_count: u8,
dst_ptr: *mut (#(#params),*),
}
impl<#(#params),*> Drop for DropGuard<#(#params),*> {
#[cold]
fn drop(&mut self) {
let dst_ptr = self.dst_ptr;
match self.init_count {
#(#drop_arms,)*
// Impossible, given the `init_count` is bounded by the number of fields.
_ => { debug_assert!(false, "init_count out of bounds"); },
}
}
}
let mut guard = DropGuard { init_count: 0, dst_ptr };
let init_count = &mut guard.init_count;
if let TypeMeta::Static { size, .. } = Self::TYPE_META {
// SAFETY: `size` is the serialized size of the tuple, which is the sum
// of the serialized sizes of the members.
// Calling `read` on each field will consume exactly `size` bytes,
// fully consuming the trusted window.
let mut reader = unsafe { reader.as_trusted_for(size) }?;
#(#read_impl)*
} else {
#(#read_impl)*
}
core::mem::forget(guard);
Ok(())
}
}
};
write!(out, "{stream}")?;
}
Ok(())
}