error checking tweaks

(cherry picked from commit 6ac38519b710e69a0c30eb0fe8fc5fa712168cb8)
This commit is contained in:
Taeer Bar-Yam 2024-05-09 12:41:34 -04:00 committed by Robert Hensing
parent c2159c8834
commit 48af0f9e41
5 changed files with 14 additions and 8 deletions

View file

@ -11,6 +11,8 @@ impl Context {
pub fn new() -> Self {
let ctx = unsafe { raw::c_context_create() };
if ctx.is_null() {
// We've failed to allocate a (relatively small) Context struct.
// We're almost certainly going to crash anyways.
panic!("nix_c_context_create returned a null pointer");
}
let ctx = Context {
@ -24,7 +26,7 @@ impl Context {
pub fn check_err(&self) -> Result<()> {
let err = unsafe { raw::err_code(self.inner.as_ptr()) };
if err != raw::NIX_OK.try_into().unwrap() {
// msgp is a borrowed pointer, so we don't need to free it
// msgp is a borrowed pointer (pointing into the context), so we don't need to free it
let msgp = unsafe { raw::err_msg(null_mut(), self.inner.as_ptr(), null_mut()) };
// Turn the i8 pointer into a Rust string by copying
let msg: &str = unsafe { core::ffi::CStr::from_ptr(msgp).to_str()? };

View file

@ -1,6 +1,8 @@
/// Callback for nix_store_get_uri and other functions that return a string.
///
/// This function is used by the other nix_* crates, and you should never need to call it yourself.
///
/// Some functions in the nix library "return" strings without giving you ownership over them, by letting you pass a callback function that gets to look at that string. This callback simply turns that string pointer into an owned rust String.
pub unsafe extern "C" fn callback_get_vec_u8(
start: *const ::std::os::raw::c_char,
n: std::os::raw::c_uint,