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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
#![deny(rustdoc::broken_intra_doc_links)]
#![deny(missing_docs)]
#![deny(rustdoc::missing_crate_level_docs)]
#![cfg_attr(feature = "nightly", feature(core_intrinsics))]
#[cfg(feature = "validation")]
pub mod validation;
#[cfg(feature = "vtable_cache")]
use core::sync::atomic::{AtomicU64, Ordering};
use core::{
alloc::Layout,
any::Any,
hash::{Hash, Hasher},
marker::PhantomData,
ptr,
};
use ptr_meta::{DynMetadata, Pointee};
#[cfg(feature = "vtable_cache")]
use rkyv::with::{Atomic, With};
use rkyv::{
from_archived,
ser::{ScratchSpace, Serializer},
to_archived, Archived, Fallible, Serialize,
};
pub use rkyv_dyn_derive::archive_dyn;
use rkyv_typename::TypeName;
use std::collections::{hash_map::DefaultHasher, HashMap};
#[cfg(feature = "validation")]
pub use validation::{CheckDynError, DynContext};
#[doc(hidden)]
pub use inventory;
#[cfg(all(feature = "vtable_cache", feature = "nightly"))]
use core::intrinsics::likely;
#[cfg(all(feature = "vtable_cache", not(feature = "nightly")))]
#[inline]
fn likely(b: bool) -> bool {
b
}
pub type DynError = Box<dyn Any>;
pub trait DynSerializer {
fn pos_dyn(&self) -> usize;
fn write_dyn(&mut self, bytes: &[u8]) -> Result<(), DynError>;
unsafe fn push_scratch_dyn(&mut self, layout: Layout) -> Result<ptr::NonNull<[u8]>, DynError>;
unsafe fn pop_scratch_dyn(
&mut self,
ptr: ptr::NonNull<u8>,
layout: Layout,
) -> Result<(), DynError>;
}
impl<'a> Fallible for dyn DynSerializer + 'a {
type Error = DynError;
}
impl<'a> Serializer for dyn DynSerializer + 'a {
fn pos(&self) -> usize {
self.pos_dyn()
}
fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
self.write_dyn(bytes)
}
}
impl<'a> ScratchSpace for dyn DynSerializer + 'a {
unsafe fn push_scratch(&mut self, layout: Layout) -> Result<ptr::NonNull<[u8]>, Self::Error> {
self.push_scratch_dyn(layout)
}
unsafe fn pop_scratch(
&mut self,
ptr: ptr::NonNull<u8>,
layout: Layout,
) -> Result<(), Self::Error> {
self.pop_scratch_dyn(ptr, layout)
}
}
impl<S: ScratchSpace + Serializer + ?Sized> DynSerializer for &mut S {
fn pos_dyn(&self) -> usize {
self.pos()
}
fn write_dyn(&mut self, bytes: &[u8]) -> Result<(), DynError> {
self.write(bytes).map_err(|e| Box::new(e) as DynError)
}
unsafe fn push_scratch_dyn(&mut self, layout: Layout) -> Result<ptr::NonNull<[u8]>, DynError> {
self.push_scratch(layout)
.map_err(|e| Box::new(e) as DynError)
}
unsafe fn pop_scratch_dyn(
&mut self,
ptr: ptr::NonNull<u8>,
layout: Layout,
) -> Result<(), DynError> {
self.pop_scratch(ptr, layout)
.map_err(|e| Box::new(e) as DynError)
}
}
fn hash_type<T: TypeName + ?Sized>() -> u64 {
let mut hasher = DefaultHasher::new();
T::build_type_name(|piece| piece.hash(&mut hasher));
hasher.finish()
}
pub trait SerializeDyn {
fn serialize_dyn(&self, serializer: &mut dyn DynSerializer) -> Result<usize, DynError>;
fn archived_type_id(&self) -> u64;
}
impl<T: for<'a> Serialize<dyn DynSerializer + 'a>> SerializeDyn for T
where
T::Archived: TypeName,
{
fn serialize_dyn(&self, serializer: &mut dyn DynSerializer) -> Result<usize, DynError> {
serializer.serialize_value(self)
}
fn archived_type_id(&self) -> u64 {
hash_type::<T::Archived>()
}
}
pub trait DynDeserializer {}
impl<'a> Fallible for dyn DynDeserializer + 'a {
type Error = DynError;
}
impl<D: Fallible + ?Sized> DynDeserializer for &mut D {}
pub trait DeserializeDyn<T: Pointee + ?Sized> {
unsafe fn deserialize_dyn(
&self,
deserializer: &mut dyn DynDeserializer,
alloc: &mut dyn FnMut(Layout) -> *mut u8,
) -> Result<*mut (), DynError>;
fn deserialize_dyn_metadata(
&self,
deserializer: &mut dyn DynDeserializer,
) -> Result<T::Metadata, DynError>;
}
#[cfg_attr(feature = "strict", repr(C))]
pub struct ArchivedDynMetadata<T: ?Sized> {
type_id: Archived<u64>,
#[cfg(feature = "vtable_cache")]
cached_vtable: Archived<With<AtomicU64, Atomic>>,
#[cfg(not(feature = "vtable_cache"))]
#[allow(dead_code)]
cached_vtable: Archived<u64>,
phantom: PhantomData<T>,
}
impl<T: TypeName + ?Sized> ArchivedDynMetadata<T> {
pub unsafe fn emplace(type_id: u64, out: *mut Self) {
ptr::addr_of_mut!((*out).type_id).write(to_archived!(type_id));
#[cfg(feature = "vtable_cache")]
{
let cached_vtable = ptr::addr_of_mut!((*out).cached_vtable);
(*cached_vtable).store(0u64, Ordering::Relaxed);
}
#[cfg(not(feature = "vtable_cache"))]
ptr::addr_of_mut!((*out).cached_vtable).write(to_archived!(0u64));
}
fn lookup_vtable(&self) -> usize {
IMPL_REGISTRY
.get::<T>(from_archived!(self.type_id))
.expect("attempted to get vtable for an unregistered impl")
.vtable
}
#[cfg(feature = "vtable_cache")]
pub fn vtable(&self) -> usize {
let cached_vtable = self.cached_vtable.load(Ordering::Relaxed);
if likely(cached_vtable != 0) {
return cached_vtable as usize;
}
let vtable = self.lookup_vtable();
self.cached_vtable
.store(vtable as usize as u64, Ordering::Relaxed);
vtable
}
#[cfg(not(feature = "vtable_cache"))]
pub fn vtable(&self) -> usize {
self.lookup_vtable()
}
pub fn pointer_metadata(&self) -> DynMetadata<T> {
unsafe { core::mem::transmute(self.vtable()) }
}
}
#[cfg(debug_assertions)]
#[doc(hidden)]
#[derive(Copy, Clone)]
pub struct ImplDebugInfo {
pub file: &'static str,
pub line: u32,
pub column: u32,
}
#[cfg(debug_assertions)]
#[doc(hidden)]
#[macro_export]
macro_rules! debug_info {
() => {
rkyv_dyn::ImplDebugInfo {
file: core::file!(),
line: core::line!(),
column: core::column!(),
}
};
}
#[cfg(not(debug_assertions))]
#[doc(hidden)]
#[derive(Copy, Clone)]
pub struct ImplDebugInfo;
#[cfg(not(debug_assertions))]
#[doc(hidden)]
#[macro_export]
macro_rules! debug_info {
() => {
rkyv_dyn::ImplDebugInfo
};
}
#[doc(hidden)]
#[derive(Clone, Copy)]
pub struct ImplData {
pub vtable: usize,
pub debug_info: ImplDebugInfo,
}
#[derive(Clone, Copy, Hash, Eq, PartialEq)]
struct ImplId {
trait_id: u64,
type_id: u64,
}
impl ImplId {
fn new<TY: TypeName, TR: TypeName + ?Sized>() -> Self {
Self::from_type_id::<TR>(hash_type::<TY>())
}
fn from_type_id<TR: TypeName + ?Sized>(type_id: u64) -> Self {
Self {
trait_id: hash_type::<TR>(),
type_id: type_id | 1,
}
}
}
#[doc(hidden)]
pub struct ImplEntry {
impl_id: ImplId,
data: ImplData,
}
impl ImplEntry {
#[doc(hidden)]
pub fn new<TY: TypeName + RegisteredImpl<TR>, TR: TypeName + ?Sized>() -> Self {
Self {
impl_id: ImplId::new::<TY, TR>(),
data: ImplData {
vtable: <TY as RegisteredImpl<TR>>::vtable(),
debug_info: <TY as RegisteredImpl<TR>>::debug_info(),
},
}
}
}
inventory::collect!(ImplEntry);
struct ImplRegistry {
id_to_data: HashMap<ImplId, ImplData>,
}
impl ImplRegistry {
fn new() -> Self {
Self {
id_to_data: HashMap::new(),
}
}
fn add_entry(&mut self, entry: &ImplEntry) {
let old_value = self.id_to_data.insert(entry.impl_id, entry.data);
#[cfg(debug_assertions)]
if let Some(old_data) = old_value {
eprintln!("impl id conflict, a trait implementation was likely added twice (but it's possible there was a hash collision)");
eprintln!(
"existing impl registered at {}:{}:{}",
old_data.debug_info.file, old_data.debug_info.line, old_data.debug_info.column
);
eprintln!(
"new impl registered at {}:{}:{}",
entry.data.debug_info.file,
entry.data.debug_info.line,
entry.data.debug_info.column
);
panic!();
}
debug_assert!(old_value.is_none(), "impl id conflict, a trait implementation was likely added twice (but it's possible there was a hash collision)");
}
fn get<T: TypeName + ?Sized>(&self, type_id: u64) -> Option<&ImplData> {
self.id_to_data.get(&ImplId::from_type_id::<T>(type_id))
}
}
lazy_static::lazy_static! {
static ref IMPL_REGISTRY: ImplRegistry = {
let mut result = ImplRegistry::new();
for entry in inventory::iter::<ImplEntry> {
result.add_entry(entry);
}
result
};
}
#[doc(hidden)]
pub unsafe trait RegisteredImpl<T: ?Sized> {
fn vtable() -> usize;
fn debug_info() -> ImplDebugInfo;
}
#[doc(hidden)]
#[cfg(not(feature = "validation"))]
#[macro_export]
macro_rules! register_validation {
($type:ty as $trait:ty) => {};
}
#[macro_export]
macro_rules! register_impl {
($type:ty as $trait:ty) => {
const _: () = {
use rkyv_dyn::{
debug_info, inventory, register_validation, ImplData, ImplDebugInfo, ImplEntry,
RegisteredImpl,
};
unsafe impl RegisteredImpl<$trait> for $type {
fn vtable() -> usize {
unsafe {
core::mem::transmute(ptr_meta::metadata(
core::ptr::null::<$type>() as *const $trait
))
}
}
fn debug_info() -> ImplDebugInfo {
debug_info!()
}
}
inventory::submit! { ImplEntry::new::<$type, $trait>() }
register_validation!($type as $trait);
};
};
}