diff --git a/bucket_map/src/bucket_storage.rs b/bucket_map/src/bucket_storage.rs index b03990f3c99930..a898ca49b66bfe 100644 --- a/bucket_map/src/bucket_storage.rs +++ b/bucket_map/src/bucket_storage.rs @@ -170,13 +170,7 @@ impl BucketStorage { } pub fn get(&self, ix: u64) -> &T { - let start = self.get_start_offset_no_header(ix); - let end = start + std::mem::size_of::(); - let item_slice: &[u8] = &self.mmap[start..end]; - unsafe { - let item = item_slice.as_ptr() as *const T; - &*item - } + &self.get_cell_slice::(ix, 1)[0] } pub(crate) fn get_start_offset_with_header(&self, ix: u64) -> usize { @@ -190,13 +184,18 @@ impl BucketStorage { pub fn get_cell_slice(&self, ix: u64, len: u64) -> &[T] { let start = self.get_start_offset_no_header(ix); - let end = start + std::mem::size_of::() * len as usize; - //debug!("GET slice {} {}", start, end); - let item_slice: &[u8] = &self.mmap[start..end]; - unsafe { - let item = item_slice.as_ptr() as *const T; - std::slice::from_raw_parts(item, len as usize) - } + let len = std::mem::size_of::() * len as usize; + let slice = { + let slice = &self.mmap[start..]; + debug_assert!(slice.len() >= len); + &slice[..len] + }; + let ptr = { + let ptr = slice.as_ptr() as *const T; + debug_assert!(ptr as usize % std::mem::align_of::() == 0); + ptr + }; + unsafe { std::slice::from_raw_parts(ptr, len) } } pub(crate) fn get_mut_from_parts(item_slice: &mut [u8]) -> &mut T { @@ -206,21 +205,23 @@ impl BucketStorage { } pub fn get_mut(&mut self, ix: u64) -> &mut T { - let start = self.get_start_offset_no_header(ix); - let item_slice = &mut self.mmap[start..]; - let item_slice = &mut item_slice[..std::mem::size_of::()]; - Self::get_mut_from_parts(item_slice) + &mut self.get_mut_cell_slice::(ix, 1)[0] } pub fn get_mut_cell_slice(&mut self, ix: u64, len: u64) -> &mut [T] { let start = self.get_start_offset_no_header(ix); - let end = start + std::mem::size_of::() * len as usize; - //debug!("GET mut slice {} {}", start, end); - let item_slice: &[u8] = &self.mmap[start..end]; - unsafe { - let item = item_slice.as_ptr() as *mut T; - std::slice::from_raw_parts_mut(item, len as usize) - } + let len = std::mem::size_of::() * len as usize; + let slice = { + let slice = &mut self.mmap[start..]; + debug_assert!(slice.len() >= len); + &mut slice[..len] + }; + let ptr = { + let ptr = slice.as_mut_ptr() as *mut T; + debug_assert!(ptr as usize % std::mem::align_of::() == 0); + ptr + }; + unsafe { std::slice::from_raw_parts_mut(ptr, len) } } fn new_map(