From c837c7cc3b688b2441c2ad0a2d1ef4dd79e5d51d Mon Sep 17 00:00:00 2001 From: Wolfgang Bumiller Date: Wed, 25 Nov 2020 12:08:51 +0100 Subject: [PATCH] add pv_ref, drop unsafe from pv_raw pv_raw itself doesn't actually dereference the pointer and performs the necessary checks to not be considered unsafe per se, the `pv_ref()` and `pv_mut_ref()` method now returns a mutable reference. Signed-off-by: Wolfgang Bumiller --- perlmod/src/scalar.rs | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/perlmod/src/scalar.rs b/perlmod/src/scalar.rs index 84d8e7d..bbd7f93 100644 --- a/perlmod/src/scalar.rs +++ b/perlmod/src/scalar.rs @@ -256,11 +256,7 @@ impl ScalarRef { } /// Interpret the byte string as a raw pointer. - /// - /// # Safety - /// - /// The user is responsible for making sure the underlying pointer is correct. - pub unsafe fn pv_raw(&self) -> Result<*mut T, Error> { + pub fn pv_raw(&self) -> Result<*mut T, Error> { let bytes = self.pv_bytes(); let bytes: [u8; mem::size_of::()] = bytes @@ -270,6 +266,25 @@ impl ScalarRef { Ok(usize::from_ne_bytes(bytes) as *mut T) } + /// Interpret the byte string as a pointer and return it as a reference for convenience. + /// + /// # Safety + /// + /// The user is responsible for making sure the underlying pointer is correct. + pub unsafe fn pv_ref(&self) -> Result<&T, Error> { + self.pv_raw().map(|p| unsafe { &*p }) + } + + /// Interpret the byte string as a pointer and return it as a mutable reference for + /// convenience. + /// + /// # Safety + /// + /// The user is responsible for making sure the underlying pointer is correct. + pub unsafe fn pv_mut_ref(&self) -> Result<&mut T, Error> { + self.pv_raw().map(|p| unsafe { &mut *p }) + } + /// Create another owned reference to this value. pub fn clone_ref(&self) -> Scalar { unsafe { Scalar::from_raw_ref(self.sv()) }