diff --git a/src/collections/raw_vec.rs b/src/collections/raw_vec.rs index 088430ecf66725df09cb21e7c4edf7b675f80a37..c1b4806d59ab89348ef4c6225d1660cf1a1291aa 100644 --- a/src/collections/raw_vec.rs +++ b/src/collections/raw_vec.rs @@ -11,10 +11,12 @@ enum AllocError { /// ensuring that no illegal mutable access occurs. /// A lot of the logic is simply stolen from the std lib. The destructor will /// free the backing memory, but will not run any destructors. +/// Try to use functions to modify the length. But feel free if you know what +/// you're doing pub struct RawVec { base: *mut T, cap: usize, - len: usize, + pub len: usize, } impl RawVec { @@ -38,16 +40,19 @@ impl RawVec { return result; } + #[inline] pub unsafe fn get(&self, idx: usize) -> *const T { debug_assert!(idx < self.len); return self.base.add(idx); } + #[inline] pub unsafe fn get_mut(&self, idx: usize) -> *mut T { debug_assert!(idx < self.len); return self.base.add(idx); } + /// Pushes a new element to the end of the list. pub fn push(&mut self, item: T) { self.ensure_space(1).unwrap(); unsafe { @@ -57,10 +62,30 @@ impl RawVec { } } + /// Moves the elements in the range [from_idx, from_idx + num_to_move) to + /// the range [to_idx, to_idx + num_to_move). Caller must make sure that all + /// non-overlapping elements of the second range had their destructor called + /// in case those elements were used. + pub fn move_range(&mut self, from_idx: usize, to_idx: usize, num_to_move: usize) { + debug_assert!(from_idx + num_to_move <= self.len); + debug_assert!(to_idx + num_to_move <= self.len); // maybe not in future, for now this is fine + unsafe { + let source = self.base.add(from_idx); + let target = self.base.add(to_idx); + std::ptr::copy(source, target, num_to_move); + } + } + pub fn len(&self) -> usize { return self.len; } + pub fn as_slice(&self) -> &[T] { + return unsafe{ + std::slice::from_raw_parts(self.base, self.len) + }; + } + fn ensure_space(&mut self, additional: usize) -> Result<(), AllocError>{ debug_assert!(Self::T_SIZE != 0); debug_assert!(self.cap >= self.len);