Skip to content

Instantly share code, notes, and snippets.

@saethlin
Created April 15, 2018 18:49
Show Gist options
  • Save saethlin/ac0526eb7d5fc8c45e097fc604ada4d1 to your computer and use it in GitHub Desktop.
Save saethlin/ac0526eb7d5fc8c45e097fc604ada4d1 to your computer and use it in GitHub Desktop.
Rust TinyPtrVec
#![feature(untagged_unions)]
#[repr(C)]
struct MyVec<T> {
data: *mut *const T,
length: usize,
capacity: usize,
}
union TinyPtrVec<T> {
outline: MyVec<T>,
inline: [*const T; 3],
bytes: (u64, u64, u64),
}
impl<T> TinyPtrVec<T> {
fn get(&self, index: usize) -> *const T {
unsafe {
let pointer_byte = self.bytes.0;
let inline_len = pointer_byte & 0x4;
if inline_len <= 3 { // We can use the inline vector
if index == 0 { // Clear the low bits first
((pointer_byte & !0x4) as *const T)
} else {
self.inline[index]
}
} else { // Use the out-of-line vector
std::slice::from_raw_parts(self.outline.data, self.outline.length)[index]
}
}
}
}
fn main() {
println!("{}", std::mem::size_of::<Vec<u8>>());
println!("{}", std::mem::size_of::<TinyPtrVec<u8>>());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment