rkyv/impls/alloc/
boxed.rs1use crate::{
2 boxed::{ArchivedBox, BoxResolver},
3 Archive, ArchivePointee, ArchiveUnsized, Deserialize, DeserializeUnsized, Fallible, Serialize,
4 SerializeUnsized,
5};
6#[cfg(not(feature = "std"))]
7use ::alloc::{alloc, boxed::Box};
8use ::core::cmp;
9#[cfg(feature = "std")]
10use ::std::alloc;
11
12impl<T: ArchiveUnsized + ?Sized> Archive for Box<T> {
13 type Archived = ArchivedBox<T::Archived>;
14 type Resolver = BoxResolver<T::MetadataResolver>;
15
16 #[inline]
17 unsafe fn resolve(&self, pos: usize, resolver: Self::Resolver, out: *mut Self::Archived) {
18 ArchivedBox::resolve_from_ref(self.as_ref(), pos, resolver, out);
19 }
20}
21
22impl<T: SerializeUnsized<S> + ?Sized, S: Fallible + ?Sized> Serialize<S> for Box<T> {
23 #[inline]
24 fn serialize(&self, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
25 ArchivedBox::serialize_from_ref(self.as_ref(), serializer)
26 }
27}
28
29impl<T, D> Deserialize<Box<T>, D> for ArchivedBox<T::Archived>
30where
31 T: ArchiveUnsized + ?Sized,
32 T::Archived: DeserializeUnsized<T, D>,
33 D: Fallible + ?Sized,
34{
35 #[inline]
36 fn deserialize(&self, deserializer: &mut D) -> Result<Box<T>, D::Error> {
37 unsafe {
38 let data_address = self.get().deserialize_unsized(deserializer, |layout| {
39 let ptr = alloc::alloc(layout);
40 if ptr.is_null() {
41 alloc::handle_alloc_error(layout);
42 }
43 ptr
44 })?;
45 let metadata = self.get().deserialize_metadata(deserializer)?;
46 let ptr = ptr_meta::from_raw_parts_mut(data_address, metadata);
47 Ok(Box::from_raw(ptr))
48 }
49 }
50}
51
52impl<T: ArchivePointee + PartialEq<U> + ?Sized, U: ?Sized> PartialEq<Box<U>> for ArchivedBox<T> {
53 #[inline]
54 fn eq(&self, other: &Box<U>) -> bool {
55 self.get().eq(other.as_ref())
56 }
57}
58
59impl<T: ArchivePointee + PartialOrd<U> + ?Sized, U: ?Sized> PartialOrd<Box<U>> for ArchivedBox<T> {
60 #[inline]
61 fn partial_cmp(&self, other: &Box<U>) -> Option<cmp::Ordering> {
62 self.get().partial_cmp(other.as_ref())
63 }
64}