Created
April 15, 2018 18:49
-
-
Save saethlin/ac0526eb7d5fc8c45e097fc604ada4d1 to your computer and use it in GitHub Desktop.
Rust TinyPtrVec
This file contains hidden or 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(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