diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..3550a30 --- /dev/null +++ b/.envrc @@ -0,0 +1 @@ +use flake diff --git a/examples/bus-blocking.rs b/examples/bus-blocking.rs index e0af60a..ee60ba4 100644 --- a/examples/bus-blocking.rs +++ b/examples/bus-blocking.rs @@ -7,15 +7,15 @@ fn main() { let bn = bus::BusName::from_bytes(b"com.codyps.systemd-test\0").unwrap(); bus.request_name(bn, 0).unwrap(); - println!("got name {:?}", bn); + println!("got name {bn:?}"); let op = bus::ObjectPath::from_bytes(b"/com/codyps/systemd_test\0").unwrap(); bus.add_object(op, |m| { - println!("message: {:?}", m); + println!("message: {m:?}"); Ok(()) }) .unwrap(); - println!("added object: {:?}", op); + println!("added object: {op:?}"); loop { println!("wait?"); diff --git a/examples/journal-logger.rs b/examples/journal-logger.rs index 7d4c0f4..99dcf3e 100644 --- a/examples/journal-logger.rs +++ b/examples/journal-logger.rs @@ -3,7 +3,6 @@ #[cfg(feature = "journal")] mod x { //! Follow future journal log messages and print up to 100 of them. - use std::io::ErrorKind; use systemd::journal::{self, JournalRecord, JournalSeek}; use systemd::Error; @@ -30,23 +29,23 @@ mod x { let mut i = 0; reader .watch_all_elements(|record: JournalRecord| { - let unit = record.get(KEY_UNIT).ok_or_else(|| { - Error::new(ErrorKind::Other, "Could not get unit from record") - })?; - let message = record.get(KEY_MESSAGE).ok_or_else(|| { - Error::new(ErrorKind::Other, "Could not get message from record") - })?; - println!("[{}] {}", unit, message); + let unit = record + .get(KEY_UNIT) + .ok_or_else(|| Error::other("Could not get unit from record"))?; + let message = record + .get(KEY_MESSAGE) + .ok_or_else(|| Error::other("Could not get message from record"))?; + println!("[{unit}] {message}"); i += 1; if i < MAX_MESSAGES { Ok(()) } else { - Err(Error::new(ErrorKind::Other, "Done watching")) + Err(Error::other("Done watching")) } }) .unwrap_or_else(|e| { - println!("Stop watching log. Reason: {}", e); + println!("Stop watching log. Reason: {e}"); }); println!("End of example."); diff --git a/examples/journal-reader.rs b/examples/journal-reader.rs index 0173fbf..a8a68a3 100644 --- a/examples/journal-reader.rs +++ b/examples/journal-reader.rs @@ -46,7 +46,7 @@ mod x { .map(|v| v.into_owned()) }); - println!("[{:?}] {:?}", unit, message); + println!("[{unit:?}] {message:?}"); i += 1; if i >= MAX_MESSAGES { diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..52f2185 --- /dev/null +++ b/flake.lock @@ -0,0 +1,60 @@ +{ + "nodes": { + "flake-utils": { + "inputs": { + "systems": "systems" + }, + "locked": { + "lastModified": 1731533236, + "narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "11707dc2f618dd54ca8739b309ec4fc024de578b", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1752683762, + "narHash": "sha256-CVC4bpthYhKk4Qb4mt00SqfJ7CJ4vfTX06pLN2OHa1c=", + "owner": "NixOS", + "repo": "nixpkgs", + "rev": "fa64ec5c1ca6f17746f3defedb988b9248e97616", + "type": "github" + }, + "original": { + "id": "nixpkgs", + "ref": "nixpkgs-unstable", + "type": "indirect" + } + }, + "root": { + "inputs": { + "flake-utils": "flake-utils", + "nixpkgs": "nixpkgs" + } + }, + "systems": { + "locked": { + "lastModified": 1681028828, + "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", + "owner": "nix-systems", + "repo": "default", + "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", + "type": "github" + }, + "original": { + "owner": "nix-systems", + "repo": "default", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..393b752 --- /dev/null +++ b/flake.nix @@ -0,0 +1,34 @@ +{ + inputs = { + nixpkgs.url = "nixpkgs/nixpkgs-unstable"; + flake-utils.url = "github:numtide/flake-utils"; + }; + + outputs = { self, flake-utils, nixpkgs }: + flake-utils.lib.eachDefaultSystem (system: + let + pkgs = ((import nixpkgs) { + inherit system; + }); + in + { + formatter = pkgs.nixpkgs-fmt; + + devShells.default = pkgs.mkShell { + nativeBuildInputs = with pkgs; [ + rustc + cargo + rustfmt + sccache + clippy + rust-analyzer + systemd + pkg-config + ]; + + RUSTC_WRAPPER = "sccache"; + RUST_SRC_PATH = "${pkgs.rust.packages.stable.rustPlatform.rustLibSrc}"; + }; + } + ); +} diff --git a/libsystemd-sys/build.rs b/libsystemd-sys/build.rs index 0f21681..54ef67d 100644 --- a/libsystemd-sys/build.rs +++ b/libsystemd-sys/build.rs @@ -5,15 +5,15 @@ fn main() { let name_upper = name.to_ascii_uppercase(); let mut be = build_env::BuildEnv::from_env().unwrap(); - let lib_var = format!("{}_LIBS", name_upper); - let lib_dir_var = format!("{}_LIB_DIR", name_upper); + let lib_var = format!("{name_upper}_LIBS"); + let lib_dir_var = format!("{name_upper}_LIB_DIR"); let libs = be.var(lib_var); let lib_dir = match be.var(lib_dir_var.clone()) { Some(lib_dir) => lib_dir, None => { // No lib_dir specified, use pkg-config - let ln_vn = format!("{}_PKG_NAME", name_upper); + let ln_vn = format!("{name_upper}_PKG_NAME"); let library_name = be .var(&ln_vn) .map(|v| { @@ -24,7 +24,7 @@ fn main() { ) }) }) - .unwrap_or_else(|| format!("lib{}", name)); + .unwrap_or_else(|| format!("lib{name}")); let library = pkg_config::find_library(&library_name); @@ -34,7 +34,7 @@ fn main() { return; } Err(error) => { - eprintln!("pkg_config could not find {:?}: {}", library_name, error); + eprintln!("pkg_config could not find {library_name:?}: {error}"); std::process::exit(1); } }; @@ -57,11 +57,11 @@ fn main() { Some(libs) => { //let libs = libs.expect(&format!("non utf-8 value provided in {}", lib_var)); for lib in libs.into_string().unwrap().split(':') { - println!("cargo:rustc-link-lib={}", lib); + println!("cargo:rustc-link-lib={lib}"); } } None => { - println!("cargo:rustc-link-lib={}", name); + println!("cargo:rustc-link-lib={name}"); } } } diff --git a/src/bus/mod.rs b/src/bus/mod.rs index 6165f21..94bdeb7 100644 --- a/src/bus/mod.rs +++ b/src/bus/mod.rs @@ -16,6 +16,7 @@ // than what is possible with sd-bus directly. //use enumflags2_derive::EnumFlags; +use crate::ffi_result; use ffi::{c_char, c_int, c_void, pid_t}; use foreign_types::{foreign_type, ForeignType, ForeignTypeRef}; use std::ffi::CStr; @@ -867,21 +868,21 @@ impl Bus { #[inline] pub fn default() -> crate::Result { let mut b = MaybeUninit::uninit(); - sd_try!(ffi::bus::sd_bus_default(b.as_mut_ptr())); + ffi_result(unsafe { ffi::bus::sd_bus_default(b.as_mut_ptr()) })?; Ok(unsafe { Bus::from_ptr(b.assume_init()) }) } #[inline] pub fn default_user() -> crate::Result { let mut b = MaybeUninit::uninit(); - sd_try!(ffi::bus::sd_bus_default_user(b.as_mut_ptr())); + ffi_result(unsafe { ffi::bus::sd_bus_default_user(b.as_mut_ptr()) })?; Ok(unsafe { Bus::from_ptr(b.assume_init()) }) } #[inline] pub fn default_system() -> super::Result { let mut b = MaybeUninit::uninit(); - sd_try!(ffi::bus::sd_bus_default_system(b.as_mut_ptr())); + ffi_result(unsafe { ffi::bus::sd_bus_default_system(b.as_mut_ptr()) })?; Ok(unsafe { Bus::from_ptr(b.assume_init()) }) } } @@ -929,7 +930,7 @@ impl BusRef { /// [`sd_bus_get_fd`]: https://www.freedesktop.org/software/systemd/man/sd_bus_get_fd.html #[inline] pub fn fd(&self) -> super::Result { - Ok(sd_try!(ffi::bus::sd_bus_get_fd(self.as_ptr()))) + ffi_result(unsafe { ffi::bus::sd_bus_get_fd(self.as_ptr()) }) } /// Returns the I/O events to wait for, suitable for passing to poll or a similar call. @@ -940,7 +941,7 @@ impl BusRef { /// [`sd_bus_get_events`]: https://www.freedesktop.org/software/systemd/man/sd_bus_get_events.html #[inline] pub fn events(&self) -> super::Result { - Ok(sd_try!(ffi::bus::sd_bus_get_events(self.as_ptr()))) + ffi_result(unsafe { ffi::bus::sd_bus_get_events(self.as_ptr()) }) } /// Returns the time-out in us to pass to `poll()` or a similar call when waiting for events on @@ -952,7 +953,7 @@ impl BusRef { #[inline] pub fn timeout(&self) -> super::Result { let mut b = MaybeUninit::uninit(); - sd_try!(ffi::bus::sd_bus_get_timeout(self.as_ptr(), b.as_mut_ptr())); + ffi_result(unsafe { ffi::bus::sd_bus_get_timeout(self.as_ptr(), b.as_mut_ptr()) })?; let b = unsafe { b.assume_init() }; Ok(b) } @@ -971,7 +972,7 @@ impl BusRef { #[inline] pub fn process(&mut self) -> super::Result>> { let mut b = MaybeUninit::uninit(); - let r = sd_try!(ffi::bus::sd_bus_process(self.as_ptr(), b.as_mut_ptr())); + let r = ffi_result(unsafe { ffi::bus::sd_bus_process(self.as_ptr(), b.as_mut_ptr()) })?; if r > 0 { let b = unsafe { b.assume_init() }; if b.is_null() { @@ -993,11 +994,9 @@ impl BusRef { max_priority: i64, ) -> super::Result>> { let mut b = MaybeUninit::uninit(); - let r = sd_try!(ffi::bus::sd_bus_process_priority( - self.as_ptr(), - max_priority, - b.as_mut_ptr() - )); + let r = ffi_result(unsafe { + ffi::bus::sd_bus_process_priority(self.as_ptr(), max_priority, b.as_mut_ptr()) + })?; if r > 0 { let b = unsafe { b.assume_init() }; if b.is_null() { @@ -1023,10 +1022,12 @@ impl BusRef { /// [`sd_bus_wait`]: https://www.freedesktop.org/software/systemd/man/sd_bus_wait.html #[inline] pub fn wait(&mut self, timeout: Option) -> super::Result { - Ok(sd_try!(ffi::bus::sd_bus_wait( - self.as_ptr(), - timeout.map(usec_from_duration).unwrap_or(u64::MAX) - )) > 0) + Ok(ffi_result(unsafe { + ffi::bus::sd_bus_wait( + self.as_ptr(), + timeout.map(usec_from_duration).unwrap_or(u64::MAX), + ) + })? > 0) } /// Get the unique name (address) of this connection to this `Bus`. @@ -1039,23 +1040,20 @@ impl BusRef { #[inline] pub fn unique_name(&self) -> super::Result<&BusName> { let mut e = MaybeUninit::uninit(); - sd_try!(ffi::bus::sd_bus_get_unique_name( - self.as_ptr(), - e.as_mut_ptr() - )); + ffi_result(unsafe { ffi::bus::sd_bus_get_unique_name(self.as_ptr(), e.as_mut_ptr()) })?; let e = unsafe { e.assume_init() }; Ok(unsafe { BusName::from_ptr_unchecked(e) }) } pub fn scope(&self) -> super::Result<&CStr> { let mut ret = ptr::null(); - sd_try!(ffi::bus::sd_bus_get_scope(self.as_ptr(), &mut ret)); + ffi_result(unsafe { ffi::bus::sd_bus_get_scope(self.as_ptr(), &mut ret) })?; Ok(unsafe { CStr::from_ptr(ret) }) } pub fn tid(&self) -> super::Result { let mut ret = 0; - sd_try!(ffi::bus::sd_bus_get_tid(self.as_ptr(), &mut ret)); + ffi_result(unsafe { ffi::bus::sd_bus_get_tid(self.as_ptr(), &mut ret) })?; Ok(ret) } @@ -1063,13 +1061,13 @@ impl BusRef { pub fn description(&self) -> super::Result<&CStr> { let mut ret = ptr::null(); - sd_try!(ffi::bus::sd_bus_get_description(self.as_ptr(), &mut ret)); + ffi_result(unsafe { ffi::bus::sd_bus_get_description(self.as_ptr(), &mut ret) })?; Ok(unsafe { CStr::from_ptr(ret) }) } pub fn address(&self) -> super::Result<&CStr> { let mut ret = ptr::null(); - sd_try!(ffi::bus::sd_bus_get_address(self.as_ptr(), &mut ret)); + ffi_result(unsafe { ffi::bus::sd_bus_get_address(self.as_ptr(), &mut ret) })?; Ok(unsafe { CStr::from_ptr(ret) }) } @@ -1086,13 +1084,13 @@ impl BusRef { pub fn n_queued_write(&self) -> super::Result { let mut ret = Default::default(); - sd_try!(ffi::bus::sd_bus_get_n_queued_write(self.as_ptr(), &mut ret)); + ffi_result(unsafe { ffi::bus::sd_bus_get_n_queued_write(self.as_ptr(), &mut ret) })?; Ok(ret) } pub fn n_queued_read(&self) -> super::Result { let mut ret = Default::default(); - sd_try!(ffi::bus::sd_bus_get_n_queued_read(self.as_ptr(), &mut ret)); + ffi_result(unsafe { ffi::bus::sd_bus_get_n_queued_read(self.as_ptr(), &mut ret) })?; Ok(ret) } @@ -1105,10 +1103,7 @@ impl BusRef { pub fn method_call_timeout(&self) -> super::Result { let mut ret = Default::default(); - sd_try!(ffi::bus::sd_bus_get_method_call_timeout( - self.as_ptr(), - &mut ret - )); + ffi_result(unsafe { ffi::bus::sd_bus_get_method_call_timeout(self.as_ptr(), &mut ret) })?; Ok(ret) } @@ -1130,13 +1125,15 @@ impl BusRef { member: &MemberName, ) -> super::Result { let mut m = MaybeUninit::uninit(); - sd_try!(ffi::bus::sd_bus_message_new_signal( - self.as_ptr(), - m.as_mut_ptr(), - path.as_ptr() as *const _, - interface.as_ptr() as *const _, - member.as_ptr() as *const _ - )); + ffi_result(unsafe { + ffi::bus::sd_bus_message_new_signal( + self.as_ptr(), + m.as_mut_ptr(), + path.as_ptr() as *const _, + interface.as_ptr() as *const _, + member.as_ptr() as *const _, + ) + })?; let m = unsafe { m.assume_init() }; Ok(unsafe { Message::from_ptr(m) }) } @@ -1153,14 +1150,16 @@ impl BusRef { member: &MemberName, ) -> super::Result { let mut m = MaybeUninit::uninit(); - sd_try!(ffi::bus::sd_bus_message_new_method_call( - self.as_ptr(), - m.as_mut_ptr(), - dest as *const _ as *const _, - path as *const _ as *const _, - interface as *const _ as *const _, - member as *const _ as *const _ - )); + ffi_result(unsafe { + ffi::bus::sd_bus_message_new_method_call( + self.as_ptr(), + m.as_mut_ptr(), + dest as *const _ as *const _, + path as *const _ as *const _, + interface as *const _ as *const _, + member as *const _ as *const _, + ) + })?; let m = unsafe { m.assume_init() }; Ok(unsafe { Message::from_ptr(m) }) } @@ -1176,11 +1175,9 @@ impl BusRef { /// [`sd_bus_request_name`]: https://www.freedesktop.org/software/systemd/man/sd_bus_request_name.html #[inline] pub fn request_name(&mut self, name: &BusName, flags: u64) -> super::Result<()> { - sd_try!(ffi::bus::sd_bus_request_name( - self.as_ptr(), - name as *const _ as *const _, - flags - )); + ffi_result(unsafe { + ffi::bus::sd_bus_request_name(self.as_ptr(), name as *const _ as *const _, flags) + })?; Ok(()) } @@ -1231,10 +1228,9 @@ impl BusRef { /// This blocks. To get async behavior, use `request_name` directly. #[inline] pub fn release_name(&self, name: &BusName) -> super::Result<()> { - sd_try!(ffi::bus::sd_bus_release_name( - self.as_ptr(), - name as *const _ as *const _ - )); + ffi_result(unsafe { + ffi::bus::sd_bus_release_name(self.as_ptr(), name as *const _ as *const _) + })?; Ok(()) } @@ -1279,11 +1275,13 @@ impl BusRef { #[inline] pub fn add_object_manager(&self, path: &ObjectPath) -> super::Result<()> { - sd_try!(ffi::bus::sd_bus_add_object_manager( - self.as_ptr(), - ptr::null_mut(), - path as *const _ as *const _ - )); + ffi_result(unsafe { + ffi::bus::sd_bus_add_object_manager( + self.as_ptr(), + ptr::null_mut(), + path as *const _ as *const _, + ) + })?; Ok(()) } @@ -1294,12 +1292,12 @@ impl BusRef { // userdata: T) // -> super::Result<()> { // let u = Box::into_raw(Box::new(userdata)); - // sd_try!(ffi::bus::sd_bus_add_object_vtable(self.raw, + // ffi_result(unsafe {ffi::bus::sd_bus_add_object_vtable(self.raw, // ptr::null_mut(), // path.as_ptr() as *const _, // interface.as_ptr() as *const _, // vtable.as_ptr(), - // Box::into_raw(Box::new(T)))); + // Box::into_raw(Box::new(T)))})?; // Ok(()) // } @@ -1403,10 +1401,9 @@ impl MessageRef { /// [`sd_bus_message_set_destination`]: https://www.freedesktop.org/software/systemd/man/sd_bus_message_set_destination.html #[inline] pub fn set_destination(&mut self, dest: &BusName) -> super::Result<()> { - sd_try!(ffi::bus::sd_bus_message_set_destination( - self.as_ptr(), - dest as *const _ as *const _ - )); + ffi_result(unsafe { + ffi::bus::sd_bus_message_set_destination(self.as_ptr(), dest as *const _ as *const _) + })?; Ok(()) } @@ -1429,10 +1426,9 @@ impl MessageRef { /// [`sd_bus_message_set_auto_start`]: https://www.freedesktop.org/software/systemd/man/sd_bus_message_set_auto_start.html #[inline] pub fn set_auto_start(&mut self, yes: bool) -> super::Result<()> { - sd_try!(ffi::bus::sd_bus_message_set_auto_start( - self.as_ptr(), - yes as c_int - )); + ffi_result(unsafe { + ffi::bus::sd_bus_message_set_auto_start(self.as_ptr(), yes as c_int) + })?; Ok(()) } @@ -1602,11 +1598,9 @@ impl MessageRef { pub fn send(&mut self) -> super::Result { // self.bus().send(self) let mut m = MaybeUninit::uninit(); - sd_try!(ffi::bus::sd_bus_send( - ptr::null_mut(), - self.as_ptr(), - m.as_mut_ptr() - )); + ffi_result(unsafe { + ffi::bus::sd_bus_send(ptr::null_mut(), self.as_ptr(), m.as_mut_ptr()) + })?; let m = unsafe { m.assume_init() }; Ok(m) } @@ -1620,11 +1614,9 @@ impl MessageRef { #[inline] pub fn send_no_reply(&mut self) -> super::Result<()> { // self.bus().send_no_reply(self) - sd_try!(ffi::bus::sd_bus_send( - ptr::null_mut(), - self.as_ptr(), - ptr::null_mut() - )); + ffi_result(unsafe { + ffi::bus::sd_bus_send(ptr::null_mut(), self.as_ptr(), ptr::null_mut()) + })?; Ok(()) } @@ -1641,12 +1633,14 @@ impl MessageRef { pub fn send_to(&mut self, dest: &BusName) -> super::Result { // self.bus().send_to(self, dest) let mut c = MaybeUninit::uninit(); - sd_try!(ffi::bus::sd_bus_send_to( - ptr::null_mut(), - self.as_ptr(), - dest as *const _ as *const _, - c.as_mut_ptr() - )); + ffi_result(unsafe { + ffi::bus::sd_bus_send_to( + ptr::null_mut(), + self.as_ptr(), + dest as *const _ as *const _, + c.as_mut_ptr(), + ) + })?; let c = unsafe { c.assume_init() }; Ok(c) } @@ -1661,12 +1655,14 @@ impl MessageRef { #[inline] pub fn send_to_no_reply(&mut self, dest: &BusName) -> super::Result<()> { // self.bus().send_to_no_reply(self, dest) - sd_try!(ffi::bus::sd_bus_send_to( - ptr::null_mut(), - self.as_ptr(), - dest as *const _ as *const _, - ptr::null_mut() - )); + ffi_result(unsafe { + ffi::bus::sd_bus_send_to( + ptr::null_mut(), + self.as_ptr(), + dest as *const _ as *const _, + ptr::null_mut(), + ) + })?; Ok(()) } @@ -1754,11 +1750,9 @@ impl MessageRef { #[inline] pub fn new_method_error(&mut self, error: &Error) -> crate::Result { let mut m = MaybeUninit::uninit(); - sd_try!(ffi::bus::sd_bus_message_new_method_error( - self.as_ptr(), - m.as_mut_ptr(), - error.as_ptr() - )); + ffi_result(unsafe { + ffi::bus::sd_bus_message_new_method_error(self.as_ptr(), m.as_mut_ptr(), error.as_ptr()) + })?; Ok(unsafe { Message::from_ptr(m.assume_init()) }) } @@ -1768,10 +1762,9 @@ impl MessageRef { #[inline] pub fn new_method_return(&mut self) -> crate::Result { let mut m = MaybeUninit::uninit(); - sd_try!(ffi::bus::sd_bus_message_new_method_return( - self.as_ptr(), - m.as_mut_ptr() - )); + ffi_result(unsafe { + ffi::bus::sd_bus_message_new_method_return(self.as_ptr(), m.as_mut_ptr()) + })?; Ok(unsafe { Message::from_ptr(m.assume_init()) }) } @@ -1817,11 +1810,9 @@ impl MessageRef { #[inline] pub fn iter(&mut self) -> crate::Result> { /* probe the `Message` to check if we can iterate on it */ - sd_try!(ffi::bus::sd_bus_message_peek_type( - self.as_ptr(), - ptr::null_mut(), - ptr::null_mut() - )); + ffi_result(unsafe { + ffi::bus::sd_bus_message_peek_type(self.as_ptr(), ptr::null_mut(), ptr::null_mut()) + })?; Ok(MessageIter { raw: self.as_ptr(), life: PhantomData, diff --git a/src/bus/types.rs b/src/bus/types.rs index 682d8c2..297be83 100644 --- a/src/bus/types.rs +++ b/src/bus/types.rs @@ -91,7 +91,7 @@ impl<'a, T: SdBusMessageDirect + 'a> FromSdBusMessage<'a> for T { // impl ToSdBusMessage for $typ { // fn to_message(&self, m: &mut MessageRef) -> ::systemdsuper::Result<()> { // let c_type : [u8;2] = [ $dbus_type, '\0' ]; -// sd_try!(ffi::sd_bus_message_append(m, &c_type, self as *const _)); +// ffi_result(unsafe { ffi::sd_bus_message_append(m, &c_type, self as *const _)})?; // Ok(()) // } // } @@ -100,7 +100,7 @@ impl<'a, T: SdBusMessageDirect + 'a> FromSdBusMessage<'a> for T { // fn from_message(m: &mut MessageRef) -> ::systemd::Result { // let c_type : [u8;2] = [ $dbus_type, '\0' ]; // let v : Self = unsafe { uninitialized() }; -// sd_try!(ffi::sd_bus_message_read(m, &c_type, &v)); +// ffi_result(unsafe { ffi::sd_bus_message_read(m, &c_type, &v)})?; // Ok(v) // } // } @@ -176,7 +176,7 @@ impl<'a> FromSdBusMessage<'a> for UnixFd { } } -impl<'a> ToSdBusMessage for &'a bus::ObjectPath { +impl ToSdBusMessage for &bus::ObjectPath { fn to_message(&self, m: &mut MessageRef) -> crate::Result<()> { unsafe { m.append_basic_raw(b'o', self.as_ptr() as *const _) }?; Ok(()) @@ -201,7 +201,7 @@ impl<'a> FromSdBusMessage<'a> for &'a bus::ObjectPath { } } -impl<'a> ToSdBusMessage for &'a Utf8CStr { +impl ToSdBusMessage for &Utf8CStr { fn to_message(&self, m: &mut MessageRef) -> crate::Result<()> { unsafe { m.append_basic_raw(b's', self.as_ptr() as *const _) } } diff --git a/src/daemon.rs b/src/daemon.rs index 588a1c9..9f6014c 100644 --- a/src/daemon.rs +++ b/src/daemon.rs @@ -4,6 +4,7 @@ /// [libsystemd](https://crates.io/crates/libsystemd) crate, and you may prefer to use it instead. use super::ffi::{c_int, pid_t, size_t}; use super::{Error, Result}; +use crate::ffi_result; use ::ffi::daemon as ffi; use cstr_argument::CStrArgument; use libc::{c_char, c_uint}; @@ -74,7 +75,7 @@ impl ListenFds { // Constructs a new set from the number of file_descriptors fn new(unset_environment: bool) -> Result { // in order to use rust's locking of the environment, do the env var unsetting ourselves - let num_fds = sd_try!(ffi::sd_listen_fds(0)); + let num_fds = ffi_result(unsafe { ffi::sd_listen_fds(0) })?; if unset_environment { env::remove_var("LISTEN_FDS"); env::remove_var("LISTEN_PID"); @@ -134,10 +135,8 @@ pub fn listen_fds(unset_environment: bool) -> Result { /// supplied, the file descriptor must also match the path. pub fn is_fifo(fd: Fd, path: Option) -> Result { let path = path.map(|x| x.into_cstr()); - let result = sd_try!(ffi::sd_is_fifo( - fd, - path.map_or(null(), |x| x.as_ref().as_ptr()) - )); + let result = + ffi_result(unsafe { ffi::sd_is_fifo(fd, path.map_or(null(), |x| x.as_ref().as_ptr())) })?; Ok(result != 0) } @@ -145,10 +144,9 @@ pub fn is_fifo(fd: Fd, path: Option) -> Result { /// If a path is supplied, the file descriptor must also match the path. pub fn is_special(fd: Fd, path: Option) -> Result { let path = path.map(|x| x.into_cstr()); - let result = sd_try!(ffi::sd_is_special( - fd, - path.map_or(null(), |x| x.as_ref().as_ptr()) - )); + let result = ffi_result(unsafe { + ffi::sd_is_special(fd, path.map_or(null(), |x| x.as_ref().as_ptr())) + })?; Ok(result != 0) } @@ -187,7 +185,7 @@ pub fn is_socket( let c_socktype = get_c_socktype(socktype); let c_listening = get_c_listening(listening); - let result = sd_try!(ffi::sd_is_socket(fd, c_family, c_socktype, c_listening)); + let result = ffi_result(unsafe { ffi::sd_is_socket(fd, c_family, c_socktype, c_listening) })?; Ok(result != 0) } @@ -206,13 +204,9 @@ pub fn is_socket_inet( let c_listening = get_c_listening(listening); let c_port = port.unwrap_or(0); - let result = sd_try!(ffi::sd_is_socket_inet( - fd, - c_family, - c_socktype, - c_listening, - c_port - )); + let result = ffi_result(unsafe { + ffi::sd_is_socket_inet(fd, c_family, c_socktype, c_listening, c_port) + })?; Ok(result != 0) } @@ -260,13 +254,9 @@ pub fn is_socket_unix( } } - let result = sd_try!(ffi::sd_is_socket_unix( - fd, - c_socktype, - c_listening, - c_path, - c_length - )); + let result = ffi_result(unsafe { + ffi::sd_is_socket_unix(fd, c_socktype, c_listening, c_path, c_length) + })?; Ok(result != 0) } @@ -274,10 +264,8 @@ pub fn is_socket_unix( /// path is supplied, it will also verify the name. pub fn is_mq(fd: Fd, path: Option) -> Result { let path = path.map(|x| x.into_cstr()); - let result = sd_try!(ffi::sd_is_mq( - fd, - path.map_or(null(), |x| x.as_ref().as_ptr()) - )); + let result = + ffi_result(unsafe { ffi::sd_is_mq(fd, path.map_or(null(), |x| x.as_ref().as_ptr())) })?; Ok(result != 0) } /// Converts a state map to a C-string for notify @@ -306,7 +294,8 @@ where V: AsRef + 'a, { let c_state = state_to_c_string(state); - let result = sd_try!(ffi::sd_notify(unset_environment as c_int, c_state.as_ptr())); + let result = + ffi_result(unsafe { ffi::sd_notify(unset_environment as c_int, c_state.as_ptr()) })?; Ok(result != 0) } @@ -319,11 +308,9 @@ where V: AsRef + 'a, { let c_state = state_to_c_string(state); - let result = sd_try!(ffi::sd_pid_notify( - pid, - unset_environment as c_int, - c_state.as_ptr() - )); + let result = ffi_result(unsafe { + ffi::sd_pid_notify(pid, unset_environment as c_int, c_state.as_ptr()) + })?; Ok(result != 0) } @@ -340,19 +327,21 @@ where V: AsRef + 'a, { let c_state = state_to_c_string(state); - let result = sd_try!(ffi::sd_pid_notify_with_fds( - pid, - unset_environment as c_int, - c_state.as_ptr(), - fds.as_ptr(), - fds.len() as c_uint - )); + let result = ffi_result(unsafe { + ffi::sd_pid_notify_with_fds( + pid, + unset_environment as c_int, + c_state.as_ptr(), + fds.as_ptr(), + fds.len() as c_uint, + ) + })?; Ok(result != 0) } /// Returns true if the system was booted with systemd. pub fn booted() -> Result { - let result = sd_try!(ffi::sd_booted()); + let result = ffi_result(unsafe { ffi::sd_booted() })?; Ok(result != 0) } @@ -360,9 +349,6 @@ pub fn booted() -> Result { /// response from the process. If 0, the watchdog is disabled. pub fn watchdog_enabled(unset_environment: bool) -> Result { let mut timeout: u64 = 0; - sd_try!(ffi::sd_watchdog_enabled( - unset_environment as c_int, - &mut timeout - )); + ffi_result(unsafe { ffi::sd_watchdog_enabled(unset_environment as c_int, &mut timeout) })?; Ok(timeout) } diff --git a/src/id128.rs b/src/id128.rs index c72f98e..5517bdb 100644 --- a/src/id128.rs +++ b/src/id128.rs @@ -4,6 +4,7 @@ //! simpler string format. See `man 3 sd-id128` for more details. use super::Result; +use crate::ffi_result; use std::ffi::CStr; use std::fmt; @@ -24,7 +25,7 @@ impl fmt::Debug for Id128 { impl fmt::Display for Id128 { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { for b in self.inner.bytes.iter() { - write!(fmt, "{:02x}", b)?; + write!(fmt, "{b:02x}")?; } Ok(()) } @@ -63,43 +64,41 @@ impl<'de> serde::Deserialize<'de> for Id128 { impl Id128 { pub fn from_cstr(s: &CStr) -> Result { let mut r = Id128::default(); - sd_try!(ffi::id128::sd_id128_from_string(s.as_ptr(), &mut r.inner)); + ffi_result(unsafe { ffi::id128::sd_id128_from_string(s.as_ptr(), &mut r.inner) })?; Ok(r) } pub fn from_random() -> Result { let mut r = Id128::default(); - sd_try!(ffi::id128::sd_id128_randomize(&mut r.inner)); + ffi_result(unsafe { ffi::id128::sd_id128_randomize(&mut r.inner) })?; Ok(r) } pub fn from_machine() -> Result { let mut r = Id128::default(); - sd_try!(ffi::id128::sd_id128_get_machine(&mut r.inner)); + ffi_result(unsafe { ffi::id128::sd_id128_get_machine(&mut r.inner) })?; Ok(r) } pub fn from_machine_app_specific(app_id: &Id128) -> Result { let mut r = Id128::default(); - sd_try!(ffi::id128::sd_id128_get_machine_app_specific( - *app_id.as_raw(), - &mut r.inner - )); + ffi_result(unsafe { + ffi::id128::sd_id128_get_machine_app_specific(*app_id.as_raw(), &mut r.inner) + })?; Ok(r) } pub fn from_boot() -> Result { let mut r = Id128::default(); - sd_try!(ffi::id128::sd_id128_get_boot(&mut r.inner)); + ffi_result(unsafe { ffi::id128::sd_id128_get_boot(&mut r.inner) })?; Ok(r) } pub fn from_boot_app_specific(app_id: &Id128) -> Result { let mut r = Id128::default(); - sd_try!(ffi::id128::sd_id128_get_boot_app_specific( - *app_id.as_raw(), - &mut r.inner - )); + ffi_result(unsafe { + ffi::id128::sd_id128_get_boot_app_specific(*app_id.as_raw(), &mut r.inner) + })?; Ok(r) } diff --git a/src/journal.rs b/src/journal.rs index aa4835e..f22bdd0 100644 --- a/src/journal.rs +++ b/src/journal.rs @@ -1,6 +1,7 @@ use super::{free_cstring, usec_from_duration, Result}; use crate::ffi::const_iovec; use crate::ffi::journal as ffi; +use crate::ffi_result; use crate::id128::Id128; use cstr_argument::CStrArgument; use foreign_types::{foreign_type, ForeignType, ForeignTypeRef}; @@ -39,7 +40,7 @@ pub fn send(args: &[&str]) -> c_int { /// Send a simple message to systemd-journald. pub fn print(lvl: u32, s: &str) -> c_int { - send(&[&format!("PRIORITY={}", lvl), &format!("MESSAGE={}", s)]) + send(&[&format!("PRIORITY={lvl}"), &format!("MESSAGE={s}")]) } enum SyslogLevel { @@ -68,11 +69,11 @@ impl From for SyslogLevel { /// Record a log entry, with custom priority and location. pub fn log(level: usize, file: &str, line: u32, module_path: &str, args: &fmt::Arguments<'_>) { send(&[ - &format!("PRIORITY={}", level), - &format!("MESSAGE={}", args), - &format!("CODE_LINE={}", line), - &format!("CODE_FILE={}", file), - &format!("CODE_MODULE={}", module_path), + &format!("PRIORITY={level}"), + &format!("MESSAGE={args}"), + &format!("CODE_LINE={line}"), + &format!("CODE_FILE={file}"), + &format!("CODE_MODULE={module_path}"), ]); } @@ -84,11 +85,9 @@ pub fn log_record(record: &Record<'_>) { format!("TARGET={}", record.target()), ]; let opt_keys = [ - record.line().map(|line| format!("CODE_LINE={}", line)), - record.file().map(|file| format!("CODE_FILE={}", file)), - record - .module_path() - .map(|path| format!("CODE_FUNC={}", path)), + record.line().map(|line| format!("CODE_LINE={line}")), + record.file().map(|file| format!("CODE_FILE={file}")), + record.module_path().map(|path| format!("CODE_FUNC={path}")), ]; collect_and_send(keys.iter().chain(opt_keys.iter().flatten())); @@ -274,7 +273,7 @@ impl<'a> fmt::Display for DisplayEntryData<'a> { } Ok(None) => break, Err(e) => { - writeln!(fmt, "E: {:?}", e)?; + writeln!(fmt, "E: {e:?}")?; break; } } @@ -673,7 +672,7 @@ impl JournalRef { /// [`sd_journal_get_fd`]: https://www.freedesktop.org/software/systemd/man/sd_journal_get_fd.html #[inline] pub fn fd(&self) -> Result { - Ok(sd_try!(ffi::sd_journal_get_fd(self.as_ptr()))) + ffi_result(unsafe { ffi::sd_journal_get_fd(self.as_ptr()) }) } /// Fields that are longer that this number of bytes _may_ be truncated when retrieved by this [`Journal`] @@ -751,10 +750,7 @@ impl JournalRef { ffi::sd_journal_enumerate_data(self.as_ptr(), data.as_mut_ptr(), data_len.as_mut_ptr()) }); - let v = match r { - Err(e) => return Err(e), - Ok(v) => v, - }; + let v = r?; if v == 0 { return Ok(None); @@ -854,7 +850,7 @@ impl JournalRef { pub fn wait(&mut self, wait_time: Option) -> Result { let time = wait_time.map(usec_from_duration).unwrap_or(u64::MAX); - match sd_try!(ffi::sd_journal_wait(self.as_ptr(), time)) { + match ffi_result(unsafe { ffi::sd_journal_wait(self.as_ptr(), time) })? { ffi::SD_JOURNAL_NOP => Ok(JournalWaitResult::Nop), ffi::SD_JOURNAL_APPEND => Ok(JournalWaitResult::Append), ffi::SD_JOURNAL_INVALIDATE => Ok(JournalWaitResult::Invalidate), @@ -970,7 +966,7 @@ impl JournalRef { pub fn cursor(&self) -> Result { let mut c_cursor: *const c_char = ptr::null_mut(); - sd_try!(ffi::sd_journal_get_cursor(self.as_ptr(), &mut c_cursor)); + ffi_result(unsafe { ffi::sd_journal_get_cursor(self.as_ptr(), &mut c_cursor) })?; let cursor = unsafe { free_cstring(c_cursor as *mut _).unwrap() }; Ok(cursor) } @@ -980,19 +976,14 @@ impl JournalRef { /// Corresponds to `sd_journal_test_cursor()`. pub fn test_cursor(&self, cursor: A) -> Result { let c = cursor.into_cstr(); - crate::ffi_result(unsafe { - ffi::sd_journal_test_cursor(self.as_ptr(), c.as_ref().as_ptr()) - }) - .map(|v| v != 0) + ffi_result(unsafe { ffi::sd_journal_test_cursor(self.as_ptr(), c.as_ref().as_ptr()) }) + .map(|v| v != 0) } /// Returns timestamp at which current journal entry was recorded. pub fn timestamp(&self) -> Result { let mut timestamp_us: u64 = 0; - sd_try!(ffi::sd_journal_get_realtime_usec( - self.as_ptr(), - &mut timestamp_us - )); + ffi_result(unsafe { ffi::sd_journal_get_realtime_usec(self.as_ptr(), &mut timestamp_us) })?; Ok(system_time_from_realtime_usec(timestamp_us)) } @@ -1000,11 +991,13 @@ impl JournalRef { pub fn monotonic_timestamp(&self) -> Result<(u64, Id128)> { let mut monotonic_timestamp_us: u64 = 0; let mut id = Id128::default(); - sd_try!(ffi::sd_journal_get_monotonic_usec( - self.as_ptr(), - &mut monotonic_timestamp_us, - &mut id.inner, - )); + ffi_result(unsafe { + ffi::sd_journal_get_monotonic_usec( + self.as_ptr(), + &mut monotonic_timestamp_us, + &mut id.inner, + ) + })?; Ok((monotonic_timestamp_us, id)) } @@ -1012,11 +1005,13 @@ impl JournalRef { /// the current entry is not from the current system boot. pub fn monotonic_timestamp_current_boot(&self) -> Result { let mut monotonic_timestamp_us: u64 = 0; - sd_try!(ffi::sd_journal_get_monotonic_usec( - self.as_ptr(), - &mut monotonic_timestamp_us, - ptr::null_mut(), - )); + ffi_result(unsafe { + ffi::sd_journal_get_monotonic_usec( + self.as_ptr(), + &mut monotonic_timestamp_us, + ptr::null_mut(), + ) + })?; Ok(monotonic_timestamp_us) } @@ -1028,19 +1023,19 @@ impl JournalRef { filter.extend(val.into()); let data = filter.as_ptr() as *const c_void; let datalen = filter.len() as size_t; - sd_try!(ffi::sd_journal_add_match(self.as_ptr(), data, datalen)); + ffi_result(unsafe { ffi::sd_journal_add_match(self.as_ptr(), data, datalen) })?; Ok(self) } /// Inserts a disjunction (i.e. logical OR) in the match list. pub fn match_or(&mut self) -> Result<&mut JournalRef> { - sd_try!(ffi::sd_journal_add_disjunction(self.as_ptr())); + ffi_result(unsafe { ffi::sd_journal_add_disjunction(self.as_ptr()) })?; Ok(self) } /// Inserts a conjunction (i.e. logical AND) in the match list. pub fn match_and(&mut self) -> Result<&mut JournalRef> { - sd_try!(ffi::sd_journal_add_conjunction(self.as_ptr())); + ffi_result(unsafe { ffi::sd_journal_add_conjunction(self.as_ptr()) })?; Ok(self) } diff --git a/src/lib.rs b/src/lib.rs index 2fd0ee2..971e8e8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -48,20 +48,6 @@ unsafe fn free_cstring(ptr: *mut c_char) -> Option { Some(s) } -/// An analogue of `try!()` for systemd FFI calls. -/// -/// The parameter should be a call to a systemd FFI fn with an c_int return -/// value. It is called, and if the return is negative then `sd_try!()` -/// interprets it as an error code and returns IoError from the enclosing fn. -/// Otherwise, the value of `sd_try!()` is the non-negative value returned by -/// the FFI call. -#[macro_export] -macro_rules! sd_try { - ($e:expr) => {{ - $crate::ffi_result(unsafe { $e })? - }}; -} - /// High-level interface to the systemd journal. /// /// The main interface for writing to the journal is `fn log()`, and the main diff --git a/src/login.rs b/src/login.rs index 176d710..610a17a 100644 --- a/src/login.rs +++ b/src/login.rs @@ -1,5 +1,6 @@ use super::ffi::{c_char, c_uint, pid_t, uid_t}; use super::{free_cstring, Result}; +use crate::ffi_result; use ::ffi::login as ffi; use cstr_argument::CStrArgument; use std::ptr; @@ -21,8 +22,10 @@ pub fn get_unit(unit_type: UnitType, pid: Option) -> Result { let mut c_unit_name: *mut c_char = ptr::null_mut(); let p: pid_t = pid.unwrap_or(0); match unit_type { - UnitType::UserUnit => sd_try!(ffi::sd_pid_get_user_unit(p, &mut c_unit_name)), - UnitType::SystemUnit => sd_try!(ffi::sd_pid_get_unit(p, &mut c_unit_name)), + UnitType::UserUnit => { + ffi_result(unsafe { ffi::sd_pid_get_user_unit(p, &mut c_unit_name) })? + } + UnitType::SystemUnit => ffi_result(unsafe { ffi::sd_pid_get_unit(p, &mut c_unit_name) })?, }; let unit_name = unsafe { free_cstring(c_unit_name).unwrap() }; Ok(unit_name) @@ -37,8 +40,10 @@ pub fn get_slice(slice_type: UnitType, pid: Option) -> Result { let mut c_slice_name: *mut c_char = ptr::null_mut(); let p: pid_t = pid.unwrap_or(0); match slice_type { - UnitType::UserUnit => sd_try!(ffi::sd_pid_get_user_slice(p, &mut c_slice_name)), - UnitType::SystemUnit => sd_try!(ffi::sd_pid_get_slice(p, &mut c_slice_name)), + UnitType::UserUnit => { + ffi_result(unsafe { ffi::sd_pid_get_user_slice(p, &mut c_slice_name) })? + } + UnitType::SystemUnit => ffi_result(unsafe { ffi::sd_pid_get_slice(p, &mut c_slice_name) })?, }; let slice_id = unsafe { free_cstring(c_slice_name).unwrap() }; Ok(slice_id) @@ -53,7 +58,7 @@ pub fn get_slice(slice_type: UnitType, pid: Option) -> Result { pub fn get_machine_name(pid: Option) -> Result { let mut c_machine_name: *mut c_char = ptr::null_mut(); let p: pid_t = pid.unwrap_or(0); - sd_try!(ffi::sd_pid_get_machine_name(p, &mut c_machine_name)); + ffi_result(unsafe { ffi::sd_pid_get_machine_name(p, &mut c_machine_name) })?; let machine_id = unsafe { free_cstring(c_machine_name).unwrap() }; Ok(machine_id) } @@ -69,7 +74,7 @@ pub fn get_machine_name(pid: Option) -> Result { pub fn get_cgroup(pid: Option) -> Result { let mut c_cgroup: *mut c_char = ptr::null_mut(); let p: pid_t = pid.unwrap_or(0); - sd_try!(ffi::sd_pid_get_cgroup(p, &mut c_cgroup)); + ffi_result(unsafe { ffi::sd_pid_get_cgroup(p, &mut c_cgroup) })?; let cg = unsafe { free_cstring(c_cgroup).unwrap() }; Ok(cg) } @@ -82,7 +87,7 @@ pub fn get_cgroup(pid: Option) -> Result { pub fn get_session(pid: Option) -> Result { let mut c_session: *mut c_char = ptr::null_mut(); let p: pid_t = pid.unwrap_or(0); - sd_try!(ffi::sd_pid_get_session(p, &mut c_session)); + ffi_result(unsafe { ffi::sd_pid_get_session(p, &mut c_session) })?; let ss = unsafe { free_cstring(c_session).unwrap() }; Ok(ss) } @@ -94,10 +99,7 @@ pub fn get_session(pid: Option) -> Result { pub fn get_seat(session: S) -> Result { let session = session.into_cstr(); let mut c_seat: *mut c_char = ptr::null_mut(); - sd_try!(ffi::sd_session_get_seat( - session.as_ref().as_ptr(), - &mut c_seat - )); + ffi_result(unsafe { ffi::sd_session_get_seat(session.as_ref().as_ptr(), &mut c_seat) })?; let ss = unsafe { free_cstring(c_seat).unwrap() }; Ok(ss) } @@ -108,7 +110,7 @@ pub fn get_seat(session: S) -> Result { pub fn get_vt(session: S) -> Result { let session = session.into_cstr(); let c_vt: *mut c_uint = ptr::null_mut(); - sd_try!(ffi::sd_session_get_vt(session.as_ref().as_ptr(), c_vt)); + ffi_result(unsafe { ffi::sd_session_get_vt(session.as_ref().as_ptr(), c_vt) })?; Ok(unsafe { *c_vt }) } @@ -120,6 +122,6 @@ pub fn get_vt(session: S) -> Result { pub fn get_owner_uid(pid: Option) -> Result { let mut c_owner_uid: u32 = 0u32; let p: pid_t = pid.unwrap_or(0); - sd_try!(ffi::sd_pid_get_owner_uid(p, &mut c_owner_uid)); + ffi_result(unsafe { ffi::sd_pid_get_owner_uid(p, &mut c_owner_uid) })?; Ok(c_owner_uid as uid_t) } diff --git a/src/unit.rs b/src/unit.rs index 632279d..88edaba 100644 --- a/src/unit.rs +++ b/src/unit.rs @@ -14,7 +14,7 @@ pub fn escape_name(s: &str) -> String { b'_' | b':' => escaped.push(char::from(b)), // all ASCII alphanumeric characters _ if b.is_ascii_alphanumeric() => escaped.push(char::from(b)), - _ => escaped.push_str(&format!("\\x{:02x}", b)), + _ => escaped.push_str(&format!("\\x{b:02x}")), } } escaped diff --git a/tests/bus.rs b/tests/bus.rs index 4a88545..109efd4 100644 --- a/tests/bus.rs +++ b/tests/bus.rs @@ -64,5 +64,5 @@ fn bad_signature_on_call() { m.append(23u64).unwrap(); let r = m.call(0).err().unwrap(); - println!("{:?}", r); + println!("{r:?}"); } diff --git a/tests/journal.rs b/tests/journal.rs index 7139784..16f3423 100644 --- a/tests/journal.rs +++ b/tests/journal.rs @@ -103,7 +103,7 @@ fn test_simple_match() { let key = "RUST_TEST_MARKER"; let value = "RUST_SYSTEMD_SIMPLE_MATCH"; let msg = "MESSAGE=rust-systemd test_match"; - let filter = format!("{}={}", key, value); + let filter = format!("{key}={value}"); let mut j = journal::OpenOptions::default().open().unwrap(); // check for positive matches @@ -127,7 +127,7 @@ fn test_simple_match() { } let entryval = j.get_data(key).unwrap(); - println!("k,v: {:?}, {:?}", key, entryval); + println!("k,v: {key:?}, {entryval:?}"); if entryval.is_none() { println!("E: {}", j.display_entry_data()); continue; diff --git a/tests/login.rs b/tests/login.rs index 1e8523a..4ca7a22 100644 --- a/tests/login.rs +++ b/tests/login.rs @@ -9,17 +9,14 @@ fn test_get_unit() { let su = login::get_unit(login::UnitType::SystemUnit, None); let has_systemd = booted(); assert!(has_systemd.is_ok()); - match has_systemd.unwrap() { - // This is not running in a unit at all - false => { - assert!(uu.is_err()); - assert!(su.is_err()); - } + if has_systemd.unwrap() { // User units run under a system unit (E.g. user@1000.service) - true => { - assert!(su.is_ok()); - } - }; + assert!(su.is_ok()); + } else { + // This is not running in a unit at all + assert!(uu.is_err()); + assert!(su.is_err()); + } } #[test] @@ -28,19 +25,16 @@ fn test_get_slice() { let ss = login::get_slice(login::UnitType::SystemUnit, None); let has_systemd = booted(); assert!(has_systemd.is_ok()); - match has_systemd.unwrap() { - // This is running in the top-level generic slice - false => { - assert_eq!(ss.unwrap(), "-.slice"); - } + if has_systemd.unwrap() { // This is running in a system slice, and perhaps // in an user one too - true => { - if ss.is_err() && us.is_err() { - panic!("ss: {:?}, us: {:?}", ss, us); - } + if ss.is_err() && us.is_err() { + panic!("ss: {:?}, us: {:?}", ss, us); } - }; + } else { + // This is running in the top-level generic slice + assert_eq!(ss.unwrap(), "-.slice"); + } } #[test] @@ -48,14 +42,12 @@ fn test_get_machine_name() { let mname = login::get_machine_name(None); let has_systemd = booted(); assert!(has_systemd.is_ok()); - match has_systemd.unwrap() { + if !has_systemd.unwrap() { // No machined registration - false => { - assert!(mname.is_err()); - } + assert!(mname.is_err()); + } else { // This is unpredictable, based on testing environment - true => {} - }; + } } #[test] @@ -63,12 +55,12 @@ fn test_get_cgroup() { let cg = login::get_cgroup(None); let has_systemd = booted(); assert!(has_systemd.is_ok()); - match has_systemd.unwrap() { + if has_systemd.unwrap() { // Running under systemd, inside a slice somewhere - true => assert!(cg.is_ok()), + assert!(cg.is_ok()); + } else { // Nothing meaningful to check here - false => {} - }; + } } #[test] @@ -76,21 +68,19 @@ fn test_get_session() { let ss = login::get_session(None); let has_systemd = booted(); assert!(has_systemd.is_ok()); - match has_systemd.unwrap() { + if has_systemd.unwrap() { // Running under systemd, inside a slice somewhere - true => { - // even in this case, we might get a "no data available" (github actions runners return - // this) - if let Err(e) = ss { - match e.raw_os_error() { - Some(libc::ENODATA) => { /* ok */ } - _ => panic!("{}", e), - } + // even in this case, we might get a "no data available" (github actions runners return + // this) + if let Err(e) = ss { + match e.raw_os_error() { + Some(libc::ENODATA) => { /* ok */ } + _ => panic!("{}", e), } } + } else { // Nothing meaningful to check here - false => {} - }; + } } #[test] @@ -98,19 +88,17 @@ fn test_get_owner_uid() { let ou = login::get_owner_uid(None); let has_systemd = booted(); assert!(has_systemd.is_ok()); - match has_systemd.unwrap() { + if has_systemd.unwrap() { // Running under systemd, inside a slice somewhere - true => { - // even in this case, we might get a "no data available" (github actions runners return - // this) - if let Err(e) = ou { - match e.raw_os_error() { - Some(libc::ENODATA) => { /* ok */ } - _ => panic!("{}", e), - } + // even in this case, we might get a "no data available" (github actions runners return + // this) + if let Err(e) = ou { + match e.raw_os_error() { + Some(libc::ENODATA) => { /* ok */ } + _ => panic!("{}", e), } } + } else { // Nothing meaningful to check here - false => {} - }; + } }