From b32002d7962d5b80671740593737f5f6f11f4a30 Mon Sep 17 00:00:00 2001 From: Bjorn Neergaard Date: Sun, 1 Apr 2018 09:47:29 -0600 Subject: [PATCH] Use a static empty string instead of a new allocation every invocation --- Cargo.toml | 2 +- src/byond.rs | 28 +++++++++++++++------------- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 134b105d..09a61122 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rust-g" -version = "0.1.2" +version = "0.1.3" authors = ["Bjorn Neergaard "] [lib] diff --git a/src/byond.rs b/src/byond.rs index 9f1358e9..a0f364c6 100644 --- a/src/byond.rs +++ b/src/byond.rs @@ -5,8 +5,9 @@ use std::slice; use libc::{c_char, c_int}; +static EMPTY_STRING: &[c_char; 1] = &[0]; thread_local! { - static RETURN_STRING: Cell = Cell::new(Default::default()); + static RETURN_STRING: Cell = Cell::new(CString::default()); } pub fn parse_args<'a>(argc: c_int, argv: *const *const c_char) -> Vec> { @@ -20,24 +21,25 @@ pub fn parse_args<'a>(argc: c_int, argv: *const *const c_char) -> Vec) -> *const c_char { - let cstring = match string { - Some(msg) => CString::new(msg).expect("null in returned string!"), - None => CString::new("").unwrap(), - }; - let ptr = cstring.as_ptr(); - - RETURN_STRING.with(|cell| { - cell.set(cstring); - }); + match string { + Some(string) => { + RETURN_STRING.with(|cell| { + let cstring = CString::new(string).expect("null in returned string!"); + let ptr = cstring.as_ptr(); - ptr as *const c_char + cell.set(cstring); + ptr as *const c_char + }) + }, + None => EMPTY_STRING as *const c_char, + } } #[macro_export] macro_rules! byond_function { ($name:ident() $body:block) => { #[no_mangle] - pub extern "C" fn $name( + pub unsafe extern "C" fn $name( _argc: ::libc::c_int, _argv: *const *const ::libc::c_char ) -> *const ::libc::c_char { $crate::byond::return_string((|| $body)()) @@ -46,7 +48,7 @@ macro_rules! byond_function { ($name:ident($($arg:ident),*) $body:block) => { #[no_mangle] - pub extern "C" fn $name( + pub unsafe extern "C" fn $name( _argc: ::libc::c_int, _argv: *const *const ::libc::c_char ) -> *const ::libc::c_char { let __args = $crate::byond::parse_args(_argc, _argv);