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 /// Converts the vector into `Vec<u8>`.
462 ///
463 /// This method reallocates and copies the underlying bytes. Any excess
464 /// capacity is dropped.
465 #[inline]
466 pub fn into_vec(self) -> Vec<u8> {
467 Vec::from(self.as_ref())
468 }
469
470 /// Reads all bytes until EOF from `r` and appends them to this
471 /// `FBuf`.
472 ///
473 /// If successful, this function will return the total number of bytes
474 /// read.
475 pub fn extend_from_reader<R: Read + ?Sized>(&mut self, r: &mut R) -> io::Result<usize> {
476 let start_len = self.len();
477 let start_cap = self.capacity();
478
479 // Extra initialized bytes from previous loop iteration.
480 let mut initialized = 0;
481 loop {
482 if self.len() == self.capacity() {
483 // No available capacity, reserve some space.
484 self.reserve(32);
485 }
486
487 let read_buf_start = unsafe { self.as_mut_ptr().add(self.len) };
488 let read_buf_len = self.capacity() - self.len();
489
490 // Initialize the uninitialized portion of the available space.
491 unsafe {
492 // The first `initialized` bytes don't need to be zeroed.
493 // This leaves us `read_buf_len - initialized` bytes to zero
494 // starting at `initialized`.
495 core::ptr::write_bytes(
496 read_buf_start.add(initialized),
497 0,
498 read_buf_len - initialized,
499 );
500 }
501
502 // The entire read buffer is now initialized, so we can create a
503 // mutable slice of it.
504 let read_buf = unsafe { core::slice::from_raw_parts_mut(read_buf_start, read_buf_len) };
505
506 match r.read(read_buf) {
507 Ok(read) => {
508 // We filled `read` additional bytes.
509 unsafe {
510 self.set_len(self.len() + read);
511 }
512 initialized = read_buf_len - read;
513
514 if read == 0 {
515 return Ok(self.len() - start_len);
516 }
517 }
518 Err(e) if e.kind() == ErrorKind::Interrupted => continue,
519 Err(e) => return Err(e),
520 }
521
522 if self.len() == self.capacity() && self.capacity() == start_cap {
523 // The buffer might be an exact fit. Let's read into a probe buffer
524 // and see if it returns `Ok(0)`. If so, we've avoided an
525 // unnecessary doubling of the capacity. But if not, append the
526 // probe buffer to the primary buffer and let its capacity grow.
527 let mut probe = [0u8; 32];
528
529 loop {
530 match r.read(&mut probe) {
531 Ok(0) => return Ok(self.len() - start_len),
532 Ok(n) => {
533 self.extend_from_slice(&probe[..n]);
534 break;
535 }
536 Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
537 Err(e) => return Err(e),
538 }
539 }
540 }
541 }
542 }
543
544 /// Reads `len` bytes from `file` at the given `offset` and appends them to
545 /// this `FBuf`.
546 ///
547 /// This avoids zero-initializing the buffer before reading into it.
548 pub fn read_exact_at(
549 &mut self,
550 file: &File,
551 mut offset: u64,
552 mut len: usize,
553 ) -> Result<(), IoError> {
554 self.reserve(len);
555 while len > 0 {
556 let retval = unsafe {
557 libc::pread(
558 file.as_raw_fd(),
559 self.as_mut_ptr().add(self.len) as *mut c_void,
560 len,
561 offset as i64,
562 )
563 };
564 match retval.cmp(&0) {
565 Ordering::Equal => return Err(ErrorKind::UnexpectedEof.into()),
566 Ordering::Less => {
567 let error = IoError::last_os_error();
568 if error.kind() != ErrorKind::Interrupted {
569 return Err(error);
570 }
571 }
572 Ordering::Greater => {
573 self.len += retval as usize;
574 len -= retval as usize;
575 offset += retval as u64;
576 }
577 }
578 }
579 Ok(())
580 }
581}
582
583impl From<FBuf> for Vec<u8> {
584 #[inline]
585 fn from(aligned: FBuf) -> Self {
586 aligned.to_vec()
587 }
588}
589
590impl AsMut<[u8]> for FBuf {
591 #[inline]
592 fn as_mut(&mut self) -> &mut [u8] {
593 self.as_mut_slice()
594 }
595}
596
597impl AsRef<[u8]> for FBuf {
598 #[inline]
599 fn as_ref(&self) -> &[u8] {
600 self.as_slice()
601 }
602}
603
604impl Borrow<[u8]> for FBuf {
605 #[inline]
606 fn borrow(&self) -> &[u8] {
607 self.as_slice()
608 }
609}
610
611impl BorrowMut<[u8]> for FBuf {
612 #[inline]
613 fn borrow_mut(&mut self) -> &mut [u8] {
614 self.as_mut_slice()
615 }
616}
617
618impl Clone for FBuf {
619 #[inline]
620 fn clone(&self) -> Self {
621 unsafe {
622 let mut result = FBuf::with_capacity(self.len);
623 result.len = self.len;
624 core::ptr::copy_nonoverlapping(self.as_ptr(), result.as_mut_ptr(), self.len);
625 result
626 }
627 }
628}
629
630impl fmt::Debug for FBuf {
631 #[inline]
632 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
633 self.as_slice().fmt(f)
634 }
635}
636
637impl Default for FBuf {
638 #[inline]
639 fn default() -> Self {
640 Self::new()
641 }
642}
643
644impl Deref for FBuf {
645 type Target = [u8];
646
647 #[inline]
648 fn deref(&self) -> &Self::Target {
649 self.as_slice()
650 }
651}
652
653impl DerefMut for FBuf {
654 #[inline]
655 fn deref_mut(&mut self) -> &mut Self::Target {
656 self.as_mut_slice()
657 }
658}
659
660impl<I: slice::SliceIndex<[u8]>> Index<I> for FBuf {
661 type Output = <I as slice::SliceIndex<[u8]>>::Output;
662
663 #[inline]
664 fn index(&self, index: I) -> &Self::Output {
665 &self.as_slice()[index]
666 }
667}
668
669impl<I: slice::SliceIndex<[u8]>> IndexMut<I> for FBuf {
670 #[inline]
671 fn index_mut(&mut self, index: I) -> &mut Self::Output {
672 &mut self.as_mut_slice()[index]
673 }
674}
675
676impl io::Write for FBuf {
677 #[inline]
678 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
679 self.extend_from_slice(buf);
680 Ok(buf.len())
681 }
682
683 #[inline]
684 fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
685 let len = bufs.iter().map(|b| b.len()).sum();
686 self.reserve(len);
687 for buf in bufs {
688 self.extend_from_slice(buf);
689 }
690 Ok(len)
691 }
692
693 fn flush(&mut self) -> io::Result<()> {
694 Ok(())
695 }
696
697 #[inline]
698 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
699 self.extend_from_slice(buf);
700 Ok(())
701 }
702}
703
704#[cfg(test)]
705impl Eq for FBuf {}
706
707#[cfg(test)]
708impl PartialEq<Self> for FBuf {
709 fn eq(&self, other: &Self) -> bool {
710 self.as_slice() == other.as_slice()
711 }
712}
713
714#[cfg(test)]
715impl PartialOrd for FBuf {
716 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
717 self.as_slice().partial_cmp(other.as_slice())
718 }
719}
720
721impl Archive for FBuf {
722 type Archived = ArchivedVec<u8>;
723 type Resolver = VecResolver;
724
725 #[inline]
726 unsafe fn resolve(&self, pos: usize, resolver: Self::Resolver, out: *mut Self::Archived) {
727 unsafe {
728 ArchivedVec::resolve_from_slice(self.as_slice(), pos, resolver, out);
729 }
730 }
731}
732
733impl<S: ScratchSpace + Serializer + ?Sized> Serialize<S> for FBuf {
734 #[inline]
735 fn serialize(&self, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
736 serializer.align(Self::ALIGNMENT)?;
737 ArchivedVec::<Archived<u8>>::serialize_from_slice(self.as_slice(), serializer)
738 }
739}
740
741// SAFETY: FBuf is safe to send to another thread
742unsafe impl Send for FBuf {}
743
744// SAFETY: FBuf is safe to share between threads
745unsafe impl Sync for FBuf {}
746
747impl Unpin for FBuf {}
748
749/// An [`rkyv`] serializer made specifically to work with [`FBuf`].
750///
751/// This serializer makes it easier for the compiler to perform emplacement
752/// optimizations and may give better performance than a basic
753/// `WriteSerializer`.
754#[derive(Debug)]
755pub struct FBufSerializer<A> {
756 inner: A,
757 limit: usize,
758}
759
760#[derive(Debug)]
761pub struct LimitExceeded;
762
763impl<A: Borrow<FBuf>> FBufSerializer<A> {
764 /// Creates a new `FBufSerializer` by wrapping a `Borrow<FBuf>`.
765 #[inline]
766 pub fn new(inner: A, limit: usize) -> Self {
767 Self { inner, limit }
768 }
769
770 /// Consumes the serializer and returns the underlying type.
771 #[inline]
772 pub fn into_inner(self) -> A {
773 self.inner
774 }
775}
776
777impl<A: Default> Default for FBufSerializer<A> {
778 #[inline]
779 fn default() -> Self {
780 Self {
781 inner: A::default(),
782 limit: usize::MAX,
783 }
784 }
785}
786
787impl<A> Fallible for FBufSerializer<A> {
788 type Error = LimitExceeded;
789}
790
791impl<A: Borrow<FBuf> + BorrowMut<FBuf>> Serializer for FBufSerializer<A> {
792 #[inline]
793 fn pos(&self) -> usize {
794 self.inner.borrow().len()
795 }
796
797 #[inline]
798 fn write(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
799 let vec = self.inner.borrow_mut();
800 if vec.len() + bytes.len() > self.limit {
801 Err(LimitExceeded)
802 } else {
803 vec.extend_from_slice(bytes);
804 Ok(())
805 }
806 }
807
808 #[inline]
809 unsafe fn resolve_aligned<T: Archive + ?Sized>(
810 &mut self,
811 value: &T,
812 resolver: T::Resolver,
813 ) -> Result<usize, Self::Error> {
814 unsafe {
815 let pos = self.pos();
816 debug_assert_eq!(pos & (mem::align_of::<T::Archived>() - 1), 0);
817 let vec = self.inner.borrow_mut();
818 let additional = mem::size_of::<T::Archived>();
819 if vec.len() + additional > self.limit {
820 return Err(LimitExceeded);
821 }
822 vec.reserve(additional);
823 vec.set_len(vec.len() + additional);
824
825 let ptr = vec.as_mut_ptr().add(pos).cast::<T::Archived>();
826 ptr.write_bytes(0, 1);
827 value.resolve(pos, resolver, ptr);
828
829 Ok(pos)
830 }
831 }
832
833 #[inline]
834 unsafe fn resolve_unsized_aligned<T: ArchiveUnsized + ?Sized>(
835 &mut self,
836 value: &T,
837 to: usize,
838 metadata_resolver: T::MetadataResolver,
839 ) -> Result<usize, Self::Error> {
840 unsafe {
841 let from = self.pos();
842 debug_assert_eq!(from & (mem::align_of::<RelPtr<T::Archived>>() - 1), 0);
843 let vec = self.inner.borrow_mut();
844 let additional = mem::size_of::<RelPtr<T::Archived>>();
845 if vec.len() + additional > self.limit {
846 return Err(LimitExceeded);
847 }
848 vec.reserve(additional);
849 vec.set_len(vec.len() + additional);
850
851 let ptr = vec.as_mut_ptr().add(from).cast::<RelPtr<T::Archived>>();
852 ptr.write_bytes(0, 1);
853
854 value.resolve_unsized(from, to, metadata_resolver, ptr);
855 Ok(from)
856 }
857 }
858}