Mercurial > crates > nonstick
comparison 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 |
comparison
equal
deleted
inserted
replaced
94:db167f96ba46 | 95:51c9d7e8261a |
---|---|
50 /// <code>pam_get_<var>whatever</var></code> function. | 50 /// <code>pam_get_<var>whatever</var></code> function. |
51 /// | 51 /// |
52 /// # Safety | 52 /// # Safety |
53 /// | 53 /// |
54 /// It's on you to provide a valid string. | 54 /// It's on you to provide a valid string. |
55 pub unsafe fn copy_pam_string(result_ptr: *const c_char) -> Result<String> { | 55 pub unsafe fn copy_pam_string(result_ptr: *const c_char) -> Result<Option<String>> { |
56 Ok(wrap_string(result_ptr)? | 56 let borrowed = match NonNull::new(result_ptr.cast_mut()) { |
57 .map(String::from) | 57 Some(data) => Some( |
58 .unwrap_or_default()) | |
59 } | |
60 | |
61 /// Wraps a string returned from PAM as an `Option<&str>`. | |
62 pub unsafe fn wrap_string<'a>(data: *const c_char) -> Result<Option<&'a str>> { | |
63 match NonNull::new(data.cast_mut()) { | |
64 Some(data) => Ok(Some( | |
65 CStr::from_ptr(data.as_ptr()) | 58 CStr::from_ptr(data.as_ptr()) |
66 .to_str() | 59 .to_str() |
67 .map_err(|_| ErrorCode::ConversationError)?, | 60 .map_err(|_| ErrorCode::ConversationError)?, |
68 )), | 61 ), |
69 None => Ok(None), | 62 None => return Ok(None), |
70 } | 63 }; |
64 Ok(borrowed.map(String::from)) | |
71 } | 65 } |
72 | 66 |
73 /// Allocates a string with the given contents on the C heap. | 67 /// Allocates a string with the given contents on the C heap. |
74 /// | 68 /// |
75 /// This is like [`CString::new`], but: | 69 /// This is like [`CString::new`], but: |
190 let str = malloc_str("hello there").unwrap(); | 184 let str = malloc_str("hello there").unwrap(); |
191 let str = str.as_ptr(); | 185 let str = str.as_ptr(); |
192 malloc_str("hell\0 there").unwrap_err(); | 186 malloc_str("hell\0 there").unwrap_err(); |
193 unsafe { | 187 unsafe { |
194 let copied = copy_pam_string(str).unwrap(); | 188 let copied = copy_pam_string(str).unwrap(); |
195 assert_eq!("hello there", copied); | 189 assert_eq!("hello there", copied.unwrap()); |
196 zero_c_string(str); | 190 zero_c_string(str); |
197 let idx_three = str.add(3).as_mut().unwrap(); | 191 let idx_three = str.add(3).as_mut().unwrap(); |
198 *idx_three = 0x80u8 as i8; | 192 *idx_three = 0x80u8 as i8; |
199 let zeroed = copy_pam_string(str).unwrap(); | 193 let zeroed = copy_pam_string(str).unwrap().unwrap(); |
200 assert!(zeroed.is_empty()); | 194 assert!(zeroed.is_empty()); |
201 free(str); | 195 free(str); |
202 } | 196 } |
203 } | 197 } |
204 | 198 |