Skip to main content

Resources

Struct Resources 

Source
pub struct Resources(/* private fields */);
Expand description

Map from TypeId to type.

Implementations§

Source§

impl Resources

A Resource container, which provides methods to insert, access and manage the contained resources.

Many methods take &self which works because everything is stored with interior mutability. In case you violate the borrowing rules of Rust (multiple reads xor one write), you will get a panic.

§Resource Ids

Resources are identified by TypeIds, which consist of a TypeId.

Source

pub fn new() -> Self

Creates an empty Resources map.

The map is initially created with a capacity of 0, so it will not allocate until it is first inserted into.

§Examples
use resman::Resources;
let mut resources = Resources::new();
Source

pub fn with_capacity(capacity: usize) -> Self

Creates an empty Resources map with the specified capacity.

The map will be able to hold at least capacity elements without reallocating. If capacity is 0, the map will not allocate.

§Examples
use resman::Resources;
let resources: Resources = Resources::with_capacity(10);
Source

pub fn into_inner(self) -> RtMap<TypeId, Box<dyn Resource>>

Returns the inner RtMap.

Source

pub fn capacity(&self) -> usize

Returns the number of elements the map can hold without reallocating.

This number is a lower bound; the Resources<K, V> might be able to hold more, but is guaranteed to be able to hold at least this many.

§Examples
use resman::Resources;
let resources: Resources = Resources::with_capacity(100);
assert!(resources.capacity() >= 100);
Source

pub fn entry<R>(&mut self) -> Entry<'_, R>
where R: Resource,

Returns an entry for the resource with type R.

Source

pub fn insert<R>(&mut self, r: R)
where R: Resource,

Inserts a resource into the map. If the resource existed before, it will be overwritten.

§Examples

Every type satisfying Any + Send + Sync automatically implements Resource, thus can be added:

struct MyRes(i32);

When you have a resource, simply insert it like this:

use resman::Resources;

let mut resources = Resources::default();
resources.insert(MyRes(5));
Examples found in repository?
examples/simple.rs (line 12)
9fn main() {
10    let mut resources = Resources::default();
11
12    resources.insert(A(1));
13    resources.insert(B(2));
14
15    // We can validly have two mutable borrows from the `Resources` map!
16    let mut a = resources.borrow_mut::<A>();
17    let mut b = resources.borrow_mut::<B>();
18    a.0 = 2;
19    b.0 = 3;
20
21    // We need to explicitly drop the A and B borrows, because they are runtime
22    // managed borrows, and rustc doesn't know to drop them before the immutable
23    // borrows after this.
24    drop(a);
25    drop(b);
26
27    // Multiple immutable borrows to the same resource are valid.
28    let a_0 = resources.borrow::<A>();
29    let _a_1 = resources.borrow::<A>();
30    let b = resources.borrow::<B>();
31
32    println!("A: {}", a_0.0);
33    println!("B: {}", b.0);
34
35    // Trying to mutably borrow a resource that is already borrowed (immutably
36    // or mutably) returns `Err`.
37    let a_try_borrow_mut = resources.try_borrow_mut::<A>();
38    let exists = if a_try_borrow_mut.is_ok() {
39        "Ok(..)"
40    } else {
41        "Err"
42    };
43    println!("a_try_borrow_mut: {}", exists); // prints "Err"
44}
Source

pub fn insert_raw(&mut self, type_id: TypeId, resource: Box<dyn Resource>)

Inserts an already boxed resource into the map.

Source

pub fn remove<R>(&mut self) -> R
where R: Resource,

Removes a resource of type R from this container and returns its ownership to the caller. In case there is no such resource in this, container, None will be returned.

Use this method with caution; other functions and systems might assume this resource still exists. Thus, only use this if you’re sure no system will try to access this resource after you removed it (or else you will get a panic).

§Panics

Panics if the resource doesn’t exist in this container.

Source

pub fn try_remove<R>(&mut self) -> Result<R, ResourceFetchError>
where R: Resource,

Removes a resource of type R from this container and returns its ownership to the caller. In case there is no such resource in this, container, None will be returned.

Use this method with caution; other functions and systems might assume this resource still exists. Thus, only use this if you’re sure no system will try to access this resource after you removed it (or else you will get a panic).

Source

pub fn contains<R>(&self) -> bool
where R: Resource,

Returns true if the specified resource type R exists in self.

Source

pub fn borrow<R>(&self) -> Ref<'_, R>
where R: Resource,

Returns the R resource in the resource map.

See try_borrow for a non-panicking version of this function.

§Panics

Panics if the resource doesn’t exist. Panics if the resource is being accessed mutably.

Examples found in repository?
examples/simple.rs (line 28)
9fn main() {
10    let mut resources = Resources::default();
11
12    resources.insert(A(1));
13    resources.insert(B(2));
14
15    // We can validly have two mutable borrows from the `Resources` map!
16    let mut a = resources.borrow_mut::<A>();
17    let mut b = resources.borrow_mut::<B>();
18    a.0 = 2;
19    b.0 = 3;
20
21    // We need to explicitly drop the A and B borrows, because they are runtime
22    // managed borrows, and rustc doesn't know to drop them before the immutable
23    // borrows after this.
24    drop(a);
25    drop(b);
26
27    // Multiple immutable borrows to the same resource are valid.
28    let a_0 = resources.borrow::<A>();
29    let _a_1 = resources.borrow::<A>();
30    let b = resources.borrow::<B>();
31
32    println!("A: {}", a_0.0);
33    println!("B: {}", b.0);
34
35    // Trying to mutably borrow a resource that is already borrowed (immutably
36    // or mutably) returns `Err`.
37    let a_try_borrow_mut = resources.try_borrow_mut::<A>();
38    let exists = if a_try_borrow_mut.is_ok() {
39        "Ok(..)"
40    } else {
41        "Err"
42    };
43    println!("a_try_borrow_mut: {}", exists); // prints "Err"
44}
Source

pub fn try_borrow<R>(&self) -> Result<Ref<'_, R>, BorrowFail>
where R: Resource,

Returns an immutable reference to R if it exists, None otherwise.

Source

pub fn borrow_mut<R>(&self) -> RefMut<'_, R>
where R: Resource,

Returns a mutable reference to R if it exists, None otherwise.

§Panics

Panics if the resource doesn’t exist. Panics if the resource is already accessed.

Examples found in repository?
examples/simple.rs (line 16)
9fn main() {
10    let mut resources = Resources::default();
11
12    resources.insert(A(1));
13    resources.insert(B(2));
14
15    // We can validly have two mutable borrows from the `Resources` map!
16    let mut a = resources.borrow_mut::<A>();
17    let mut b = resources.borrow_mut::<B>();
18    a.0 = 2;
19    b.0 = 3;
20
21    // We need to explicitly drop the A and B borrows, because they are runtime
22    // managed borrows, and rustc doesn't know to drop them before the immutable
23    // borrows after this.
24    drop(a);
25    drop(b);
26
27    // Multiple immutable borrows to the same resource are valid.
28    let a_0 = resources.borrow::<A>();
29    let _a_1 = resources.borrow::<A>();
30    let b = resources.borrow::<B>();
31
32    println!("A: {}", a_0.0);
33    println!("B: {}", b.0);
34
35    // Trying to mutably borrow a resource that is already borrowed (immutably
36    // or mutably) returns `Err`.
37    let a_try_borrow_mut = resources.try_borrow_mut::<A>();
38    let exists = if a_try_borrow_mut.is_ok() {
39        "Ok(..)"
40    } else {
41        "Err"
42    };
43    println!("a_try_borrow_mut: {}", exists); // prints "Err"
44}
Source

pub fn try_borrow_mut<R>(&self) -> Result<RefMut<'_, R>, BorrowFail>
where R: Resource,

Returns a mutable reference to R if it exists, None otherwise.

Examples found in repository?
examples/simple.rs (line 37)
9fn main() {
10    let mut resources = Resources::default();
11
12    resources.insert(A(1));
13    resources.insert(B(2));
14
15    // We can validly have two mutable borrows from the `Resources` map!
16    let mut a = resources.borrow_mut::<A>();
17    let mut b = resources.borrow_mut::<B>();
18    a.0 = 2;
19    b.0 = 3;
20
21    // We need to explicitly drop the A and B borrows, because they are runtime
22    // managed borrows, and rustc doesn't know to drop them before the immutable
23    // borrows after this.
24    drop(a);
25    drop(b);
26
27    // Multiple immutable borrows to the same resource are valid.
28    let a_0 = resources.borrow::<A>();
29    let _a_1 = resources.borrow::<A>();
30    let b = resources.borrow::<B>();
31
32    println!("A: {}", a_0.0);
33    println!("B: {}", b.0);
34
35    // Trying to mutably borrow a resource that is already borrowed (immutably
36    // or mutably) returns `Err`.
37    let a_try_borrow_mut = resources.try_borrow_mut::<A>();
38    let exists = if a_try_borrow_mut.is_ok() {
39        "Ok(..)"
40    } else {
41        "Err"
42    };
43    println!("a_try_borrow_mut: {}", exists); // prints "Err"
44}
Source

pub fn get_mut<R: Resource>(&mut self) -> Option<&mut R>

Retrieves a resource without fetching, which is cheaper, but only available with &mut self.

Source

pub fn get_resource_mut(&mut self, id: TypeId) -> Option<&mut dyn Resource>

Retrieves a resource without fetching, which is cheaper, but only available with &mut self.

Source

pub fn get_raw(&self, id: &TypeId) -> Option<&Cell<Box<dyn Resource>>>

Get raw access to the underlying cell.

Source

pub fn merge(&mut self, other: Resources)

Merges the other Resources map over this one.

Methods from Deref<Target = RtMap<TypeId, Box<dyn Resource>>>§

Source

pub fn capacity(&self) -> usize

Returns the number of elements the map can hold without reallocating.

This number is a lower bound; the RtMap<K, V> might be able to hold more, but is guaranteed to be able to hold at least this many.

§Examples
use rt_map::RtMap;
let map: RtMap<i32, i32> = RtMap::with_capacity(100);
assert!(map.capacity() >= 100);
Source

pub fn entry(&mut self, k: K) -> Entry<'_, K, V>

Gets the given key’s corresponding entry in the map for in-place manipulation.

Source

pub fn insert(&mut self, k: K, v: V) -> Option<V>

Inserts a key-value pair into the map.

If the map did not have this key present, None is returned.

If the map did have this key present, the value is updated, and the old value is returned. The key is not updated, though; this matters for types that can be == without being identical.

§Examples
use rt_map::RtMap;

let mut map = RtMap::new();
assert_eq!(map.insert(37, "a"), None);
assert_eq!(map.is_empty(), false);

map.insert(37, "b");
assert_eq!(map.insert(37, "c"), Some("b"));
assert_eq!(*map.borrow(&37), "c");
Source

pub fn is_empty(&self) -> bool

Returns true if the map contains no elements.

§Examples
use rt_map::RtMap;

let mut a = RtMap::new();
assert!(a.is_empty());
a.insert(1, "a");
assert!(!a.is_empty());
Source

pub fn remove<Q>(&mut self, k: &Q) -> Option<V>
where Q: Hash + Eq + ?Sized, K: Borrow<Q>,

Removes a key from the map, returning the value at the key if the key was previously in the map.

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type.

§Examples
use rt_map::RtMap;

let mut map = RtMap::new();
map.insert(1, "a");
assert_eq!(map.remove(&1), Some("a"));
assert_eq!(map.remove(&1), None);
Source

pub fn contains_key<Q>(&self, k: &Q) -> bool
where Q: Hash + Eq + ?Sized, K: Borrow<Q>,

Returns true if the map contains a value for the specified key.

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type.

Source

pub fn borrow<Q>(&self, k: &Q) -> Ref<'_, V>
where Q: Hash + Eq + Debug + ?Sized, K: Borrow<Q>,

Returns a reference to the value corresponding to the key.

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type.

See try_borrow for a non-panicking version of this function.

§Panics
  • Panics if the resource doesn’t exist.
  • Panics if the resource is being accessed mutably.
Source

pub fn try_borrow<Q>(&self, k: &Q) -> Result<Ref<'_, V>, BorrowFail>
where Q: Hash + Eq + ?Sized, K: Borrow<Q>,

Returns a reference to the value if it exists and is not mutably borrowed, None otherwise.

Source

pub fn borrow_mut<Q>(&self, k: &Q) -> RefMut<'_, V>
where Q: Hash + Eq + Debug + ?Sized, K: Borrow<Q>,

Returns a reference to the value if it exists and is not borrowed, None otherwise.

§Panics
  • Panics if the resource doesn’t exist.
  • Panics if the resource is already accessed.
Source

pub fn try_borrow_mut<Q>(&self, k: &Q) -> Result<RefMut<'_, V>, BorrowFail>
where Q: Hash + Eq + ?Sized, K: Borrow<Q>,

Returns a mutable reference to R if it exists, None otherwise.

Source

pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
where Q: Hash + Eq + ?Sized, K: Borrow<Q>,

Retrieves a resource without fetching, which is cheaper, but only available with &mut self.

Source

pub fn get_resource_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
where Q: Hash + Eq + ?Sized, K: Borrow<Q>,

Retrieves a resource without fetching, which is cheaper, but only available with &mut self.

Source

pub fn get_raw<Q>(&self, k: &Q) -> Option<&Cell<V>>
where Q: Hash + Eq + ?Sized, K: Borrow<Q>,

Get raw access to the underlying cell.

Methods from Deref<Target = HashMap<K, Cell<V>>>§

1.0.0 · Source

pub fn capacity(&self) -> usize

Returns the number of elements the map can hold without reallocating.

This number is a lower bound; the HashMap<K, V> might be able to hold more, but is guaranteed to be able to hold at least this many.

§Examples
use std::collections::HashMap;
let map: HashMap<i32, i32> = HashMap::with_capacity(100);
assert!(map.capacity() >= 100);
1.0.0 · Source

pub fn keys(&self) -> Keys<'_, K, V>

An iterator visiting all keys in arbitrary order. The iterator element type is &'a K.

§Examples
use std::collections::HashMap;

let map: HashMap<&str, i32> = HashMap::from([
    ("a", 1),
    ("b", 2),
    ("c", 3),
]);

let mut values: Vec<_> = map.keys().copied().collect();
values.sort();

assert_eq!(values, vec!["a", "b", "c"]);
§Performance

In the current implementation, iterating over keys takes O(capacity) time instead of O(len) because it internally visits empty buckets too.

1.0.0 · Source

pub fn values(&self) -> Values<'_, K, V>

An iterator visiting all values in arbitrary order. The iterator element type is &'a V.

§Examples
use std::collections::HashMap;

let map: HashMap<&str, i32> = HashMap::from([
    ("a", 1),
    ("b", 2),
    ("c", 3),
]);

let mut values: Vec<_> = map.values().copied().collect();
values.sort();

assert_eq!(values, vec![1, 2, 3]);
§Performance

In the current implementation, iterating over values takes O(capacity) time instead of O(len) because it internally visits empty buckets too.

1.0.0 · Source

pub fn iter(&self) -> Iter<'_, K, V>

An iterator visiting all key-value pairs in arbitrary order. The iterator element type is (&'a K, &'a V).

§Examples
use std::collections::HashMap;

let map = HashMap::from([
    ("a", 1),
    ("b", 2),
    ("c", 3),
]);

let mut count = 0;

for (_key, _val) in map.iter() {
    count += 1;
}

assert_eq!(count, 3);
§Performance

In the current implementation, iterating over map takes O(capacity) time instead of O(len) because it internally visits empty buckets too.

1.0.0 · Source

pub fn len(&self) -> usize

Returns the number of elements in the map.

§Examples
use std::collections::HashMap;

let mut a = HashMap::new();
assert_eq!(a.len(), 0);
a.insert(1, "a");
assert_eq!(a.len(), 1);
1.0.0 · Source

pub fn is_empty(&self) -> bool

Returns true if the map contains no elements.

§Examples
use std::collections::HashMap;

let mut a = HashMap::new();
assert!(a.is_empty());
a.insert(1, "a");
assert!(!a.is_empty());
1.9.0 · Source

pub fn hasher(&self) -> &S

Returns a reference to the map’s BuildHasher.

§Examples
use std::collections::HashMap;
use std::hash::RandomState;

let hasher = RandomState::new();
let map: HashMap<i32, i32> = HashMap::with_hasher(hasher);
let hasher: &RandomState = map.hasher();
1.0.0 · Source

pub fn get<Q>(&self, k: &Q) -> Option<&V>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Returns a reference to the value corresponding to the key.

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type.

§Examples
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.get(&1), Some(&"a"));
assert_eq!(map.get(&2), None);
1.40.0 · Source

pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Returns the key-value pair corresponding to the supplied key. This is potentially useful:

  • for key types where non-identical keys can be considered equal;
  • for getting the &K stored key value from a borrowed &Q lookup key; or
  • for getting a reference to a key with the same lifetime as the collection.

The supplied key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type.

§Examples
use std::collections::HashMap;
use std::hash::{Hash, Hasher};

#[derive(Clone, Copy, Debug)]
struct S {
    id: u32,
    name: &'static str, // ignored by equality and hashing operations
}

impl PartialEq for S {
    fn eq(&self, other: &S) -> bool {
        self.id == other.id
    }
}

impl Eq for S {}

impl Hash for S {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id.hash(state);
    }
}

let j_a = S { id: 1, name: "Jessica" };
let j_b = S { id: 1, name: "Jess" };
let p = S { id: 2, name: "Paul" };
assert_eq!(j_a, j_b);

let mut map = HashMap::new();
map.insert(j_a, "Paris");
assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris")));
assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case
assert_eq!(map.get_key_value(&p), None);
1.0.0 · Source

pub fn contains_key<Q>(&self, k: &Q) -> bool
where K: Borrow<Q>, Q: Hash + Eq + ?Sized,

Returns true if the map contains a value for the specified key.

The key may be any borrowed form of the map’s key type, but Hash and Eq on the borrowed form must match those for the key type.

§Examples
use std::collections::HashMap;

let mut map = HashMap::new();
map.insert(1, "a");
assert_eq!(map.contains_key(&1), true);
assert_eq!(map.contains_key(&2), false);

Trait Implementations§

Source§

impl Debug for Resources

Available on crate feature debug only.
Source§

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

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

impl Default for Resources

Source§

fn default() -> Resources

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

impl Deref for Resources

Source§

type Target = RtMap<TypeId, Box<dyn Resource>>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl DerefMut for Resources

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.

Auto Trait Implementations§

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> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Sync + Send>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
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<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Resource for T
where T: Any + Debug + Send + Sync,

Source§

fn type_id(&self) -> TypeId

Source§

fn type_name(&self) -> TypeNameLit

Source§

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

Source§

type Error = !

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.