Skip to main content

scope

Function scope 

Source
pub fn scope<C, G, R>(
    _anchor: Anchor,
    outer: &mut Bank<C>,
    f: impl FnOnce(&mut Bank<G>) -> R,
) -> R
where C: Group, G: Group, R: BankSafe,
Available on crate feature bank only.
Expand description

Enter group G’s bank for the duration of f, then restore the caller (C).

This is the safe heart of the crate. It switches to G, hands f a fresh Bank<G> token, runs it, and switches back to C. Threading the caller’s &mut Bank<C> is what makes the cross-bank footgun a compile error: a reference borrowed from one token cannot survive a nested scope that needs the same token &mut.

The switch is elided entirely when G is FIXED or C == G (same group, folded at compile time), so same-bank work costs nothing.

§Examples

fn run(anchor: Anchor, bank: &mut Bank<GroupZero>) {
    let first = scope(anchor, bank, |b: &mut Bank<Sound>| *b.local(&MELODY).first().unwrap());
    // back in the caller's bank here
}

The borrow checker stops a banked reference from escaping the switch:

fn leak<'a>(anchor: Anchor, bank: &mut Bank<GroupZero>, data: &'a Far<u8, G>) -> &'a u8 {
    scope(anchor, bank, |g| g.local(data)) // ERROR: the ref borrows the inner token
}