Skip to content

Instantly share code, notes, and snippets.

@ben0x539
Created September 25, 2014 21:52
Show Gist options
  • Select an option

  • Save ben0x539/4517e404aab56c9e2e1e to your computer and use it in GitHub Desktop.

Select an option

Save ben0x539/4517e404aab56c9e2e1e to your computer and use it in GitHub Desktop.
use self::string10_mod::inlinevec::InlineVec as VecString10;
use self::int4_mod::inlinevec::InlineVec as FourBoundedArray;
mod string10_mod {
type T = String;
static N: uint = 10;
static Size: uint = 3 * 8;
static Align: uint = 8;
#[path = "../inlinevec.rs"] pub mod inlinevec;
}
mod int4_mod {
type T = i32;
static N: uint = 4;
static Size: uint = 4;
static Align: uint = 4;
#[path = "../inlinevec.rs"] pub mod inlinevec;
}
fn main() {
let mut v = VecString10::new();
v.push("heh".to_string());
v.push("ok it works i guess".to_string());
println!("sizeof: {}\n\
size of 10 strings: {}\n",
std::mem::size_of::<VecString10>(),
std::mem::size_of::<String>() * 10,
);
let mut x = FourBoundedArray::new(); // n == 4
println!("{}", x); // []
x.push(1);
println!("{}", x); // [1]
x.push(2);
x.push(3);
x.push(4);
println!("{}", x); // [1, 2, 3, 4]
x.pop();
println!("{}", x); // [1, 2, 3]
x.push(5);
x.push(6); // error
}
use super::T as T;
use super::N as N;
use super::Size as Size;
use super::Align as Align;
use std::mem;
use std::ptr;
use std::raw;
use std::fmt;
#[unsafe_no_drop_flag]
pub struct InlineVec {
buf: [u8, .. ((N*Size) + Align - 1)],
length: uint,
}
impl InlineVec {
pub fn new() -> InlineVec {
unsafe {
InlineVec {
buf: mem::uninitialized(),
length: 0,
}
}
}
pub fn push(&mut self, v: T) {
assert!(self.length < Size);
let start = self.align_mut();
unsafe { ptr::write(start.offset(self.length as int), v); }
self.length += 1;
}
pub fn pop(&mut self) -> T {
assert!(self.length > 0);
let start = self.align();
self.length -= 1;
unsafe { ptr::read(start.offset(self.length as int)) }
}
pub fn as_slice(&self) -> &[T] {
unsafe {
mem::transmute(raw::Slice {
data: self.align(),
len: self.length as uint
})
}
}
pub fn as_mut_slice(&self) -> &mut [T] {
unsafe {
mem::transmute(raw::Slice {
data: self.align(),
len: self.length as uint
})
}
}
fn align(&self) -> *const T {
(((&self.buf[0] as *const _ as uint) + Align - 1) / Align * Align) as *const T
}
fn align_mut(&mut self) -> *mut T {
(((&self.buf[0] as *const _ as uint) + Align - 1) / Align * Align) as *mut T
}
}
impl Drop for InlineVec {
fn drop(&mut self) {
let start = self.align();
for i in range(0, self.length) {
unsafe { ptr::read(start.offset(i as int)); }
}
self.length = 0;
}
}
impl /* <T: Show>. ... */ fmt::Show for InlineVec {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::FormatError> {
self.as_slice().fmt(f)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment