Created
June 1, 2015 12:24
-
-
Save ayosec/acb5d7dc8d73dd774164 to your computer and use it in GitHub Desktop.
Small string in Rust
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
use std::mem; | |
use std::fmt::Write; | |
fn dump_bytes<T>(val: &T) -> String { | |
let mut output = String::new(); | |
let bytes = unsafe { | |
let pointer: *const u8 = std::mem::transmute(val); | |
std::slice::from_raw_parts(pointer, std::mem::size_of::<T>()) | |
}; | |
for byte in bytes { | |
match *byte { | |
32...128 => { output.push(*byte as char); }, | |
x => { let _ = write!(&mut output, "({})", x); }, | |
} | |
} | |
output | |
} | |
fn dump_qwords<T>(val: &T) -> String { | |
let qwords = unsafe { | |
let pointer: *const u64 = std::mem::transmute(val); | |
std::slice::from_raw_parts(pointer, std::mem::size_of::<T>() / 8) | |
}; | |
qwords.iter().map(|&qword| format!("{:016x}", qword)).collect::<Vec<_>>().connect(" ") | |
} | |
enum StringContainer { | |
EmbeddedASCII([u8; 47]), | |
StaticRef(&'static str), | |
Owned(String), | |
} | |
fn main() { | |
let items = vec![ | |
StringContainer::Owned("foo".to_string()), | |
StringContainer::EmbeddedASCII([65; 47]), | |
StringContainer::StaticRef("foo") | |
]; | |
for item in &items { | |
println!("-"); | |
println!("Size: {} bytes", mem::size_of_val(item)); | |
println!("bytes(x) = {}", dump_bytes(item)); | |
println!("qwords(x) = {}", dump_qwords(item)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment