more functionalities for the vec

This commit is contained in:
Christoph J. Scherr 2025-06-04 21:30:22 +02:00
parent 325c491691
commit 9f09799413
Signed by: PlexSheep
GPG key ID: 9EB784BB202BB7BB

View file

@ -4,7 +4,6 @@
//! https://doc.rust-lang.org/nomicon/vec/vec.html //! https://doc.rust-lang.org/nomicon/vec/vec.html
use std::{ use std::{
marker::PhantomData,
mem, mem,
ops::{Deref, DerefMut, Index, IndexMut}, ops::{Deref, DerefMut, Index, IndexMut},
ptr, ptr,
@ -15,7 +14,6 @@ use crate::raw_vec::RawVec;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Vec<T> { pub struct Vec<T> {
used: usize, used: usize,
marker: PhantomData<T>,
buf: RawVec<T>, buf: RawVec<T>,
} }
@ -32,7 +30,6 @@ impl<T> Vec<T> {
} }
Vec { Vec {
used: 0, used: 0,
marker: PhantomData,
buf: RawVec::new(), buf: RawVec::new(),
} }
} }
@ -47,6 +44,14 @@ impl<T> Vec<T> {
v 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> { pub fn pop(&mut self) -> Option<T> {
if self.used == 0 { if self.used == 0 {
None None
@ -121,6 +126,32 @@ impl<T> Vec<T> {
pub fn reserve(&mut self, added_capacity: usize) { pub fn reserve(&mut self, added_capacity: usize) {
self.buf.grow_by(added_capacity); 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> { 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: Send> Send for Vec<T> {}
unsafe impl<T: Sync> Sync for Vec<T> {} unsafe impl<T: Sync> Sync for Vec<T> {}