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.
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.
Sourcepub fn new() -> Self
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();Sourcepub fn with_capacity(capacity: usize) -> Self
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);Sourcepub fn capacity(&self) -> usize
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);Sourcepub fn entry<R>(&mut self) -> Entry<'_, R>where
R: Resource,
pub fn entry<R>(&mut self) -> Entry<'_, R>where
R: Resource,
Returns an entry for the resource with type R.
Sourcepub fn insert<R>(&mut self, r: R)where
R: Resource,
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?
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}Sourcepub fn insert_raw(&mut self, type_id: TypeId, resource: Box<dyn Resource>)
pub fn insert_raw(&mut self, type_id: TypeId, resource: Box<dyn Resource>)
Inserts an already boxed resource into the map.
Sourcepub fn remove<R>(&mut self) -> Rwhere
R: Resource,
pub fn remove<R>(&mut self) -> Rwhere
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.
Sourcepub fn try_remove<R>(&mut self) -> Result<R, ResourceFetchError>where
R: Resource,
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).
Sourcepub fn contains<R>(&self) -> boolwhere
R: Resource,
pub fn contains<R>(&self) -> boolwhere
R: Resource,
Returns true if the specified resource type R exists in self.
Sourcepub fn borrow<R>(&self) -> Ref<'_, R>where
R: Resource,
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?
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}Sourcepub fn try_borrow<R>(&self) -> Result<Ref<'_, R>, BorrowFail>where
R: Resource,
pub fn try_borrow<R>(&self) -> Result<Ref<'_, R>, BorrowFail>where
R: Resource,
Returns an immutable reference to R if it exists, None otherwise.
Sourcepub fn borrow_mut<R>(&self) -> RefMut<'_, R>where
R: Resource,
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?
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}Sourcepub fn try_borrow_mut<R>(&self) -> Result<RefMut<'_, R>, BorrowFail>where
R: Resource,
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?
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}Sourcepub fn get_mut<R: Resource>(&mut self) -> Option<&mut R>
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.
Sourcepub fn get_resource_mut(&mut self, id: TypeId) -> Option<&mut dyn Resource>
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.
Methods from Deref<Target = RtMap<TypeId, Box<dyn Resource>>>§
Sourcepub fn capacity(&self) -> usize
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);Sourcepub fn entry(&mut self, k: K) -> Entry<'_, K, V>
pub fn entry(&mut self, k: K) -> Entry<'_, K, V>
Gets the given key’s corresponding entry in the map for in-place manipulation.
Sourcepub fn insert(&mut self, k: K, v: V) -> Option<V>
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");Sourcepub fn is_empty(&self) -> bool
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());Sourcepub fn remove<Q>(&mut self, k: &Q) -> Option<V>
pub fn remove<Q>(&mut self, k: &Q) -> Option<V>
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);Sourcepub fn contains_key<Q>(&self, k: &Q) -> bool
pub fn contains_key<Q>(&self, k: &Q) -> bool
Sourcepub fn borrow<Q>(&self, k: &Q) -> Ref<'_, V>
pub fn borrow<Q>(&self, k: &Q) -> Ref<'_, V>
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.
Sourcepub fn try_borrow<Q>(&self, k: &Q) -> Result<Ref<'_, V>, BorrowFail>
pub fn try_borrow<Q>(&self, k: &Q) -> Result<Ref<'_, V>, BorrowFail>
Returns a reference to the value if it exists and is not mutably
borrowed, None otherwise.
Sourcepub fn borrow_mut<Q>(&self, k: &Q) -> RefMut<'_, V>
pub fn borrow_mut<Q>(&self, k: &Q) -> RefMut<'_, V>
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.
Sourcepub fn try_borrow_mut<Q>(&self, k: &Q) -> Result<RefMut<'_, V>, BorrowFail>
pub fn try_borrow_mut<Q>(&self, k: &Q) -> Result<RefMut<'_, V>, BorrowFail>
Returns a mutable reference to R if it exists, None otherwise.
Sourcepub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
pub fn get_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
Retrieves a resource without fetching, which is cheaper, but only
available with &mut self.
Sourcepub fn get_resource_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
pub fn get_resource_mut<Q>(&mut self, k: &Q) -> Option<&mut V>
Retrieves a resource without fetching, which is cheaper, but only
available with &mut self.
Methods from Deref<Target = HashMap<K, Cell<V>>>§
1.0.0 · Sourcepub fn capacity(&self) -> usize
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 · Sourcepub fn keys(&self) -> Keys<'_, K, V> ⓘ
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 · Sourcepub fn values(&self) -> Values<'_, K, V> ⓘ
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 · Sourcepub fn iter(&self) -> Iter<'_, K, V> ⓘ
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 · Sourcepub fn len(&self) -> usize
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 · Sourcepub fn is_empty(&self) -> bool
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 · Sourcepub fn hasher(&self) -> &S
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 · Sourcepub fn get<Q>(&self, k: &Q) -> Option<&V>
pub fn get<Q>(&self, k: &Q) -> Option<&V>
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 · Sourcepub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
pub fn get_key_value<Q>(&self, k: &Q) -> Option<(&K, &V)>
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
&Kstored key value from a borrowed&Qlookup 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 · Sourcepub fn contains_key<Q>(&self, k: &Q) -> bool
pub fn contains_key<Q>(&self, k: &Q) -> bool
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§
Auto Trait Implementations§
impl !RefUnwindSafe for Resources
impl !UnwindSafe for Resources
impl Freeze for Resources
impl Send for Resources
impl Sync for Resources
impl Unpin for Resources
impl UnsafeUnpin for Resources
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
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>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
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)
fn as_any(&self) -> &(dyn Any + 'static)
&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)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.