Created
December 2, 2015 20:35
-
-
Save Swatinem/34ac667b170a069b326d to your computer and use it in GitHub Desktop.
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
#![feature(alloc)] | |
#![feature(heap_api)] | |
extern crate alloc; | |
use alloc::heap::{usable_size}; | |
use std::mem::{align_of, size_of}; | |
use std::str::{from_utf8}; | |
fn print_vec_sizes<T>(v: &Vec<T>) { | |
let elem_size = size_of::<T>(); | |
let elem_align = align_of::<T>(); | |
let cap = v.capacity(); | |
let actual = elem_size * cap; | |
let usable = usable_size(actual, elem_align); | |
let possible = usable / elem_size; | |
println!("item size/align: {:#?}/{:#?} ; cap/mem: {:#?}/{:#?} ; usable cap/mem {:#?}/{:#?}", | |
elem_size, elem_align, cap, actual, possible, usable); | |
} | |
fn print_string_sizes(s: &mut String) { | |
unsafe { | |
print_vec_sizes(s.as_mut_vec()); | |
} | |
} | |
fn main() { | |
let mut v: Vec<u32> = Vec::new(); | |
v.push(1); | |
print_vec_sizes(&v); | |
v.reserve(1024); | |
print_vec_sizes(&v); | |
v.extend([1; 1025].iter()); | |
print_vec_sizes(&v); | |
let mut s = String::new(); | |
s.extend("a".chars()); | |
print_string_sizes(&mut s); | |
s.reserve(1024); | |
print_string_sizes(&mut s); | |
s.extend(from_utf8(&[97u8; 1025]).unwrap().chars()); | |
print_string_sizes(&mut s); | |
} |
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
item size/align: 4/4 ; cap/mem: 4/16 ; usable cap/mem 4/16 | |
item size/align: 4/4 ; cap/mem: 1025/4100 ; usable cap/mem 2048/8192 | |
item size/align: 4/4 ; cap/mem: 2050/8200 ; usable cap/mem 3072/12288 | |
item size/align: 1/1 ; cap/mem: 1/1 ; usable cap/mem 8/8 | |
item size/align: 1/1 ; cap/mem: 1025/1025 ; usable cap/mem 1280/1280 | |
item size/align: 1/1 ; cap/mem: 2050/2050 ; usable cap/mem 2560/2560 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment