1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#![feature(raw_vec_internals, core_intrinsics)]
extern crate alloc;
use std::cell::Cell;
use std::intrinsics::assume;
use std::ops::{Deref, DerefMut};
use alloc::raw_vec::RawVec;
pub struct ConstVec<T> {
buf: RawVec<T>,
len: Cell<usize>
}
impl<T> ConstVec<T> {
pub fn new(capacity: usize) -> ConstVec<T> {
ConstVec {
buf: RawVec::with_capacity(capacity),
len: Cell::new(0)
}
}
pub fn capacity(&self) -> usize {
self.buf.cap()
}
pub fn len(&self) -> usize {
self.len.get()
}
#[inline]
pub fn as_ptr(&self) -> *const T {
let ptr = self.buf.ptr();
unsafe { assume(!ptr.is_null()); }
ptr
}
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut T {
let ptr = self.buf.ptr();
unsafe { assume(!ptr.is_null()); }
ptr
}
pub fn push(&self, value: T) {
if self.len() == self.buf.cap() {
panic!("not enough space!")
}
unsafe {
let ptr = self.buf.ptr();
assume(!ptr.is_null());
let end = ptr.add(self.len());
std::ptr::write(end, value);
self.len.set(self.len() + 1);
}
}
}
impl<T> Deref for ConstVec<T> {
type Target = [T];
fn deref(&self) -> &[T] {
unsafe {
std::slice::from_raw_parts(self.as_ptr(), self.len())
}
}
}
impl<T> DerefMut for ConstVec<T> {
fn deref_mut(&mut self) -> &mut [T] {
unsafe {
std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.len())
}
}
}