Struct Resources

pub struct Resources { /* private fields */ }

Implementations§

§

impl Resources

pub const CAPACITY: usize = 256usize

Maximum number of distinct resource types; replacing a type uses no slot.

pub fn insert<T>(&mut self, value: T) -> Result<Option<T>, T>
where T: Any,

Replace an existing value of T, returning it. Capacity failure returns the input.

pub fn get_or_insert_with<T>( &mut self, initialize: impl FnOnce() -> T, ) -> Result<&mut T, ResourceError>
where T: Any,

Return the existing resource, or initialize and insert it exactly once.

initialize is not called if T is present, even when the store is full. For an absent type at capacity, return ResourceError::Capacity without calling it. A panic in the initializer inserts nothing. Removing or clearing the resource permits it to be initialized again.

use ferravex_engine::resources::{ResourceError, Resources};

let mut resources = Resources::default();
resources.get_or_insert_with(Vec::<u32>::new)?.push(7);
let values = resources.get_or_insert_with(|| vec![99_u32])?;
assert_eq!(values, &[7]);

pub fn try_init<T, E>( &mut self, initialize: impl FnOnce() -> Result<T, E>, ) -> Result<&mut T, ResourceInitError<E>>
where T: Any,

Return the existing resource, or try to initialize and insert it.

The initializer runs only when T is absent and capacity is available. Failure preserves the original error and inserts nothing, so the caller can retry. Initializer panics also insert nothing; side effects performed by the initializer itself are the caller’s responsibility.

use ferravex_engine::resources::{ResourceInitError, Resources};

struct TickRate(u32);
let mut resources = Resources::default();
let rate = resources.try_init(|| "60".parse::<u32>().map(TickRate))?;
assert_eq!(rate.0, 60);
// A later caller reuses it without parsing a second configuration.
let rate = resources.try_init(|| "invalid".parse::<u32>().map(TickRate))?;
assert_eq!(rate.0, 60);

pub fn try_update<T, E>( &mut self, update: impl FnOnce(&T) -> Result<T, E>, ) -> Result<T, ResourceUpdateError<E>>
where T: Any,

Build a checked replacement from a shared borrow, returning the old value.

update runs exactly once if T exists, including at capacity. A missing type returns ResourceError::Missing inside ResourceUpdateError::Resource without calling it; use Self::try_init to initialize absent resources. An error or panic in update leaves the original value in its slot. Only Ok(replacement) commits the replacement, transferring ownership of the previous value to the caller without dropping it inside this method.

The store reuses the existing allocation and never changes its type count. Neither Clone nor Send/Sync is required. The callback’s own allocations, external side effects, and changes made through interior mutability are outside this guarantee and cannot be rolled back.

use ferravex_engine::resources::{ResourceUpdateError, Resources};

let mut resources = Resources::default();
resources.get_or_insert_with(|| 3_u32).unwrap();
let result = resources.try_update(|lives: &u32| {
    lives.checked_sub(4).ok_or("not enough lives")
});
assert!(matches!(result, Err(ResourceUpdateError::Update {
    source: "not enough lives", ..
})));
assert_eq!(resources.get::<u32>(), Some(&3));
let previous = resources.try_update(|lives: &u32| {
    lives.checked_sub(1).ok_or("not enough lives")
}).unwrap();
assert_eq!(previous, 3);
assert_eq!(resources.get::<u32>(), Some(&2));

pub fn require<T>(&self) -> Result<&T, ResourceError>
where T: Any,

Borrow a required resource, reporting its Rust type name if absent.

use ferravex_engine::resources::{ResourceError, Resources};

struct Settings { sound: bool }
let mut resources = Resources::default();
resources.get_or_insert_with(|| Settings { sound: true })?;
assert!(resources.require::<Settings>()?.sound);
assert!(matches!(resources.require::<u64>(), Err(ResourceError::Missing { .. })));

pub fn require_mut<T>(&mut self) -> Result<&mut T, ResourceError>
where T: Any,

Mutably borrow a required resource, reporting its Rust type name if absent.

use ferravex_engine::resources::{ResourceError, Resources};

let mut resources = Resources::default();
resources.get_or_insert_with(|| 0_u64)?;
*resources.require_mut::<u64>()? += 1;
assert_eq!(*resources.require::<u64>()?, 1);

pub fn with2_mut<A, B, R>( &mut self, access: impl FnOnce(&mut A, &mut B) -> R, ) -> Result<R, ResourceAccessError>
where A: Any, B: Any,

Call access once with mutable references to two distinct resources.

All types must be distinct and present before the callback runs; see ResourceAccessError for error precedence and argument indices. Access works at full capacity, never inserts/removes resources, and preserves their allocations. References cannot escape the callback’s scope.

The outer Result describes access validation only. If the callback returns a Result, it is returned inside Ok. Mutations made by the callback persist even if it returns an error or panics; this is not a transaction like Self::try_update. After an unwind, all entries remain installed and can be borrowed again. Shared interior mutations and other callback side effects are likewise not rolled back.

use ferravex_engine::resources::{ResourceAccessError, Resources};

let mut resources = Resources::default();
resources.insert(2_u32).unwrap();
resources.insert(10_u64).unwrap();
let total = resources.with2_mut(|lives: &mut u32, score: &mut u64| {
    *lives -= 1;
    *score += 5;
    *score
})?;
assert_eq!(total, 15);
assert_eq!(resources.get::<u32>(), Some(&1));

Resource borrows cannot be returned from the callback:

ⓘ
use ferravex_engine::resources::Resources;
let mut resources = Resources::default();
let escaped = resources.with2_mut::<u32, u64, _>(|a, _| a);

pub fn with2_mut_ref<A, B, R>( &mut self, access: impl FnOnce(&mut A, &B) -> R, ) -> Result<R, ResourceAccessError>
where A: Any, B: Any,

Call access with mutable A and shared B, requiring distinct types.

Uses Self::with2_mut’s validation, scope and side-effect contract. Reorder type arguments when the resource to mutate is otherwise second.

use ferravex_engine::resources::{ResourceAccessError, Resources};

let mut resources = Resources::default();
resources.insert(10_u64).unwrap();
resources.insert(3_u32).unwrap();
resources.with2_mut_ref(|score: &mut u64, reward: &u32| {
    *score += u64::from(*reward);
})?;
assert_eq!(resources.get::<u64>(), Some(&13));
assert_eq!(resources.get::<u32>(), Some(&3));

pub fn with3_mut<A, B, C, R>( &mut self, access: impl FnOnce(&mut A, &mut B, &mut C) -> R, ) -> Result<R, ResourceAccessError>
where A: Any, B: Any, C: Any,

Call access with mutable references to three distinct resources.

Uses Self::with2_mut’s validation, scope and side-effect contract. Missing argument indices are 0 (A), 1 (B) and 2 (C).

use ferravex_engine::resources::{ResourceAccessError, Resources};

let mut resources = Resources::default();
resources.insert(2_u32).unwrap();
resources.insert(10_u64).unwrap();
resources.insert(false).unwrap();
resources.with3_mut(|lives: &mut u32, score: &mut u64, won: &mut bool| {
    *lives -= 1;
    *score += 5;
    *won = *score >= 15;
})?;
assert_eq!(resources.get::<bool>(), Some(&true));

pub fn with3_mut_mut_ref<A, B, C, R>( &mut self, access: impl FnOnce(&mut A, &mut B, &C) -> R, ) -> Result<R, ResourceAccessError>
where A: Any, B: Any, C: Any,

Call access with mutable A/B and shared C, all distinct types.

Uses Self::with2_mut’s validation, scope and side-effect contract. This recipe admits a job only if both the per-tick work allowance and the bounded accepted-job queue have room. The caller invokes it on an actual simulation tick and resets the budget at its chosen tick boundary.

use ferravex_engine::{
    events::{EventQueue, Overflow},
    resources::{ResourceAccessError, Resources},
    work_budget::WorkBudget,
};

struct Job { id: u32, cost: u64 }
let mut resources = Resources::default();
resources.get_or_insert_with(|| WorkBudget::new(3)).unwrap();
resources.get_or_insert_with(|| EventQueue::<u32>::new(1, Overflow::RejectNewest))
    .unwrap();
resources.get_or_insert_with(|| Job { id: 7, cost: 2 }).unwrap();
let admit = |budget: &mut WorkBudget, accepted: &mut EventQueue<u32>, job: &Job| {
    if accepted.is_full() || !budget.try_consume(job.cost) {
        return false;
    }
    accepted.send(job.id).expect("queue capacity checked");
    true
};
assert!(resources.with3_mut_mut_ref(admit)?);
assert!(!resources.with3_mut_mut_ref(admit)?); // Full: no charge, no event.
assert_eq!(resources.get::<WorkBudget>().unwrap().remaining(), 1);
assert_eq!(resources.get_mut::<EventQueue<u32>>().unwrap().pop(), Some(7));
assert!(!resources.with3_mut_mut_ref(admit)?); // Budget exhausted.
assert!(resources.get::<EventQueue<u32>>().unwrap().is_empty());

pub fn with3_mut_ref_ref<A, B, C, R>( &mut self, access: impl FnOnce(&mut A, &B, &C) -> R, ) -> Result<R, ResourceAccessError>
where A: Any, B: Any, C: Any,

Call access with mutable A and shared B/C, all distinct types.

Uses Self::with2_mut’s validation, scope and side-effect contract. Even the two shared arguments must differ in type. Use separate shared Self::require calls when repeated shared access is intended.

use ferravex_engine::resources::{ResourceAccessError, Resources};

let mut resources = Resources::default();
resources.insert(0_u64).unwrap();
resources.insert(3_u32).unwrap();
resources.insert(true).unwrap();
resources.with3_mut_ref_ref(|score: &mut u64, reward: &u32, enabled: &bool| {
    if *enabled { *score += u64::from(*reward); }
})?;
assert_eq!(resources.get::<u64>(), Some(&3));

pub fn get<T>(&self) -> Option<&T>
where T: Any,

pub fn get_mut<T>(&mut self) -> Option<&mut T>
where T: Any,

pub fn remove<T>(&mut self) -> Option<T>
where T: Any,

pub fn contains<T>(&self) -> bool
where T: Any,

pub fn len(&self) -> usize

pub fn is_empty(&self) -> bool

pub fn clear(&mut self)

Trait Implementations§

§

impl Default for Resources

§

fn default() -> Resources

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

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> 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, 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.