nexus-rt 2.0.3

Single-threaded, event-driven runtime primitives with pre-resolved dispatch
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
//! Handler parameter resolution and dispatch primitives.

use std::ops::{Deref, DerefMut};

use crate::Resource;
use crate::callback::Callback;
use crate::resource::{Res, ResMut, Seq, SeqMut};
use crate::shutdown::Shutdown;
use crate::world::{Registry, ResourceId, World};

// =============================================================================
// Param
// =============================================================================

/// Trait for types that can be resolved from a [`Registry`] at build time
/// and fetched from [`World`] at dispatch time.
///
/// Analogous to Bevy's `SystemParam`.
///
/// Two-phase resolution:
///
/// 1. **Build time** — [`init`](Self::init) resolves opaque state (e.g. a
///    [`ResourceId`]) from the registry. This panics if the required type
///    isn't registered — giving an early build-time error.
/// 2. **Dispatch time** — [`fetch`](Self::fetch) uses the cached state to
///    produce a reference via a single pointer deref — zero framework overhead.
///
/// # Built-in impls
///
/// | Param | State | Description |
/// |-------|-------|-------------|
/// | [`Res<T>`] | `ResourceId` | Shared read |
/// | [`ResMut<T>`] | `ResourceId` | Exclusive write |
/// | [`Option<Res<T>>`] | `Option<ResourceId>` | Optional shared read |
/// | [`Option<ResMut<T>>`] | `Option<ResourceId>` | Optional exclusive write |
/// | [`Local<T>`] | `T` | Per-handler state (not in World) |
/// | [`RegistryRef`] | `()` | Read-only registry access |
/// | `()` | `()` | Event-only handlers |
/// | Tuples of params | Tuple of states | Up to 8 params |
pub trait Param {
    /// Opaque state cached at build time (e.g. [`ResourceId`]).
    ///
    /// `Send` is required because state is stored in handler types
    /// ([`Callback`]), and handlers must be `Send` (they live in
    /// [`World`], which is `Send`).
    type State: Send;

    /// The item produced at dispatch time.
    type Item<'w>;

    /// Resolve state from the registry. Called once at build time.
    ///
    /// # Panics
    ///
    /// Panics if the required resource is not registered.
    fn init(registry: &Registry) -> Self::State;

    /// Fetch the item using cached state.
    ///
    /// # Safety
    ///
    /// - `state` must have been produced by [`init`](Self::init) on the
    ///   same registry that built the `world`.
    /// - Caller ensures no aliasing violations.
    unsafe fn fetch<'w>(world: &'w World, state: &'w mut Self::State) -> Self::Item<'w>;

    /// The ResourceId this param accesses, if any.
    ///
    /// Returns `None` for params that don't access World resources
    /// (e.g. `Local<T>`). Used by [`Registry::check_access`] to enforce
    /// one borrow per resource per handler.
    fn resource_id(state: &Self::State) -> Option<ResourceId> {
        let _ = state;
        None
    }
}

// -- Res<T> ------------------------------------------------------------------

impl<T: Resource> Param for Res<'_, T> {
    type State = ResourceId;
    type Item<'w> = Res<'w, T>;

    fn init(registry: &Registry) -> ResourceId {
        registry.id::<T>()
    }

    #[inline(always)]
    unsafe fn fetch<'w>(world: &'w World, state: &'w mut ResourceId) -> Res<'w, T> {
        let id = *state;
        #[cfg(debug_assertions)]
        world.track_borrow(id);
        // SAFETY: state was produced by init() on the same world.
        // Caller ensures no mutable alias exists for T.
        unsafe { Res::new(world.get::<T>(id)) }
    }

    fn resource_id(state: &ResourceId) -> Option<ResourceId> {
        Some(*state)
    }
}

// -- ResMut<T> ---------------------------------------------------------------

impl<T: Resource> Param for ResMut<'_, T> {
    type State = ResourceId;
    type Item<'w> = ResMut<'w, T>;

    fn init(registry: &Registry) -> ResourceId {
        registry.id::<T>()
    }

    #[inline(always)]
    unsafe fn fetch<'w>(world: &'w World, state: &'w mut ResourceId) -> ResMut<'w, T> {
        let id = *state;
        #[cfg(debug_assertions)]
        world.track_borrow(id);
        // SAFETY: state was produced by init() on the same world.
        // Caller ensures no aliases exist for T.
        unsafe { ResMut::new(world.get_mut::<T>(id)) }
    }

    fn resource_id(state: &ResourceId) -> Option<ResourceId> {
        Some(*state)
    }
}

// -- Option<Res<T>> ----------------------------------------------------------

impl<T: Resource> Param for Option<Res<'_, T>> {
    type State = Option<ResourceId>;
    type Item<'w> = Option<Res<'w, T>>;

    fn init(registry: &Registry) -> Option<ResourceId> {
        registry.try_id::<T>()
    }

    #[inline(always)]
    unsafe fn fetch<'w>(world: &'w World, state: &'w mut Option<ResourceId>) -> Option<Res<'w, T>> {
        // SAFETY: state was produced by init() on the same world.
        // Caller ensures no mutable alias exists for T.
        state.map(|id| {
            #[cfg(debug_assertions)]
            world.track_borrow(id);
            unsafe { Res::new(world.get::<T>(id)) }
        })
    }

    fn resource_id(state: &Option<ResourceId>) -> Option<ResourceId> {
        *state
    }
}

// -- Option<ResMut<T>> -------------------------------------------------------

impl<T: Resource> Param for Option<ResMut<'_, T>> {
    type State = Option<ResourceId>;
    type Item<'w> = Option<ResMut<'w, T>>;

    fn init(registry: &Registry) -> Option<ResourceId> {
        registry.try_id::<T>()
    }

    #[inline(always)]
    unsafe fn fetch<'w>(
        world: &'w World,
        state: &'w mut Option<ResourceId>,
    ) -> Option<ResMut<'w, T>> {
        // SAFETY: state was produced by init() on the same world.
        // Caller ensures no aliases exist for T.
        state.map(|id| {
            #[cfg(debug_assertions)]
            world.track_borrow(id);
            unsafe { ResMut::new(world.get_mut::<T>(id)) }
        })
    }

    fn resource_id(state: &Option<ResourceId>) -> Option<ResourceId> {
        *state
    }
}

// -- Seq (read-only sequence) ------------------------------------------------

impl Param for Seq {
    type State = ();
    type Item<'w> = Seq;

    fn init(_registry: &Registry) {}

    #[inline(always)]
    unsafe fn fetch<'w>(world: &'w World, _state: &'w mut ()) -> Seq {
        Seq(world.current_sequence())
    }
}

// -- SeqMut (mutable sequence) -----------------------------------------------

impl Param for SeqMut<'_> {
    type State = ();
    type Item<'w> = SeqMut<'w>;

    fn init(_registry: &Registry) {}

    #[inline(always)]
    unsafe fn fetch<'w>(world: &'w World, _state: &'w mut ()) -> SeqMut<'w> {
        SeqMut(world.sequence_cell())
    }
}

// -- Shutdown ----------------------------------------------------------------

impl Param for Shutdown<'_> {
    type State = ();
    type Item<'w> = Shutdown<'w>;

    fn init(_registry: &Registry) {}

    #[inline(always)]
    unsafe fn fetch<'w>(world: &'w World, _state: &'w mut ()) -> Shutdown<'w> {
        // Borrow the AtomicBool directly — lifetime-bound to World.
        // No Arc::clone, no raw pointer. Safe by construction.
        Shutdown(world.shutdown_flag())
    }
}

// =============================================================================
// Tuple impls
// =============================================================================

/// Unit impl — event-only handlers with no resource parameters.
impl Param for () {
    type State = ();
    type Item<'w> = ();

    fn init(_registry: &Registry) {}

    #[inline(always)]
    unsafe fn fetch<'w>(_world: &'w World, _state: &'w mut ()) {}
}

macro_rules! impl_param_tuple {
    ($($P:ident),+) => {
        impl<$($P: Param),+> Param for ($($P,)+) {
            type State = ($($P::State,)+);
            type Item<'w> = ($($P::Item<'w>,)+);

            fn init(registry: &Registry) -> Self::State {
                ($($P::init(registry),)+)
            }

            #[inline(always)]
            #[allow(non_snake_case)]
            unsafe fn fetch<'w>(world: &'w World, state: &'w mut Self::State) -> Self::Item<'w> {
                let ($($P,)+) = state;
                // SAFETY: caller upholds aliasing invariants for all params.
                unsafe { ($($P::fetch(world, $P),)+) }
            }
        }
    };
}

all_tuples!(impl_param_tuple);

// =============================================================================
// Local<T> — per-handler state
// =============================================================================

/// Per-handler local state. Stored inside the dispatch wrapper (e.g.
/// [`Callback`] or pipeline step), not in [`World`].
///
/// Analogous to Bevy's `Local<T>`.
///
/// Initialized with [`Default::default()`] at handler creation time. Mutated
/// freely at dispatch time — each handler/stage instance has its own
/// independent copy.
///
/// # Examples
///
/// ```ignore
/// fn count_events(mut count: Local<u64>, event: u32) {
///     *count += 1;
///     println!("event #{}: {}", *count, event);
/// }
/// ```
pub struct Local<'s, T: Default + Send + 'static> {
    value: &'s mut T,
}

impl<'s, T: Default + Send + 'static> Local<'s, T> {
    pub(crate) fn new(value: &'s mut T) -> Self {
        Self { value }
    }
}

impl<T: Default + Send + std::fmt::Debug + 'static> std::fmt::Debug for Local<'_, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.value.fmt(f)
    }
}

impl<T: Default + Send + 'static> Deref for Local<'_, T> {
    type Target = T;

    #[inline(always)]
    fn deref(&self) -> &T {
        self.value
    }
}

impl<T: Default + Send + 'static> DerefMut for Local<'_, T> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut T {
        self.value
    }
}

impl<T: Default + Send + 'static> Param for Local<'_, T> {
    type State = T;
    type Item<'s> = Local<'s, T>;

    fn init(_registry: &Registry) -> T {
        T::default()
    }

    #[inline(always)]
    unsafe fn fetch<'s>(_world: &'s World, state: &'s mut T) -> Local<'s, T> {
        // SAFETY: The dispatch wrapper (Callback or Stage) owns state
        // exclusively. Single-threaded dispatch ensures no aliasing.
        // Lifetime 's is bounded by the handler/stage's run() call.
        Local::new(state)
    }
}

// =============================================================================
// RegistryRef — read-only access to the type registry during dispatch
// =============================================================================

/// Read-only access to the [`Registry`] during handler dispatch.
///
/// Allows handlers to create new handlers at runtime by calling
/// [`into_handler`](crate::IntoHandler::into_handler) or
/// [`into_callback`](crate::IntoCallback::into_callback) on the
/// borrowed registry.
///
/// No [`ResourceId`] needed — the registry is part of [`World`]'s
/// structure, not a registered resource.
pub struct RegistryRef<'w> {
    registry: &'w Registry,
}

impl Deref for RegistryRef<'_> {
    type Target = Registry;

    #[inline(always)]
    fn deref(&self) -> &Registry {
        self.registry
    }
}

impl Param for RegistryRef<'_> {
    type State = ();
    type Item<'w> = RegistryRef<'w>;

    fn init(_registry: &Registry) {}

    #[inline(always)]
    unsafe fn fetch<'w>(world: &'w World, _state: &'w mut ()) -> RegistryRef<'w> {
        RegistryRef {
            registry: world.registry(),
        }
    }
}

// =============================================================================
// Handler<E> — object-safe dispatch trait
// =============================================================================

/// Object-safe dispatch trait for event handlers.
///
/// Analogous to Bevy's `System` trait.
///
/// Enables `Box<dyn Handler<E>>` for type-erased heterogeneous dispatch.
/// Storage and scheduling are the driver's responsibility — this trait
/// only defines the dispatch interface.
///
/// `Send` is required because handlers live in [`World`] (via driver
/// storage like timer wheels), and `World` is `Send`. All concrete
/// handler types ([`Callback`], [`HandlerFn`]) satisfy this automatically
/// for typical usage (function pointers, `ResourceId` state, `Send` context).
///
/// Takes `&mut World` — drivers call this directly in their poll loop.
pub trait Handler<E>: Send {
    /// Run this handler with the given event.
    fn run(&mut self, world: &mut World, event: E);

    /// Returns the handler's name.
    ///
    /// Default returns `"<unnamed>"`. [`Callback`] captures the
    /// function's [`type_name`](std::any::type_name) at construction time.
    fn name(&self) -> &'static str {
        "<unnamed>"
    }
}

impl<E> Handler<E> for Box<dyn Handler<E>> {
    fn run(&mut self, world: &mut World, event: E) {
        (**self).run(world, event);
    }

    fn name(&self) -> &'static str {
        (**self).name()
    }
}

// =============================================================================
// CtxFree<F> — coherence wrapper for context-free handlers
// =============================================================================

/// Wrapper that marks a function as context-free.
///
/// Prevents coherence overlap between the context-owning and context-free
/// [`Handler`] impls on [`Callback`]. `CtxFree<F>` is a plain struct and
/// can never satisfy `FnMut` bounds, so the compiler proves the two impls
/// are disjoint.
///
/// Users don't construct this directly — [`IntoHandler`] wraps the
/// function automatically.
#[doc(hidden)]
pub struct CtxFree<F>(pub(crate) F);

/// Type alias for context-free handlers (no owned context).
///
/// This is `Callback<(), CtxFree<F>, Params>` — the `ctx: ()` field
/// is a ZST (zero bytes), identical codegen.
///
/// Created by [`IntoHandler::into_handler`]. Use [`HandlerFn`] in type
/// annotations when you need to name the concrete type rather than
/// `Box<dyn Handler<E>>`.
pub type HandlerFn<F, Params> = Callback<(), CtxFree<F>, Params>;

// =============================================================================
// IntoHandler — conversion trait
// =============================================================================

/// Converts a plain function into a [`Handler`].
///
/// Analogous to Bevy's `IntoSystem`.
///
/// Event `E` is always the last function parameter. Everything before
/// it is resolved as [`Param`] from a [`Registry`].
///
/// # Named functions only
///
/// Closures do not work with `IntoHandler` due to Rust's HRTB inference
/// limitations with GATs. Use named `fn` items instead. This is the same
/// limitation as Bevy's system registration.
///
/// # Factory functions and `use<>` (Rust 2024)
///
/// If you write a function that takes `&Registry` and returns
/// `impl Handler<E>`, Rust 2024 captures the registry borrow in the
/// return type. Add `+ use<...>` listing only the type parameters the
/// handler actually holds:
///
/// ```ignore
/// fn build_handler<C: Config>(
///     reg: &Registry,
/// ) -> impl Handler<Order> + use<C> {
///     process_order::<C>.into_handler(reg)
/// }
/// ```
///
/// See the [crate-level docs](crate#returning-impl-handler-from-functions-rust-2024)
/// for details.
///
/// # Examples
///
/// ```
/// use nexus_rt::{Res, ResMut, IntoHandler, WorldBuilder, Resource};
///
/// #[derive(Resource)]
/// struct Counter(u64);
/// #[derive(Resource)]
/// struct Flag(bool);
///
/// fn tick(counter: Res<Counter>, mut flag: ResMut<Flag>, event: u32) {
///     if event > 0 {
///         flag.0 = true;
///     }
/// }
///
/// let mut builder = WorldBuilder::new();
/// builder.register(Counter(0));
/// builder.register(Flag(false));
///
/// let mut handler = tick.into_handler(builder.registry());
/// ```
#[diagnostic::on_unimplemented(
    message = "this function cannot be converted into a handler",
    note = "handler signature: `fn(Res<A>, ResMut<B>, ..., Event)` — resources first, event last",
    note = "closures with resource parameters (Res<T>, ResMut<T>) are not supported — use a named `fn`",
    note = "arity-0 closures (`fn(Event)` with no resources) ARE supported"
)]
pub trait IntoHandler<E, Params> {
    /// The concrete handler type produced.
    type Handler: Handler<E> + 'static;

    /// Convert this function into a handler, resolving parameters from the registry.
    #[must_use = "the handler must be stored or dispatched — discarding it does nothing"]
    fn into_handler(self, registry: &Registry) -> Self::Handler;
}

// =============================================================================
// Per-arity impls via macro — context-free path (Callback<(), CtxFree<F>, P>)
// =============================================================================

// Arity 0: fn(E) — event-only handler, no resource params.
impl<E, F: FnMut(E) + Send + 'static> IntoHandler<E, ()> for F {
    type Handler = Callback<(), CtxFree<F>, ()>;

    fn into_handler(self, registry: &Registry) -> Self::Handler {
        Callback {
            ctx: (),
            f: CtxFree(self),
            state: <() as Param>::init(registry),
            name: std::any::type_name::<F>(),
        }
    }
}

impl<E, F: FnMut(E) + Send + 'static> Handler<E> for Callback<(), CtxFree<F>, ()> {
    fn run(&mut self, _world: &mut World, event: E) {
        (self.f.0)(event);
    }

    fn name(&self) -> &'static str {
        self.name
    }
}

macro_rules! impl_into_handler {
    ($($P:ident),+) => {
        impl<E, F: Send + 'static, $($P: Param + 'static),+> IntoHandler<E, ($($P,)+)> for F
        where
            // Double-bound pattern (from Bevy):
            // - First bound: compiler uses P directly to infer Param
            //   types from the function signature (GATs aren't injective,
            //   so P::Item<'w> alone can't determine P).
            // - Second bound: verifies the function is callable with the
            //   fetched items at any lifetime.
            for<'a> &'a mut F: FnMut($($P,)+ E) + FnMut($($P::Item<'a>,)+ E),
        {
            type Handler = Callback<(), CtxFree<F>, ($($P,)+)>;

            fn into_handler(self, registry: &Registry) -> Self::Handler {
                let state = <($($P,)+) as Param>::init(registry);
                {
                    #[allow(non_snake_case)]
                    let ($($P,)+) = &state;
                    registry.check_access(&[
                        $(
                            (<$P as Param>::resource_id($P),
                             std::any::type_name::<$P>()),
                        )+
                    ]);
                }
                Callback {
                    ctx: (),
                    f: CtxFree(self),
                    state,
                    name: std::any::type_name::<F>(),
                }
            }
        }

        impl<E, F: Send + 'static, $($P: Param + 'static),+> Handler<E>
            for Callback<(), CtxFree<F>, ($($P,)+)>
        where
            for<'a> &'a mut F: FnMut($($P,)+ E) + FnMut($($P::Item<'a>,)+ E),
        {
            #[allow(non_snake_case)]
            fn run(&mut self, world: &mut World, event: E) {
                // Helper binds the HRTB lifetime at a concrete call site.
                #[allow(clippy::too_many_arguments)]
                fn call_inner<$($P,)+ Ev>(
                    mut f: impl FnMut($($P,)+ Ev),
                    $($P: $P,)+
                    event: Ev,
                ) {
                    f($($P,)+ event);
                }

                // SAFETY: state was produced by init() on the same registry
                // that built this world. Single-threaded sequential dispatch
                // ensures no mutable aliasing across params.
                #[cfg(debug_assertions)]
                world.clear_borrows();
                let ($($P,)+) = unsafe {
                    <($($P,)+) as Param>::fetch(world, &mut self.state)
                };
                call_inner(&mut self.f.0, $($P,)+ event);
            }

            fn name(&self) -> &'static str {
                self.name
            }
        }
    };
}

all_tuples!(impl_into_handler);

// =============================================================================
// Opaque — marker for closures with unresolved dependencies
// =============================================================================

/// Marker occupying the `Params` position in step and handler traits to
/// indicate that a closure manages its own resource access via
/// `world.resource::<T>()` rather than through [`Param`] resolution.
///
/// `Opaque` is **not** a [`Param`]. It exists solely so the compiler can
/// distinguish three disjoint impl tiers without coherence conflicts:
///
/// | `Params` type | Function shape | Resolution |
/// |---|---|---|
/// | `()` | `FnMut(E)` | No resources needed |
/// | `(P0,)` … `(P0..P7,)` | `fn(Res<A>, ResMut<B>, E)` | Build-time [`Param::init`], dispatch-time [`Param::fetch`] |
/// | `Opaque` | `FnMut(&mut World, E)` | None — caller owns all access |
///
/// Because `&mut World` does not implement `Param`, the `Opaque` impls
/// are always disjoint from the arity-based impls — the compiler infers
/// `Params` unambiguously from the closure/function signature.
///
/// # When to use
///
/// Prefer named functions with [`Param`] parameters — they resolve to a
/// direct pointer dereference per resource (single deref, no HashMap
/// lookup). Use `Opaque` closures as an escape hatch when:
///
/// - You need **conditional** resource access (different resources
///   depending on runtime state).
/// - You need access to a resource whose type isn't known at build time.
/// - You're prototyping and want to defer the named-function refactor.
///
/// # Example
///
/// ```ignore
/// // Named function — preferred, hot path:
/// pipeline.guard(check_risk, &reg)    // fn(Res<Config>, &Order) -> bool
///
/// // Arity-0 closure — no World access:
/// pipeline.guard(|o: &Order| o.price > 100.0, &reg)
///
/// // Opaque closure — escape hatch, HashMap lookups:
/// pipeline.guard(|w: &mut World, o: &Order| {
///     let cfg = w.resource::<Config>();
///     o.price > cfg.threshold
/// }, &reg)
/// ```
pub struct Opaque;

/// Marker type for handlers whose parameters are already resolved.
///
/// Used by the blanket [`IntoHandler`] impl for any [`Handler<E>`].
/// Enables passing already-built pipelines, templates, callbacks, and
/// `Box<dyn Handler<E>>` where `IntoHandler` is expected.
///
/// The `registry` argument to [`IntoHandler::into_handler`] is ignored —
/// the handler's parameters were resolved against the registry it was
/// originally built with. Callers must ensure the handler is run against
/// the same [`World`] it was resolved for.
///
/// When returning a resolved handler from a factory function, the Rust
/// 2024 `+ use<...>` annotation applies — see [`IntoHandler`] docs.
///
/// Users never need to name this type — it's inferred automatically.
pub struct Resolved;

impl<E, H: Handler<E> + 'static> IntoHandler<E, Resolved> for H {
    type Handler = H;

    fn into_handler(self, _registry: &Registry) -> H {
        self
    }
}

// =============================================================================
// OpaqueHandler — Handler<E> for FnMut(&mut World, E) closures
// =============================================================================

/// Wrapper for closures that receive `&mut World` directly as a [`Handler`].
///
/// Created by [`IntoHandler::into_handler`] when the function signature is
/// `FnMut(&mut World, E)`. The closure handles its own resource access —
/// no [`Param`] resolution occurs.
///
/// Prefer named functions with [`Param`] resolution for hot-path handlers.
/// `OpaqueHandler` is an escape hatch for cases where dynamic or conditional
/// resource access is needed.
pub struct OpaqueHandler<F> {
    f: F,
    name: &'static str,
}

impl<E, F: FnMut(&mut World, E) + Send + 'static> Handler<E> for OpaqueHandler<F> {
    fn run(&mut self, world: &mut World, event: E) {
        (self.f)(world, event);
    }

    fn name(&self) -> &'static str {
        self.name
    }
}

impl<E, F: FnMut(&mut World, E) + Send + 'static> IntoHandler<E, Opaque> for F {
    type Handler = OpaqueHandler<F>;

    fn into_handler(self, _registry: &Registry) -> Self::Handler {
        OpaqueHandler {
            f: self,
            name: std::any::type_name::<F>(),
        }
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::WorldBuilder;
    use crate::world::Sequence;

    // -- Param tests ----------------------------------------------------

    #[test]
    fn res_param() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(42);
        let mut world = builder.build();

        let mut state = <Res<u64> as Param>::init(world.registry_mut());
        // SAFETY: state from init on same registry, no aliasing.
        let res = unsafe { <Res<u64> as Param>::fetch(&world, &mut state) };
        assert_eq!(*res, 42);
    }

    #[test]
    fn res_mut_param() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(1);
        let mut world = builder.build();

        let mut state = <ResMut<u64> as Param>::init(world.registry_mut());
        // SAFETY: state from init on same registry, no aliasing.
        unsafe {
            let mut res = <ResMut<u64> as Param>::fetch(&world, &mut state);
            *res = 99;
        }
        // New dispatch phase — previous borrows dropped above.
        #[cfg(debug_assertions)]
        world.clear_borrows();
        unsafe {
            let mut read_state = <Res<u64> as Param>::init(world.registry_mut());
            let res = <Res<u64> as Param>::fetch(&world, &mut read_state);
            assert_eq!(*res, 99);
        }
    }

    #[test]
    fn tuple_param() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(10);
        builder.register::<bool>(true);
        let mut world = builder.build();

        let mut state = <(Res<u64>, ResMut<bool>) as Param>::init(world.registry_mut());
        // SAFETY: different types, no aliasing.
        unsafe {
            let (counter, mut flag) =
                <(Res<u64>, ResMut<bool>) as Param>::fetch(&world, &mut state);
            assert_eq!(*counter, 10);
            assert!(*flag);
            *flag = false;
        }
        // New dispatch phase — previous borrows dropped above.
        #[cfg(debug_assertions)]
        world.clear_borrows();
        unsafe {
            let mut read_state = <Res<bool> as Param>::init(world.registry_mut());
            let res = <Res<bool> as Param>::fetch(&world, &mut read_state);
            assert!(!*res);
        }
    }

    #[test]
    fn empty_tuple_param() {
        let mut world = WorldBuilder::new().build();
        <() as Param>::init(world.registry_mut());
        // SAFETY: no params to alias.
        unsafe { <() as Param>::fetch(&world, &mut ()) };
    }

    // -- Handler dispatch tests -----------------------------------------------

    fn event_only_handler(event: u32) {
        assert_eq!(event, 42);
    }

    #[test]
    fn event_only_dispatch() {
        let mut world = WorldBuilder::new().build();
        let mut sys = event_only_handler.into_handler(world.registry_mut());
        sys.run(&mut world, 42u32);
    }

    fn one_res_handler(counter: Res<u64>, event: u32) {
        assert_eq!(*counter, 10);
        assert_eq!(event, 5);
    }

    #[test]
    fn one_res_and_event() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(10);
        let mut world = builder.build();

        let mut sys = one_res_handler.into_handler(world.registry_mut());
        sys.run(&mut world, 5u32);
    }

    fn two_res_handler(counter: Res<u64>, flag: Res<bool>, event: u32) {
        assert_eq!(*counter, 10);
        assert!(*flag);
        assert_eq!(event, 7);
    }

    #[test]
    fn two_res_and_event() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(10);
        builder.register::<bool>(true);
        let mut world = builder.build();

        let mut sys = two_res_handler.into_handler(world.registry_mut());
        sys.run(&mut world, 7u32);
    }

    fn accumulate(mut counter: ResMut<u64>, event: u64) {
        *counter += event;
    }

    #[test]
    fn mutation_through_res_mut() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(0);
        let mut world = builder.build();

        let mut sys = accumulate.into_handler(world.registry_mut());

        sys.run(&mut world, 10u64);
        sys.run(&mut world, 5u64);

        assert_eq!(*world.resource::<u64>(), 15);
    }

    fn add_handler(mut counter: ResMut<u64>, event: u64) {
        *counter += event;
    }

    fn mul_handler(mut counter: ResMut<u64>, event: u64) {
        *counter *= event;
    }

    #[test]
    fn box_dyn_type_erasure() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(0);
        let mut world = builder.build();

        let sys_a = add_handler.into_handler(world.registry_mut());
        let sys_b = mul_handler.into_handler(world.registry_mut());

        let mut handlers: Vec<Box<dyn Handler<u64>>> = vec![Box::new(sys_a), Box::new(sys_b)];

        for h in &mut handlers {
            h.run(&mut world, 3u64);
        }
        // 0 + 3 = 3, then 3 * 3 = 9
        assert_eq!(*world.resource::<u64>(), 9);
    }

    // -- Local<T> tests -------------------------------------------------------

    fn local_counter(mut count: Local<u64>, _event: u32) {
        *count += 1;
    }

    #[test]
    fn local_default_init() {
        let mut world = WorldBuilder::new().build();
        let mut sys = local_counter.into_handler(world.registry_mut());
        // Ran once — count should be 1 (started at 0). No panic means init worked.
        sys.run(&mut world, 1u32);
    }

    #[test]
    fn local_persists_across_runs() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(0);
        let mut world = builder.build();

        fn accumulate_local(mut count: Local<u64>, mut total: ResMut<u64>, _event: u32) {
            *count += 1;
            *total = *count;
        }

        let mut sys = accumulate_local.into_handler(world.registry_mut());
        sys.run(&mut world, 0u32);
        sys.run(&mut world, 0u32);
        sys.run(&mut world, 0u32);

        assert_eq!(*world.resource::<u64>(), 3);
    }

    #[test]
    fn local_independent_per_handler() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(0);
        let mut world = builder.build();

        fn inc_local(mut count: Local<u64>, mut total: ResMut<u64>, _event: u32) {
            *count += 1;
            *total += *count;
        }

        let mut sys_a = inc_local.into_handler(world.registry_mut());
        let mut sys_b = inc_local.into_handler(world.registry_mut());

        sys_a.run(&mut world, 0u32); // local=1, total=0+1=1
        sys_b.run(&mut world, 0u32); // local=1, total=1+1=2
        sys_a.run(&mut world, 0u32); // local=2, total=2+2=4

        assert_eq!(*world.resource::<u64>(), 4);
    }

    // -- Option<Res<T>> / Option<ResMut<T>> tests -----------------------------

    #[test]
    fn option_res_none_when_missing() {
        let mut world = WorldBuilder::new().build();
        let mut state = <Option<Res<u64>> as Param>::init(world.registry_mut());
        let opt = unsafe { <Option<Res<u64>> as Param>::fetch(&world, &mut state) };
        assert!(opt.is_none());
    }

    #[test]
    fn option_res_some_when_present() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(42);
        let mut world = builder.build();

        let mut state = <Option<Res<u64>> as Param>::init(world.registry_mut());
        let opt = unsafe { <Option<Res<u64>> as Param>::fetch(&world, &mut state) };
        assert_eq!(*opt.unwrap(), 42);
    }

    #[test]
    fn option_res_mut_some_when_present() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(1);
        let mut world = builder.build();

        let mut state = <Option<ResMut<u64>> as Param>::init(world.registry_mut());
        unsafe {
            let opt = <Option<ResMut<u64>> as Param>::fetch(&world, &mut state);
            *opt.unwrap() = 99;
        }
        #[cfg(debug_assertions)]
        world.clear_borrows();
        unsafe {
            let mut read_state = <Res<u64> as Param>::init(world.registry_mut());
            let res = <Res<u64> as Param>::fetch(&world, &mut read_state);
            assert_eq!(*res, 99);
        }
    }

    fn optional_handler(opt: Option<Res<String>>, _event: u32) {
        assert!(opt.is_none());
    }

    #[test]
    fn option_in_handler() {
        let mut world = WorldBuilder::new().build();
        let mut sys = optional_handler.into_handler(world.registry_mut());
        sys.run(&mut world, 0u32);
    }

    // -- Access conflict detection ----------------------------------------

    #[test]
    #[should_panic(expected = "conflicting access")]
    fn duplicate_res_panics() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(0);
        let mut world = builder.build();

        fn bad(a: Res<u64>, b: Res<u64>, _e: ()) {
            let _ = (*a, *b);
        }

        let _sys = bad.into_handler(world.registry_mut());
    }

    #[test]
    #[should_panic(expected = "conflicting access")]
    fn duplicate_res_mut_panics() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(0);
        let mut world = builder.build();

        fn bad(a: ResMut<u64>, b: ResMut<u64>, _e: ()) {
            let _ = (&*a, &*b);
        }

        let _sys = bad.into_handler(world.registry_mut());
    }

    #[test]
    #[should_panic(expected = "conflicting access")]
    fn duplicate_mixed_panics() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(0);
        let mut world = builder.build();

        fn bad(a: Res<u64>, b: ResMut<u64>, _e: ()) {
            let _ = (*a, &*b);
        }

        let _sys = bad.into_handler(world.registry_mut());
    }

    #[test]
    fn different_types_no_conflict() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(0);
        builder.register::<u32>(0);
        let mut world = builder.build();

        fn ok(a: Res<u64>, b: ResMut<u32>, _e: ()) {
            let _ = (*a, &*b);
        }

        let _sys = ok.into_handler(world.registry_mut());
    }

    #[test]
    fn local_no_conflict() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(0);
        let mut world = builder.build();

        fn ok(local: Local<u64>, val: ResMut<u64>, _e: ()) {
            let _ = (&*local, &*val);
        }

        let _sys = ok.into_handler(world.registry_mut());
    }

    // -- OpaqueHandler tests --------------------------------------------------

    #[test]
    fn opaque_handler_dispatch() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(0);
        let mut world = builder.build();

        let opaque_fn = |w: &mut World, event: u64| {
            let current = *w.resource::<u64>();
            *w.resource_mut::<u64>() = current + event;
        };

        let mut h = opaque_fn.into_handler(world.registry_mut());
        h.run(&mut world, 10u64);
        h.run(&mut world, 5u64);

        assert_eq!(*world.resource::<u64>(), 15);
    }

    #[test]
    fn opaque_handler_boxed() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(0);
        let mut world = builder.build();

        let opaque_fn = |w: &mut World, event: u64| {
            *w.resource_mut::<u64>() += event;
        };

        let mut h: Box<dyn Handler<u64>> = Box::new(opaque_fn.into_handler(world.registry_mut()));
        h.run(&mut world, 7u64);

        assert_eq!(*world.resource::<u64>(), 7);
    }

    // -- Seq / SeqMut tests ------------------------------------------------

    #[test]
    fn seq_reads_current() {
        fn check(seq: Seq, mut out: ResMut<i64>, _event: ()) {
            *out = seq.get();
        }

        let mut builder = WorldBuilder::new();
        builder.register::<i64>(0);
        let mut world = builder.build();
        world.next_sequence(); // seq=1

        let mut handler = check.into_handler(world.registry_mut());
        handler.run(&mut world, ());
        assert_eq!(*world.resource::<i64>(), 1);
    }

    #[test]
    fn seq_mut_advances() {
        fn stamp(mut seq: SeqMut, mut counter: ResMut<u64>, _event: ()) {
            let a = seq.advance();
            let b = seq.advance();
            *counter = a.get() as u64 * 100 + b.get() as u64;
        }

        let mut builder = WorldBuilder::new();
        builder.register::<u64>(0);
        let mut world = builder.build();
        // seq starts at 0, handler advances twice → 1, 2
        let mut handler = stamp.into_handler(world.registry_mut());
        handler.run(&mut world, ());
        assert_eq!(*world.resource::<u64>(), 100 + 2);
        // World sequence is now 2
        assert_eq!(world.current_sequence(), Sequence(2));
    }

    #[test]
    fn seq_mut_persistent_across_dispatches() {
        fn advance(mut seq: SeqMut, _event: ()) {
            seq.advance();
        }

        let builder = WorldBuilder::new();
        let mut world = builder.build();
        let mut handler = advance.into_handler(world.registry_mut());
        handler.run(&mut world, ());
        handler.run(&mut world, ());
        handler.run(&mut world, ());
        assert_eq!(world.current_sequence(), Sequence(3));
    }

    // -- Seq position / arity coverage ------------------------------------

    #[test]
    fn seq_only_param() {
        fn handle(seq: Seq, _event: ()) {
            assert!(seq.get() >= 0);
        }

        let builder = WorldBuilder::new();
        let mut world = builder.build();
        let mut h = handle.into_handler(world.registry_mut());
        h.run(&mut world, ());
    }

    #[test]
    fn seq_first_with_res() {
        fn handle(seq: Seq, config: Res<u64>, mut out: ResMut<i64>, _event: ()) {
            *out = seq.get() + *config as i64;
        }

        let mut builder = WorldBuilder::new();
        builder.register::<u64>(100);
        builder.register::<i64>(0);
        let mut world = builder.build();
        world.next_sequence();
        let mut h = handle.into_handler(world.registry_mut());
        h.run(&mut world, ());
        assert_eq!(*world.resource::<i64>(), 101);
    }

    #[test]
    fn seq_middle_position() {
        fn handle(config: Res<u64>, seq: Seq, mut out: ResMut<i64>, _event: ()) {
            *out = *config as i64 + seq.get();
        }

        let mut builder = WorldBuilder::new();
        builder.register::<u64>(50);
        builder.register::<i64>(0);
        let mut world = builder.build();
        world.next_sequence(); // seq=1
        let mut h = handle.into_handler(world.registry_mut());
        h.run(&mut world, ());
        assert_eq!(*world.resource::<i64>(), 51);
    }

    #[test]
    fn seq_last_position() {
        fn handle(mut out: ResMut<i64>, seq: Seq, _event: ()) {
            *out = seq.get();
        }

        let mut builder = WorldBuilder::new();
        builder.register::<i64>(0);
        let mut world = builder.build();
        world.next_sequence();
        world.next_sequence(); // seq=2
        let mut h = handle.into_handler(world.registry_mut());
        h.run(&mut world, ());
        assert_eq!(*world.resource::<i64>(), 2);
    }

    #[test]
    fn seq_mut_only_param() {
        fn handle(mut seq: SeqMut, _event: ()) {
            seq.advance();
        }

        let builder = WorldBuilder::new();
        let mut world = builder.build();
        let mut h = handle.into_handler(world.registry_mut());
        h.run(&mut world, ());
        assert_eq!(world.current_sequence(), Sequence(1));
    }

    #[test]
    fn seq_mut_first_with_res() {
        fn handle(mut seq: SeqMut, mut out: ResMut<i64>, _event: ()) {
            let s = seq.advance();
            *out = s.0;
        }

        let mut builder = WorldBuilder::new();
        builder.register::<i64>(0);
        let mut world = builder.build();
        let mut h = handle.into_handler(world.registry_mut());
        h.run(&mut world, ());
        assert_eq!(*world.resource::<i64>(), 1);
    }

    #[test]
    fn seq_mut_middle_position() {
        fn handle(config: Res<u64>, mut seq: SeqMut, mut out: ResMut<i64>, _event: ()) {
            let s = seq.advance();
            *out = s.0 + *config as i64;
        }

        let mut builder = WorldBuilder::new();
        builder.register::<u64>(10);
        builder.register::<i64>(0);
        let mut world = builder.build();
        let mut h = handle.into_handler(world.registry_mut());
        h.run(&mut world, ());
        assert_eq!(*world.resource::<i64>(), 11);
    }

    #[test]
    fn seq_mut_last_position() {
        fn handle(mut out: ResMut<i64>, mut seq: SeqMut, _event: ()) {
            let s = seq.advance();
            *out = s.0;
        }

        let mut builder = WorldBuilder::new();
        builder.register::<i64>(0);
        let mut world = builder.build();
        let mut h = handle.into_handler(world.registry_mut());
        h.run(&mut world, ());
        assert_eq!(*world.resource::<i64>(), 1);
    }

    #[test]
    fn seq_mut_multiple_advances_in_one_dispatch() {
        fn handle(mut seq: SeqMut, mut out: ResMut<Vec<i64>>, _event: ()) {
            out.push(seq.advance().0);
            out.push(seq.advance().0);
            out.push(seq.advance().0);
        }

        let mut builder = WorldBuilder::new();
        builder.register::<Vec<i64>>(Vec::new());
        let mut world = builder.build();
        let mut h = handle.into_handler(world.registry_mut());
        h.run(&mut world, ());
        assert_eq!(*world.resource::<Vec<i64>>(), vec![1, 2, 3]);
        assert_eq!(world.current_sequence(), Sequence(3));
    }

    // =========================================================================
    // Resolved — blanket IntoHandler for Handler<E>
    // =========================================================================

    #[test]
    fn concrete_handler_satisfies_into_handler() {
        // A concrete Handler<E> type should satisfy IntoHandler<E, Resolved>
        fn accept_into_handler<E, P>(h: impl IntoHandler<E, P>, reg: &Registry) -> impl Handler<E> {
            h.into_handler(reg)
        }

        let mut builder = WorldBuilder::new();
        builder.register::<u64>(0);
        let world = builder.build();

        fn bump(mut val: ResMut<u64>, event: u64) {
            *val += event;
        }

        // Build a concrete handler, pass it where IntoHandler is expected
        let handler = bump.into_handler(world.registry());
        let _resolved = accept_into_handler(handler, world.registry());
    }

    #[test]
    fn handler_impl_into_handler_dispatches() {
        let mut builder = WorldBuilder::new();
        builder.register::<u64>(0);

        fn add_event(mut val: ResMut<u64>, event: u64) {
            *val += event;
        }

        // Build handler from function, then re-pass as IntoHandler via Resolved
        let handler = add_event.into_handler(builder.registry());
        let mut resolved = handler.into_handler(builder.registry());
        let mut world = builder.build();

        resolved.run(&mut world, 42);
        assert_eq!(*world.resource::<u64>(), 42);
    }
}