rkyv 0.8.17

Zero-copy deserialization framework for Rust
Documentation
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
//! Archived versions of shared pointers.

use core::{borrow::Borrow, cmp, fmt, hash, marker::PhantomData, ops::Deref};

use munge::munge;
use rancor::{Fallible, Source};

use crate::{
    primitive::FixedUsize,
    seal::Seal,
    ser::{Sharing, SharingExt, Writer, WriterExt as _},
    traits::ArchivePointee,
    ArchiveUnsized, Place, Portable, RelPtr, SerializeUnsized,
};

/// A type marker for `ArchivedRc`.
pub trait Flavor: 'static {
    /// If `true`, cyclic `ArchivedRc`s with this flavor will not fail
    /// validation. If `false`, cyclic `ArchivedRc`s with this flavor will fail
    /// validation.
    const ALLOW_CYCLES: bool;
}

/// The flavor type for [`Rc`](crate::alloc::rc::Rc).
pub struct RcFlavor;

impl Flavor for RcFlavor {
    const ALLOW_CYCLES: bool = false;
}

/// The flavor type for [`Arc`](crate::alloc::sync::Arc).
pub struct ArcFlavor;

impl Flavor for ArcFlavor {
    const ALLOW_CYCLES: bool = false;
}

/// An archived `Rc`.
///
/// This is a thin wrapper around a [`RelPtr`] to the archived type paired with
/// a "flavor" type. Because there may be many varieties of shared pointers and
/// they may not be used together, the flavor helps check that memory is not
/// being shared incorrectly during validation.
#[derive(Portable)]
#[rkyv(crate)]
#[repr(transparent)]
#[cfg_attr(
    feature = "bytecheck",
    derive(bytecheck::CheckBytes),
    bytecheck(verify)
)]
pub struct ArchivedRc<T: ArchivePointee + ?Sized, F> {
    ptr: RelPtr<T>,
    _phantom: PhantomData<F>,
}

impl<T: ArchivePointee + ?Sized, F> ArchivedRc<T, F> {
    /// Gets the value of the `ArchivedRc`.
    pub fn get(&self) -> &T {
        unsafe { &*self.ptr.as_ptr() }
    }

    /// Gets the sealed value of this `ArchivedRc`.
    ///
    /// # Safety
    ///
    /// Any other pointers to the same value must not be dereferenced for the
    /// duration of the returned borrow.
    pub unsafe fn get_seal_unchecked(this: Seal<'_, Self>) -> Seal<'_, T> {
        munge!(let Self { ptr, _phantom: _ } = this);
        Seal::new(unsafe { &mut *RelPtr::as_mut_ptr(ptr) })
    }

    /// Resolves an archived `Rc` from a given reference.
    pub fn resolve_from_ref<U: ArchiveUnsized<Archived = T> + ?Sized>(
        value: &U,
        resolver: RcResolver,
        out: Place<Self>,
    ) {
        munge!(let ArchivedRc { ptr, .. } = out);
        RelPtr::emplace_unsized(
            resolver.pos as usize,
            value.archived_metadata(),
            ptr,
        );
    }

    /// Serializes an archived `Rc` from a given reference.
    pub fn serialize_from_ref<U, S>(
        value: &U,
        serializer: &mut S,
    ) -> Result<RcResolver, S::Error>
    where
        U: SerializeUnsized<S> + ?Sized,
        S: Fallible + Writer + Sharing + ?Sized,
        S::Error: Source,
    {
        let pos = serializer.serialize_shared(value)?;

        // The positions of serialized `Rc` values must be unique. If we didn't
        // write any data by serializing `value`, pad the serializer by a byte
        // to ensure that our position will be unique.
        if serializer.pos() == pos {
            serializer.pad(1)?;
        }

        Ok(RcResolver {
            pos: pos as FixedUsize,
        })
    }
}

impl<T, F> AsRef<T> for ArchivedRc<T, F>
where
    T: ArchivePointee + ?Sized,
{
    fn as_ref(&self) -> &T {
        self.get()
    }
}

impl<T, F> Borrow<T> for ArchivedRc<T, F>
where
    T: ArchivePointee + ?Sized,
{
    fn borrow(&self) -> &T {
        self.get()
    }
}

impl<T, F> fmt::Debug for ArchivedRc<T, F>
where
    T: ArchivePointee + fmt::Debug + ?Sized,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.get().fmt(f)
    }
}

impl<T, F> Deref for ArchivedRc<T, F>
where
    T: ArchivePointee + ?Sized,
{
    type Target = T;
    fn deref(&self) -> &Self::Target {
        self.get()
    }
}

impl<T, F> fmt::Display for ArchivedRc<T, F>
where
    T: ArchivePointee + fmt::Display + ?Sized,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.get().fmt(f)
    }
}

impl<T, F> Eq for ArchivedRc<T, F> where T: ArchivePointee + Eq + ?Sized {}

impl<T, F> hash::Hash for ArchivedRc<T, F>
where
    T: ArchivePointee + hash::Hash + ?Sized,
{
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        self.get().hash(state)
    }
}

impl<T, F> Ord for ArchivedRc<T, F>
where
    T: ArchivePointee + Ord + ?Sized,
{
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.get().cmp(other.get())
    }
}

impl<T, TF, U, UF> PartialEq<ArchivedRc<U, UF>> for ArchivedRc<T, TF>
where
    T: ArchivePointee + PartialEq<U> + ?Sized,
    U: ArchivePointee + ?Sized,
{
    fn eq(&self, other: &ArchivedRc<U, UF>) -> bool {
        self.get().eq(other.get())
    }
}

impl<T, TF, U, UF> PartialOrd<ArchivedRc<U, UF>> for ArchivedRc<T, TF>
where
    T: ArchivePointee + PartialOrd<U> + ?Sized,
    U: ArchivePointee + ?Sized,
{
    fn partial_cmp(&self, other: &ArchivedRc<U, UF>) -> Option<cmp::Ordering> {
        self.get().partial_cmp(other.get())
    }
}

impl<T, F> fmt::Pointer for ArchivedRc<T, F> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Pointer::fmt(&self.ptr.base(), f)
    }
}

/// The resolver for `Rc`.
pub struct RcResolver {
    pos: FixedUsize,
}

impl RcResolver {
    /// Creates a new [`RcResolver`] from the position of a serialized value.
    ///
    /// In most cases, you won't need to create a [`RcResolver`] yourself and
    /// can instead obtain it through [`ArchivedRc::serialize_from_ref`].
    pub fn from_pos(pos: usize) -> Self {
        Self {
            pos: pos as FixedUsize,
        }
    }
}

/// An archived `rc::Weak`.
///
/// This is essentially just an optional [`ArchivedRc`].
#[derive(Portable)]
#[rkyv(crate)]
#[repr(transparent)]
#[cfg_attr(
    feature = "bytecheck",
    derive(bytecheck::CheckBytes),
    bytecheck(verify)
)]
pub struct ArchivedRcWeak<T: ArchivePointee + ?Sized, F> {
    ptr: RelPtr<T>,
    _phantom: PhantomData<F>,
}

impl<T: ArchivePointee + ?Sized, F> ArchivedRcWeak<T, F> {
    /// Attempts to upgrade the weak pointer to an `ArchivedArc`.
    ///
    /// Returns `None` if a null weak pointer was serialized.
    pub fn upgrade(&self) -> Option<&ArchivedRc<T, F>> {
        if self.ptr.is_invalid() {
            None
        } else {
            Some(unsafe { &*(self as *const Self).cast() })
        }
    }

    /// Attempts to upgrade a sealed weak pointer.
    pub fn upgrade_seal(
        this: Seal<'_, Self>,
    ) -> Option<Seal<'_, ArchivedRc<T, F>>> {
        let this = unsafe { this.unseal_unchecked() };
        if this.ptr.is_invalid() {
            None
        } else {
            Some(Seal::new(unsafe { &mut *(this as *mut Self).cast() }))
        }
    }

    /// Resolves an archived `Weak` from a given optional reference.
    pub fn resolve_from_ref<U: ArchiveUnsized<Archived = T> + ?Sized>(
        value: Option<&U>,
        resolver: RcWeakResolver,
        out: Place<Self>,
    ) {
        match value {
            None => {
                munge!(let ArchivedRcWeak { ptr, _phantom: _ } = out);
                RelPtr::emplace_invalid(ptr);
            }
            Some(value) => {
                let out = unsafe { out.cast_unchecked::<ArchivedRc<T, F>>() };
                ArchivedRc::resolve_from_ref(value, resolver.inner, out);
            }
        }
    }

    /// Serializes an archived `Weak` from a given optional reference.
    pub fn serialize_from_ref<U, S>(
        value: Option<&U>,
        serializer: &mut S,
    ) -> Result<RcWeakResolver, S::Error>
    where
        U: SerializeUnsized<S, Archived = T> + ?Sized,
        S: Fallible + Writer + Sharing + ?Sized,
        S::Error: Source,
    {
        Ok(match value {
            None => RcWeakResolver {
                inner: RcResolver { pos: 0 },
            },
            Some(r) => RcWeakResolver {
                inner: ArchivedRc::<T, F>::serialize_from_ref(r, serializer)?,
            },
        })
    }
}

