From 87f33f144ea4a26f517c1fbb9c65de7257949fcc Mon Sep 17 00:00:00 2001 From: AzureMarker Date: Sat, 23 Dec 2023 14:44:49 -0500 Subject: [PATCH] Improve some service start/stop error handling --- ctru-rs/src/error.rs | 6 +++++- ctru-rs/src/services/ir_user.rs | 15 ++++++++++++--- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/ctru-rs/src/error.rs b/ctru-rs/src/error.rs index 87170ad..186de3d 100644 --- a/ctru-rs/src/error.rs +++ b/ctru-rs/src/error.rs @@ -94,6 +94,8 @@ pub enum Error { /// Size of the requested data (in bytes). wanted: usize, }, + /// An error that doesn't fit into the other categories. + Other(String), } impl Error { @@ -153,6 +155,7 @@ impl fmt::Debug for Error { .field("provided", provided) .field("wanted", wanted) .finish(), + Self::Other(err) => f.debug_tuple("Other").field(err).finish(), } } } @@ -175,7 +178,8 @@ impl fmt::Display for Error { Self::OutputAlreadyRedirected => { write!(f, "output streams are already redirected to 3dslink") } - Self::BufferTooShort{provided, wanted} => write!(f, "the provided buffer's length is too short (length = {provided}) to hold the wanted data (size = {wanted})") + Self::BufferTooShort{provided, wanted} => write!(f, "the provided buffer's length is too short (length = {provided}) to hold the wanted data (size = {wanted})"), + Self::Other(err) => write!(f, "{err}"), } } } diff --git a/ctru-rs/src/services/ir_user.rs b/ctru-rs/src/services/ir_user.rs index bb451d0..0860046 100644 --- a/ctru-rs/src/services/ir_user.rs +++ b/ctru-rs/src/services/ir_user.rs @@ -1,5 +1,6 @@ use crate::error::ResultCode; use crate::services::ServiceReference; +use crate::Error; use ctru_sys::{Handle, MEMPERM_READ, MEMPERM_READWRITE}; use std::alloc::Layout; use std::cmp::max; @@ -107,14 +108,22 @@ impl IrUser { recv_buffer_size, recv_packet_count, }; - *IR_USER_STATE.lock().unwrap() = Some(user_state); + let mut ir_user_state = IR_USER_STATE + .lock() + .map_err(|e| Error::Other(format!("Failed to write to IR_USER_STATE: {e}")))?; + *ir_user_state = Some(user_state); Ok(()) }, || { // Remove our service state from the global location - let mut shared_mem_guard = IR_USER_STATE.lock().unwrap(); - let shared_mem = shared_mem_guard.take().unwrap(); + let mut shared_mem_guard = IR_USER_STATE + .lock() + .expect("Failed to write to IR_USER_STATE"); + let Some(shared_mem) = shared_mem_guard.take() else { + // If we don't have any state, then we don't need to clean up. + return; + }; (move || unsafe { // Close service and memory handles