ygopro-handler 0.1.1

A type-erased, plugin-based message handler framework for YGOPro duel rooms.
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
//! The handler abstraction: extract parameters, produce a response, and combine them.
//!
//! This module defines how a handler receives a [`Bundle`] (via [`FromRequest`]), produces
//! a response (via [`IntoResponse`]), and how responses are combined across the handler
//! chain ([`Call`]). It also provides the three handler wrappers:
//! [`tower_handler::TowerHandler`], [`async_handler::AsyncHandler`], and
//! [`sync_handler::SyncHandler`].

use std::future::Future;
use std::pin::Pin;

/// The type-erased state carried through the handler chain.
#[derive(Debug)]
pub struct State {
    /// The type-erased state map.
    pub data: anymap3::Map<dyn std::any::Any + Send + Sync>,
}

impl State {
    /// Create an empty state.
    pub fn new() -> Self {
        State { data: Default::default() }
    }
}

impl Default for State {
    fn default() -> Self {
        Self::new()
    }
}

/// A value that can be converted into a response.
pub trait IntoResponse<Res> {
    /// Convert this value into a response.
    fn into_response(self) -> Res;
}

impl<T: Send> IntoResponse<T> for T {
    fn into_response(self) -> T {
        self
    }
}

/// Define how A value be extracted from a [`Bundle`].
pub trait FromRequest<Req, State, Res>: Sized
where
    Req: Send,
    State: Send,
    Res: Send,
{
    /// Extract this value from the bundle.
    fn from_request(bundle: &mut Bundle<Req, State, Res>) -> Option<Self>;
}

/// A flag that stops the handler chain.
#[derive(Debug)]
pub struct StopFlag(pub bool);

impl Default for StopFlag {
    fn default() -> Self {
        Self(false)
    }
}

/// The container passed through the handler chain, carrying the request, response, state,
/// and a stop flag.
#[derive(Debug)]
#[repr(C)]
pub struct Bundle<Req, State = crate::handler::State, Res = ()> {
    /// The request being processed.
    pub request: Req,
    /// The response being built.
    pub response: Res,
    /// A flag to stop the chain.
    pub stop_flag: StopFlag,
    // In order to make multiple Call impl in SyncHandler, we must put state
    // in the last position because we use the mem-order trick here.
    /// The state shared across handlers.
    pub state: State,
}

impl<Req, State, Res> Bundle<Req, State, Res> {
    /// Create a bundle from a request, state, and response.
    pub fn new(request: Req, state: State, response: Res) -> Self {
        Bundle { request, state, response, stop_flag: Default::default() }
    }
}

/// A handler that takes extracted parameters and returns a future yielding a response.
pub trait Handler<T, Req, State, Res>: Clone + Send + Sync + Sized + 'static
where
    State: Send,
{
    /// The future produced when calling the handler.
    type Future: Future<Output = Option<Res>> + Send;

    /// Call the handler with the bundle.
    fn call(&self, bundle: &mut Bundle<Req, State, Res>) -> Self::Future;
}

impl<F, Fut, Output, Req, State, Res> Handler<((),), Req, State, Res> for F
where
    F: Fn() -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Output> + Send + 'static,
    Output: IntoResponse<Res> + 'static,
    Req: Send + 'static,
    State: Send + 'static,
    Res: Send + 'static,
{
    type Future = Pin<Box<dyn Future<Output = Option<Res>> + Send>>;

    fn call(&self, _bundle: &mut Bundle<Req, State, Res>) -> Self::Future {
        let fut = (self)();
        Box::pin(async move { Some(fut.await.into_response()) })
    }
}

impl<F, Output, Req, State, Res> Handler<Option<()>, Req, State, Res> for F
where
    F: Fn() -> Output + Clone + Send + Sync + 'static,
    Output: IntoResponse<Res> + 'static,
    Req: Send,
    State: Send,
    Res: Send,
{
    type Future = std::future::Ready<Option<Res>>;

    fn call(&self, _bundle: &mut Bundle<Req, State, Res>) -> Self::Future {
        std::future::ready(Some((self)().into_response()))
    }
}

macro_rules! impl_handler {
    ([$($ty:ident),*], $last:ident) => {
        #[allow(non_snake_case, unused_mut)]
        impl<F, Fut, Output, Req, State, Res, $($ty,)* $last> Handler<((), $($ty,)* $last,), Req, State, Res> for F
        where
            F: Fn($($ty,)* $last,) -> Fut + Clone + Send + Sync + 'static,
            Fut: Future<Output = Output> + Send + 'static,
            Output: IntoResponse<Res> + 'static,
            Req: Send + 'static,
            State: Send + 'static,
            Res: Send + 'static,
            $( $ty: FromRequest<Req, State, Res> + Send + 'static, )*
            $last: FromRequest<Req, State, Res> + Send + 'static,
        {
            type Future = Pin<Box<dyn Future<Output = Option<Res>> + Send>>;

            fn call(&self, bundle: &mut Bundle<Req, State, Res>) -> Self::Future {
                $(
                    let $ty = match $ty::from_request(bundle) {
                        Some(value) => value,
                        None => return Box::pin(std::future::ready(None)),
                    };
                )*

                let $last = match $last::from_request(bundle) {
                    Some(value) => value,
                    None => return Box::pin(std::future::ready(None)),
                };

                let handler = self.clone();
                Box::pin(async move {
                    let fut = handler($($ty,)* $last,);
                    Some(fut.await.into_response())
                })
            }
        }

        #[allow(non_snake_case, unused_mut)]
        impl<F, Output, Req, State, Res, $($ty,)* $last> Handler<Option<((), $($ty,)* $last,)>, Req, State, Res> for F
        where
            F: Fn($($ty,)* $last,) -> Output + Clone + Send + Sync + 'static,
            Output: IntoResponse<Res> + 'static,
            Req: Send,
            State: Send,
            Res: Send,
            $( $ty: FromRequest<Req, State, Res> + Send, )*
            $last: FromRequest<Req, State, Res> + Send,
        {
            type Future = std::future::Ready<Option<Res>>;

            fn call(&self, bundle: &mut Bundle<Req, State, Res>) -> Self::Future {
                $(
                    let $ty = match $ty::from_request(bundle) {
                        Some(value) => value,
                        None => return std::future::ready(None),
                    };
                )*

                let $last = match $last::from_request(bundle) {
                    Some(value) => value,
                    None => return std::future::ready(None),
                };

                std::future::ready(Some((self)($($ty,)* $last,).into_response()))
            }
        }
    };
}

impl_handler!([], T1);
impl_handler!([T1], T2);
impl_handler!([T1, T2], T3);
impl_handler!([T1, T2, T3], T4);
impl_handler!([T1, T2, T3, T4], T5);
impl_handler!([T1, T2, T3, T4, T5], T6);
impl_handler!([T1, T2, T3, T4, T5, T6], T7);
impl_handler!([T1, T2, T3, T4, T5, T6, T7], T8);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8], T9);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8, T9], T10);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], T11);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11], T12);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12], T13);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13], T14);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14], T15);
impl_handler!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15], T16);

/// A type-erased handler callable with a whole bundle.
pub trait Call<Req, State, Res>: Send + Sync {
    /// Call the handler, returning the updated bundle.
    fn call(&self, bundle: Bundle<Req, State, Res>) -> Pin<Box<dyn Future<Output = Bundle<Req, State, Res>> + Send>>;
    /// The handler's priority, used to sort the chain.
    fn priority(&self) -> u8;
}

/// A handler wrapper that integrates with the tower ecosystem.
pub mod tower_handler {
    use std::convert::Infallible;
    use std::future::Future;
    use std::marker::PhantomData;
    use std::pin::Pin;
    use std::task::Poll;

