From 885e947e79c6177b332fd9a2473fe8b1a2e9fd59 Mon Sep 17 00:00:00 2001 From: Ben Pfaff Date: Thu, 17 Jul 2025 18:12:26 -0700 Subject: [PATCH] rust: Add element_offset() and subslice_range() functions. --- rust/pspp/src/lib.rs | 55 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/rust/pspp/src/lib.rs b/rust/pspp/src/lib.rs index ee567c5d81..9ae4bdfcd9 100644 --- a/rust/pspp/src/lib.rs +++ b/rust/pspp/src/lib.rs @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License along with // this program. If not, see . +use std::ops::Range; + pub mod calendar; pub mod command; pub mod crypto; @@ -33,3 +35,56 @@ pub mod output; pub mod prompt; pub mod settings; pub mod sys; + +/// This is [slice::element_offset] copied out from the standard library so that +/// we can use it while it is still experimental. +#[allow(dead_code)] +pub(crate) fn element_offset(slice: &[T], element: &T) -> Option { + if size_of::() == 0 { + panic!("elements are zero-sized"); + } + + let slice_start = slice.as_ptr().addr(); + let elem_start = std::ptr::from_ref(element).addr(); + + let byte_offset = elem_start.wrapping_sub(slice_start); + + if byte_offset % size_of::() != 0 { + return None; + } + + let offset = byte_offset / size_of::(); + + if offset < slice.len() { + Some(offset) + } else { + None + } +} + +/// This is [slice::subslice_range] copied out from the standard library so that +/// we can use it while it is still experimental. +#[allow(dead_code)] +pub(crate) fn subslice_range(slice: &[T], subslice: &[T]) -> Option> { + if size_of::() == 0 { + panic!("elements are zero-sized"); + } + + let slice_start = slice.as_ptr().addr(); + let subslice_start = subslice.as_ptr().addr(); + + let byte_start = subslice_start.wrapping_sub(slice_start); + + if byte_start % size_of::() != 0 { + return None; + } + + let start = byte_start / size_of::(); + let end = start.wrapping_add(subslice.len()); + + if start <= slice.len() && end <= slice.len() { + Some(start..end) + } else { + None + } +} -- 2.30.2