better naming

This commit is contained in:
nora 2021-12-22 20:48:54 +01:00
parent 29cfe9d3e2
commit 9a4bf51a5f
3 changed files with 24 additions and 7 deletions

View file

@ -95,11 +95,26 @@ impl<T: ?Sized> Vechonk<T> {
self.raw.pop()
}
/// Insert an element at an index.
/// * If the insertion was successful, the old element is returned.
pub fn insert(&mut self, _index: usize, _element: Box<T>) {
todo!()
}
/// Replace an element at an index.
/// This could be O(n) worst case, if the new element is too big, and every other element needs to be realigned.
/// Even worse, after all the copying, it might realloc anyways because it couldn't fit in the space.
///
/// Returns the old element at that
pub fn replace(&mut self, _index: usize, _element: Box<T>) -> Box<T> {
todo!()
}
/// Replace an element at an index.
/// * If the replacement was successful without moving the other elements, the old element is returned.
/// * If the new element doesn't fit the gap or can't be aligned, it is returned.
pub fn try_insert(&mut self, index: usize, element: Box<T>) -> Result<Box<T>, Box<T>> {
self.raw.try_insert_elem(element, index)
///
/// This is guaranteed to be O(1)
pub fn try_replace(&mut self, index: usize, element: Box<T>) -> Result<Box<T>, Box<T>> {
self.raw.try_replace_elem(element, index)
}
/// An iterator over the elements yielding shared references
@ -179,7 +194,7 @@ impl<T: ?Sized> MutGuard<T> {
/// * If the element fits in the space, the old element is returned
/// * If the element does not fit in the space, the new element is returned again
pub fn try_write(&mut self, element: Box<T>) -> Result<Box<T>, Box<T>> {
self.raw.try_insert_elem(element, self.index)
self.raw.try_replace_elem(element, self.index)
}
}

View file

@ -127,7 +127,7 @@ impl<T: ?Sized> RawVechonk<T> {
/// Insert an element at an index.
/// * If the insertion was successful, the old element is returned.
/// * If the new element doesn't fit the gap or can't be aligned, it is returned.
pub fn try_insert_elem(&mut self, element: Box<T>, index: usize) -> Result<Box<T>, Box<T>> {
pub fn try_replace_elem(&mut self, element: Box<T>, index: usize) -> Result<Box<T>, Box<T>> {
if index >= self.len {
// out of bounds
return Err(element);
@ -328,6 +328,8 @@ impl<T: ?Sized> RawVechonk<T> {
/// The caller must either set the `len` to zero, or copy the elements to the new allocation by saving
/// `self.ptr` before calling this function.
unsafe fn realloc(&mut self, size: NonZeroUsize) {
// TODO this is *not* sound, since the alignment of some big elements might be wrong now
let layout = Layout::from_size_align(size.get(), Self::data_align()).unwrap();
// SAFETY: layout is guaranteed to have a non-zero size

View file

@ -262,7 +262,7 @@ fn get_mut_mutating() {
fn insert() {
let mut chonk: Vechonk<str> = vechonk!["hello".into(), "uwu".into()];
chonk.try_insert(0, "owo".into()).unwrap();
chonk.try_replace(0, "owo".into()).unwrap();
assert_eq!(&chonk[0], "owo");
}