From 09542c9be075f2f9210e3e14c9e3f4deb5bfcd81 Mon Sep 17 00:00:00 2001 From: bit-aloo Date: Thu, 31 Jul 2025 20:04:00 +0530 Subject: [PATCH] ensure f64 slice view is properly aligned and sized --- core/vector/vector_types.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/core/vector/vector_types.rs b/core/vector/vector_types.rs index 7f4360174..37bc13731 100644 --- a/core/vector/vector_types.rs +++ b/core/vector/vector_types.rs @@ -54,7 +54,32 @@ impl Vector { unsafe { std::slice::from_raw_parts(ptr as *const f32, self.dims) } } + /// # Safety + /// + /// This method is used to reinterpret the underlying `Vec` data + /// as a `&[f64]` slice. This is only valid if: + /// - The buffer is correctly aligned for `f64` + /// - The length of the buffer is exactly `dims * size_of::()` pub fn as_f64_slice(&self) -> &[f64] { + if self.dims == 0 { + return &[]; + } + + assert_eq!( + self.data.len(), + self.dims * std::mem::size_of::(), + "data length must equal dims * size_of::()" + ); + + let ptr = self.data.as_ptr(); + let align = std::mem::align_of::(); + assert_eq!( + ptr.align_offset(align), + 0, + "data pointer must be aligned to {} bytes for f64 access", + align + ); + unsafe { std::slice::from_raw_parts(self.data.as_ptr() as *const f64, self.dims) } } }