impl<T: ArchivePointee + fmt::Debug + ?Sized, F> fmt::Debug
    for ArchivedRcWeak<T, F>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "(Weak)")
    }
}

/// The resolver for `rc::Weak`.
pub struct RcWeakResolver {
    inner: RcResolver,
}

#[cfg(feature = "bytecheck")]
mod verify {
    use core::{any::TypeId, error::Error, fmt};

    use bytecheck::{
        rancor::{Fallible, Source},
        CheckBytes, Verify,
    };
    use rancor::fail;

    use crate::{
        erased::{ErasedPtr, FromMetadata, Metadata},
        rc::{ArchivedRc, ArchivedRcWeak, Flavor},
        traits::{ArchivePointee, LayoutRaw},
        validation::{
            shared::ValidationState, ArchiveContext, ArchiveContextExt,
            SharedContext,
        },
    };

    #[derive(Debug)]
    struct CyclicSharedPointerError;

    impl fmt::Display for CyclicSharedPointerError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "encountered cyclic shared pointers while validating")
        }
    }

    impl Error for CyclicSharedPointerError {}

    unsafe impl<T, F, C> Verify<C> for ArchivedRc<T, F>
    where
        T: ArchivePointee + CheckBytes<C> + LayoutRaw + ?Sized + 'static,
        T::ArchivedMetadata: CheckBytes<C>,
        T::Metadata: Into<Metadata> + FromMetadata,
        F: Flavor,
        C: Fallible + ArchiveContext + SharedContext + ?Sized,
        C::Error: Source,
    {
        fn verify(&self, context: &mut C) -> Result<(), C::Error> {
            let ptr = self.ptr.as_ptr_wrapping();
            let shared_type_id = TypeId::of::<ArchivedRc<T, F>>();
            let erased_ptr = ErasedPtr::new(ptr.cast_mut());

            let result =
                context.start_shared(shared_type_id, erased_ptr, |a, b| {
                    let a = unsafe { T::Metadata::from_metadata(a) };
                    let b = unsafe { T::Metadata::from_metadata(b) };
                    a == b
                })?;
            match result {
                ValidationState::Started => {
                    context.in_subtree(ptr, |context| unsafe {
                        T::check_bytes(ptr, context)
                    })?;
                    context.finish_shared(shared_type_id, erased_ptr)?;
                }
                ValidationState::Pending => {
                    if !F::ALLOW_CYCLES {
                        fail!(CyclicSharedPointerError)
                    }
                }
                ValidationState::Finished => (),
            }

            Ok(())
        }
    }

    unsafe impl<T, F, C> Verify<C> for ArchivedRcWeak<T, F>
    where
        T: ArchivePointee + CheckBytes<C> + LayoutRaw + ?Sized + 'static,
        T::ArchivedMetadata: CheckBytes<C>,
        T::Metadata: Into<Metadata> + FromMetadata,
        F: Flavor,
        C: Fallible + ArchiveContext + SharedContext + ?Sized,
        C::Error: Source,
    {
        fn verify(&self, context: &mut C) -> Result<(), C::Error> {
            if self.ptr.is_invalid() {
                Ok(())
            } else {
                // SAFETY: `ArchivedRc` and `ArchivedRcWeak` are
                // `repr(transparent)` and so have the same layout as each
                // other.
                let rc = unsafe {
                    &*(self as *const Self).cast::<ArchivedRc<T, F>>()
                };
                rc.verify(context)
            }
        }
    }
}