Mercurial > crates > nonstick
comparison src/memory.rs @ 60:05cc2c27334f
The Big Refactor: clean up docs and exports.
- Brings the most important symbols in the library to the root
with `pub use` statements.
- Expands and updates documentation.
- Rearranges things extensively to make the external interface nicer
and make the structure easier to understand.
- Renames a few things (e.g. `Result`).
| author | Paul Fisher <paul@pfish.zone> |
|---|---|
| date | Wed, 21 May 2025 19:00:51 -0400 |
| parents | |
| children | bbe84835d6db |
comparison
equal
deleted
inserted
replaced
| 59:3f4a77aa88be | 60:05cc2c27334f |
|---|---|
| 1 //! Utility functions for dealing with memory copying and stuff. | |
| 2 | |
| 3 use crate::ErrorCode; | |
| 4 use libc::c_char; | |
| 5 use std::ffi::{CStr, CString}; | |
| 6 | |
| 7 /// Safely converts a `&str` option to a `CString` option. | |
| 8 pub fn option_cstr(prompt: Option<&str>) -> crate::Result<Option<CString>> { | |
| 9 prompt | |
| 10 .map(CString::new) | |
| 11 .transpose() | |
| 12 .map_err(|_| ErrorCode::ConversationError) | |
| 13 } | |
| 14 | |
| 15 /// Gets the pointer to the given CString, or a null pointer if absent. | |
| 16 pub fn prompt_ptr(prompt: Option<&CString>) -> *const c_char { | |
| 17 match prompt { | |
| 18 Some(c_str) => c_str.as_ptr(), | |
| 19 None => std::ptr::null(), | |
| 20 } | |
| 21 } | |
| 22 | |
| 23 /// Creates an owned copy of a string that is returned from a | |
| 24 /// <code>pam_get_<var>whatever</var></code> function. | |
| 25 pub fn copy_pam_string(result_ptr: *const c_char) -> crate::Result<String> { | |
| 26 // We really shouldn't get a null pointer back here, but if we do, return nothing. | |
| 27 if result_ptr.is_null() { | |
| 28 return Ok(String::new()); | |
| 29 } | |
| 30 let bytes = unsafe { CStr::from_ptr(result_ptr) }; | |
| 31 bytes | |
| 32 .to_str() | |
| 33 .map(String::from) | |
| 34 .map_err(|_| ErrorCode::ConversationError) | |
| 35 } |
