feat: Add nix-util crate with Context wrapper

(cherry picked from commit 6c8e116e8bbaecce2b77fd9e0db89f366b57f9b6)
This commit is contained in:
Robert Hensing 2024-02-16 09:59:51 +01:00
parent 61975ac8e4
commit 7ef434a6d7
5 changed files with 80 additions and 0 deletions

14
rust/Cargo.lock generated
View file

@ -11,6 +11,12 @@ dependencies = [
"memchr",
]
[[package]]
name = "anyhow"
version = "1.0.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "080e9890a082662b09c1ad45f567faeeb47f22b5fb23895fbe1e651e718e25ca"
[[package]]
name = "bindgen"
version = "0.69.4"
@ -166,6 +172,14 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "nix-util"
version = "0.1.0"
dependencies = [
"anyhow",
"nix-c-raw",
]
[[package]]
name = "nixops4"
version = "0.1.0"

View file

@ -1,5 +1,6 @@
[workspace]
members = [
"nix-c-raw",
"nix-util",
]
resolver = "2"

10
rust/nix-util/Cargo.toml Normal file
View file

@ -0,0 +1,10 @@
[package]
name = "nix-util"
version = "0.1.0"
edition = "2021"
[lib]
[dependencies]
anyhow = "1.0.79"
nix-c-raw = { path = "../nix-c-raw" }

View file

@ -0,0 +1,54 @@
use anyhow::{bail, Result};
use nix_c_raw as raw;
use std::ptr::null_mut;
use std::ptr::NonNull;
pub struct Context {
inner: NonNull<raw::nix_c_context>,
}
impl Context {
pub fn new() -> Self {
let ctx = unsafe { raw::nix_c_context_create() };
if ctx.is_null() {
panic!("nix_c_context_create returned a null pointer");
}
let ctx = Context {
inner: NonNull::new(ctx).unwrap(),
};
ctx
}
pub fn ptr(&self) -> *mut raw::nix_c_context {
self.inner.as_ptr()
}
pub fn check_err(&self) -> Result<()> {
let err = unsafe { raw::nix_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
let msgp = unsafe { raw::nix_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()? };
bail!("{}", msg);
}
Ok(())
}
}
impl Drop for Context {
fn drop(&mut self) {
unsafe {
raw::nix_c_context_free(self.inner.as_ptr());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn context_new_and_drop() {
// don't crash
let _c = Context::new();
}
}

1
rust/nix-util/src/lib.rs Normal file
View file

@ -0,0 +1 @@
pub mod context;