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