From: Ben Pfaff Date: Fri, 18 Jul 2025 01:12:26 +0000 (-0700) Subject: rust: Add element_offset() and subslice_range() functions. X-Git-Url: https://pintos-os.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=885e947e79c6177b332fd9a2473fe8b1a2e9fd59;p=pspp rust: Add element_offset() and subslice_range() functions. --- 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 + } +}