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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
//! Serialization and deserialization.
//!
//! This is *not* the well-known `serde` crate. We use custom serialization methods because we need
//! to serialize not only data structures, but objects with real-world side-effects, e.g. files.
use crate::;
use Any;
use ;
use fmt;
use Result;
use NonZeroUsize;
use c_void;
/// Stateful serialization.
/// Stateful deserialization.
/// A serializable object with complicated serialization/deserialization.
///
/// This trait should only be implemented, not used directly. If you ever need to specify a generic
/// type of a serializable object, you're looking for [`Object`].
///
/// If you have a type for which `#[derive(Object)]` does not produce the desired semantics (e.g.
/// you have additional state stored elsewhere that should be dumped in the serialization stream),
/// implement this trait based on this template:
///
/// ```rust
/// use crossmist::{Deserializer, NonTrivialObject, Object, Serializer};
/// use std::io::Result;
///
/// struct SimplePair<T: Object, U: Object> {
/// first: T,
/// second: U,
/// }
///
/// unsafe impl<T: Object, U: Object> NonTrivialObject for SimplePair<T, U> {
/// fn serialize_self_non_trivial(&self, s: &mut Serializer) {
/// s.serialize(&self.first);
/// s.serialize(&self.second);
/// }
/// unsafe fn deserialize_self_non_trivial(d: &mut Deserializer) -> Result<Self> {
/// let first = d.deserialize::<T>()?;
/// let second = d.deserialize::<U>()?;
/// Ok(Self { first, second })
/// }
/// }
/// ```
///
/// Note that DSTs cannot be objects (but `Box<dyn Trait>` and `Box<[T]>` are fine).
///
///
/// # Cyclic structures
///
/// Occasionally, you might need to serialize recursive structures that might contain loops. You're
/// probably better of using [`std::rc::Rc`] or [`std::sync::Arc`] or rewriting your structures, but
/// if nothing better comes to your mind, you can do the same thing that `Rc` does:
///
/// ```rust
/// # use crossmist::{Deserializer, NonTrivialObject, Object, Serializer};
/// # use std::io::Result;
/// # use std::os::raw::c_void;
/// # use std::rc::Rc;
/// struct CustomRc<T: 'static>(Rc<T>);
///
/// unsafe impl<T: 'static + Object> NonTrivialObject for CustomRc<T> {
/// fn serialize_self_non_trivial(&self, s: &mut Serializer) {
/// // Any unique identifier works, but it must be *globally* unique, not just for objects
/// // of the same type.
/// match s.learn_cyclic(Rc::as_ptr(&self.0) as *const c_void) {
/// None => {
/// // This is the first time we see this object -- encode a marker followed by its
/// // contents. Under the hood, learn_cyclic remembers this object.
/// s.serialize(&0usize);
/// s.serialize(&*self.0);
/// }
/// Some(id) => {
/// // We have seen this object before -- store its ID instead
/// s.serialize(&id);
/// }
/// }
/// }
/// unsafe fn deserialize_self_non_trivial(d: &mut Deserializer) -> Result<Self> {
/// let id = d.deserialize::<usize>()?;
/// match std::num::NonZeroUsize::new(id) {
/// None => {
/// // If 0 is stored, this is the first time we see this object -- decode its
/// // contents
/// let rc = Rc::<T>::new(d.deserialize()?);
/// // Tell the deserializer about this object. Note that you don't specify the ID:
/// // learn_cyclic infers it automatically. To make sure numeration is consistent
/// // with the serializer, call learn_cyclic in the same order in both. For
/// // instance, when encoding a set, make sure that data is serialized in the same
/// // order as it is deserialized. This should already be the case unless you
/// // serialize data in a very bizarre way. Also, notice that learn_cyclic does not
/// // have to store the exact object you are deserializing in: in this case, we
/// // store the Rc itself, not CustomRc.
/// d.learn_cyclic(rc.clone());
/// Ok(Self(rc))
/// }
/// Some(id) => {
/// // If a non-zero value is stored, this is an ID of an already existing object.
/// // Notice that you must specify the type of the object you expect to be stored.
/// // get_cyclic returns a reference to the object. In case of Rc, cloning it is
/// // sufficient.
/// Ok(Self(d.get_cyclic::<Rc<T>>(id).clone()))
/// }
/// }
/// }
/// }
/// ```
///
///
/// # File descriptors
///
/// Sometimes, you might need to serialize objects that store references to files. This is done
/// automatically for [`std::fs::File`], [`OwnedHandle`] and related types, but if you have a
/// different runtime, things might get a bit complicated.
///
/// In this case, the following example should be of help:
///
/// ```rust
/// # use crossmist::{
/// # handles::{AsRawHandle, OwnedHandle},
/// # Deserializer, NonTrivialObject, Object, Serializer,
/// # };
/// # use std::fs::File;
/// # use std::io::Result;
/// struct CustomFile(std::fs::File);
///
/// unsafe impl NonTrivialObject for CustomFile {
/// fn serialize_self_non_trivial(&self, s: &mut Serializer) {
/// // add_handle memorizes the handle (fd) and returns its ID
/// let handle = s.add_handle(self.0.as_raw_handle());
/// s.serialize(&handle)
/// }
/// unsafe fn deserialize_self_non_trivial(d: &mut Deserializer) -> Result<Self> {
/// // Deserializing OwnedHandle results in the ID being resolved into the handle, which can
/// // then be used to create the instance of the object we are deserializing
/// Ok(Self(d.deserialize::<OwnedHandle>()?.into()))
/// }
/// }
/// ```
///
///
/// # Safety
///
/// An implementation of this trait function is safe if the order of serialized types during
/// serialization and deserialization matches, up to serialization layout. See the documentation of
/// [`Deserializer::deserialize`] for more details.
pub unsafe