Add error handling for initialization failure.

This commit is contained in:
Nolan Darilek 2021-11-19 08:38:17 -06:00
parent 006a4835be
commit 4c8521ccb8
2 changed files with 39 additions and 11 deletions

View File

@ -1,13 +1,13 @@
use speech_dispatcher::*;
use std::io;
fn main() {
fn main() -> Result<(), Box<dyn std::error::Error>> {
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(())
}

View File

@ -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<S: Into<String>>(
client_name: S,
connection_name: S,
user_name: S,
mode: Mode,
) -> Self {
) -> Result<Self, SpeechDispatcherError> {
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<S: Into<String>>(