Struct OptVec

Source
pub struct OptVec<T, S> { /* private fields */ }
Expand description

A vector containing optional values.

The vector would be useful when you need invariant index regardless of insertion and removal. If you remove an item from the vector, the slot remains vacant rather than removing the space by moving right items. Then the vacant slot can be filled when you insert an item into the vector.

For more understanding, see the diagram below.

vector -> [ None, Some, None ]
occupied    No    Yes   No
vacant      Yes   No    Yes

* length: 1
* number of slots: 3
* number of vacancies: 2

Implementations§

Source§

impl<T, S> OptVec<T, S>
where S: Default,

Source

pub fn new() -> Self

Creates a new empty vector.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<i32, RandomState>::new();
Source§

impl<T, S> OptVec<T, S>

Source

pub fn len(&self) -> usize

Returns number of items, which is occupied slots in other words.

Returned value is equal to self.num_slots() - self.num_vacancies().

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add(0);
assert_eq!(v.len(), 1);
Source

pub fn is_empty(&self) -> bool

Returns true is the vector is empty.

Note that vector may have slots in it even if it’s empty.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<i32, RandomState>::new();
assert!(v.is_empty());
Source

pub fn num_slots(&self) -> usize

Returns number of all slots including occupied and vacant slots.

Returned value is equal to self.len() + self.num_vacancies().

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add(0);
assert_eq!(v.num_slots(), 1);
Source

pub fn num_vacancies(&self) -> usize

Returns number of vacant slots.

Returned value is equal to self.num_slots() - self.len().

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add(0);
v.take(0);
assert_eq!(v.num_vacancies(), 1);
Source

pub fn is_vacant(&self, index: usize) -> bool

Returns true if the slot is vacant.

§Panics

Panics if the given index is out of bounds.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add(0);
v.take(0);
assert!(v.is_vacant(0));
Source

pub fn is_occupied(&self, index: usize) -> bool

Returns true if the slot is occupied.

§Panics

Panics if the given index is out of bounds.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add(0);
assert!(v.is_occupied(0));
Source

pub fn as_slice(&self) -> &[Option<T>]

Creates a slice from the vector.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add(0);
v.add(1);
assert_eq!(v.as_slice(), &[Some(0), Some(1)]);
Source

pub unsafe fn as_mut_slice(&mut self) -> &mut [Option<T>]

Creates a mutable slice from the vector.

Caller must not modify occupied/vacant status in the returned slice because the vector is tracking the status.

§Safety

Undefined behavior if caller take out a value from an occupied slot, or insert a value into a vacant slot.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add(0);
v.add(1);
assert_eq!(v.as_slice(), &[Some(0), Some(1)]);
Source

pub fn get(&self, index: usize) -> Option<&T>

Returns shared reference to the value at the given index if the index is in bounds and the slot is occupied.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add(0);
assert_eq!(v.get(0), Some(&0));
Source

pub unsafe fn get_unchecked(&self, index: usize) -> &T

Returns shared reference to the value at the given index.

§Safety

Undefined behavior if

  • The index is out of bounds.
  • The slot is vacant.
§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add(0);
assert_eq!(unsafe { v.get_unchecked(0) }, &0);
Source

pub fn get_mut(&mut self, index: usize) -> Option<&mut T>

Returns mutable reference to the value at the given index if the index is in bounds and the slot is occupied.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add(0);
assert_eq!(v.get_mut(0), Some(&mut 0));
Source

pub unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T

Returns shared reference to the value at the given index.

§Safety

Undefined behavior if

  • The index is out of bounds.
  • The slot is vacant.
§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add(0);
assert_eq!(unsafe { v.get_unchecked_mut(0) }, &mut 0);
Source

pub fn pairs(&self) -> impl Iterator<Item = (usize, &T)>

Returns an iterator visiting all values with corresponding indices.

As return type says, vacant slots are filtered out from the iteration.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add('a');
v.add('b');
let pairs = v.pairs().collect::<Vec<_>>();
assert_eq!(pairs, [(0, &'a'), (1, &'b')]);
Source

pub fn pairs_mut(&mut self) -> impl Iterator<Item = (usize, &mut T)>

Returns a mutable iterator visiting all values with corresponding indices.

As return type says, vacant slots are filtered out from the iteration.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add('a');
v.add('b');
let pairs = v.pairs_mut().collect::<Vec<_>>();
assert_eq!(pairs, [(0, &mut 'a'), (1, &mut 'b')]);
Source

pub fn slots(&self) -> Iter<'_, Option<T>>

Returns an iterator visiting all slots regardless of whether the slot is occupied or not.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add('a');
v.add('b');
v.take(0);
let slots = v.slots().cloned().collect::<Vec<_>>();
assert_eq!(slots, [None, Some('b')]);
Source

pub fn iter(&self) -> impl Iterator<Item = &T> + Clone

Returns an iterator visiting all values.

As return type says, vacant slots are filtered out from the iteration.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add('a');
v.add('b');
let values = v.iter().collect::<Vec<_>>();
assert_eq!(values, [&'a', &'b']);
Source

pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T>

Returns a mutable iterator visiting all values.

As return type says, vacant slots are filtered out from the iteration.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add('a');
v.add('b');
let values = v.iter_mut().collect::<Vec<_>>();
assert_eq!(values, [&mut 'a', &mut 'b']);
Source§

impl<T, S> OptVec<T, S>
where S: BuildHasher,

Source

pub fn set(&mut self, index: usize, value: Option<T>) -> Option<T>

Sets a slot with the given optional value and returns old value.

§Panics

Panics if the given index is out of bounds.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add(0);
assert_eq!(v.set(0, None), Some(0));
Source

pub fn next_index(&self) -> usize

Returns the next index that will be returned on the next call to OptVec::add.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
assert_eq!(v.next_index(), 0);

v.add(0);
v.add(1);
v.take(0);
assert_eq!(v.next_index(), 0);
Source

pub fn add(&mut self, value: T) -> usize

Inserts the given value into the vector.

The vector prefers to insert values into vacant slots if possible. But if the vector doesn’t have any vacant slots, then the value is appended to the end of the vector.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add(0);
assert_eq!(v.len(), 1);
Source

pub fn push(&mut self, value: Option<T>)

Appends the given optional value to the end of the vector.

Note that this method won’t insert the value into a vacant slot. It just makes a new slot at the end of the vector then puts the value in the slot.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add(0);
v.take(0);
v.push(Some(0));
assert_eq!(v.as_slice(), &[None, Some(0)]);
Source

pub fn take(&mut self, index: usize) -> Option<T>

Takes value out of the slot at the given index.

After calling the method, the slot remains vacant.

§Panics

Panics if the given index is out of bounds.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.add(0);
assert_eq!(v.take(0), Some(0));
assert_eq!(v.take(0), None);
Source

pub fn resize(&mut self, new_len: usize, value: Option<T>)
where T: Clone,

Resizes the vector to the given length.

If the new length is greater than previous length of the vector, then the vector is extended with the given optional value. Otherwise, the vector is shrunk.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.resize(2, Some(0));
assert_eq!(v.as_slice(), &[Some(0), Some(0)]);
Source

pub fn resize_with<F>(&mut self, new_len: usize, f: F)
where F: FnMut() -> Option<T>,

Resizes the vector to the given length.

If the new length is greater than previous length of the vector, then the vector is extended with optional values the given function generates. In this case, generated values are appended in order. Otherwise, the vector is shrunk.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.resize_with(2, || Some(0));
assert_eq!(v.as_slice(), &[Some(0), Some(0)]);
Source

pub fn truncate(&mut self, len: usize)

Shrinks the vector to the given length, and drops abandoned items.

If the given length is greater than or equal to the current length of the vector, nothing takes place.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.resize_with(4, || Some(0));
v.truncate(2);
assert_eq!(v.as_slice(), &[Some(0), Some(0)]);
Source

pub fn shrink_to_fit(&mut self)

Removes vacant slots from the end of the vector, then shrinks capacity of the vector as much as possible.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.resize(5, Some(0));
v.resize(10, None);
v.shrink_to_fit();
assert_eq!(v.num_vacancies(), 0);
Source

pub fn extend_set(&mut self, index: usize, value: T) -> Option<T>

Sets a slot with the given optional value and returns old value.

Unlike OptVec::set, this method doesn’t panic even if the index is out of bounds, extending the vector with vacant slots instead.

§Examples
use my_ecs::ds::OptVec;
use std::hash::RandomState;

let mut v = OptVec::<_, RandomState>::new();
v.extend_set(2, 0);
assert_eq!(v.as_slice(), &[None, None, Some(0)]);

Trait Implementations§

Source§

impl<T: Clone, S: Clone> Clone for OptVec<T, S>

Source§

fn clone(&self) -> OptVec<T, S>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug, S: Debug> Debug for OptVec<T, S>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Default, S: Default> Default for OptVec<T, S>

Source§

fn default() -> OptVec<T, S>

Returns the “default value” for a type. Read more
Source§

impl<T, S> From<OptVec<T, S>> for Vec<T>
where S: BuildHasher,

Source§

fn from(value: OptVec<T, S>) -> Self

Converts to this type from the input type.
Source§

impl<T, S> Index<usize> for OptVec<T, S>

Source§

type Output = Option<T>

The returned type after indexing.
Source§

fn index(&self, index: usize) -> &Self::Output

Performs the indexing (container[index]) operation. Read more
Source§

impl<T, S> IntoIterator for OptVec<T, S>
where S: BuildHasher,

Source§

type Item = T

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<T, S>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<T, S> Resource for OptVec<T, S>
where T: Send + 'static, S: Send + 'static,

Auto Trait Implementations§

§

impl<T, S> Freeze for OptVec<T, S>
where S: Freeze,

§

impl<T, S> RefUnwindSafe for OptVec<T, S>

§

impl<T, S> Send for OptVec<T, S>
where S: Send, T: Send,

§

impl<T, S> Sync for OptVec<T, S>
where S: Sync, T: Sync,

§

impl<T, S> Unpin for OptVec<T, S>
where S: Unpin, T: Unpin,

§

impl<T, S> UnwindSafe for OptVec<T, S>
where S: UnwindSafe, T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.