From 4c8521ccb8e83e7e3e75e102da9b10af6eca8cd9 Mon Sep 17 00:00:00 2001 From: Nolan Darilek Date: Fri, 19 Nov 2021 08:38:17 -0600 Subject: [PATCH] Add error handling for initialization failure. --- speech-dispatcher/examples/hello_world.rs | 5 ++- speech-dispatcher/src/lib.rs | 45 ++++++++++++++++++----- 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/speech-dispatcher/examples/hello_world.rs b/speech-dispatcher/examples/hello_world.rs index 8882cee..00ba239 100644 --- a/speech-dispatcher/examples/hello_world.rs +++ b/speech-dispatcher/examples/hello_world.rs @@ -1,13 +1,13 @@ use speech_dispatcher::*; use std::io; -fn main() { +fn main() -> Result<(), Box> { let connection = speech_dispatcher::Connection::open( "hello_world", "hello_world", "hello_world", Mode::Threaded, - ); + )?; connection.on_begin(Some(Box::new(|msg_id, client_id| { println!("Beginning {} from {}", msg_id, client_id) }))); @@ -36,4 +36,5 @@ fn main() { connection.set_punctuation(Punctuation::None); let mut _input = String::new(); io::stdin().read_line(&mut _input).unwrap(); + Ok(()) } diff --git a/speech-dispatcher/src/lib.rs b/speech-dispatcher/src/lib.rs index d3353ae..9050b9c 100644 --- a/speech-dispatcher/src/lib.rs +++ b/speech-dispatcher/src/lib.rs @@ -1,9 +1,12 @@ #![allow(non_upper_case_globals)] -use std::collections::HashMap; -use std::ffi::{CStr, CString}; -use std::marker::Send; -use std::sync::Mutex; +use std::{ + collections::HashMap, + ffi::{CStr, CString}, + fmt, + marker::Send, + sync::Mutex, +}; use lazy_static::lazy_static; use speech_dispatcher_sys::*; @@ -145,13 +148,29 @@ unsafe extern "C" fn cb_im(msg_id: u64, client_id: u64, state: u32, index_mark: } } +#[derive(Debug)] +pub enum SpeechDispatcherError { + InitializationError, +} + +impl std::error::Error for SpeechDispatcherError {} + +impl fmt::Display for SpeechDispatcherError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use SpeechDispatcherError::*; + match self { + InitializationError => write!(f, "Failed to initialize"), + } + } +} + impl Connection { pub fn open>( client_name: S, connection_name: S, user_name: S, mode: Mode, - ) -> Self { + ) -> Result { let clientname = CString::new(client_name.into()).unwrap(); let connectionname = CString::new(connection_name.into()).unwrap(); let username = CString::new(user_name.into()).unwrap(); @@ -162,11 +181,19 @@ impl Connection { username.as_ptr(), mode as u32, ); - Self::setup_connection(c) + if c.is_null() { + None + } else { + Some(Self::setup_connection(c)) + } }; - let mut c = Self(connection, 0); - c.setup(); - c + if let Some(connection) = connection { + let mut c = Self(connection, 0); + c.setup(); + Ok(c) + } else { + Err(SpeechDispatcherError::InitializationError) + } } pub unsafe fn open2>(