    use tower::Service;
    use tower::ServiceExt;
    use tower::util::BoxCloneService;

    use super::Bundle;
    use super::Call;
    use super::Handler;

    struct HandlerService<H, T, Req, State, Res> {
        handler: H,
        _marker: PhantomData<fn() -> (T, Req, State, Res)>,
    }

    impl<H, T, Req, State, Res> HandlerService<H, T, Req, State, Res> {
        fn new(handler: H) -> Self {
            Self { handler, _marker: PhantomData }
        }
    }

    impl<H, T, Req, State, Res> Clone for HandlerService<H, T, Req, State, Res>
    where
        H: Clone,
    {
        fn clone(&self) -> Self {
            Self { handler: self.handler.clone(), _marker: PhantomData }
        }
    }

    impl<H, T, Req, State, Res> Service<Bundle<Req, State, Res>> for HandlerService<H, T, Req, State, Res>
    where
        H: Handler<T, Req, State, Res> + Clone,
        Req: Send + 'static,
        State: Send + 'static,
        Res: Send + 'static + std::ops::Mul<Output = Res>,
    {
        type Response = Bundle<Req, State, Res>;
        type Error = Infallible;
        type Future = HandlerServiceFuture<H::Future, Req, State, Res>;

        fn call(&mut self, bundle: Bundle<Req, State, Res>) -> Self::Future {
            let mut bundle = Box::new(bundle);
            let future = self.handler.call(&mut *bundle);
            HandlerServiceFuture { future, bundle: Some(bundle) }
        }

        fn poll_ready(&mut self, _: &mut std::task::Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }
    }

    pin_project_lite::pin_project! {
                struct HandlerServiceFuture<F, Req, State, Res> {
            #[pin]
            future: F,
            bundle: Option<Box<Bundle<Req, State, Res>>>,
        }
    }

    impl<F, Req, State, Res> Future for HandlerServiceFuture<F, Req, State, Res>
    where
        F: Future<Output = Option<Res>>,
        Res: std::ops::Mul<Output = Res>,
    {
        type Output = Result<Bundle<Req, State, Res>, Infallible>;

        fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
            let this = self.project();
            match this.future.poll(cx) {
                Poll::Ready(Some(response)) => {
                    let mut bundle = *this.bundle.take().unwrap();
                    bundle.response = bundle.response * response;
                    Poll::Ready(Ok(bundle))
                }
                Poll::Ready(None) => {
                    Poll::Ready(Ok(*this.bundle.take().unwrap()))
                }
                Poll::Pending => Poll::Pending,
            }
        }
    }

    /// A type-erased handler backed by a tower [`Service`].
    ///
    /// The most feature-complete and the slowest wrapper: it inserts a tower `Service`
    /// layer (`HandlerService`), a boxed future (`HandlerServiceFuture`), and a
    /// `BoxCloneService`, so every call pays for several layers of boxing and a
    /// `oneshot` dispatch.
    pub struct TowerHandler<Req, State, Res> {
        /// The boxed tower service.
        pub service: BoxCloneService<Bundle<Req, State, Res>, Bundle<Req, State, Res>, Infallible>,
        /// The handler's priority.
        pub priority: u8,
        /// The handler's name.
        pub name: &'static str,
        /// The module the handler was registered from.
        pub module_name: &'static str,
    }

    unsafe impl<Req, State, Res> Sync for TowerHandler<Req, State, Res> {}

    impl<Req, State, Res> TowerHandler<Req, State, Res>
    where
        Req: Send + 'static,
        State: Send + 'static,
        Res: Send + std::ops::Mul<Output = Res> + 'static,
    {
        /// Create a tower-backed handler.
        pub fn new<T: 'static>(
            priority: u8,
            name: &'static str,
            module_name: &'static str,
            handler: impl Handler<T, Req, State, Res>,
        ) -> Self {
            let service = HandlerService::new(handler);
            Self {
                priority,
                name,
                module_name,
                service: BoxCloneService::new(service),
            }
        }
    }

    impl<Req, State, Res> Service<Bundle<Req, State, Res>> for TowerHandler<Req, State, Res>
    where
        Req: Send + 'static,
        State: Send + 'static,
        Res: Send + 'static,
    {
        type Response = Bundle<Req, State, Res>;
        type Error = Infallible;
        type Future = futures::future::BoxFuture<'static, Result<Bundle<Req, State, Res>, Infallible>>;

        fn poll_ready(&mut self, cx: &mut std::task::Context<'_>) -> Poll<Result<(), Self::Error>> {
            self.service.poll_ready(cx)
        }

        fn call(&mut self, bundle: Bundle<Req, State, Res>) -> Self::Future {
            self.service.call(bundle)
        }
    }

    impl<Req, State, Res> Clone for TowerHandler<Req, State, Res> {
        fn clone(&self) -> Self {
            Self {
                service: self.service.clone(),
                priority: self.priority,
                name: self.name,
                module_name: self.module_name,
            }
        }
    }

    impl<Req, State, Res> Call<Req, State, Res> for TowerHandler<Req, State, Res>
    where
        Req: Send + 'static,
        State: Send + 'static,
        Res: Send + 'static,
    {
        fn call(&self, bundle: Bundle<Req, State, Res>) -> Pin<Box<dyn Future<Output = Bundle<Req, State, Res>> + Send>> {
            let service = self.service.clone();
            Box::pin(async move { service.oneshot(bundle).await.unwrap() })
        }

        fn priority(&self) -> u8 {
            self.priority
        }
    }
}

/// A type-erased asynchronous handler.
pub mod async_handler {
    use std::future::Future;
    use std::marker::PhantomData;
    use std::pin::Pin;
    use std::sync::Arc;

    use super::Bundle;
    use super::Call;
    use super::Handler;

    struct HandlerWrapper<H, T, Req, State, Res> {
        handler: H,
        priority: u8,
        _phantom: PhantomData<fn() -> (T, Req, State, Res)>,
    }

    impl<H, T, Req, State, Res> Clone for HandlerWrapper<H, T, Req, State, Res>
    where
        H: Clone,
    {
        fn clone(&self) -> Self {
            Self {
                handler: self.handler.clone(),
                priority: self.priority,
                _phantom: PhantomData,
            }
        }
    }

    impl<H, T, Req, State, Res> Call<Req, State, Res> for HandlerWrapper<H, T, Req, State, Res>
    where
        H: Handler<T, Req, State, Res>,
        <H as Handler<T, Req, State, Res>>::Future: 'static,
        T: 'static,
        Req: Send + 'static,
        State: Send + 'static,
        Res: Send + std::ops::Mul<Output = Res> + 'static,
    {
        fn call(&self, bundle: Bundle<Req, State, Res>) -> Pin<Box<dyn Future<Output = Bundle<Req, State, Res>> + Send>> {
            let handler = self.handler.clone();
            Box::pin(async move {
                let mut bundle = bundle;
                if let Some(response) = handler.call(&mut bundle).await {
                    bundle.response = bundle.response * response;
                }
                bundle
            })
        }

        fn priority(&self) -> u8 {
            self.priority
        }
    }

    /// A type-erased asynchronous handler held in an [`Arc`].
    ///
    /// It gives up the tower adaptation layer, holding the handler in an `Arc<dyn Call>`
    /// and boxing only the future. This drops the extra `Service` boxing while staying
    /// cloneable through a cheap `Arc` clone.
    pub struct AsyncHandler<Req, State, Res> {
        /// The handler's name.
        pub name: &'static str,
        /// The module the handler was registered from.
        pub module_name: &'static str,
        handler: Arc<dyn Call<Req, State, Res>>,
    }

    impl<Req, State, Res> Clone for AsyncHandler<Req, State, Res> {
        fn clone(&self) -> Self {
            Self {
                name: self.name,
                module_name: self.module_name,
                handler: self.handler.clone(),
            }
        }
    }

    impl<Req, State, Res> AsyncHandler<Req, State, Res>
    where
        Req: Send + 'static,
        State: Send + 'static,
        Res: Send + std::ops::Mul<Output = Res> + 'static,
    {
        /// Create an async handler.
        pub fn new<T: 'static, H: Handler<T, Req, State, Res>>(
            priority: u8,
            name: &'static str,
            module_name: &'static str,
            handler: H,
        ) -> Self
        where
            <H as Handler<T, Req, State, Res>>::Future: 'static,
        {
            let wrapper = HandlerWrapper {
                handler,
                priority,
                _phantom: PhantomData,
            };
            Self {
                name,
                module_name,
                handler: Arc::new(wrapper),
            }
        }
    }

    impl<Req, State, Res> Call<Req, State, Res> for AsyncHandler<Req, State, Res>
    where
        Req: Send + 'static,
        State: Send + 'static,
        Res: Send + 'static,
    {
        fn call(&self, bundle: Bundle<Req, State, Res>) -> Pin<Box<dyn Future<Output = Bundle<Req, State, Res>> + Send>> {
            self.handler.call(bundle)
        }

        fn priority(&self) -> u8 {
            self.handler.priority()
        }
    }
}

/// A type-erased synchronous handler.
pub mod sync_handler {
    use std::future::Future;
    use std::pin::Pin;

    use super::Bundle;
    use super::Call;
    use super::Handler;

    /// Type-erased synchronous handler wrapper.
    ///
    /// Uses raw pointers and monomorphized function pointers to achieve type erasure
    /// without requiring `'static` bounds on `Req`, `State`, `Res`, or the handler's
    /// type parameter `T`. It gives up the async nature of [`Handler`] (its future is
    /// always `Ready`), in exchange boxing nothing per call and enabling the dual-state
    /// trick ([`WithSubState`]).
    ///
    /// The caller is responsible for ensuring soundness.
    #[repr(C)]
    pub struct SyncHandler<Req, State, Res> {
        /// The handler's name. It is often function name.
        pub name: &'static str,
        /// The module the handler was registered from. It is often produced by `module_path!()`.
        pub module_name: &'static str,
        priority: u8,
        handler_pointer: *const (),
        call_fn: unsafe fn(*const (), &mut Bundle<Req, State, Res>) -> Option<Res>,
        clone_fn: unsafe fn(*const ()) -> *const (),
        drop_fn: unsafe fn(*const ()),
    }

    /// Safety: the stored handler satisfies `Send + Sync` via the `Handler` trait bound.
    unsafe impl<Req, State, Res> Send for SyncHandler<Req, State, Res> {}
    /// Safety: the stored handler satisfies `Send + Sync` via the `Handler` trait bound.
    unsafe impl<Req, State, Res> Sync for SyncHandler<Req, State, Res> {}

    impl<Req, State, Res> SyncHandler<Req, State, Res>
    where
        Req: Send,
        State: Send,
        Res: Send,
    {
        /// Create a synchronous handler.
        pub fn new<T, H: Handler<T, Req, State, Res, Future = std::future::Ready<Option<Res>>>>(
            priority: u8,
            name: &'static str,
            module_name: &'static str,
            handler: H,
        ) -> Self {
            let handler_pointer = Box::into_raw(Box::new(handler)) as *const ();

            unsafe fn call_erased<H, T, Req, State, Res>(
                pointer: *const (),
                bundle: &mut Bundle<Req, State, Res>,
            ) -> Option<Res>
            where
                H: Handler<T, Req, State, Res, Future = std::future::Ready<Option<Res>>>,
                State: Send,
            {
                let handler = unsafe { &*(pointer as *const H) };
                handler.call(bundle).into_inner()
            }

            unsafe fn clone_erased<H: Clone>(pointer: *const ()) -> *const () {
                let handler = unsafe { &*(pointer as *const H) };
                Box::into_raw(Box::new(handler.clone())) as *const ()
            }

            unsafe fn drop_erased<H>(pointer: *const ()) {
                drop(unsafe { Box::from_raw(pointer as *mut H) });
            }

            Self {
                name,
                module_name,
                priority,
                handler_pointer,
                call_fn: call_erased::<H, T, Req, State, Res>,
                clone_fn: clone_erased::<H>,
                drop_fn: drop_erased::<H>,
            }
        }
    }

    impl<Req, State, Res> Clone for SyncHandler<Req, State, Res> {
        fn clone(&self) -> Self {
            Self {
                name: self.name,
                module_name: self.module_name,
                priority: self.priority,
                handler_pointer: unsafe { (self.clone_fn)(self.handler_pointer) },
                call_fn: self.call_fn,
                clone_fn: self.clone_fn,
                drop_fn: self.drop_fn,
            }
        }
    }

    impl<Req, State, Res> Drop for SyncHandler<Req, State, Res> {
        fn drop(&mut self) {
            unsafe { (self.drop_fn)(self.handler_pointer) }
        }
    }

    impl<Req, SubState, Target, Res> Call<Req, Target, Res> for SyncHandler<Req, SubState, Res>
    where
        Req: Send + 'static,
        SubState: Send + 'static,
        Target: Send + 'static + WithSubState<SubState>,
        Res: Send + std::ops::Mul<Output = Res> + 'static,
    {
        fn call(&self, bundle: Bundle<Req, Target, Res>) -> Pin<Box<dyn Future<Output = Bundle<Req, Target, Res>> + Send>> {
            let mut bundle = bundle;
            let result = unsafe {
                // safety: Target: WithSubState<SubState> makes SubState a layout prefix of Target,
                // and Bundle putting state last keeps the leading fields at identical offsets.
                let sub_bundle = &mut *(&mut bundle as *mut Bundle<Req, Target, Res> as *mut Bundle<Req, SubState, Res>);
                (self.call_fn)(self.handler_pointer, sub_bundle)
            };
            if let Some(response) = result {
                bundle.response = bundle.response * response;
            }
            Box::pin(async move { bundle })
        }

        fn priority(&self) -> u8 {
            self.priority
        }
    }

    /// A state whose `states` map is the leading field (offset 0) and whose `duel`
    /// field follows at the same offset as `SubState`'s, so that `&mut Self` can be
    /// reinterpreted as `&mut SubState`.
    ///
    /// # Safety
    /// The implementor must guarantee that every field of `SubState` the handler
    /// will read through the reinterpreted view resides at the same offset in
    /// `Self`. For duel states this holds because the `states` map comes first in
    /// both (offset 0) and `Self`'s duel starts with `SubState`'s duel as a prefix.
    pub unsafe trait WithSubState<SubState> {}

    unsafe impl<T> WithSubState<T> for T {}

    /// Assert the layout of [`SyncHandler`] is identical across two state types.
    pub fn assert_sync_handler_layout<Req, SubState, Target, Res>() {
        const {
            assert!(std::mem::size_of::<SyncHandler<Req, SubState, Res>>() == std::mem::size_of::<SyncHandler<Req, Target, Res>>());
            assert!(std::mem::align_of::<SyncHandler<Req, SubState, Res>>() == std::mem::align_of::<SyncHandler<Req, Target, Res>>());
            assert!(std::mem::offset_of!(SyncHandler<Req, SubState, Res>, call_fn) == std::mem::offset_of!(SyncHandler<Req, Target, Res>, call_fn));
            assert!(std::mem::offset_of!(SyncHandler<Req, SubState, Res>, handler_pointer) == std::mem::offset_of!(SyncHandler<Req, Target, Res>, handler_pointer));
        };
    }
}