Skip to content

Instantly share code, notes, and snippets.

@ArtemGr
Last active October 27, 2015 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArtemGr/e11cdacf8b5315498c00 to your computer and use it in GitHub Desktop.
Save ArtemGr/e11cdacf8b5315498c00 to your computer and use it in GitHub Desktop.
gstring - Rust macros to make strings on stack
/// A helper to build a string on the stack.
///
/// Given an array it makes a writeable cursor available to the passed code block.
///
/// Returns a &str slice pointing at memory between the array start and the cursor.
///
/// Example:
///
/// use std::io::Write;
/// let mut foobar: [u8; 128] = unsafe {std::mem::uninitialized()};
/// let foobar = gstring! (foobar, {
/// write! (foobar, "foo") .unwrap();
/// write! (foobar, "bar") .unwrap();
/// });
macro_rules! gstring {($array: ident, $code: block) => {{
let end = {
let mut $array = std::io::Cursor::new (&mut $array[..]);
let $array = &mut $array;
$code;
$array.position() as usize
};
unsafe {std::str::from_utf8_unchecked (&$array[0..end])}}
}}
fn main() {
use std::io::Write;
let mut two_and_two: [u8; 32] = unsafe {std::mem::uninitialized()};
let two_and_two = gstring! (two_and_two, {
write! (two_and_two, "2 + 2 = {}", 2 + 2) .unwrap();
});
println! ("{}", two_and_two);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment