my-ecs 0.1.2

An Entity Component System (ECS) library
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
use super::{
    query::{
        EntQueryInfo, EntQueryKey, EntQueryMut, Query, QueryInfo, QueryKey, QueryMut, ResQuery,
        ResQueryInfo, ResQueryKey, ResQueryMut, StoreEntQueryInfo, StoreQueryInfo,
        StoreResQueryInfo,
    },
    select::{
        FilterInfo, FilterKey, FilteredRaw, SelectInfo, SelectKey, SelectedRaw, StoreFilterInfo,
        StoreSelectInfo,
    },
};
use crate::{
    ecs::resource::ResourceKey,
    utils::ds::{ATypeId, Borrowed, ManagedConstPtr, ManagedMutPtr},
    FxBuildHasher,
};
use my_utils::debug_format;
use once_cell::sync::Lazy;
use std::{
    any,
    collections::HashMap,
    fmt,
    hash::BuildHasher,
    marker::PhantomData,
    sync::{Arc, Mutex},
};

/// A storage including request, query and filter information together.
//
// When a system is registered, it's corresponding request and related other information is
// registered here, and it can be shared from other systems. When it comes to unregister, each
// system data will unregister itself from this storage when it's dropped.
pub(crate) static RINFO_STOR: Lazy<Arc<Mutex<RequestInfoStorage<FxBuildHasher>>>> =
    Lazy::new(|| Arc::new(Mutex::new(RequestInfoStorage::new())));

/// Storage containing request and other info.
#[derive(Debug)]
pub(crate) struct RequestInfoStorage<S> {
    /// [`RequestKey`] -> [`RequestInfo`].
    rinfo: HashMap<RequestKey, Arc<RequestInfo>, S>,

    /// [`QueryKey`] -> [`QueryInfo`].
    qinfo: HashMap<QueryKey, Arc<QueryInfo>, S>,

    /// [`ResQueryKey`] -> [`ResQueryInfo`].
    rqinfo: HashMap<ResQueryKey, Arc<ResQueryInfo>, S>,

    /// [`EntQueryKey`] -> [`EntQueryInfo`].
    eqinfo: HashMap<EntQueryKey, Arc<EntQueryInfo>, S>,

    /// [`SelectKey`] -> [`SelectInfo`].
    sinfo: HashMap<SelectKey, Arc<SelectInfo>, S>,

    /// [`FilterKey`] -> [`FilterInfo`].
    finfo: HashMap<FilterKey, Arc<FilterInfo>, S>,
}

impl<S> RequestInfoStorage<S>
where
    S: Default,
{
    fn new() -> Self {
        Self {
            rinfo: HashMap::default(),
            qinfo: HashMap::default(),
            rqinfo: HashMap::default(),
            eqinfo: HashMap::default(),
            sinfo: HashMap::default(),
            finfo: HashMap::default(),
        }
    }
}

