|
| 1 | +// SPDX-License-Identifier: Apache-2.0 |
| 2 | +// SPDX-FileCopyrightText: Copyright the Vortex contributors |
| 3 | + |
| 4 | +use std::ptr; |
| 5 | + |
| 6 | +use vortex_error::VortexResult; |
| 7 | +use vortex_error::vortex_ensure; |
| 8 | + |
| 9 | +use crate::BufferMut; |
| 10 | + |
| 11 | +/// Writes slices sequentially into the spare capacity of an empty [`BufferMut`]. |
| 12 | +/// |
| 13 | +/// This is useful when the caller knows the final output length up front and wants to avoid |
| 14 | +/// repeatedly growing the initialized length while copying contiguous source slices. |
| 15 | +pub struct SpareBufferWriter<'a, T> { |
| 16 | + buffer: &'a mut BufferMut<T>, |
| 17 | + next: *mut T, |
| 18 | + remaining: usize, |
| 19 | + output_len: usize, |
| 20 | +} |
| 21 | + |
| 22 | +impl<'a, T: Copy> SpareBufferWriter<'a, T> { |
| 23 | + /// Creates a writer for `output_len` values in `buffer`'s spare capacity. |
| 24 | + /// |
| 25 | + /// The target buffer must be empty and have capacity for at least `output_len` values. |
| 26 | + pub fn new(buffer: &'a mut BufferMut<T>, output_len: usize) -> VortexResult<Self> { |
| 27 | + vortex_ensure!( |
| 28 | + buffer.is_empty(), |
| 29 | + "slice copy buffer already has {} initialized values", |
| 30 | + buffer.len() |
| 31 | + ); |
| 32 | + vortex_ensure!( |
| 33 | + output_len <= buffer.capacity(), |
| 34 | + "slice copy output length {output_len} exceeds buffer capacity {}", |
| 35 | + buffer.capacity() |
| 36 | + ); |
| 37 | + |
| 38 | + let next = buffer.spare_capacity_mut().as_mut_ptr().cast(); |
| 39 | + Ok(Self { |
| 40 | + buffer, |
| 41 | + next, |
| 42 | + remaining: output_len, |
| 43 | + output_len, |
| 44 | + }) |
| 45 | + } |
| 46 | + |
| 47 | + /// Copies `source` into the next output slots. |
| 48 | + #[inline] |
| 49 | + pub fn copy_slice(&mut self, source: &[T]) -> VortexResult<()> { |
| 50 | + vortex_ensure!( |
| 51 | + source.len() <= self.remaining, |
| 52 | + "slice copy length {} exceeds remaining output length {}", |
| 53 | + source.len(), |
| 54 | + self.remaining |
| 55 | + ); |
| 56 | + // SAFETY: the check above proves that `source` fits in the remaining output slots. |
| 57 | + unsafe { self.copy_slice_unchecked(source) }; |
| 58 | + Ok(()) |
| 59 | + } |
| 60 | + |
| 61 | + /// Copies `source` to the next output slots without checking the remaining output length. |
| 62 | + /// |
| 63 | + /// # Safety |
| 64 | + /// |
| 65 | + /// The caller must ensure that `source.len()` does not exceed the remaining output length. |
| 66 | + #[inline] |
| 67 | + pub unsafe fn copy_slice_unchecked(&mut self, source: &[T]) { |
| 68 | + debug_assert!(source.len() <= self.remaining); |
| 69 | + // SAFETY: `next` points to the first unwritten slot, the caller guarantees the source fits |
| 70 | + // in the remaining capacity, and the mutable buffer borrow prevents reallocation. |
| 71 | + unsafe { |
| 72 | + ptr::copy_nonoverlapping(source.as_ptr(), self.next, source.len()); |
| 73 | + self.next = self.next.add(source.len()); |
| 74 | + } |
| 75 | + self.remaining -= source.len(); |
| 76 | + } |
| 77 | + |
| 78 | + /// Sets the target buffer length after exactly `output_len` values have been written. |
| 79 | + pub fn finish(self) -> VortexResult<()> { |
| 80 | + vortex_ensure!( |
| 81 | + self.remaining == 0, |
| 82 | + "slice copy length {} does not match declared output length {}", |
| 83 | + self.output_len - self.remaining, |
| 84 | + self.output_len |
| 85 | + ); |
| 86 | + // SAFETY: successful calls to the copy methods initialized exactly `output_len` slots. |
| 87 | + unsafe { |
| 88 | + self.buffer.set_len(self.output_len); |
| 89 | + } |
| 90 | + Ok(()) |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +#[cfg(test)] |
| 95 | +mod tests { |
| 96 | + use vortex_error::VortexResult; |
| 97 | + |
| 98 | + use super::SpareBufferWriter; |
| 99 | + use crate::BufferMut; |
| 100 | + |
| 101 | + #[test] |
| 102 | + fn writes_slices_into_spare_capacity() -> VortexResult<()> { |
| 103 | + let mut buffer = BufferMut::with_capacity(4); |
| 104 | + |
| 105 | + let mut writer = SpareBufferWriter::new(&mut buffer, 4)?; |
| 106 | + writer.copy_slice(&[1u16, 2])?; |
| 107 | + writer.copy_slice(&[3u16, 4])?; |
| 108 | + writer.finish()?; |
| 109 | + |
| 110 | + assert_eq!(buffer.as_slice(), &[1u16, 2, 3, 4]); |
| 111 | + Ok(()) |
| 112 | + } |
| 113 | + |
| 114 | + #[test] |
| 115 | + fn rejects_overlong_copy() -> VortexResult<()> { |
| 116 | + let mut buffer = BufferMut::with_capacity(2); |
| 117 | + |
| 118 | + let mut writer = SpareBufferWriter::new(&mut buffer, 2)?; |
| 119 | + let error = writer.copy_slice(&[1u16, 2, 3]).unwrap_err(); |
| 120 | + |
| 121 | + assert!( |
| 122 | + error |
| 123 | + .to_string() |
| 124 | + .contains("exceeds remaining output length") |
| 125 | + ); |
| 126 | + Ok(()) |
| 127 | + } |
| 128 | + |
| 129 | + #[test] |
| 130 | + fn rejects_incomplete_finish() -> VortexResult<()> { |
| 131 | + let mut buffer = BufferMut::with_capacity(2); |
| 132 | + |
| 133 | + let writer = SpareBufferWriter::<u16>::new(&mut buffer, 2)?; |
| 134 | + let error = writer.finish().unwrap_err(); |
| 135 | + |
| 136 | + assert!( |
| 137 | + error |
| 138 | + .to_string() |
| 139 | + .contains("does not match declared output length") |
| 140 | + ); |
| 141 | + Ok(()) |
| 142 | + } |
| 143 | +} |
0 commit comments