Module entity_vec

Module entity_vec 

Source
Expand description

An EntityVec<E: Entity, V> is a vector of values of type V that can only be indexed by keys of type EntityId<E>.

An EntityVec<E: Entity, V> is a thin wrapper around a Vec<V> that enforces type safety of the indexing (key) values. The most common Vec<V> methods are implemented.

Importantly, while EntityVec<E: Entity, V> can be indexed by an EntityId<E> value, it cannot construct an EntityId<E> value itself, because it does not guarantee that its length does not exceed the range of valid EntityId<E> values. This allows methods like EntityVec::push and EntityVec::extend that extend the length of the vector to remain unconstrained. If you need to be able to retrieve the EntityId<E> that a value is associated with (e.g. by iterating over (entity ID, value) pairs), use an EntityMap instead.

For a hash-map-like API, see EntityMap.

§Example

Imagine you have a Person entity, and you want an efficient way to store for each PersonId a Vec<Itinerary> representing different itineraries associated with that person. You might initialize itineraries_by_person: EntityVec<Person, Vec<Itinerary>> during population creation, by subscribing to the EntityCreationEvent<Person> event, or as a separate iteration over an existing population.

use ixa::data_structures::entity_vec::EntityVec;

let mut itineraries_by_person: EntityVec<Person, Vec<Itinerary>> = EntityVec::new();

// Populate in entity-id order. For example, this could be done while creating people
// or while iterating over an existing population.
for person_id in context.get_entity_iterator::<Person>() {
    let itinerary_list = compute_itineraries_for_person(person_id);
    itineraries_by_person.push(itinerary_list);
}

// Later, given an existing PersonId:
let person_id: PersonId = /* fetch the `PersonId` somehow. */;

if let Some(itineraries) = itineraries_by_person.get_mut(person_id) {
    itineraries.push(/* some Itinerary */);
}

Structs§

EntityVec
A Vec-backed collection indexed by EntityId<E>.