impl<S> RequestInfoStorage<S>
where
    S: BuildHasher,
{
    // for future use.
    #[allow(dead_code)]
    pub(crate) fn get_request_info(&self, key: &RequestKey) -> Option<&Arc<RequestInfo>> {
        StoreRequestInfo::get(self, key)
    }

    // for future use.
    #[allow(dead_code)]
    pub(crate) fn get_query_info(&self, key: &QueryKey) -> Option<&Arc<QueryInfo>> {
        StoreQueryInfo::get(self, key)
    }

    // for future use.
    #[allow(dead_code)]
    pub(crate) fn get_resource_query_info(&self, key: &ResQueryKey) -> Option<&Arc<ResQueryInfo>> {
        StoreResQueryInfo::get(self, key)
    }

    // for future use.
    #[allow(dead_code)]
    pub(crate) fn get_entity_query_info(&self, key: &EntQueryKey) -> Option<&Arc<EntQueryInfo>> {
        StoreEntQueryInfo::get(self, key)
    }

    // for future use.
    #[allow(dead_code)]
    pub(crate) fn get_select_info(&self, key: &SelectKey) -> Option<&Arc<SelectInfo>> {
        StoreSelectInfo::get(self, key)
    }

    // for future use.
    #[allow(dead_code)]
    pub(crate) fn get_filter_info(&self, key: &FilterKey) -> Option<&Arc<FilterInfo>> {
        StoreFilterInfo::get(self, key)
    }

    fn remove(&mut self, key: &RequestKey) {
        // Removes request info if it's not referenced from external anymore.
        if matches!(self.rinfo.get(key), Some(x) if Arc::strong_count(x) == 1) {
            // Safety: We checked it in matches.
            let rinfo = unsafe { self.rinfo.remove(key).unwrap_unchecked() };

            // `RequestInfo` contains other info, so copy keys and drop rinfo first in order to keep
            // remove code simple.
            let read_key = rinfo.read().0;
            let write_key = rinfo.write().0;
            let res_read_key = rinfo.res_read().0;
            let res_write_key = rinfo.res_write().0;
            let ent_write_key = rinfo.ent_write().0;
            drop(rinfo);

            // Removes read & write query and select info.
            remove_qinfo_sinfo(self, &read_key);
            remove_qinfo_sinfo(self, &write_key);

            // Removes read & write resource info.
            remove_rqinfo(self, &res_read_key);
            remove_rqinfo(self, &res_write_key);

            // Removes write entity info.
            remove_eqinfo(self, &ent_write_key);
        }

        // Removes query and select info if it's not referenced from external anymore. This function
        // must be called inside `remove()`.
        fn remove_qinfo_sinfo<S>(this: &mut RequestInfoStorage<S>, key: &QueryKey)
        where
            S: BuildHasher,
        {
            // `self.qinfo` = 1.
            const QINFO_EMPTY_STRONG_CNT: usize = 1;

            if matches! (
                this.qinfo.get(key),
                Some(x) if Arc::strong_count(x) == QINFO_EMPTY_STRONG_CNT
            ) {
                // `QueryInfo` contains `FilterInfo` in it. We need to remove `FilterInfo` first.
                // Safety: We checked it in matches.
                let qinfo = unsafe { this.qinfo.remove(key).unwrap_unchecked() };

                // Removes filter info it's not referenced from external anymore.
                for (fkey, sinfo) in qinfo.selectors() {
                    // `sinfo` + `self.sinfo` = 2.
                    const FINFO_EMPTY_STRONG_CNT: usize = 2;

                    if Arc::strong_count(sinfo) == FINFO_EMPTY_STRONG_CNT {
                        this.sinfo.remove(fkey);
                    }
                }
            }
        }

        // Removes resource query info if it's not referenced from external anymore. This function
        // must be called inside `remove()`.
        fn remove_rqinfo<S>(this: &mut RequestInfoStorage<S>, key: &ResQueryKey)
        where
            S: BuildHasher,
        {
            // `self.rqinfo` = 1.
            const EMPTY_STRONG_CNT: usize = 1;

            if matches! (
                this.rqinfo.get(key),
                Some(x) if Arc::strong_count(x) == EMPTY_STRONG_CNT
            ) {
                this.rqinfo.remove(key);
            }
        }

        // Removes entity query info if it's not referenced from external anymore. This function
        // must be called inside `remove()`.
        fn remove_eqinfo<S>(this: &mut RequestInfoStorage<S>, key: &EntQueryKey)
        where
            S: BuildHasher,
        {
            // `self.eqinfo` = 1.
            const EMPTY_STRONG_CNT: usize = 1;

            if matches! (
                this.eqinfo.get(key),
                Some(x) if Arc::strong_count(x) == EMPTY_STRONG_CNT
            ) {
                this.eqinfo.remove(key);
            }
        }
    }
}

impl<S> Default for RequestInfoStorage<S>
where
    S: Default,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<S> StoreRequestInfo for RequestInfoStorage<S>
where
    S: BuildHasher,
{
    fn contains(&self, key: &RequestKey) -> bool {
        self.rinfo.contains_key(key)
    }

    fn get(&self, key: &RequestKey) -> Option<&Arc<RequestInfo>> {
        self.rinfo.get(key)
    }

    fn insert(&mut self, key: RequestKey, info: Arc<RequestInfo>) {
        self.rinfo.insert(key, info);
    }

    // Top level cleaner.
    fn remove(&mut self, key: &RequestKey) {
        self.remove(key)
    }
}

impl<S> StoreQueryInfo for RequestInfoStorage<S>
where
    S: BuildHasher,
{
    fn contains(&self, key: &QueryKey) -> bool {
        self.qinfo.contains_key(key)
    }

    fn get(&self, key: &QueryKey) -> Option<&Arc<QueryInfo>> {
        self.qinfo.get(key)
    }

    fn insert(&mut self, key: QueryKey, info: Arc<QueryInfo>) {
        self.qinfo.insert(key, info);
    }
}

impl<S> StoreResQueryInfo for RequestInfoStorage<S>
where
    S: BuildHasher,
{
    fn contains(&self, key: &ResQueryKey) -> bool {
        self.rqinfo.contains_key(key)
    }

    fn get(&self, key: &ResQueryKey) -> Option<&Arc<ResQueryInfo>> {
        self.rqinfo.get(key)
    }

    fn insert(&mut self, key: ResQueryKey, info: Arc<ResQueryInfo>) {
        self.rqinfo.insert(key, info);
    }
}

impl<S> StoreEntQueryInfo for RequestInfoStorage<S>
where
    S: BuildHasher,
{
    fn contains(&self, key: &EntQueryKey) -> bool {
        self.eqinfo.contains_key(key)
    }

    fn get(&self, key: &EntQueryKey) -> Option<&Arc<EntQueryInfo>> {
        self.eqinfo.get(key)
    }

    fn insert(&mut self, key: EntQueryKey, info: Arc<EntQueryInfo>) {
        self.eqinfo.insert(key, info);
    }
}

impl<S> StoreSelectInfo for RequestInfoStorage<S>
where
    S: BuildHasher,
{
    fn contains(&self, key: &SelectKey) -> bool {
        self.sinfo.contains_key(key)
    }

    fn get(&self, key: &SelectKey) -> Option<&Arc<SelectInfo>> {
        self.sinfo.get(key)
    }

    fn insert(&mut self, key: SelectKey, info: Arc<SelectInfo>) {
        self.sinfo.insert(key, info);
    }
}

impl<S> StoreFilterInfo for RequestInfoStorage<S>
where
    S: BuildHasher,
{
    fn contains(&self, key: &FilterKey) -> bool {
        self.finfo.contains_key(key)
    }

    fn get(&self, key: &FilterKey) -> Option<&Arc<FilterInfo>> {
        self.finfo.get(key)
    }

    fn insert(&mut self, key: FilterKey, info: Arc<FilterInfo>) {
        self.finfo.insert(key, info);
    }
}

