Skip to content

Instantly share code, notes, and snippets.

@djkoloski
Created April 6, 2021 17:32
Show Gist options
  • Save djkoloski/a0abbf4dcc7dee17c56a571fe6306fa2 to your computer and use it in GitHub Desktop.
Save djkoloski/a0abbf4dcc7dee17c56a571fe6306fa2 to your computer and use it in GitHub Desktop.
Aligned serializer for emplacement
pub struct AlignedSerializer {
inner: AlignedVec,
}
impl AlignedSerializer {
pub fn new() -> Self {
Self {
inner: AlignedVec::new(),
}
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
inner: AlignedVec::with_capacity(capacity),
}
}
pub fn into_inner(self) -> AlignedVec {
self.inner
}
}
impl Fallible for AlignedSerializer {
type Error = Unreachable;
}
impl Serializer for AlignedSerializer {
#[inline]
fn pos(&self) -> usize {
self.inner.len()
}
#[inline]
fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
self.inner.extend_from_slice(bytes);
Ok(())
}
#[inline]
unsafe fn resolve_aligned<T: Archive + ?Sized>(&mut self, value: &T, resolver: T::Resolver) -> Result<usize, Self::Error> {
let pos = self.pos();
debug_assert!(pos & (mem::align_of::<T::Archived>() - 1) == 0);
self.inner.reserve(mem::size_of::<T::Archived>());
self.inner.as_mut_ptr().add(pos).cast::<T::Archived>().write(value.resolve(pos, resolver));
Ok(pos)
}
#[inline]
unsafe fn resolve_unsized_aligned<T: ArchiveUnsized + ?Sized>(&mut self, value: &T, to: usize, metadata_resolver: T::MetadataResolver) -> Result<usize, Self::Error> {
let from = self.pos();
debug_assert!(from & (mem::align_of::<RelPtr<T::Archived>>() - 1) == 0);
self.inner.reserve(mem::size_of::<RelPtr<T::Archived>>());
self.inner.as_mut_ptr().add(from).cast::<RelPtr<T::Archived>>().write(value.resolve_unsized(from, to, metadata_resolver));
Ok(from)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment