From b4fa7bd0cb83cf48945beca4b27ba312d12c50d6 Mon Sep 17 00:00:00 2001 From: AzureMarker Date: Sat, 23 Dec 2023 14:51:40 -0500 Subject: [PATCH] Improve packet parser error handling --- ctru-rs/examples/ir-user.rs | 5 ++++- ctru-rs/src/services/ir_user.rs | 13 +++++++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/ctru-rs/examples/ir-user.rs b/ctru-rs/examples/ir-user.rs index a8141d0..37af6ee 100644 --- a/ctru-rs/examples/ir-user.rs +++ b/ctru-rs/examples/ir-user.rs @@ -193,7 +193,10 @@ impl<'screen> CirclePadProDemo<'screen> { } fn handle_packets(&self) { - let packets = self.ir_user.get_packets(); + let packets = self + .ir_user + .get_packets() + .expect("Packets should be well formed"); let packet_count = packets.len(); let Some(last_packet) = packets.last() else { return; diff --git a/ctru-rs/src/services/ir_user.rs b/ctru-rs/src/services/ir_user.rs index 0860046..2709c13 100644 --- a/ctru-rs/src/services/ir_user.rs +++ b/ctru-rs/src/services/ir_user.rs @@ -5,6 +5,7 @@ use ctru_sys::{Handle, MEMPERM_READ, MEMPERM_READWRITE}; use std::alloc::Layout; use std::cmp::max; use std::ffi::CString; +use std::fmt::format; use std::ptr::{slice_from_raw_parts, slice_from_raw_parts_mut}; use std::sync::Mutex; @@ -243,7 +244,7 @@ impl IrUser { } /// Read and parse the current packets received from the IR device. - pub fn get_packets(&self) -> Vec { + pub fn get_packets(&self) -> Result, String> { let shared_mem_guard = IR_USER_STATE.lock().unwrap(); let user_state = shared_mem_guard.as_ref().unwrap(); let shared_mem = user_state.shared_memory; @@ -312,9 +313,13 @@ impl IrUser { // IR packets start with a magic number, so double check it let magic_number = packet_data(0); - assert_eq!(magic_number, 0xA5); + if magic_number != 0xA5 { + return Err(format!( + "Invalid magic number in packet: {magic_number:#x}, expected 0xA5" + )); + } - IrUserPacket { + Ok(IrUserPacket { magic_number: packet_data(0), destination_network_id: packet_data(1), payload_length, @@ -322,7 +327,7 @@ impl IrUser { .map(packet_data) .collect(), checksum: packet_data(payload_offset + payload_length), - } + }) }) .collect() }