Skip to main content

feldera_storage/
fbuf.rs

1//! A custom buffer type that works with our read/write APIs and the
2//! buffer-cache.
3
4// The code in this file is originally derived from the rkyv `AlignedVec`
5// type, and adapted for use within the Feldera storage engine.
6//
7// Original rkyv attribution of the code:
8//
9// SPDX-FileCopyrightText: Copyright © 2021 David Koloski
10//
11// SPDX-License-Identifier: MIT
12
13use std::{
14    alloc,
15    borrow::{Borrow, BorrowMut},
16    cmp::Ordering,
17    fmt,
18    fs::File,
19    io::{self, Error as IoError, ErrorKind, Read},
20    mem,
21    ops::{Deref, DerefMut, Index, IndexMut},
22    os::fd::AsRawFd,
23    ptr::NonNull,
24    slice,
25};
26
27use libc::c_void;
28use rkyv::{
29    Archive, Archived, Serialize,
30    ser::{ScratchSpace, Serializer},
31    vec::ArchivedVec,
32};
33use rkyv::{ArchiveUnsized, Fallible, RelPtr, vec::VecResolver};
34
35pub mod slab;
36
37use self::slab::{acquire_allocation, layout_for, recycle_or_dealloc};
38
39/// A custom buffer type that works with our read/write APIs and the
40/// buffer-cache.
41///
42/// # Invariants
43/// - `data.as_ptr()` has 512-byte alignment: This is the minimal alignment
44///   required for Direct IO.
45pub struct FBuf {
46    ptr: NonNull<u8>,
47    cap: usize,
48    len: usize,
49}
50
51impl Drop for FBuf {
52    #[inline]
53    fn drop(&mut self) {
54        if self.cap != 0 {
55            recycle_or_dealloc(self.ptr, self.cap);
56        }
57    }
58}
59
60impl FBuf {
61    /// The alignment of the vector
62    pub const ALIGNMENT: usize = 512;
63
64    /// Maximum capacity of the vector.
65    /// Dictated by the requirements of
66    /// [`alloc::Layout`](https://doc.rust-lang.org/alloc/alloc/struct.Layout.html).
67    /// "`size`, when rounded up to the nearest multiple of `align`, must not
68    /// overflow `isize` (i.e. the rounded value must be less than or equal
69    /// to `isize::MAX`)".
70    pub const MAX_CAPACITY: usize = isize::MAX as usize - (Self::ALIGNMENT - 1);
71
72    /// Constructs a new, empty `FBuf`.
73    ///
74    /// The vector will not allocate until elements are pushed into it.
75    #[inline]
76    pub fn new() -> Self {
77        FBuf {
78            ptr: NonNull::dangling(),
79            cap: 0,
80            len: 0,
81        }
82    }
83
84    /// Constructs a new, empty `FBuf` with the specified capacity.
85    ///
86    /// The vector will be able to hold at least `capacity` bytes without
87    /// reallocating. If `capacity` is 0, the vector will not allocate.
88    #[inline]
89    pub fn with_capacity(capacity: usize) -> Self {
90        if capacity == 0 {
91            Self::new()
92        } else {
93            assert!(
94                capacity <= Self::MAX_CAPACITY,
95                "`capacity` cannot exceed isize::MAX - 15"
96            );
97            let (ptr, capacity) = acquire_allocation(capacity);
98            Self {
99                ptr,
100                cap: capacity,
101                len: 0,
102            }
103        }
104    }
105
106    #[inline]
107    fn layout(&self) -> alloc::Layout {
108        layout_for(self.cap)
109    }
110
111    /// Clears the vector, removing all values.
112    ///
113    /// Note that this method has no effect on the allocated capacity of the
114    /// vector.
115    #[inline]
116    pub fn clear(&mut self) {
117        self.len = 0;
118    }
119
120    /// Change capacity of vector.
121    ///
122    /// Will set capacity to at least `new_cap`.
123    /// Can be used to either grow or shrink capacity.
124    /// Backing memory will be reallocated.
125    ///
126    /// Usually the safe methods `reserve` or `reserve_exact` are a better
127    /// choice. This method only exists as a micro-optimization for very
128    /// performance-sensitive code where the calculation of capacity
129    /// required has already been performed, and you want to avoid doing it
130    /// again, or if you want to implement a different growth strategy.
131    ///
132    /// # Safety
133    ///
134    /// - `new_cap` must be less than or equal to
135    ///   [`MAX_CAPACITY`](FBuf::MAX_CAPACITY)
136    /// - `new_cap` must be greater than or equal to [`len()`](FBuf::len)
137    #[inline]
138    pub unsafe fn change_capacity(&mut self, new_cap: usize) {
139        unsafe {
140            debug_assert!(new_cap <= Self::MAX_CAPACITY);
141            debug_assert!(new_cap >= self.len);
142
143            if new_cap > 0 {
144                let (new_ptr, new_cap) = if self.cap > 0 {
145                    let new_ptr = alloc::realloc(self.ptr.as_ptr(), self.layout(), new_cap);
146                    if new_ptr.is_null() {
147                        alloc::handle_alloc_error(layout_for(new_cap));
148                    }
149                    (NonNull::new_unchecked(new_ptr), new_cap)
150                } else {
151                    acquire_allocation(new_cap)
152                };
153                self.ptr = new_ptr;
154                self.cap = new_cap;
155            } else if self.cap > 0 {
156                recycle_or_dealloc(self.ptr, self.cap);
157                self.ptr = NonNull::dangling();
158                self.cap = 0;
159            }
160        }
161    }
162
163    /// Shrinks the capacity of the vector as much as possible.
164    ///
165    /// It will drop down as close as possible to the length but the allocator
166    /// may still inform the vector that there is space for a few more
167    /// elements.
168    #[inline]
169    pub fn shrink_to_fit(&mut self) {
170        if self.cap != self.len {
171            // New capacity cannot exceed max as it's shrinking
172            unsafe { self.change_capacity(self.len) };
173        }
174    }
175
176    /// Returns an unsafe mutable pointer to the vector's buffer.
177    ///
178    /// The caller must ensure that the vector outlives the pointer this
179    /// function returns, or else it will end up pointing to garbage.
180    /// Modifying the vector may cause its buffer to be reallocated, which
181    /// would also make any pointers to it invalid.
182    #[inline]
183    pub fn as_mut_ptr(&mut self) -> *mut u8 {
184        self.ptr.as_ptr()
185    }
186
187    /// Extracts a mutable slice of the entire vector.
188    ///
189    /// Equivalent to `&mut s[..]`.
190    #[inline]
191    pub fn as_mut_slice(&mut self) -> &mut [u8] {
192        unsafe { slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
193    }
194
195    /// Returns a raw pointer to the vector's buffer.
196    ///
197    /// The caller must ensure that the vector outlives the pointer this
198    /// function returns, or else it will end up pointing to garbage.
199    /// Modifying the vector may cause its buffer to be reallocated, which
200    /// would also make any pointers to it invalid.
201    ///
202    /// The caller must also ensure that the memory the pointer
203    /// (non-transitively) points to is never written to (except inside an
204    /// `UnsafeCell`) using this pointer or any pointer derived from it. If
205    /// you need to mutate the contents of the slice, use
206    /// [`as_mut_ptr`](FBuf::as_mut_ptr).
207    #[inline]
208    pub fn as_ptr(&self) -> *const u8 {
209        self.ptr.as_ptr()
210    }
211
212    /// Extracts a slice containing the entire vector.
213    ///
214    /// Equivalent to `&s[..]`.
215    #[inline]
216    pub fn as_slice(&self) -> &[u8] {
217        unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
218    }
219
220    /// Returns the number of elements the vector can hold without reallocating.
221    #[inline]
222    pub fn capacity(&self) -> usize {
223        self.cap
224    }
225
226    /// Reserves capacity for at least `additional` more bytes to be inserted
227    /// into the given `FBuf`. The collection may reserve more space
228    /// to avoid frequent reallocations. After calling `reserve`, capacity
229    /// will be greater than or equal to `self.len() + additional`. Does
230    /// nothing if capacity is already sufficient.
231    ///
232    /// # Panics
233    ///
234    /// Panics if the new capacity exceeds `isize::MAX - 15` bytes.
235    #[inline]
236    pub fn reserve(&mut self, additional: usize) {
237        // Cannot wrap because capacity always exceeds len,
238        // but avoids having to handle potential overflow here
239        let remaining = self.cap.wrapping_sub(self.len);
240        if additional > remaining {
241            self.do_reserve(additional);
242        }
243    }
244
245    /// Extend capacity after `reserve` has found it's necessary.
246    ///
247    /// Actually performing the extension is in this separate function marked
248    /// `#[cold]` to hint to compiler that this branch is not often taken.
249    /// This keeps the path for common case where capacity is already sufficient
250    /// as fast as possible, and makes `reserve` more likely to be inlined.
251    /// This is the same trick that Rust's `Vec::reserve` uses.
252    #[cold]
253    fn do_reserve(&mut self, additional: usize) {
254        let new_cap = self
255            .len
256            .checked_add(additional)
257            .expect("cannot reserve a larger FBuf");
258        unsafe { self.grow_capacity_to(new_cap) };
259    }
260
261    /// Grows total capacity of vector to `new_cap` or more.
262    ///
263    /// Capacity after this call will be `new_cap` rounded up to next power of
264    /// 2, unless that would exceed maximum capacity, in which case capacity
265    /// is capped at the maximum.
266    ///
267    /// This is same growth strategy used by `reserve`, `push` and
268    /// `extend_from_slice`.
269    ///
270    /// Usually the safe methods `reserve` or `reserve_exact` are a better
271    /// choice. This method only exists as a micro-optimization for very
272    /// performance-sensitive code where where the calculation of capacity
273    /// required has already been performed, and you want to avoid doing it
274    /// again.
275    ///
276    /// Maximum capacity is `isize::MAX - 15` bytes.
277    ///
278    /// # Panics
279    ///
280    /// Panics if `new_cap` exceeds `isize::MAX - 15` bytes.
281    ///
282    /// # Safety
283    ///
284    /// - `new_cap` must be greater than current [`capacity()`](FBuf::capacity)
285    #[inline]
286    pub unsafe fn grow_capacity_to(&mut self, new_cap: usize) {
287        unsafe {
288            debug_assert!(new_cap > self.cap);
289
290            let new_cap = if new_cap > (isize::MAX as usize + 1) >> 1 {
291                // Rounding up to next power of 2 would result in `isize::MAX + 1` or higher,
292                // which exceeds max capacity. So cap at max instead.
293                assert!(
294                    new_cap <= Self::MAX_CAPACITY,
295                    "cannot reserve a larger FBuf"
296                );
297                Self::MAX_CAPACITY
298            } else {
299                // Cannot overflow due to check above
300                new_cap.next_power_of_two()
301            };
302            self.change_capacity(new_cap);
303        }
304    }
305
306    /// Resizes the Vec in-place so that len is equal to new_len.
307    ///
308    /// If new_len is greater than len, the Vec is extended by the difference,
309    /// with each additional slot filled with value. If new_len is less than
310    /// len, the Vec is simply truncated.
311    ///
312    /// # Panics
313    ///
314    /// Panics if the new length exceeds `isize::MAX - 15` bytes.
315    #[inline]
316    pub fn resize(&mut self, new_len: usize, value: u8) {
317        if new_len > self.len {
318            let additional = new_len - self.len;
319            self.reserve(additional);
320            unsafe {
321                core::ptr::write_bytes(self.ptr.as_ptr().add(self.len), value, additional);
322            }
323        }
324        unsafe {
325            self.set_len(new_len);
326        }
327    }
328
329    /// Returns `true` if the vector contains no elements.
330    #[inline]
331    pub fn is_empty(&self) -> bool {
332        self.len == 0
333    }
334
335    /// Returns the number of elements in the vector, also referred to as its
336    /// 'length'.
337    #[inline]
338    pub fn len(&self) -> usize {
339        self.len
340    }
341
342    /// Copies and appends all bytes in a slice to the `FBuf`.
343    ///
344    /// The elements of the slice are appended in-order.
345    #[inline]
346    pub fn extend_from_slice(&mut self, other: &[u8]) {
347        if !other.is_empty() {
348            self.reserve(other.len());
349            unsafe {
350                core::ptr::copy_nonoverlapping(
351                    other.as_ptr(),
352                    self.as_mut_ptr().add(self.len()),
353                    other.len(),
354                );
355            }
356            self.len += other.len();
357        }
358    }
359
360    /// Removes the last element from a vector and returns it, or `None` if it
361    /// is empty.
362    #[inline]
363    pub fn pop(&mut self) -> Option<u8> {
364        if self.len == 0 {
365            None
366        } else {
367            let result = self[self.len - 1];
368            self.len -= 1;
369            Some(result)
370        }
371    }
372
373    /// Appends an element to the back of a collection.
374    ///
375    /// # Panics
376    ///
377    /// Panics if the new capacity exceeds `isize::MAX - 15` bytes.
378    #[inline]
379    pub fn push(&mut self, value: u8) {
380        if self.len == self.cap {
381            self.reserve_for_push();
382        }
383
384        unsafe {
385            self.as_mut_ptr().add(self.len).write(value);
386            self.len += 1;
387        }
388    }
389
390    /// Extend capacity by at least 1 byte after `push` has found it's
391    /// necessary.
392    ///
393    /// Actually performing the extension is in this separate function marked
394    /// `#[cold]` to hint to compiler that this branch is not often taken.
395    /// This keeps the path for common case where capacity is already sufficient
396    /// as fast as possible, and makes `push` more likely to be inlined.
397    /// This is the same trick that Rust's `Vec::push` uses.
398    #[cold]
399    fn reserve_for_push(&mut self) {
400        // `len` is always less than `isize::MAX`, so no possibility of overflow here
401        let new_cap = self.len + 1;
402        unsafe { self.grow_capacity_to(new_cap) };
403    }
404
405    /// Reserves the minimum capacity for exactly `additional` more elements to
406    /// be inserted in the given `FBuf`. After calling
407    /// `reserve_exact`, capacity will be greater than or equal
408    /// to `self.len() + additional`. Does nothing if the capacity is already
409    /// sufficient.
410    ///
411    /// Note that the allocator may give the collection more space than it
412    /// requests. Therefore, capacity can not be relied upon to be precisely
413    /// minimal. Prefer reserve if future insertions are expected.
414    ///
415    /// # Panics
416    ///
417    /// Panics if the new capacity overflows `isize::MAX - 15`.
418    #[inline]
419    pub fn reserve_exact(&mut self, additional: usize) {
420        // This function does not use the hot/cold paths trick that `reserve`
421        // and `push` do, on assumption that user probably knows this will require
422        // an increase in capacity. Otherwise, they'd likely use `reserve`.
423        let new_cap = self
424            .len
425            .checked_add(additional)
426            .expect("cannot reserve a larger FBuf");
427        if new_cap > self.cap {
428            assert!(
429                new_cap <= Self::MAX_CAPACITY,
430                "cannot reserve a larger FBuf"
431            );
432            unsafe { self.change_capacity(new_cap) };
433        }
434    }
435
436    /// Forces the length of the vector to `new_len`.
437    ///
438    /// This is a low-level operation that maintains none of the normal
439    /// invariants of the type.
440    ///
441    /// # Safety
442    ///
443    /// - `new_len` must be less than or equal to [`capacity()`](FBuf::capacity)
444    /// - The elements at `old_len..new_len` must be initialized
445    #[inline]
446    pub unsafe fn set_len(&mut self, new_len: usize) {
447        debug_assert!(new_len <= self.capacity());
448
449        self.len = new_len;
450    }
451
452    /// Converts the vector into `Box<[u8]>`.
453    ///
454    /// This method reallocates and copies the underlying bytes. Any excess
455    /// capacity is dropped.
456    #[inline]
457    pub fn into_boxed_slice(self) -> Box<[u8]> {
458        self.into_vec().into_boxed_slice()
459    }
460
461    /// Creates an `FBuf` by copying the slice.
462    pub fn from_slice(slice: &[u8]) -> Self {
463        let mut fbuf = FBuf::new();
464        fbuf.extend_from_slice(slice);
465        fbuf
466    }
467
468    /// Converts the vector into `Vec<u8>`.
469    ///
470    /// This method reallocates and copies the underlying bytes. Any excess
471    /// capacity is dropped.
472    #[inline]
473    pub fn into_vec(self) -> Vec<u8> {
474        Vec::from(self.as_ref())
475    }
476
477    /// Reads all bytes until EOF from `r` and appends them to this
478    /// `FBuf`.
479    ///
480    /// If successful, this function will return the total number of bytes
481    /// read.
482    pub fn extend_from_reader<R: Read + ?Sized>(&mut self, r: &mut R) -> io::Result<usize> {
483        let start_len = self.len();
484        let start_cap = self.capacity();
485
486        // Extra initialized bytes from previous loop iteration.
487        let mut initialized = 0;
488        loop {
489            if self.len() == self.capacity() {
490                // No available capacity, reserve some space.
491                self.reserve(32);
492            }
493
494            let read_buf_start = unsafe { self.as_mut_ptr().add(self.len) };
495            let read_buf_len = self.capacity() - self.len();
496
497            // Initialize the uninitialized portion of the available space.
498            unsafe {
499                // The first `initialized` bytes don't need to be zeroed.
500                // This leaves us `read_buf_len - initialized` bytes to zero
501                // starting at `initialized`.
502                core::ptr::write_bytes(
503                    read_buf_start.add(initialized),
504                    0,
505                    read_buf_len - initialized,
506                );
507            }
508
509            // The entire read buffer is now initialized, so we can create a
510            // mutable slice of it.
511            let read_buf = unsafe { core::slice::from_raw_parts_mut(read_buf_start, read_buf_len) };
512
513            match r.read(read_buf) {
514                Ok(read) => {
515                    // We filled `read` additional bytes.
516                    unsafe {
517                        self.set_len(self.len() + read);
518                    }
519                    initialized = read_buf_len - read;
520
521                    if read == 0 {
522                        return Ok(self.len() - start_len);
523                    }
524                }
525                Err(e) if e.kind() == ErrorKind::Interrupted => continue,
526                Err(e) => return Err(e),
527            }
528
529            if self.len() == self.capacity() && self.capacity() == start_cap {
530                // The buffer might be an exact fit. Let's read into a probe buffer
531                // and see if it returns `Ok(0)`. If so, we've avoided an
532                // unnecessary doubling of the capacity. But if not, append the
533                // probe buffer to the primary buffer and let its capacity grow.
534                let mut probe = [0u8; 32];
535
536                loop {
537                    match r.read(&mut probe) {
538                        Ok(0) => return Ok(self.len() - start_len),
539                        Ok(n) => {
540                            self.extend_from_slice(&probe[..n]);
541                            break;
542                        }
543                        Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
544                        Err(e) => return Err(e),
545                    }
546                }
547            }
548        }
549    }
550
551    /// Reads `len` bytes from `file` at the given `offset` and appends them to
552    /// this `FBuf`.
553    ///
554    /// This avoids zero-initializing the buffer before reading into it.
555    pub fn read_exact_at(
556        &mut self,
557        file: &File,
558        mut offset: u64,
559        mut len: usize,
560    ) -> Result<(), IoError> {
561        self.reserve(len);
562        while len > 0 {
563            let retval = unsafe {
564                libc::pread(
565                    file.as_raw_fd(),
566                    self.as_mut_ptr().add(self.len) as *mut c_void,
567                    len,
568                    offset as i64,
569                )
570            };
571            match retval.cmp(&0) {
572                Ordering::Equal => return Err(ErrorKind::UnexpectedEof.into()),
573                Ordering::Less => {
574                    let error = IoError::last_os_error();
575                    if error.kind() != ErrorKind::Interrupted {
576                        return Err(error);
577                    }
578                }
579                Ordering::Greater => {
580                    self.len += retval as usize;
581                    len -= retval as usize;
582                    offset += retval as u64;
583                }
584            }
585        }
586        Ok(())
587    }
588}
589
590impl From<FBuf> for Vec<u8> {
591    #[inline]
592    fn from(aligned: FBuf) -> Self {
593        aligned.to_vec()
594    }
595}
596
597impl AsMut<[u8]> for FBuf {
598    #[inline]
599    fn as_mut(&mut self) -> &mut [u8] {
600        self.as_mut_slice()
601    }
602}
603
604impl AsRef<[u8]> for FBuf {
605    #[inline]
606    fn as_ref(&self) -> &[u8] {
607        self.as_slice()
608    }
609}
610
611impl Borrow<[u8]> for FBuf {
612    #[inline]
613    fn borrow(&self) -> &[u8] {
614        self.as_slice()
615    }
616}
617
618impl BorrowMut<[u8]> for FBuf {
619    #[inline]
620    fn borrow_mut(&mut self) -> &mut [u8] {
621        self.as_mut_slice()
622    }
623}
624
625impl Clone for FBuf {
626    #[inline]
627    fn clone(&self) -> Self {
628        unsafe {
629            let mut result = FBuf::with_capacity(self.len);
630            result.len = self.len;
631            core::ptr::copy_nonoverlapping(self.as_ptr(), result.as_mut_ptr(), self.len);
632            result
633        }
634    }
635}
636
637impl fmt::Debug for FBuf {
638    #[inline]
639    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
640        self.as_slice().fmt(f)
641    }
642}
643
644impl Default for FBuf {
645    #[inline]
646    fn default() -> Self {
647        Self::new()
648    }
649}
650
651impl Deref for FBuf {
652    type Target = [u8];
653
654    #[inline]
655    fn deref(&self) -> &Self::Target {
656        self.as_slice()
657    }
658}
659
660impl DerefMut for FBuf {
661    #[inline]
662    fn deref_mut(&mut self) -> &mut Self::Target {
663        self.as_mut_slice()
664    }
665}
666
667impl<I: slice::SliceIndex<[u8]>> Index<I> for FBuf {
668    type Output = <I as slice::SliceIndex<[u8]>>::Output;
669
670    #[inline]
671    fn index(&self, index: I) -> &Self::Output {
672        &self.as_slice()[index]
673    }
674}
675
676impl<I: slice::SliceIndex<[u8]>> IndexMut<I> for FBuf {
677    #[inline]
678    fn index_mut(&mut self, index: I) -> &mut Self::Output {
679        &mut self.as_mut_slice()[index]
680    }
681}
682
683impl io::Write for FBuf {
684    #[inline]
685    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
686        self.extend_from_slice(buf);
687        Ok(buf.len())
688    }
689
690    #[inline]
691    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
692        let len = bufs.iter().map(|b| b.len()).sum();
693        self.reserve(len);
694        for buf in bufs {
695            self.extend_from_slice(buf);
696        }
697        Ok(len)
698    }
699
700    fn flush(&mut self) -> io::Result<()> {
701        Ok(())
702    }
703
704    #[inline]
705    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
706        self.extend_from_slice(buf);
707        Ok(())
708    }
709}
710
711#[cfg(test)]
712impl Eq for FBuf {}
713
714#[cfg(test)]
715impl PartialEq<Self> for FBuf {
716    fn eq(&self, other: &Self) -> bool {
717        self.as_slice() == other.as_slice()
718    }
719}
720
721#[cfg(test)]
722impl PartialOrd for FBuf {
723    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
724        self.as_slice().partial_cmp(other.as_slice())
725    }
726}
727
728impl Archive for FBuf {
729    type Archived = ArchivedVec<u8>;
730    type Resolver = VecResolver;
731
732    #[inline]
733    unsafe fn resolve(&self, pos: usize, resolver: Self::Resolver, out: *mut Self::Archived) {
734        unsafe {
735            ArchivedVec::resolve_from_slice(self.as_slice(), pos, resolver, out);
736        }
737    }
738}
739
740impl<S: ScratchSpace + Serializer + ?Sized> Serialize<S> for FBuf {
741    #[inline]
742    fn serialize(&self, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
743        serializer.align(Self::ALIGNMENT)?;
744        ArchivedVec::<Archived<u8>>::serialize_from_slice(self.as_slice(), serializer)
745    }
746}
747
748// SAFETY: FBuf is safe to send to another thread
749unsafe impl Send for FBuf {}
750
751// SAFETY: FBuf is safe to share between threads
752unsafe impl Sync for FBuf {}
753
754impl Unpin for FBuf {}
755
756/// An [`rkyv`] serializer made specifically to work with [`FBuf`].
757///
758/// This serializer makes it easier for the compiler to perform emplacement
759/// optimizations and may give better performance than a basic
760/// `WriteSerializer`.
761#[derive(Debug)]
762pub struct FBufSerializer<A> {
763    pub inner: A,
764    limit: usize,
765}
766
767#[derive(Debug)]
768pub struct LimitExceeded;
769
770impl<A: Borrow<FBuf>> FBufSerializer<A> {
771    /// Creates a new `FBufSerializer` by wrapping a `FBuf`.
772    #[inline]
773    pub fn new(inner: A) -> Self {
774        Self {
775            inner,
776            limit: usize::MAX,
777        }
778    }
779
780    pub fn with_limit(self, limit: usize) -> Self {
781        Self { limit, ..self }
782    }
783
784    /// Consumes the serializer and returns the underlying type.
785    #[inline]
786    pub fn into_inner(self) -> A {
787        self.inner
788    }
789}
790
791impl<A: Default> Default for FBufSerializer<A> {
792    #[inline]
793    fn default() -> Self {
794        Self {
795            inner: A::default(),
796            limit: usize::MAX,
797        }
798    }
799}
800
801impl<A> Fallible for FBufSerializer<A> {
802    type Error = LimitExceeded;
803}
804
805impl<A: Borrow<FBuf> + BorrowMut<FBuf>> Serializer for FBufSerializer<A> {
806    #[inline]
807    fn pos(&self) -> usize {
808        self.inner.borrow().len()
809    }
810
811    #[inline]
812    fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
813        let vec = self.inner.borrow_mut();
814        if vec.len() + bytes.len() > self.limit {
815            Err(LimitExceeded)
816        } else {
817            vec.extend_from_slice(bytes);
818            Ok(())
819        }
820    }
821
822    #[inline]
823    unsafe fn resolve_aligned<T: Archive + ?Sized>(
824        &mut self,
825        value: &T,
826        resolver: T::Resolver,
827    ) -> Result<usize, Self::Error> {
828        unsafe {
829            let pos = self.pos();
830            debug_assert_eq!(pos & (mem::align_of::<T::Archived>() - 1), 0);
831            let vec = self.inner.borrow_mut();
832            let additional = mem::size_of::<T::Archived>();
833            if vec.len() + additional > self.limit {
834                return Err(LimitExceeded);
835            }
836            vec.reserve(additional);
837            vec.set_len(vec.len() + additional);
838
839            let ptr = vec.as_mut_ptr().add(pos).cast::<T::Archived>();
840            ptr.write_bytes(0, 1);
841            value.resolve(pos, resolver, ptr);
842
843            Ok(pos)
844        }
845    }
846
847    #[inline]
848    unsafe fn resolve_unsized_aligned<T: ArchiveUnsized + ?Sized>(
849        &mut self,
850        value: &T,
851        to: usize,
852        metadata_resolver: T::MetadataResolver,
853    ) -> Result<usize, Self::Error> {
854        unsafe {
855            let from = self.pos();
856            debug_assert_eq!(from & (mem::align_of::<RelPtr<T::Archived>>() - 1), 0);
857            let vec = self.inner.borrow_mut();
858            let additional = mem::size_of::<RelPtr<T::Archived>>();
859            if vec.len() + additional > self.limit {
860                return Err(LimitExceeded);
861            }
862            vec.reserve(additional);
863            vec.set_len(vec.len() + additional);
864
865            let ptr = vec.as_mut_ptr().add(from).cast::<RelPtr<T::Archived>>();
866            ptr.write_bytes(0, 1);
867
868            value.resolve_unsized(from, to, metadata_resolver, ptr);
869            Ok(from)
870        }
871    }
872}