Skip to content

Instantly share code, notes, and snippets.

@Kerollmops
Last active December 2, 2019 22:08
Show Gist options
  • Select an option

  • Save Kerollmops/610c2d032d787db3a67e663dfc574cfa to your computer and use it in GitHub Desktop.

Select an option

Save Kerollmops/610c2d032d787db3a67e663dfc574cfa to your computer and use it in GitHub Desktop.
Clone on Resize - An alternative to the Cow type, keep a mutable slice until you really need to grow or shrink it.
pub enum Cor<'a, T: 'a> {
Borrowed(&'a mut [T]),
Owned(Vec<T>),
}
impl<T: Clone> Cor<'_, T> {
pub fn as_resizable(&mut self) -> &mut Vec<T> {
match self {
Cor::Borrowed(slice) => {
*self = Cor::Owned(slice.to_vec());
match self {
Cor::Borrowed(..) => unreachable!(),
Cor::Owned(ref mut vec) => vec,
}
},
Cor::Owned(ref mut vec) => vec,
}
}
pub fn into_resizable(self) -> Vec<T> {
match self {
Cor::Borrowed(slice) => slice.to_vec(),
Cor::Owned(vec) => vec,
}
}
}
impl<T> AsRef<[T]> for Cor<'_, T> {
fn as_ref(&self) -> &[T] {
match self {
Cor::Borrowed(slice) => slice,
Cor::Owned(vec) => vec.as_ref(),
}
}
}
impl<T> AsMut<[T]> for Cor<'_, T> {
fn as_mut(&mut self) -> &mut [T] {
match self {
Cor::Borrowed(slice) => slice,
Cor::Owned(vec) => vec.as_mut(),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment