| 1 |
use crate::{allocate::Allocator, weak_slice::WeakSliceMut}; |
| 2 |
|
| 3 |
#[derive(Debug)] |
| 4 |
pub struct Window<'a> { |
| 5 |
// the full window allocation. This is longer than w_size so that operations don't need to |
| 6 |
// perform bounds checks. |
| 7 |
buf: WeakSliceMut<'a, u8>, |
| 8 |
|
| 9 |
window_bits: usize, |
| 10 |
} |
| 11 |
|
| 12 |
impl<'a> Window<'a> { |
| 13 |
pub fn new_in(alloc: &Allocator<'a>, window_bits: usize) -> Option<Self> { |
| 14 |
let len = 2 * ((1 << window_bits) + Self::padding()); |
| 15 |
let ptr = alloc.allocate_zeroed(len)?; |
| 16 |
// SAFETY: freshly allocated buffer |
| 17 |
let buf = unsafe { WeakSliceMut::from_raw_parts_mut(ptr.as_ptr(), len) }; |
| 18 |
|
| 19 |
Some(Self { buf, window_bits }) |
| 20 |
} |
| 21 |
|
| 22 |
pub fn clone_in(&self, alloc: &Allocator<'a>) -> Option<Self> { |
| 23 |
let mut clone = Self::new_in(alloc, self.window_bits)?; |
| 24 |
|
| 25 |
clone |
| 26 |
.buf |
| 27 |
.as_mut_slice() |
| 28 |
.copy_from_slice(self.buf.as_slice()); |
| 29 |
|
| 30 |
Some(clone) |
| 31 |
} |
| 32 |
|
| 33 |
/// # Safety |
| 34 |
/// |
| 35 |
/// [`Self`] must not be used after calling this function. |
| 36 |
pub unsafe fn drop_in(&mut self, alloc: &Allocator) { |
| 37 |
if !self.buf.is_empty() { |
| 38 |
let mut buf = core::mem::replace(&mut self.buf, WeakSliceMut::empty()); |
| 39 |
unsafe { alloc.deallocate(buf.as_mut_ptr(), buf.len()) }; |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
pub fn capacity(&self) -> usize { |
| 44 |
2 * (1 << self.window_bits) |
| 45 |
} |
| 46 |
|
| 47 |
/// Returns a shared reference to the filled portion of the buffer. |
| 48 |
#[inline] |
| 49 |
pub fn filled(&self) -> &[u8] { |
| 50 |
// SAFETY: `self.buf` has been initialized for at least `filled` elements |
| 51 |
unsafe { core::slice::from_raw_parts(self.buf.as_ptr().cast(), self.buf.len()) } |
| 52 |
} |
| 53 |
|
| 54 |
/// Returns a mutable reference to the filled portion of the buffer. |
| 55 |
#[inline] |
| 56 |
pub fn filled_mut(&mut self) -> &mut [u8] { |
| 57 |
// SAFETY: `self.buf` has been initialized for at least `filled` elements |
| 58 |
unsafe { core::slice::from_raw_parts_mut(self.buf.as_mut_ptr().cast(), self.buf.len()) } |
| 59 |
} |
| 60 |
|
| 61 |
/// # Safety |
| 62 |
/// |
| 63 |
/// `src` must point to `range.end - range.start` valid (initialized!) bytes |
| 64 |
pub unsafe fn copy_and_initialize(&mut self, range: core::ops::Range<usize>, src: *const u8) { |
| 65 |
let (start, end) = (range.start, range.end); |
| 66 |
|
| 67 |
let dst = self.buf.as_mut_slice()[range].as_mut_ptr(); |
| 68 |
unsafe { core::ptr::copy_nonoverlapping(src, dst, end - start) }; |
| 69 |
} |
| 70 |
|
| 71 |
// padding required so that SIMD operations going out-of-bounds are not a problem |
| 72 |
pub fn padding() -> usize { |
| 73 |
if crate::cpu_features::is_enabled_pclmulqdq() { |
| 74 |
8 |
| 75 |
} else { |
| 76 |
0 |
| 77 |
} |
| 78 |
} |
| 79 |
} |