Last active
October 27, 2015 10:55
-
-
Save ArtemGr/e11cdacf8b5315498c00 to your computer and use it in GitHub Desktop.
gstring - Rust macros to make strings on stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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