diff src/libpam/memory.rs @ 95:51c9d7e8261a

Return owned strings rather than borrowed strings. It's going to be irritating to have to work with strings borrowed from the PAM handle rather than just using your own. They're cheap enough to copy.
author Paul Fisher <paul@pfish.zone>
date Mon, 23 Jun 2025 14:03:44 -0400
parents efc2b56c8928
children b87100c5eed4
line wrap: on
line diff
--- a/src/libpam/memory.rs	Mon Jun 23 13:04:27 2025 -0400
+++ b/src/libpam/memory.rs	Mon Jun 23 14:03:44 2025 -0400
@@ -52,22 +52,16 @@
 /// # Safety
 ///
 /// It's on you to provide a valid string.
-pub unsafe fn copy_pam_string(result_ptr: *const c_char) -> Result<String> {
-    Ok(wrap_string(result_ptr)?
-        .map(String::from)
-        .unwrap_or_default())
-}
-
-/// Wraps a string returned from PAM as an `Option<&str>`.
-pub unsafe fn wrap_string<'a>(data: *const c_char) -> Result<Option<&'a str>> {
-    match NonNull::new(data.cast_mut()) {
-        Some(data) => Ok(Some(
+pub unsafe fn copy_pam_string(result_ptr: *const c_char) -> Result<Option<String>> {
+    let borrowed = match NonNull::new(result_ptr.cast_mut()) {
+        Some(data) => Some(
             CStr::from_ptr(data.as_ptr())
                 .to_str()
                 .map_err(|_| ErrorCode::ConversationError)?,
-        )),
-        None => Ok(None),
-    }
+        ),
+        None => return Ok(None),
+    };
+    Ok(borrowed.map(String::from))
 }
 
 /// Allocates a string with the given contents on the C heap.
@@ -192,11 +186,11 @@
         malloc_str("hell\0 there").unwrap_err();
         unsafe {
             let copied = copy_pam_string(str).unwrap();
-            assert_eq!("hello there", copied);
+            assert_eq!("hello there", copied.unwrap());
             zero_c_string(str);
             let idx_three = str.add(3).as_mut().unwrap();
             *idx_three = 0x80u8 as i8;
-            let zeroed = copy_pam_string(str).unwrap();
+            let zeroed = copy_pam_string(str).unwrap().unwrap();
             assert!(zeroed.is_empty());
             free(str);
         }