more functionalities for the vec
This commit is contained in:
parent
325c491691
commit
9f09799413
1 changed files with 40 additions and 3 deletions
|
@ -4,7 +4,6 @@
|
|||
//! https://doc.rust-lang.org/nomicon/vec/vec.html
|
||||
|
||||
use std::{
|
||||
marker::PhantomData,
|
||||
mem,
|
||||
ops::{Deref, DerefMut, Index, IndexMut},
|
||||
ptr,
|
||||
|
@ -15,7 +14,6 @@ use crate::raw_vec::RawVec;
|
|||
#[derive(Clone, Debug)]
|
||||
pub struct Vec<T> {
|
||||
used: usize,
|
||||
marker: PhantomData<T>,
|
||||
buf: RawVec<T>,
|
||||
}
|
||||
|
||||
|
@ -32,7 +30,6 @@ impl<T> Vec<T> {
|
|||
}
|
||||
Vec {
|
||||
used: 0,
|
||||
marker: PhantomData,
|
||||
buf: RawVec::new(),
|
||||
}
|
||||
}
|
||||
|
@ -47,6 +44,14 @@ impl<T> Vec<T> {
|
|||
v
|
||||
}
|
||||
|
||||
pub fn from_slice(data: &[T]) -> Self {
|
||||
let mut v = Vec::<T>::with_capacity(data.len());
|
||||
unsafe {
|
||||
ptr::copy_nonoverlapping(data.as_ptr(), v.as_mut_ptr(), data.len());
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
pub fn pop(&mut self) -> Option<T> {
|
||||
if self.used == 0 {
|
||||
None
|
||||
|
@ -121,6 +126,32 @@ impl<T> Vec<T> {
|
|||
pub fn reserve(&mut self, added_capacity: usize) {
|
||||
self.buf.grow_by(added_capacity);
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn split_off(&mut self, at: usize) -> Self {
|
||||
let other_len = self.used - at;
|
||||
let mut other = Self::with_capacity(other_len);
|
||||
unsafe {
|
||||
self.set_len(at);
|
||||
other.set_len(other_len);
|
||||
ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
|
||||
}
|
||||
other
|
||||
}
|
||||
|
||||
unsafe fn set_len(&mut self, new_length: usize) {
|
||||
self.used = new_length
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn as_ptr(&self) -> *const T {
|
||||
self.buf.ptr.as_ptr()
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn as_mut_ptr(&mut self) -> *mut T {
|
||||
self.buf.ptr.as_ptr()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Index<usize> for Vec<T> {
|
||||
|
@ -158,6 +189,12 @@ impl<T> Drop for Vec<T> {
|
|||
}
|
||||
}
|
||||
|
||||
impl<T> From<&[T]> for Vec<T> {
|
||||
fn from(value: &[T]) -> Self {
|
||||
Self::from_slice(value)
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl<T: Send> Send for Vec<T> {}
|
||||
unsafe impl<T: Sync> Sync for Vec<T> {}
|
||||
|
||||
|
|
Loading…
Add table
Reference in a new issue