mirror of https://github.com/rust-lang/nomicon
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
404 lines
9.9 KiB
404 lines
9.9 KiB
8 years ago
|
# The Final Code
|
||
10 years ago
|
|
||
|
```rust
|
||
4 years ago
|
use std::alloc::{self, Layout};
|
||
|
use std::marker::PhantomData;
|
||
10 years ago
|
use std::mem;
|
||
|
use std::ops::{Deref, DerefMut};
|
||
4 years ago
|
use std::ptr::{self, NonNull};
|
||
10 years ago
|
|
||
|
struct RawVec<T> {
|
||
4 years ago
|
ptr: NonNull<T>,
|
||
10 years ago
|
cap: usize,
|
||
4 years ago
|
_marker: PhantomData<T>,
|
||
10 years ago
|
}
|
||
|
|
||
4 years ago
|
unsafe impl<T: Send> Send for RawVec<T> {}
|
||
|
unsafe impl<T: Sync> Sync for RawVec<T> {}
|
||
|
|
||
10 years ago
|
impl<T> RawVec<T> {
|
||
|
fn new() -> Self {
|
||
8 years ago
|
// !0 is usize::MAX. This branch should be stripped at compile time.
|
||
|
let cap = if mem::size_of::<T>() == 0 { !0 } else { 0 };
|
||
10 years ago
|
|
||
4 years ago
|
// `NonNull::dangling()` doubles as "unallocated" and "zero-sized allocation"
|
||
|
RawVec {
|
||
|
ptr: NonNull::dangling(),
|
||
|
cap: cap,
|
||
|
_marker: PhantomData,
|
||
|
}
|
||
10 years ago
|
}
|
||
|
|
||
|
fn grow(&mut self) {
|
||
4 years ago
|
// since we set the capacity to usize::MAX when T has size 0,
|
||
|
// getting to here necessarily means the Vec is overfull.
|
||
|
assert!(mem::size_of::<T>() != 0, "capacity overflow");
|
||
10 years ago
|
|
||
4 years ago
|
let (new_cap, new_layout) = if self.cap == 0 {
|
||
|
(1, Layout::array::<T>(1).unwrap())
|
||
|
} else {
|
||
|
// This can't overflow because we ensure self.cap <= isize::MAX.
|
||
|
let new_cap = 2 * self.cap;
|
||
|
|
||
|
// `Layout::array` checks that the number of bytes is <= usize::MAX,
|
||
|
// but this is redundant since old_layout.size() <= isize::MAX,
|
||
|
// so the `unwrap` should never fail.
|
||
|
let new_layout = Layout::array::<T>(new_cap).unwrap();
|
||
|
(new_cap, new_layout)
|
||
|
};
|
||
|
|
||
|
// Ensure that the new allocation doesn't exceed `isize::MAX` bytes.
|
||
|
assert!(
|
||
|
new_layout.size() <= isize::MAX as usize,
|
||
|
"Allocation too large"
|
||
|
);
|
||
|
|
||
|
let new_ptr = if self.cap == 0 {
|
||
|
unsafe { alloc::alloc(new_layout) }
|
||
|
} else {
|
||
|
let old_layout = Layout::array::<T>(self.cap).unwrap();
|
||
|
let old_ptr = self.ptr.as_ptr() as *mut u8;
|
||
|
unsafe { alloc::realloc(old_ptr, old_layout, new_layout.size()) }
|
||
|
};
|
||
|
|
||
|
// If allocation fails, `new_ptr` will be null, in which case we abort.
|
||
|
self.ptr = match NonNull::new(new_ptr as *mut T) {
|
||
|
Some(p) => p,
|
||
|
None => alloc::handle_alloc_error(new_layout),
|
||
|
};
|
||
|
self.cap = new_cap;
|
||
10 years ago
|
}
|
||
|
}
|
||
|
|
||
|
impl<T> Drop for RawVec<T> {
|
||
|
fn drop(&mut self) {
|
||
|
let elem_size = mem::size_of::<T>();
|
||
4 years ago
|
|
||
10 years ago
|
if self.cap != 0 && elem_size != 0 {
|
||
|
unsafe {
|
||
4 years ago
|
alloc::dealloc(
|
||
|
self.ptr.as_ptr() as *mut u8,
|
||
|
Layout::array::<T>(self.cap).unwrap(),
|
||
|
);
|
||
10 years ago
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pub struct Vec<T> {
|
||
|
buf: RawVec<T>,
|
||
|
len: usize,
|
||
|
}
|
||
|
|
||
|
impl<T> Vec<T> {
|
||
4 years ago
|
fn ptr(&self) -> *mut T {
|
||
|
self.buf.ptr.as_ptr()
|
||
|
}
|
||
10 years ago
|
|
||
4 years ago
|
fn cap(&self) -> usize {
|
||
|
self.buf.cap
|
||
|
}
|
||
10 years ago
|
|
||
|
pub fn new() -> Self {
|
||
4 years ago
|
Vec {
|
||
|
buf: RawVec::new(),
|
||
|
len: 0,
|
||
|
}
|
||
10 years ago
|
}
|
||
|
pub fn push(&mut self, elem: T) {
|
||
4 years ago
|
if self.len == self.cap() {
|
||
|
self.buf.grow();
|
||
|
}
|
||
10 years ago
|
|
||
|
unsafe {
|
||
4 years ago
|
ptr::write(self.ptr().add(self.len), elem);
|
||
10 years ago
|
}
|
||
|
|
||
4 years ago
|
// Can't overflow, we'll OOM first.
|
||
10 years ago
|
self.len += 1;
|
||
|
}
|
||
|
|
||
|
pub fn pop(&mut self) -> Option<T> {
|
||
|
if self.len == 0 {
|
||
|
None
|
||
|
} else {
|
||
|
self.len -= 1;
|
||
4 years ago
|
unsafe { Some(ptr::read(self.ptr().add(self.len))) }
|
||
10 years ago
|
}
|
||
|
}
|
||
|
|
||
|
pub fn insert(&mut self, index: usize, elem: T) {
|
||
|
assert!(index <= self.len, "index out of bounds");
|
||
4 years ago
|
if self.cap() == self.len {
|
||
|
self.buf.grow();
|
||
|
}
|
||
10 years ago
|
|
||
|
unsafe {
|
||
4 years ago
|
ptr::copy(
|
||
4 years ago
|
self.ptr().add(index),
|
||
|
self.ptr().add(index + 1),
|
||
4 years ago
|
self.len - index,
|
||
|
);
|
||
4 years ago
|
ptr::write(self.ptr().add(index), elem);
|
||
10 years ago
|
self.len += 1;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pub fn remove(&mut self, index: usize) -> T {
|
||
|
assert!(index < self.len, "index out of bounds");
|
||
|
unsafe {
|
||
|
self.len -= 1;
|
||
4 years ago
|
let result = ptr::read(self.ptr().add(index));
|
||
4 years ago
|
ptr::copy(
|
||
4 years ago
|
self.ptr().add(index + 1),
|
||
|
self.ptr().add(index),
|
||
4 years ago
|
self.len - index,
|
||
|
);
|
||
10 years ago
|
result
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pub fn into_iter(self) -> IntoIter<T> {
|
||
|
unsafe {
|
||
|
let iter = RawValIter::new(&self);
|
||
|
let buf = ptr::read(&self.buf);
|
||
|
mem::forget(self);
|
||
|
|
||
|
IntoIter {
|
||
|
iter: iter,
|
||
|
_buf: buf,
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pub fn drain(&mut self) -> Drain<T> {
|
||
|
unsafe {
|
||
10 years ago
|
let iter = RawValIter::new(&self);
|
||
|
|
||
10 years ago
|
// this is a mem::forget safety thing. If Drain is forgotten, we just
|
||
10 years ago
|
// leak the whole Vec's contents. Also we need to do this *eventually*
|
||
|
// anyway, so why not do it now?
|
||
|
self.len = 0;
|
||
|
|
||
10 years ago
|
Drain {
|
||
10 years ago
|
iter: iter,
|
||
10 years ago
|
vec: PhantomData,
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl<T> Drop for Vec<T> {
|
||
|
fn drop(&mut self) {
|
||
|
while let Some(_) = self.pop() {}
|
||
4 years ago
|
// deallocation is handled by RawVec
|
||
10 years ago
|
}
|
||
|
}
|
||
|
|
||
|
impl<T> Deref for Vec<T> {
|
||
|
type Target = [T];
|
||
|
fn deref(&self) -> &[T] {
|
||
4 years ago
|
unsafe { std::slice::from_raw_parts(self.ptr(), self.len) }
|
||
10 years ago
|
}
|
||
|
}
|
||
|
|
||
|
impl<T> DerefMut for Vec<T> {
|
||
|
fn deref_mut(&mut self) -> &mut [T] {
|
||
4 years ago
|
unsafe { std::slice::from_raw_parts_mut(self.ptr(), self.len) }
|
||
10 years ago
|
}
|
||
|
}
|
||
|
|
||
|
struct RawValIter<T> {
|
||
|
start: *const T,
|
||
|
end: *const T,
|
||
|
}
|
||
|
|
||
|
impl<T> RawValIter<T> {
|
||
|
unsafe fn new(slice: &[T]) -> Self {
|
||
|
RawValIter {
|
||
|
start: slice.as_ptr(),
|
||
|
end: if mem::size_of::<T>() == 0 {
|
||
|
((slice.as_ptr() as usize) + slice.len()) as *const _
|
||
|
} else if slice.len() == 0 {
|
||
|
slice.as_ptr()
|
||
|
} else {
|
||
4 years ago
|
slice.as_ptr().add(slice.len())
|
||
4 years ago
|
},
|
||
10 years ago
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl<T> Iterator for RawValIter<T> {
|
||
|
type Item = T;
|
||
|
fn next(&mut self) -> Option<T> {
|
||
|
if self.start == self.end {
|
||
|
None
|
||
|
} else {
|
||
|
unsafe {
|
||
|
let result = ptr::read(self.start);
|
||
9 years ago
|
self.start = if mem::size_of::<T>() == 0 {
|
||
9 years ago
|
(self.start as usize + 1) as *const _
|
||
|
} else {
|
||
|
self.start.offset(1)
|
||
|
};
|
||
10 years ago
|
Some(result)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
fn size_hint(&self) -> (usize, Option<usize>) {
|
||
|
let elem_size = mem::size_of::<T>();
|
||
4 years ago
|
let len = (self.end as usize - self.start as usize) /
|
||
|
if elem_size == 0 { 1 } else { elem_size };
|
||
10 years ago
|
(len, Some(len))
|
||
|
}
|
||
|
}
|
||
|
|
||
|
impl<T> DoubleEndedIterator for RawValIter<T> {
|
||
|
fn next_back(&mut self) -> Option<T> {
|
||
|
if self.start == self.end {
|
||
|
None
|
||
|
} else {
|
||
|
unsafe {
|
||
9 years ago
|
self.end = if mem::size_of::<T>() == 0 {
|
||
9 years ago
|
(self.end as usize - 1) as *const _
|
||
|
} else {
|
||
|
self.end.offset(-1)
|
||
|
};
|
||
10 years ago
|
Some(ptr::read(self.end))
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pub struct IntoIter<T> {
|
||
|
_buf: RawVec<T>, // we don't actually care about this. Just need it to live.
|
||
|
iter: RawValIter<T>,
|
||
|
}
|
||
|
|
||
|
impl<T> Iterator for IntoIter<T> {
|
||
|
type Item = T;
|
||
4 years ago
|
fn next(&mut self) -> Option<T> {
|
||
|
self.iter.next()
|
||
|
}
|
||
|
fn size_hint(&self) -> (usize, Option<usize>) {
|
||
|
self.iter.size_hint()
|
||
|
}
|
||
10 years ago
|
}
|
||
|
|
||
|
impl<T> DoubleEndedIterator for IntoIter<T> {
|
||
4 years ago
|
fn next_back(&mut self) -> Option<T> {
|
||
|
self.iter.next_back()
|
||
|
}
|
||
10 years ago
|
}
|
||
|
|
||
|
impl<T> Drop for IntoIter<T> {
|
||
|
fn drop(&mut self) {
|
||
|
for _ in &mut *self {}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
pub struct Drain<'a, T: 'a> {
|
||
|
vec: PhantomData<&'a mut Vec<T>>,
|
||
|
iter: RawValIter<T>,
|
||
|
}
|
||
|
|
||
|
impl<'a, T> Iterator for Drain<'a, T> {
|
||
|
type Item = T;
|
||
4 years ago
|
fn next(&mut self) -> Option<T> {
|
||
|
self.iter.next()
|
||
|
}
|
||
|
fn size_hint(&self) -> (usize, Option<usize>) {
|
||
|
self.iter.size_hint()
|
||
|
}
|
||
10 years ago
|
}
|
||
|
|
||
|
impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
|
||
4 years ago
|
fn next_back(&mut self) -> Option<T> {
|
||
|
self.iter.next_back()
|
||
|
}
|
||
10 years ago
|
}
|
||
|
|
||
|
impl<'a, T> Drop for Drain<'a, T> {
|
||
|
fn drop(&mut self) {
|
||
|
// pre-drain the iter
|
||
4 years ago
|
for _ in &mut *self {}
|
||
10 years ago
|
}
|
||
|
}
|
||
4 years ago
|
#
|
||
7 years ago
|
# fn main() {
|
||
|
# tests::create_push_pop();
|
||
|
# tests::iter_test();
|
||
|
# tests::test_drain();
|
||
|
# tests::test_zst();
|
||
7 years ago
|
# println!("All tests finished OK");
|
||
7 years ago
|
# }
|
||
4 years ago
|
#
|
||
7 years ago
|
# mod tests {
|
||
|
# use super::*;
|
||
4 years ago
|
#
|
||
7 years ago
|
# pub fn create_push_pop() {
|
||
|
# let mut v = Vec::new();
|
||
|
# v.push(1);
|
||
|
# assert_eq!(1, v.len());
|
||
|
# assert_eq!(1, v[0]);
|
||
|
# for i in v.iter_mut() {
|
||
|
# *i += 1;
|
||
|
# }
|
||
7 years ago
|
# v.insert(0, 5);
|
||
7 years ago
|
# let x = v.pop();
|
||
|
# assert_eq!(Some(2), x);
|
||
|
# assert_eq!(1, v.len());
|
||
|
# v.push(10);
|
||
|
# let x = v.remove(0);
|
||
7 years ago
|
# assert_eq!(5, x);
|
||
7 years ago
|
# assert_eq!(1, v.len());
|
||
|
# }
|
||
7 years ago
|
#
|
||
7 years ago
|
# pub fn iter_test() {
|
||
|
# let mut v = Vec::new();
|
||
|
# for i in 0..10 {
|
||
|
# v.push(Box::new(i))
|
||
|
# }
|
||
|
# let mut iter = v.into_iter();
|
||
|
# let first = iter.next().unwrap();
|
||
|
# let last = iter.next_back().unwrap();
|
||
|
# drop(iter);
|
||
|
# assert_eq!(0, *first);
|
||
|
# assert_eq!(9, *last);
|
||
|
# }
|
||
7 years ago
|
#
|
||
7 years ago
|
# pub fn test_drain() {
|
||
|
# let mut v = Vec::new();
|
||
|
# for i in 0..10 {
|
||
|
# v.push(Box::new(i))
|
||
|
# }
|
||
|
# {
|
||
|
# let mut drain = v.drain();
|
||
|
# let first = drain.next().unwrap();
|
||
|
# let last = drain.next_back().unwrap();
|
||
|
# assert_eq!(0, *first);
|
||
|
# assert_eq!(9, *last);
|
||
|
# }
|
||
|
# assert_eq!(0, v.len());
|
||
|
# v.push(Box::new(1));
|
||
|
# assert_eq!(1, *v.pop().unwrap());
|
||
|
# }
|
||
7 years ago
|
#
|
||
7 years ago
|
# pub fn test_zst() {
|
||
|
# let mut v = Vec::new();
|
||
|
# for _i in 0..10 {
|
||
|
# v.push(())
|
||
|
# }
|
||
7 years ago
|
#
|
||
7 years ago
|
# let mut count = 0;
|
||
7 years ago
|
#
|
||
7 years ago
|
# for _ in v.into_iter() {
|
||
|
# count += 1
|
||
|
# }
|
||
7 years ago
|
#
|
||
7 years ago
|
# assert_eq!(10, count);
|
||
|
# }
|
||
|
# }
|
||
10 years ago
|
```
|