Use g_strndup() instead of creating a CString and then g_strdup() it

Creating a CString involves potentially some additional allocations.
This commit is contained in:
Sebastian Dröge 2017-04-14 12:41:39 +03:00
parent 9864413be2
commit a808c34794
3 changed files with 9 additions and 18 deletions

View file

@ -8,6 +8,7 @@
use std::ffi::CString;
use std::ptr;
use libc::c_char;
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::fmt::Error as FmtError;
@ -112,15 +113,11 @@ impl ErrorMessage {
line,
} = *self;
let message_cstr = message
.as_ref()
.map(|m| CString::new(m.as_bytes()).unwrap());
let message_ptr = message_cstr.as_ref().map_or(ptr::null(), |m| m.as_ptr());
let message_ptr = message.as_ref().map_or(ptr::null(), |m| m.as_ptr()) as *const c_char;
let message_len = message.as_ref().map_or(0, |m| m.len());
let debug_cstr = debug
.as_ref()
.map(|m| CString::new(m.as_bytes()).unwrap());
let debug_ptr = debug_cstr.as_ref().map_or(ptr::null(), |m| m.as_ptr());
let debug_ptr = debug.as_ref().map_or(ptr::null(), |m| m.as_ptr()) as *const c_char;
let debug_len = debug.as_ref().map_or(0, |m| m.len());
let file_cstr = CString::new(filename.as_bytes()).unwrap();
let file_ptr = file_cstr.as_ptr();
@ -132,8 +129,8 @@ impl ErrorMessage {
gst::GST_MESSAGE_ERROR,
error_domain,
error_code,
glib::g_strdup(message_ptr),
glib::g_strdup(debug_ptr),
glib::g_strndup(message_ptr, message_len),
glib::g_strndup(debug_ptr, debug_len),
file_ptr,
function_ptr,
line as i32);

View file

@ -234,10 +234,7 @@ unsafe fn sink_get_uri(ptr: *const RsSink) -> *mut c_char {
panic_to_error!(wrap, ptr::null_mut(), {
match wrap.get_uri() {
Some(uri_str) => {
let uri_cstr = CString::new(uri_str).unwrap();
glib::g_strdup(uri_cstr.as_ptr())
}
Some(uri_str) => glib::g_strndup(uri_str.as_ptr() as *const c_char, uri_str.len()),
None => ptr::null_mut(),
}
})

View file

@ -266,10 +266,7 @@ unsafe fn source_get_uri(ptr: *const RsSrc) -> *mut c_char {
panic_to_error!(wrap, ptr::null_mut(), {
match wrap.get_uri() {
Some(uri_str) => {
let uri_cstr = CString::new(uri_str).unwrap();
glib::g_strdup(uri_cstr.as_ptr())
}
Some(uri_str) => glib::g_strndup(uri_str.as_ptr() as *const c_char, uri_str.len()),
None => ptr::null_mut(),
}
})