Skip to content

Commit

Permalink
safely handle nullptr for SBThread
Browse files Browse the repository at this point in the history
  • Loading branch information
roccoblues authored and waywardmonkeys committed Apr 17, 2024
1 parent 3e0876b commit cc6fa1b
Showing 1 changed file with 16 additions and 14 deletions.
30 changes: 16 additions & 14 deletions src/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::{
};
use std::ffi::{CStr, CString};
use std::fmt;
use std::os::raw::c_char;
use std::ptr;

/// A thread of execution.
Expand Down Expand Up @@ -127,13 +128,8 @@ impl SBThread {
}

/// The name associated with the thread, if any.
pub fn name(&self) -> &str {
unsafe {
match CStr::from_ptr(sys::SBThreadGetName(self.raw)).to_str() {
Ok(s) => s,
_ => panic!("Invalid string?"),
}
}
pub fn name(&self) -> Option<&str> {
unsafe { self.check_null_ptr(sys::SBThreadGetName(self.raw)) }
}

/// Return the queue associated with this thread, if any.
Expand All @@ -150,13 +146,8 @@ impl SBThread {
///
/// For example, this would report a `libdispatch` (Grand Central Dispatch)
/// queue name.
pub fn queue_name(&self) -> &str {
unsafe {
match CStr::from_ptr(sys::SBThreadGetQueueName(self.raw)).to_str() {
Ok(s) => s,
_ => panic!("Invalid string?"),
}
}
pub fn queue_name(&self) -> Option<&str> {
unsafe { self.check_null_ptr(sys::SBThreadGetQueueName(self.raw)) }
}

/// Return the `dispatch_queue_id` for this thread, if any.
Expand Down Expand Up @@ -322,6 +313,17 @@ impl SBThread {
None
}
}

unsafe fn check_null_ptr(&self, ptr: *const c_char) -> Option<&str> {
if !ptr.is_null() {
match CStr::from_ptr(ptr).to_str() {
Ok(s) => Some(s),
_ => panic!("Invalid string?"),
}
} else {
None
}
}
}

/// Iterate over the [frames] in a [thread].
Expand Down

0 comments on commit cc6fa1b

Please sign in to comment.