Skip to content

Commit

Permalink
Use a static empty string instead of a new allocation every invocation
Browse files Browse the repository at this point in the history
  • Loading branch information
neersighted committed Apr 1, 2018
1 parent dca83c1 commit b32002d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 14 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "rust-g"
version = "0.1.2"
version = "0.1.3"
authors = ["Bjorn Neergaard <bjorn@neersighted.com>"]

[lib]
Expand Down
28 changes: 15 additions & 13 deletions src/byond.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<CString> = Cell::new(Default::default());
static RETURN_STRING: Cell<CString> = Cell::new(CString::default());
}

pub fn parse_args<'a>(argc: c_int, argv: *const *const c_char) -> Vec<Cow<'a, str>> {
Expand All @@ -20,24 +21,25 @@ pub fn parse_args<'a>(argc: c_int, argv: *const *const c_char) -> Vec<Cow<'a, st
}

pub fn return_string(string: Option<String>) -> *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)())
Expand All @@ -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);
Expand Down

0 comments on commit b32002d

Please sign in to comment.