From 06714444bc8d67b3aa4383d0cb6e46e64f50f25f Mon Sep 17 00:00:00 2001 From: szymon Date: Wed, 30 Sep 2026 16:59:05 +0200 Subject: [PATCH] feat: change init function to return an error --- examples/server_info.rs | 2 +- examples/show_notification.rs | 2 +- src/functions.rs | 44 +++++++++++++++++++++-------------- 3 files changed, 28 insertions(+), 20 deletions(-) diff --git a/examples/server_info.rs b/examples/server_info.rs index 2ad4132..03a3f94 100644 --- a/examples/server_info.rs +++ b/examples/server_info.rs @@ -1,7 +1,7 @@ use libnotify_rs::functions::{self, uninit}; fn main() -> Result<(), Box> { - functions::init("Morbius"); + functions::init("Morbius")?; if let Some(caps) = functions::get_server_caps() { println!("=== Server caps ==="); diff --git a/examples/show_notification.rs b/examples/show_notification.rs index 6305532..5d755f3 100644 --- a/examples/show_notification.rs +++ b/examples/show_notification.rs @@ -4,7 +4,7 @@ use libnotify_rs::{ }; fn main() -> Result<(), Box> { - init("I love coffee"); + init("I love coffee")?; let mut notify = Notification::new( "Remember to drink coffe!", "Coffee is very important for your mental health!", diff --git a/src/functions.rs b/src/functions.rs index c2e79b2..af11bfe 100644 --- a/src/functions.rs +++ b/src/functions.rs @@ -10,28 +10,27 @@ use crate::libnotify::*; /// Initialized libnotify. This must be called before any other functions. /// /// Starting from 0.8, if the provided app_name is NULL, libnotify will try to figure it out from the running application. Before it was not allowed, and was causing libnotify not to be initialized. -/// -/// # Returns -/// TRUE if successful, or FALSE on error -pub fn init<'a, T>(app_name: T) -> bool +pub fn init<'a, T>(app_name: T) -> Result<(), Box> where T: Into>, { - match app_name + let app_name = app_name .into() .map(|app_name| std::ffi::CString::new(app_name)) - .transpose() - { - Ok(app_name) => unsafe { - notify_init( - app_name - .as_ref() - .map_or(std::ptr::null(), |app_name| app_name.as_ptr()), - ) != 0 - }, + .transpose()?; - Err(_) => return false, + if unsafe { + notify_init( + app_name + .as_ref() + .map_or(std::ptr::null(), |app_name| app_name.as_ptr()), + ) + } == 0 + { + return Err("Libnotify init failed".into()); } + + Ok(()) } /// Uninitializes libnotify. @@ -190,16 +189,25 @@ mod tests { #[test] fn test_initializing() { assert!(!is_initted()); - assert!(init("Morbius")); + assert!(init("Morbius").is_ok()); assert!(is_initted()); uninit(); assert!(!is_initted()); } + #[test] + fn test_bad_init() { + assert!( + init("Mor\0ius") + .unwrap_err() + .is::() + ); + } + #[test] fn test_app_name_set_and_get() { let first_name: &str = "Morbius"; - init(first_name); + let _ = init(first_name); assert_eq!(get_app_name().unwrap(), first_name); let new_name: &str = "Milo"; @@ -211,7 +219,7 @@ mod tests { #[test] fn test_app_name_bad_name() { - init("Morbius"); + let _ = init("Morbius"); let bad_name: &str = "mor\0ius"; assert!(