| 1 |
use crate::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 unsafe fn from_raw_parts(ptr: *mut u8, window_bits: usize) -> Self { |
| 14 |
let len = (1 << window_bits) * 2; |
| 15 |
let buf = unsafe { WeakSliceMut::from_raw_parts_mut(ptr, len) }; |
| 16 |
|
| 17 |
Self { buf, window_bits } |
| 18 |
} |
| 19 |
|
| 20 |
pub fn as_ptr(&self) -> *const u8 { |
| 21 |
self.buf.as_ptr() |
| 22 |
} |
| 23 |
|
| 24 |
pub fn capacity(&self) -> usize { |
| 25 |
2 * (1 << self.window_bits) |
| 26 |
} |
| 27 |
|
| 28 |
/// Returns a shared reference to the filled portion of the buffer. |
| 29 |
#[inline] |
| 30 |
pub fn filled(&self) -> &[u8] { |
| 31 |
// SAFETY: `self.buf` has been initialized for at least `filled` elements |
| 32 |
unsafe { core::slice::from_raw_parts(self.buf.as_ptr().cast(), self.buf.len()) } |
| 33 |
} |
| 34 |
|
| 35 |
/// Returns a mutable reference to the filled portion of the buffer. |
| 36 |
#[inline] |
| 37 |
pub fn filled_mut(&mut self) -> &mut [u8] { |
| 38 |
// SAFETY: `self.buf` has been initialized for at least `filled` elements |
| 39 |
unsafe { core::slice::from_raw_parts_mut(self.buf.as_mut_ptr().cast(), self.buf.len()) } |
| 40 |
} |
| 41 |
|
| 42 |
/// # Safety |
| 43 |
/// |
| 44 |
/// `src` must point to `range.end - range.start` valid (initialized!) bytes |
| 45 |
pub unsafe fn copy_and_initialize(&mut self, range: core::ops::Range<usize>, src: *const u8) { |
| 46 |
let (start, end) = (range.start, range.end); |
| 47 |
|
| 48 |
let dst = self.buf.as_mut_slice()[range].as_mut_ptr(); |
| 49 |
unsafe { core::ptr::copy_nonoverlapping(src, dst, end - start) }; |
| 50 |
} |
| 51 |
} |