Struct Registry

Source
pub struct Registry<T, ID: IdTrait = Id<T>> { /* private fields */ }
Expand description

A container that issues IDs and maps them to stored values, also called a “slot map” or an “arena”.

Implementations§

Source§

impl<T> Registry<T, Id<T>>

Source

pub fn new() -> Self

Construct a new, empty Registry<T> with the default Id type.

The Registry will not allocate until elements are inserted into it.

Examples found in repository?
examples/alice_bob.rs (line 25)
24fn main() {
25    let mut people = People::new();
26    let alice_id = new_person(&mut people, "Alice");
27    let bob_id = new_person(&mut people, "Bob");
28    add_friend(&mut people, alice_id, bob_id);
29    add_friend(&mut people, bob_id, alice_id);
30    add_friend(&mut people, alice_id, alice_id); // no-op
31}
More examples
Hide additional examples
examples/player_resource.rs (line 39)
37fn main() {
38    let mut state = GameState {
39        players: Registry::new(),
40        resources: Registry::new(),
41    };
42    let player_id = new_player(&mut state);
43    let resource_id = new_resource(&mut state, player_id);
44    assert_eq!(state.resources[resource_id].owner_id, player_id);
45    assert!(state.players[player_id].resource_ids.contains(&resource_id));
46}
Source

pub fn with_capacity(capacity: usize) -> Self

Construct a new, empty Registry<T> with the default Id type and with at least the specified capacity.

Source§

impl<T, ID: IdTrait> Registry<T, ID>

Source

pub fn with_id_type() -> Self

Construct a new, empty Registry<T> with a custom ID type.

The Registry will not allocate until elements are inserted into it.

§Example
use riddance::{Id, Registry};

type TypeErasedId = Id<()>;

let mut registry: Registry::<String, TypeErasedId> = Registry::with_id_type();
let id: TypeErasedId = registry.insert(String::from("foo"));
Source

pub fn with_id_type_and_capacity(capacity: usize) -> Self

Construct a new, empty Registry<T> with a custom ID type and with at least the specified capacity.

Source

pub fn len(&self) -> usize

Returns the number of elements in the Registry.

Source

pub fn contains_id(&self, id: ID) -> bool

Returns true if the Registry contains the given id. If remove has been called on id, contains_id will return false.

Source

pub fn get(&self, id: ID) -> Option<&T>

Get a reference to an element. If remove has been called on id, get will return None.

Source

pub fn get_mut(&mut self, id: ID) -> Option<&mut T>

Get a mutable reference to an element. If remove has been called on id, get_mut will return None.

Source

pub unsafe fn get_unchecked(&self, id: ID) -> &T

Get a reference to an element without checking the size of the Registry or the generation of the ID.

This function is safe if and only if self.contains_id(id) is true.

Source

pub unsafe fn get_unchecked_mut(&mut self, id: ID) -> &mut T

Get a mutable reference to an element without checking the size of the Registry or the generation of the ID.

This function is safe if and only if self.contains_id(id) is true.

Source

pub fn insert(&mut self, value: T) -> ID

Adds a value to the Registry and returns an ID that can be used to access that element.

Examples found in repository?
examples/player_resource.rs (lines 24-27)
23fn new_player(state: &mut GameState) -> PlayerId {
24    state.players.insert(Player {
25        points: 0,
26        resource_ids: Vec::new(),
27    })
28}
29
30fn new_resource(state: &mut GameState, owner_id: PlayerId) -> ResourceId {
31    let new_id = state.resources.insert(Resource { owner_id });
32    state.players[owner_id].resource_ids.push(new_id);
33    state.players[owner_id].points += 30;
34    new_id
35}
More examples
Hide additional examples
examples/alice_bob.rs (lines 12-15)
11fn new_person(people: &mut People, name: &str) -> PersonId {
12    people.insert(Person {
13        name: name.into(),
14        friends: Vec::new(),
15    })
16}
Source

pub fn remove(&mut self, id: ID) -> Option<T>

If id refers to an element in the Registry, remove the element and return it.

This method returns Some if any only if contains_id would have returned true. After calling remove on an ID, that ID and any copies of it become “dangling”. contains_id will return false, and get, get_mut, and any further calls to remove will return None.

Calling remove on an ID that has been reserved with reserve_id or reserve_ids but not yet given a value with insert_reserved, will free the reserved slot and return None.

See also recycle_retired.

Source

pub fn reserve_id(&self) -> ID

Reserve an ID that you can insert a value for later.

Note that this method doesn’t require mutable access to the Registry. It uses an atomic cursor internally, and you can reserve an ID while other threads are e.g. reading existing elements.

Until you call insert_reserved, the reserved slot is empty, and contains_id will report false for the reserved ID. Similarly, get and get_mut will return None. If a reservation is no longer needed, you can remove it without inserting a value.

Whenever you call a &mut self method that might change the size of the Registry or its free list (insert, insert_reserved, remove, or recycle_retired), the Registry will automatically allocate space for any pending reservations. You can optionally call allocate_reservations to do this work in advance.

To reserve many IDs at once, see reserve_ids.

Source

pub fn reserve_ids(&self, count: usize) -> ReservationIter<'_, T, ID>

Reserve a range of IDs that you can insert values for later.

See reserve_id.

Note that unconsumed IDs in this iterator are not returned to the Registry when you drop it, and the slots they refer to are effectively leaked. If you reserved more IDs than you need, you can save them for later, or you can remove them when you have mutable access to the Registry.

Source

pub fn allocate_reservations(&mut self)

Allocate space for reserved slots.

See reserve_id and reserve_ids. This method is called internally by any method that might change the size of the Registry or its free list (insert, insert_reserved, remove, or recycle_retired), so you don’t need to call it explicitly unless you want to force the allocation to happen sooner.

Source

pub fn insert_reserved( &mut self, id: ID, value: T, ) -> Result<(), InsertReservedError<T>>

Insert a value for a reserved ID.

See reserve_id and reserve_ids. Empty reservations can be filled in any order. If you try to fill a reservation multiple times, or if you call this method with IDs that aren’t reserved, it will return an error.

Source

pub fn recycle_retired(&mut self)

Mark all retired slots as free, making them available for future insertions and reservations.

Callers using Registry with the default Id type shouldn’t need this method. Id has 31 generation bits, so the retirement rate is one slot per ~2 billion removals, too slow to matter in almost any practical case. This method is intended for callers using Id32.

Dangling IDs (that is, IDs passed to remove) from before the call to recycle_retired must not be used again with any method on this Registry. Generally callers should delete all dangling IDs (or replace them with null) before calling recycle_retired. If you retain dangling IDs across a call to recycle_retired, they can collide with newly issued IDs, and calls to get, get_mut, and contains_id can return confusing results. Calling insert_reserved on these IDs can also lead to memory leaks. This behavior is memory-safe, but these are logic bugs, similar to the logic bugs that can arise if you modify a key after it’s been inserted into a HashMap.

§Panics

Registry makes a best effort to detect violations of this rule. Any method on Registry may panic if it sees an ID generation that’s newer than the corresponding slot. These checks are currently only done in debug mode, but this is not guaranteed.

Source

pub fn iter(&self) -> Iter<'_, T, ID>

Iterate over (ID, &T). Equivalent to iterating over &Registry.

Source

pub fn iter_mut(&mut self) -> IterMut<'_, T, ID>

Iterate over (ID, &mut T). Equivalent to iterating over &mut Registry.

Source

pub fn into_iter(self) -> IntoIter<T, ID>

Iterate over (ID, T). Equivalent to iterating over Registry.

Source

pub fn ids(&self) -> Ids<'_, T, ID>

Iterate over ID.

Source

pub fn values(&self) -> Values<'_, T, ID>

Iterate over &T.

Source

pub fn values_mut(&mut self) -> ValuesMut<'_, T, ID>

Iterate over &mut T.

Source

pub fn into_values(self) -> IntoValues<T, ID>

Iterate over T.

Trait Implementations§

Source§

impl<T, ID: IdTrait> Clone for Registry<T, ID>
where T: Clone,

Source§

fn clone(&self) -> Self

Returns a copy 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, ID: IdTrait> Debug for Registry<T, ID>
where T: Debug,

Source§

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

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

impl<T, ID: IdTrait> Index<ID> for Registry<T, ID>

Source§

type Output = T

The returned type after indexing.
Source§

fn index(&self, id: ID) -> &T

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

impl<T, ID: IdTrait> IndexMut<ID> for Registry<T, ID>

Source§

fn index_mut(&mut self, id: ID) -> &mut T

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

impl<'registry, T, ID: IdTrait> IntoIterator for &'registry Registry<T, ID>

Source§

type Item = (ID, &'registry T)

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'registry, T, ID>

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<'registry, T, ID: IdTrait> IntoIterator for &'registry mut Registry<T, ID>

Source§

type Item = (ID, &'registry mut T)

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'registry, T, ID>

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, ID: IdTrait> IntoIterator for Registry<T, ID>

Source§

type Item = (ID, T)

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<T, ID>

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

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<T, ID = Id<T>> !Freeze for Registry<T, ID>

§

impl<T, ID> RefUnwindSafe for Registry<T, ID>

§

impl<T, ID> Send for Registry<T, ID>
where <ID as IdTrait>::GenerationBits: Send, T: Send,

§

impl<T, ID> Sync for Registry<T, ID>
where <ID as IdTrait>::GenerationBits: Sync, T: Sync,

§

impl<T, ID> Unpin for Registry<T, ID>
where <ID as IdTrait>::GenerationBits: Unpin, T: Unpin,

§

impl<T, ID> UnwindSafe for Registry<T, ID>

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, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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> Same for T

Source§

type Output = T

Should always be Self
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.