From f642dd28fd5a794114e97774fc64c67489415fe4 Mon Sep 17 00:00:00 2001 From: Antoni Spaanderman <56turtle56@gmail.com> Date: Wed, 18 Sep 2024 22:58:57 +0200 Subject: [PATCH] add null pointer check before calling `CStr::from_ptr` also shrink unsafe blocks --- src/sdl2/filesystem.rs | 48 ++++++++++++++++++------------------------ 1 file changed, 20 insertions(+), 28 deletions(-) diff --git a/src/sdl2/filesystem.rs b/src/sdl2/filesystem.rs index 27d46c5898..5eac03dd3d 100644 --- a/src/sdl2/filesystem.rs +++ b/src/sdl2/filesystem.rs @@ -1,5 +1,4 @@ use crate::get_error; -use libc::c_char; use libc::c_void; use std::error; use std::ffi::{CStr, CString, NulError}; @@ -9,17 +8,15 @@ use crate::sys; #[doc(alias = "SDL_GetBasePath")] pub fn base_path() -> Result { - let result = unsafe { + unsafe { let buf = sys::SDL_GetBasePath(); - let s = CStr::from_ptr(buf as *const _).to_str().unwrap().to_owned(); - sys::SDL_free(buf as *mut c_void); - s - }; - - if result.is_empty() { - Err(get_error()) - } else { - Ok(result) + if buf.is_null() { + Err(get_error()) + } else { + let s = CStr::from_ptr(buf).to_str().unwrap().to_owned(); + sys::SDL_free(buf as *mut c_void); + Ok(s) + } } } @@ -58,23 +55,18 @@ impl error::Error for PrefPathError { #[doc(alias = "SDL_GetPrefPath")] pub fn pref_path(org_name: &str, app_name: &str) -> Result { use self::PrefPathError::*; - let result = unsafe { - let org = match CString::new(org_name) { - Ok(s) => s, - Err(err) => return Err(InvalidOrganizationName(err)), - }; - let app = match CString::new(app_name) { - Ok(s) => s, - Err(err) => return Err(InvalidApplicationName(err)), - }; - let buf = - sys::SDL_GetPrefPath(org.as_ptr() as *const c_char, app.as_ptr() as *const c_char); - CStr::from_ptr(buf as *const _).to_str().unwrap().to_owned() - }; - if result.is_empty() { - Err(SdlError(get_error())) - } else { - Ok(result) + let org = CString::new(org_name).map_err(InvalidOrganizationName)?; + let app = CString::new(app_name).map_err(InvalidApplicationName)?; + + unsafe { + let buf = sys::SDL_GetPrefPath(org.as_ptr(), app.as_ptr()); + if buf.is_null() { + Err(SdlError(get_error())) + } else { + let ret = CStr::from_ptr(buf).to_str().unwrap().to_owned(); + sys::SDL_free(buf as *mut c_void); + Ok(ret) + } } }