#mutability #interior-mutability #container #resources #ecs

resources

Safe store for one value of each type, with interior mutability

5 releases (2 stable)

1.1.0 Jul 2, 2020
1.0.0 Mar 17, 2020
0.2.1 Dec 13, 2019
0.2.0 Dec 13, 2019
0.1.0 Dec 12, 2019

#669 in Game dev

Download history 44/week @ 2023-11-27 74/week @ 2023-12-04 58/week @ 2023-12-11 71/week @ 2023-12-18 28/week @ 2023-12-25 17/week @ 2024-01-01 50/week @ 2024-01-08 48/week @ 2024-01-15 26/week @ 2024-01-22 20/week @ 2024-01-29 55/week @ 2024-02-05 42/week @ 2024-02-12 52/week @ 2024-02-19 73/week @ 2024-02-26 69/week @ 2024-03-04 62/week @ 2024-03-11

263 downloads per month
Used in kayak_ui

MIT/Apache

25KB
358 lines

resources

Latest Version Documentation License CI

This crate provides the Resources struct: a container that stores at most one value of each specific type, and allows safely and concurrently accessing any of them with interior mutability, without violating borrow rules.

It's intended to be used as an implementation of storage for data that is not associated with any specific entity in an ECS (entity component system), but still needs concurrent access by systems.

Cargo features

  • fetch - when enabled, exposes Resources::fetch() that allows retrieving up to 16 resources with a one-liner.

Example

use resources::*;

struct SomeNumber(usize);

struct SomeString(&'static str);

fn main() {
    let mut resources = Resources::new();
    resources.insert(SomeNumber(4));
    resources.insert(SomeString("Hello!"));
    let resources = resources;  // This shadows the mutable binding with an immutable one.

    {
        let mut some_number = resources.get_mut::<SomeNumber>().unwrap();
        let mut some_string = resources.get_mut::<SomeString>().unwrap();

        // Immutably borrowing a resource that's already borrowed mutably is not allowed.
        assert!(resources.get::<SomeNumber>().is_err());

        some_number.0 = 2;
        some_string.0 = "Bye!";
    }

    // The mutable borrows now went out of scope, so it's okay to borrow again however needed.
    assert_eq!(resources.get::<SomeNumber>().unwrap().0, 2);

    // Multiple immutable borrows are okay.
    let some_string1 = resources.get::<SomeString>().unwrap();
    let some_string2 = resources.get::<SomeString>().unwrap();
    assert_eq!(some_string1.0, some_string2.0);
}

Dependencies

~0.6–1MB
~15K SLoC