po4yka/rust-skills/rust-event-loop-state

Claude Code and agent skill by po4yka/rust-skills

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Use when designing or reviewing an event loop, tick loop, or handler registry whose handlers all need &mut to one shared mutable state, such as a game loop, a TUI loop, or a god object. Also for E0499 in a dispatch loop, E0502 on a queue peek, E0207 or E0119 on a generic Handler trait, Rc RefCell between handlers, an ECS system and world, and coroutine resume or async fn as a suspendable routine over that state. Not for async runtime scheduling; use rust-async-internals.

Install

npx vskill@latest install po4yka/rust-skills/rust-event-loop-state

SKILL.md

Rust event loop state

The loop owns the handler set and the state as two separate values, and passes one into the other. Every rule below follows from this sentence. E0499 in a dispatch loop almost never needs a different line. It needs a different owner.

This skill covers synchronous loops. For runtime behavior under tokio (select!, JoinSet, FuturesUnordered, wakers, cancellation), use the rust-async-internals skill when it is installed. The diagnostics below are from rustc 1.98.1, edition 2024.

Pick the structure from the shape of the handler set

Read the left column first. Stop at the first row that describes your handler set. Each row down costs something concrete, and you pay it whether or not you needed it.

Shape of the handler setStructureWhat it costs
Fixed at compile time. The state's fields are known to the crate that writes the loopThe loop holds Vec<Box<dyn Handler>> and State as two locals. Dispatch h.handle(&mut state, &ev)Nothing. Start here
Handlers must be reused across applications that have different statesState is a trait parameter: trait Handler<S>. Each handler declares the capability traits it needs on S. The loop registers Vec<Box<dyn Handler<App>>>Trait-solver error volume, and a blanket impl forecloses a later per-state impl on that type for every state that meets its bounds (E0119)
The component set is open at run time: plugins, scripting, save files, or a level editor decide itAn ECS-shaped dynamic world with type-erased components and systemsAliasing detection stops being a compile error. It becomes a run-time panic the first time the schedule initializes that system
None of the aboveRow 1. Do not reach furtherNothing. The shortcuts in Do not do this each move a compile error to a panic, a deadlock, or an unfixable E0499

Triage

SymptomCauseFixSection
E0499: cannot borrow *st as mutable more than once, first borrow at iter_mut(), second at the dispatch argumentThe handler collection is a field of the stateMove the field out of State, dispatch a sub-struct field, or mem::take it for the tickThe loop owns both
E0502 ... immutable borrow later used by call on while let Some(ev) = st.queue.front()The event is borrowed out of a queue inside the statePop the event by valueDrain the queue
E0499 ... first borrow later used by call, first borrow at handler constructionA handler holds a &mut into the stateStore an index or a generational keyStore a key
E0207: the type parameter S is not constrainedThe handler trait has type StateMake it trait Handler<S>State is a trait parameter
E0119: conflicting implementations of trait Handler<App>A blanket impl<S: ...> Handler<S> for X whose bounds App satisfies. An unbounded one covers every stateKeep one impl. Delete the per-state impl and move its behavior behind a capability-trait method, or replace the blanket impl with per-state impls. A bound removes the overlap only when App does not satisfy itState is a trait parameter
E0499 on &mut ctx.field where ctx implements DerefMutAuto-deref borrows the whole wrapperPlain fields, or one split() methodNo DerefMut
Run-time panic ... conflicts with a previous system parameter (an ECS code such as B0001)Two overlapping mutable views in one systemA parameter set or a disjoint filterECS
RefCell already borrowed or RefCell already mutably borrowed panic, or a hang on a nested lock()Shared state behind Rc<RefCell<_>> or Arc<Mutex<_>>, re-entered during dispatchRow 1 of the structure tableDo not do this
A routine must pause mid-work and continue next tick-A resume(&mut self, &mut State) traitSuspendable routines
implementation of Coroutine is not general enoughA coroutine resume argument is not higher-rankedSame as the row aboveSuspendable routines

Do not do this

MoveWhat actually happens
Rc<RefCell<State>> cloned into every handler, re-borrowed during dispatchThe E0499 becomes a RefCell already borrowed or RefCell already mutably borrowed panic the first time one handler calls another. The compile error told you the truth
Arc<Mutex<State>> inside one thread, re-locked during dispatchThe nested lock() never returns. std leaves the outcome unspecified: it can deadlock or panic. A deadlock gives no output and no backtrace, and it needs no load to happen
unsafe { &mut *ptr } to hand two handlers the stateTwo live &mut to one place are undefined behavior. Miri rejects it under Stacked Borrows and Tree Borrows
async fn(&mut State) as a suspendable routineE0499 before any executor runs. No version of this works
An ECS taken for ergonomics, not for an open component setYou pay run-time conflict panics for a component set the compiler could have checked
std::mem::take(&mut st.handlers), then st.handlers = hsEvery handler registered during the tick is silently dropped. Call hs.append(&mut st.handlers) first
A bare usize slot key when slots are removed or reusedThe key names a different slot, or an out-of-bounds slot, with no error. Use a generational key

The first two rows are about re-entrant dispatch inside one synchronous loop. Under a runtime the same shapes read differently: Arc<Mutex<State>> across separate tasks is a valid, serializing choice.

Verify

The change is complete when every row that applies to it is green.

ClaimCheckWhat a green result does not prove
The loop, handlers, and state borrow correctly (structure rows 1 and 2)cargo check --locked --all-targets on the crateNothing about a RefCell or Mutex that remains, or about ECS access
No re-entrant RefCell or Mutex path remainsrg -e 'Rc<RefCell<' -e 'Arc<Mutex<' over the state and handler types. Then a test that dispatches one event through every handler, including a handler that triggers another, under the timeout belowPaths the test does not reach. A cell behind a type alias
A handler that enqueues cannot stall the tickA test with a handler that enqueues on every event. Run one tick under the timeout belowHandlers that enqueue only on some events
No ECS access conflictA test that initializes and runs every real schedule once against an empty worldSystems added to a schedule at run time
Dispatch that still contains unsafe does not aliasWhen a nightly toolchain with the miri component is installed, cargo +nightly miri test --locked on the dispatch tests. Otherwise report the dispatch as not checked by MiriPaths the tests do not reach

The rust-sanitizers-miri skill, when it is installed, owns the Miri flags and the Stacked Borrows and Tree Borrows policy. Without it, gate on the default Stacked Borrows run and treat MIRIFLAGS="-Zmiri-tree-borrows" as a second opinion.

A re-locked Mutex usually fails as a hang (std may also panic), and an always-enqueuing while let drain fails as a hang. libtest warns after 60 seconds and never ends the test. Build the state and run one tick inside std::thread::spawn. Send () on a std::sync::mpsc channel when the tick returns. Assert rx.recv_timeout(Duration::from_secs(5)).is_ok(). A panic in the thread drops the sender, so the same assert also catches a RefCell panic. If cargo-nextest is installed, slow-timeout = { period = "5s", terminate-after = 1 } under [profile.default] in .config/nextest.toml also ends a hung test.

Read references/review-checklist.md when you review an existing loop. It asks one question per defect class in this skill.

The loop owns both, separately

Put the handler collection inside the state and dispatch &mut State into the handlers, and the call cannot type-check. The iterator holds a mutable borrow of *st for the whole loop body, so the &mut State argument is a second mutable borrow of the same place:

rust,compile_fail,E0499
struct Event(u32);
struct State { counter: u32, handlers: Vec<Box<dyn Handler>> }
trait Handler { fn handle(&mut self, st: &mut State, ev: &Event); }
fn tick(st: &mut State, ev: Event) {
for h in st.handlers.iter_mut() {
h.handle(st, &ev);
}
}

No interior mutability fixes this. Move the collection out. Two locals in the loop are two independent owners, so the two borrows are provably disjoint:

rust,run
struct Event(u32);
struct State { counter: u32 }
trait Handler { fn handle(&mut self, st: &mut State, ev: &Event); }
struct Add;
impl Handler for Add {
fn handle(&mut self, st: &mut State, ev: &Event) { st.counter += ev.0; }
}
struct Double;
impl Handler for Double {
fn handle(&mut self, st: &mut State, _ev: &Event) { st.counter *= 2; }
}
fn tick(handlers: &mut [Box<dyn Handler>], st: &mut State, ev: Event) {
for h in handlers.iter_mut() { h.handle(st, &ev); }
}
fn main() {
let mut handlers: Vec<Box<dyn Handler>> = vec![Box::new(Add), Box::new(Double)];
let mut st = State { counter: 0 };
tick(&mut handlers, &mut st, Event(3)); // (0 + 3) * 2
tick(&mut handlers, &mut st, Event(4)); // (6 + 4) * 2
assert_eq!(st.counter, 20);
println!("counter={}", st.counter); // counter=20
}

When an existing codebase cannot move the field yet, use one of two repairs:

  • Group the rest of the state in a sub-struct, make the handler trait take that sub-struct,

and dispatch &mut st.rest. st.handlers and st.rest are disjoint field borrows, so the handler field can stay.

  • Use std::mem::take(&mut st.handlers) for the tick only when a handler must also mutate the

handler set. The put-back is the trap: a handler that registers a new handler during the tick puts it into the empty field, and a plain assignment drops it. Append the newcomers first. Read the "Migration" section of references/state-partitioning.md for the runnable version and its panic limit.

Drain the queue by value

front() returns a reference tied to *st. The reference is an argument of the dispatch call, so NLL keeps it live across the call, and the whole state stays borrowed (E0502). pop_front() produces an owned Event, so no borrow of the state survives into the handler, and a handler can push more events back:

rust,run
use std::collections::VecDeque;
struct Event(u32);
struct State { counter: u32, queue: VecDeque<Event> }
fn handle(st: &mut State, ev: Event) {
st.counter += ev.0;
if ev.0 > 1 { st.queue.push_back(Event(ev.0 - 1)); } // handlers may enqueue
}
fn main() {
let mut st = State { counter: 0, queue: VecDeque::from([Event(3)]) };
while let Some(ev) = st.queue.pop_front() { handle(&mut st, ev); }
assert_eq!(st.counter, 6);
println!("counter={}", st.counter); // counter=6
}

A handler that enqueues on every event makes that while let spin forever. Read the length first and drain exactly one batch per tick: for _ in 0..st.queue.len() { let Some(ev) = st.queue.pop_front() else { break }; handle(st, ev); }.

A handler stores a key, never a borrow

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
2
Repository forks
1
7-day trend score
10

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/po4yka/rust-skills/rust-event-loop-state/badge)](https://verified-skill.com/skills/po4yka/rust-skills/rust-event-loop-state)

Something wrong with this skill or its page? Tell us.