/// A system request for a components, resources, and entity containers.
///
/// All systems must declare their own requests in advance. The crate exploits the information to
/// avoid data race and dead-lock between systems. A request consists of read and write requests
/// like so,
///
/// * Read - Read request for a set of components.
/// * Write - Write request for a set of components.
/// * ResRead - Read request for a set of resources.
/// * ResWrite - Write request for a set of resources.
/// * EntWrite - Write request for a set of entity containers.
pub trait Request: 'static {
    type Read: Query;
    type Write: QueryMut;
    type ResRead: ResQuery;
    type ResWrite: ResQueryMut;
    type EntWrite: EntQueryMut;

    #[doc(hidden)]
    fn key() -> RequestKey {
        RequestKey::of::<Self>()
    }

    #[doc(hidden)]
    fn get_info_from<S>(stor: &mut S) -> &Arc<RequestInfo>
    where
        S: StoreRequestInfo + ?Sized,
    {
        let key = Self::key();

        if !StoreRequestInfo::contains(stor, &key) {
            let rinfo = Arc::new(Self::info_from(stor));
            StoreRequestInfo::insert(stor, key, rinfo);
        }

        // Safety: Inserted right before.
        unsafe { StoreRequestInfo::get(stor, &key).unwrap_unchecked() }
    }

    #[doc(hidden)]
    fn info_from<S>(stor: &mut S) -> RequestInfo
    where
        S: StoreRequestInfo + ?Sized,
    {
        // TODO: create new()
        RequestInfo {
            name: any::type_name::<Self>(),
            read: (
                Self::Read::key(),
                Arc::clone(Self::Read::get_info_from(stor)),
            ),
            write: (
                Self::Write::key(),
                Arc::clone(Self::Write::get_info_from(stor)),
            ),
            res_read: (
                Self::ResRead::key(),
                Arc::clone(Self::ResRead::get_info_from(stor)),
            ),
            res_write: (
                Self::ResWrite::key(),
                Arc::clone(Self::ResWrite::get_info_from(stor)),
            ),
            ent_write: (
                Self::EntWrite::key(),
                Arc::clone(Self::EntWrite::get_info_from(stor)),
            ),
        }
    }
}

/// Blanket implementation of [`Request`] for tuples of queries.
impl<R, W, RR, RW, EW> Request for (R, W, RR, RW, EW)
where
    R: Query,
    W: QueryMut,
    RR: ResQuery,
    RW: ResQueryMut,
    EW: EntQueryMut,
{
    type Read = R;
    type Write = W;
    type ResRead = RR;
    type ResWrite = RW;
    type EntWrite = EW;
}

pub trait StoreRequestInfo: StoreQueryInfo + StoreResQueryInfo + StoreEntQueryInfo {
    fn contains(&self, key: &RequestKey) -> bool;
    fn get(&self, key: &RequestKey) -> Option<&Arc<RequestInfo>>;
    fn insert(&mut self, key: RequestKey, info: Arc<RequestInfo>);
    fn remove(&mut self, key: &RequestKey);
}

/// Unique identifier for a type implementing [`Request`].
pub type RequestKey = ATypeId<RequestKey_>;
pub struct RequestKey_;

#[derive(Clone)]
pub struct RequestInfo {
    read: (QueryKey, Arc<QueryInfo>),
    write: (QueryKey, Arc<QueryInfo>),
    res_read: (ResQueryKey, Arc<ResQueryInfo>),
    res_write: (ResQueryKey, Arc<ResQueryInfo>),
    ent_write: (EntQueryKey, Arc<EntQueryInfo>),
    name: &'static str,
}

impl fmt::Debug for RequestInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RequestInfo")
            .field("name", &self.name())
            .field("read", &self.read())
            .field("write", &self.write())
            .field("res_read", &self.res_read())
            .field("res_write", &self.res_write())
            .field("ent_write", &self.ent_write())
            .finish()
    }
}

impl RequestInfo {
    pub(crate) const fn read(&self) -> &(QueryKey, Arc<QueryInfo>) {
        &self.read
    }

    pub(crate) const fn write(&self) -> &(QueryKey, Arc<QueryInfo>) {
        &self.write
    }

    pub(crate) const fn res_read(&self) -> &(ResQueryKey, Arc<ResQueryInfo>) {
        &self.res_read
    }

    pub(crate) const fn res_write(&self) -> &(ResQueryKey, Arc<ResQueryInfo>) {
        &self.res_write
    }

    pub(crate) const fn ent_write(&self) -> &(EntQueryKey, Arc<EntQueryInfo>) {
        &self.ent_write
    }

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

    pub(crate) fn resource_keys(&self) -> impl Iterator<Item = &ResourceKey> {
        let read = self.res_read().1.as_ref();
        let write = self.res_write().1.as_ref();
        read.resource_keys().iter().chain(write.resource_keys())
    }

    pub(crate) fn filters(&self) -> &[(FilterKey, Arc<FilterInfo>)] {
        self.ent_write().1.as_ref().filters()
    }

    /// Determines whether the request info is valid or not in terms of `Read`, `Write`, `ResRead`,
    /// and `ResWrite`.
    ///
    /// Request info that meets conditions below is valid.
    /// - Write query selectors are disjoint against other selectors.
    /// - Write resource query doesn't overlap other read or write resource query.
    ///
    /// Note that request info cannot validate `EntWrite` itself. That must be validated outside.
    pub(crate) fn validate(&self) -> Result<(), String> {
        // 1. Write query contains disjoint selectors only?
        let (_, r_qinfo) = self.read();
        let (_, w_qinfo) = self.write();
        let r_sels = r_qinfo.selectors();
        let w_sels = w_qinfo.selectors();
        for i in 0..w_sels.len() {
            // Doesn't overlap other write?
            for j in i + 1..w_sels.len() {
                if !w_sels[i].1.is_disjoint(&w_sels[j].1) {
                    let reason = debug_format!(
                        "`{}` and `{}` are not disjoint in request `{}`",
                        w_sels[i].1.name(),
                        w_sels[j].1.name(),
                        self.name(),
                    );
                    return Err(reason);
                }
            }
            // Doesn't overlap read?
            for (_, r_sel) in r_sels.iter() {
                if !w_sels[i].1.is_disjoint(r_sel) {
                    let reason = debug_format!(
                        "`{}` and `{}` are not disjoint in request `{}`",
                        w_sels[i].1.name(),
                        r_sel.name(),
                        self.name(),
                    );
                    return Err(reason);
                }
            }
        }

        // 2. Write resource query doesn't overlap other resource queries?
        let (_, r_rqinfo) = self.res_read();
        let (_, w_rqinfo) = self.res_write();
        let r_keys = r_rqinfo.resource_keys();
        let w_keys = w_rqinfo.resource_keys();
        for i in 0..w_keys.len() {
            // Doesn't overlap other write?
            for j in i + 1..w_keys.len() {
                if w_keys[i] == w_keys[j] {
                    let reason = debug_format!(
                        "duplicate resource query `{:?}` in request `{}`",
                        w_keys[i],
                        self.name(),
                    );
                    return Err(reason);
                }
            }
            // Doesn't overlap read?
            for r_key in r_keys.iter() {
                if &w_keys[i] == r_key {
                    let reason = debug_format!(
                        "duplicate resource query `{:?}` in request `{}`",
                        w_keys[i],
                        self.name(),
                    );
                    return Err(reason);
                }
            }
        }

        Ok(())
    }
}

/// Empty request.
impl Request for () {
    type Read = ();
    type Write = ();
    type ResRead = ();
    type ResWrite = ();
    type EntWrite = ();
}

/// System buffer for its request.
///
/// System request, [`Request`], is composed of requests for read, write, resource read, resource
/// write, and entity write. They are actually pointers to the requesting data. Each request means,
/// - Read or write: Read or write requests for specific
///   [`Component`](crate::ecs::ent::component::Component)s.
/// - Resource read or write: Read or write requests for specific
///   [`Resource`](crate::ecs::resource::Resource)s.
/// - Entity write: Write requests for specific entity containers.
//
// Why buffer for system rather than request?
// Q. Systems may have the same request, so can they share the same buffer?
// A. Because of borrow check, we need system-individual buffer.
// - We check borrow status, so we need to borrow and release data everytime.
//   * Borrow check helps us avoid running into hidden data race during development.
#[derive(Debug)]
pub struct SystemBuffer {
    /// Buffer for read-only borrowed component arrays for the system's request.
    pub(crate) read: Box<[SelectedRaw]>,

    /// Buffer for writable borrowed component arrays for the system's request.
    pub(crate) write: Box<[SelectedRaw]>,

    /// Buffer for read-only borrowed resources for the system's request.
    pub(crate) res_read: Vec<Borrowed<ManagedConstPtr<u8>>>,

    /// Buffer for writable borrowed resources for the system's request.
    pub(crate) res_write: Vec<Borrowed<ManagedMutPtr<u8>>>,

    /// Buffer for writable borrowed entity container for the system's request.
    pub(crate) ent_write: Box<[FilteredRaw]>,
}

// We're going to send this buffer to other threads with a system implementation. So it's needed to
// be `Send` like `dyn Invoke + Send`. Obviously, it includes raw pointers, which are unsafe to be
// sent. But scheduler guarantees there will be no violation.
unsafe impl Send for SystemBuffer {}

impl SystemBuffer {
    pub(crate) fn new() -> Self {
        Self {
            read: [].into(),
            write: [].into(),
            res_read: Vec::new(),
            res_write: Vec::new(),
            ent_write: [].into(),
        }
    }

    pub(crate) fn clear(&mut self) {
        #[cfg(feature = "check")]
        self.clear_force();
    }

    pub(crate) fn clear_force(&mut self) {
        for read in self.read.iter_mut() {
            read.clear();
        }
        for write in self.write.iter_mut() {
            write.clear();
        }
        self.res_read.clear();
        self.res_write.clear();
        for ent_write in self.ent_write.iter_mut() {
            ent_write.clear();
        }
    }
}

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

/// A response corresponding to a [`Request`].
pub struct Response<'buf, Req> {
    buf: &'buf mut SystemBuffer,
    _marker: PhantomData<Req>,
}

impl<'buf, Req: Request> Response<'buf, Req> {
    pub(crate) fn new(buf: &'buf mut SystemBuffer) -> Self {
        Self {
            buf,
            _marker: PhantomData,
        }
    }

    pub fn all(&mut self) -> ResponseAll<'_, Req> {
        ResponseAll {
            read: <Req::Read as Query>::convert(&mut self.buf.read),
            write: <Req::Write as QueryMut>::convert(&mut self.buf.write),
            res_read: <Req::ResRead as ResQuery>::convert(&mut self.buf.res_read),
            res_write: <Req::ResWrite as ResQueryMut>::convert(&mut self.buf.res_write),
            ent_write: <Req::EntWrite as EntQueryMut>::convert(&mut self.buf.ent_write),
        }
    }

    pub fn read(&mut self) -> <Req::Read as Query>::Output<'_> {
        <Req::Read as Query>::convert(&mut self.buf.read)
    }

    pub fn write(&mut self) -> <Req::Write as QueryMut>::Output<'_> {
        <Req::Write as QueryMut>::convert(&mut self.buf.write)
    }

    pub fn res_read(&mut self) -> <Req::ResRead as ResQuery>::Output<'_> {
        <Req::ResRead as ResQuery>::convert(&mut self.buf.res_read)
    }

    pub fn res_write(&mut self) -> <Req::ResWrite as ResQueryMut>::Output<'_> {
        <Req::ResWrite as ResQueryMut>::convert(&mut self.buf.res_write)
    }

    pub fn ent_write(&mut self) -> <Req::EntWrite as EntQueryMut>::Output<'_> {
        <Req::EntWrite as EntQueryMut>::convert(&mut self.buf.ent_write)
    }
}

impl<Req> Drop for Response<'_, Req> {
    fn drop(&mut self) {
        self.buf.clear();
    }
}

pub struct ResponseAll<'a, Req: Request> {
    pub read: <Req::Read as Query>::Output<'a>,
    pub write: <Req::Write as QueryMut>::Output<'a>,
    pub res_read: <Req::ResRead as ResQuery>::Output<'a>,
    pub res_write: <Req::ResWrite as ResQueryMut>::Output<'a>,
    pub ent_write: <Req::EntWrite as EntQueryMut>::Output<'a>,
}