Skip to content

Commit 49c92ef

Browse files
committed
safely handle nullptr for SBValue (fixes endoli#23)
1 parent 26774b3 commit 49c92ef

File tree

1 file changed

+20
-28
lines changed

1 file changed

+20
-28
lines changed

src/value.rs

+20-28
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use crate::{
1010
};
1111
use std::ffi::{CStr, CString};
1212
use std::fmt;
13+
use std::os::raw::c_char;
1314

1415
/// The value of a variable, register or expression.
1516
pub struct SBValue {
@@ -53,33 +54,18 @@ impl SBValue {
5354
}
5455

5556
#[allow(missing_docs)]
56-
pub fn name(&self) -> &str {
57-
unsafe {
58-
match CStr::from_ptr(sys::SBValueGetName(self.raw)).to_str() {
59-
Ok(s) => s,
60-
_ => panic!("Invalid string?"),
61-
}
62-
}
57+
pub fn name(&self) -> Option<&str> {
58+
unsafe { self.check_null_ptr(sys::SBValueGetName(self.raw)) }
6359
}
6460

6561
#[allow(missing_docs)]
66-
pub fn type_name(&self) -> &str {
67-
unsafe {
68-
match CStr::from_ptr(sys::SBValueGetTypeName(self.raw)).to_str() {
69-
Ok(s) => s,
70-
_ => panic!("Invalid string?"),
71-
}
72-
}
62+
pub fn type_name(&self) -> Option<&str> {
63+
unsafe { self.check_null_ptr(sys::SBValueGetTypeName(self.raw)) }
7364
}
7465

7566
#[allow(missing_docs)]
76-
pub fn display_type_name(&self) -> &str {
77-
unsafe {
78-
match CStr::from_ptr(sys::SBValueGetDisplayTypeName(self.raw)).to_str() {
79-
Ok(s) => s,
80-
_ => panic!("Invalid string?"),
81-
}
82-
}
67+
pub fn display_type_name(&self) -> Option<&str> {
68+
unsafe { self.check_null_ptr(sys::SBValueGetDisplayTypeName(self.raw)) }
8369
}
8470

8571
#[allow(missing_docs)]
@@ -103,13 +89,8 @@ impl SBValue {
10389
}
10490

10591
#[allow(missing_docs)]
106-
pub fn value(&self) -> &str {
107-
unsafe {
108-
match CStr::from_ptr(sys::SBValueGetValue(self.raw)).to_str() {
109-
Ok(s) => s,
110-
_ => panic!("Invalid string?"),
111-
}
112-
}
92+
pub fn value(&self) -> Option<&str> {
93+
unsafe { self.check_null_ptr(sys::SBValueGetValue(self.raw)) }
11394
}
11495

11596
#[allow(missing_docs)]
@@ -257,6 +238,17 @@ impl SBValue {
257238
pub fn address(&self) -> Option<SBAddress> {
258239
SBAddress::maybe_wrap(unsafe { sys::SBValueGetAddress(self.raw) })
259240
}
241+
242+
unsafe fn check_null_ptr(&self, ptr: *const c_char) -> Option<&str> {
243+
if !ptr.is_null() {
244+
match CStr::from_ptr(ptr).to_str() {
245+
Ok(s) => Some(s),
246+
_ => panic!("Invalid string?"),
247+
}
248+
} else {
249+
None
250+
}
251+
}
260252
}
261253

262254
impl Clone for SBValue {

0 commit comments

Comments
 (0)