npsd 0.2.0

Network payload serializer / deserializer framework
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
use std::borrow::Cow;

#[cfg(feature = "info")]
use std::collections::LinkedList;

#[cfg(feature = "sync")]
use crate::{FromPayload, IntoPayload, Middleware};

#[cfg(feature = "async")]
use crate::{AsyncFromPayload, AsyncIntoPayload, AsyncMiddleware};

#[cfg(feature = "crossbeam")]
use crate::Stack;

use crate::{AnyBox, Error};

/// A no-op implementation of the `Middleware` and `AsyncMiddleware` traits.
///
/// This implementation is used when no middleware processing is required. It simply forwards the
/// serialization and deserialization tasks to the respective methods of the value being processed,
/// and provides basic read/write operations to the underlying `Cow` buffer.
///
/// # Middleware Methods
/// - `fn into_payload<C, T: IntoPayload<C>>(
///       &mut self,
///       value: &T,
///       ctx: &mut C
///   ) -> Result<(), Error>`:
///     - Converts a value into a payload of bytes. This method forwards the serialization task to
///       the `into_payload` method of the value being processed.
/// - `fn from_payload<'a, C, T: FromPayload<'a, C>>(
///       &mut self,
///       ctx: &mut C
///   ) -> Result<T, Error>`:
///     - Converts a payload of bytes back into a value. This method forwards the deserialization task
///       to the `from_payload` method of the type being processed.
/// - `fn write<T>(&mut self, data: &[T]) -> Result<(), Error>`:
///     - Writes data to the underlying buffer.
/// - `fn read<'a, T>(&mut self, nbytes: usize) -> Result<&'a [T], Error>`:
///     - Reads data from the underlying buffer.
/// - `fn read_mut<'a, T>(&mut self, nbytes: usize) -> Result<&'a mut [T], Error>`:
///     - Reads data from the underlying buffer as mut.
/// - `fn push<T: AnyBox<'a>>(&mut self, value: Box<T>) -> Result<&'a T, Error>`:
///     - Pushes a value onto the stack.
/// - `fn push_mut<T: AnyBox<'a>>(&mut self, value: Box<T>) -> Result<&'a mut T, Error>`:
///     - Pushes a mutable value onto the stack.
/// - `fn push_array<T: AnyBox<'a>>(&mut self, values: Box<[T]>) -> Result<&'a [T], Error>`:
///     - Pushes an array of values onto the stack.
/// - `fn push_array_mut<T: AnyBox<'a>>(&mut self, values: Box<[T]>) -> Result<&'a mut [T], Error>`:
///     - Pushes a mutable array of values onto the stack.
#[cfg(feature = "sync")]
impl<'a> Middleware<'a> for Next<'a> {
    #[inline(always)]
    fn into_payload<C, T: IntoPayload<C>>(&mut self, value: &T, ctx: &mut C) -> Result<(), Error> {   
        value.into_payload(ctx, self)
    }

    #[inline(always)]
    fn from_payload<C, T: FromPayload<'a, C>>(&mut self, ctx: &mut C) -> Result<T, Error> {
        T::from_payload(ctx, self)
    }

    #[inline(always)]
    fn write<T>(&mut self, data: &[T]) -> Result<(), Error> {
        self.buf.write(data)
    }

    #[inline(always)]
    fn read<T>(&mut self, nbytes: usize) -> Result<&'a [T], Error> {
        self.buf.read(nbytes)
    }

    #[inline(always)]
    fn read_mut<T>(&mut self, nbytes: usize) -> Result<&'a mut [T], Error> {
        self.buf.read_mut(nbytes)
    }

    #[cfg(feature = "crossbeam")]
    #[inline(always)]
    fn push<T: AnyBox<'a>>(&mut self, value: Box<T>) -> Result<&'a T, Error> {
        Ok(self.stack.push(value))
    }

    #[cfg(feature = "crossbeam")]
    #[inline(always)]
    fn push_mut<T: AnyBox<'a>>(&mut self, value: Box<T>) -> Result<&'a mut T, Error> {
        Ok(self.stack.push_mut(value))
    }

    #[cfg(feature = "crossbeam")]
    #[inline(always)]
    fn push_array<T: AnyBox<'a>>(&mut self, values: Box<[T]>) -> Result<&'a [T], Error> {
        Ok(self.stack.push_array(values))
    }

    #[cfg(feature = "crossbeam")]
    #[inline(always)]
    fn push_array_mut<T: AnyBox<'a>>(&mut self, values: Box<[T]>) -> Result<&'a mut [T], Error> {
        Ok(self.stack.push_array_mut(values))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    fn push<T: AnyBox<'a>>(&mut self, _value: Box<T>) -> Result<&'a T, Error> {
        Err(Error::Stack("References disabled".to_string()))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    fn push_mut<T: AnyBox<'a>>(&mut self, _value: Box<T>) -> Result<&'a mut T, Error> {
        Err(Error::Stack("References disabled".to_string()))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    fn push_array<T: AnyBox<'a>>(&mut self, _values: Box<[T]>) -> Result<&'a [T], Error> {
        Err(Error::Stack("References disabled".to_string()))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    fn push_array_mut<T: AnyBox<'a>>(&mut self, _values: Box<[T]>) -> Result<&'a mut [T], Error> {
        Err(Error::Stack("References disabled".to_string()))
    }
}

/// # AsyncMiddleware Methods
/// - `fn poll_into_payload<C, T: AsyncIntoPayload<C>>(
///       &mut self,
///       value: &T,
///       ctx: &mut C
///   ) -> impl Future<Output = Result<(), Error>>`:
///     - Asynchronously converts a value into a payload of bytes. This method forwards the serialization
///       task to the `poll_into_payload` method of the value being processed.
/// - `fn poll_from_payload<'a, C, T: AsyncFromPayload<'a, C>>(
///       &mut self,
///       ctx: &mut C
///   ) -> impl Future<Output = Result<T, Error>>`:
///     - Asynchronously converts a payload of bytes back into a value. This method forwards the deserialization
///       task to the `poll_from_payload` method of the type being processed.
/// - `async fn poll_write<T>(&mut self, data: &[T]) -> Result<(), Error>`:
///     - Asynchronously writes data to the underlying buffer.
/// - `async fn poll_read<T: 'a>(&mut self, nbytes: usize) -> Result<&'a [T], Error>`:
///     - Asynchronously reads data from the underlying buffer.
/// - `async fn poll_read_mut<T: 'a>(&mut self, nbytes: usize) -> Result<&'a mut [T], Error>`:
///     - Asynchronously reads data from the underlying buffer as mut.
/// - `async fn poll_push<T: AnyBox<'a>>(&mut self, value: Box<T>) -> Result<&'a T, Error>`:
///     - Asynchronously pushes a value onto the stack.
/// - `async fn poll_push_mut<T: AnyBox<'a>>(&mut self, value: Box<T>) -> Result<&'a mut T, Error>`:
///     - Asynchronously pushes a mutable value onto the stack.
/// - `async fn poll_push_array<T: AnyBox<'a>>(&mut self, values: Box<[T]>) -> Result<&'a [T], Error>`:
///     - Asynchronously pushes an array of values onto the stack.
/// - `async fn poll_push_array_mut<T: AnyBox<'a>>(&mut self, values: Box<[T]>) -> Result<&'a mut [T], Error>`:
///     - Asynchronously pushes a mutable array of values onto the stack.
#[cfg(feature = "async")]
impl<'a> AsyncMiddleware<'a> for Next<'a> {
    #[inline(always)]
    fn poll_into_payload<C: Send + Sync, T: AsyncIntoPayload<C>>(
        &mut self,
        value: &T,
        ctx: &mut C
    ) -> impl core::future::Future<Output = Result<(), Error>> {
        value.poll_into_payload(ctx, self)
    }
    
    #[inline(always)]
    fn poll_from_payload<C: Send + Sync, T: AsyncFromPayload<'a, C>> (
        &mut self,
        ctx: &mut C,
    ) -> impl core::future::Future<Output = Result<T, Error>> {
        T::poll_from_payload(ctx, self)
    }

    #[inline(always)]
    async fn poll_write<T>(&mut self, data: &[T]) -> Result<(), Error> {
        self.buf.write(data)
    }

    #[inline(always)]
    async fn poll_read<T: 'a>(&mut self, nbytes: usize) -> Result<&'a [T], Error> {
        self.buf.read(nbytes)
    }

    #[inline(always)]
    async fn poll_read_mut<T: 'a>(&mut self, nbytes: usize) -> Result<&'a mut [T], Error> {
        self.buf.read_mut(nbytes)
    }

    #[cfg(feature = "crossbeam")]
    #[inline(always)]
    async fn poll_push<T: AnyBox<'a>>(&mut self, value: Box<T>) -> Result<&'a T, Error> {
        Ok(self.stack.push(value))
    }

    #[cfg(feature = "crossbeam")]
    #[inline(always)]
    async fn poll_push_mut<T: AnyBox<'a>>(&mut self, value: Box<T>) -> Result<&'a mut T, Error> {
        Ok(self.stack.push_mut(value))
    }

    #[cfg(feature = "crossbeam")]
    #[inline(always)]
    async fn poll_push_array<T: AnyBox<'a>>(&mut self, values: Box<[T]>) -> Result<&'a [T], Error> {
        Ok(self.stack.push_array(values))
    }

    #[cfg(feature = "crossbeam")]
    #[inline(always)]
    async fn poll_push_array_mut<T: AnyBox<'a>>(&mut self, values: Box<[T]>) -> Result<&'a mut [T], Error> {
        Ok(self.stack.push_array_mut(values))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    async fn poll_push<T: AnyBox<'a>>(&mut self, _value: Box<T>) -> Result<&'a T, Error> {
        Err(Error::Stack("References disabled".to_string()))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    async fn poll_push_mut<T: AnyBox<'a>>(&mut self, _value: Box<T>) -> Result<&'a mut T, Error> {
        Err(Error::Stack("References disabled".to_string()))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    async fn poll_push_array<T: AnyBox<'a>>(&mut self, _values: Box<[T]>) -> Result<&'a [T], Error> {
        Err(Error::Stack("References disabled".to_string()))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    async fn poll_push_array_mut<T: AnyBox<'a>>(&mut self, _values: Box<[T]>) -> Result<&'a mut [T], Error> {
        Err(Error::Stack("References disabled".to_string()))
    }
}

/// # Trait Implementations
/// ## CowRw
/// Provides basic read and write operations for `Cow<'_, [u8]>`:
/// - `fn write<T>(&mut self, data: &[T]) -> Result<(), Error>`:
///     - Writes data to the underlying `Cow` buffer, ensuring the size of `T` is 1 byte.
/// - `fn read<'a, T>(&mut self, nbytes: usize) -> Result<&'a [T], Error>`:
///     - Reads data from the underlying `Cow` buffer, ensuring the size of `T` is 1 byte.
/// - `fn read_mut<'a, T>(&mut self, nbytes: usize) -> Result<&'a mut [T], Error>`:
///     - Reads data as mut from the underlying `Cow` buffer, ensuring the size of `T` is 1 byte.
pub trait CowRw {
    fn write<T>(&mut self, data: &[T]) -> Result<(), Error>;
    fn read<'a, 'b, T>(&'b mut self, nbytes: usize) -> Result<&'a [T], Error>;
    fn read_mut<'a, 'b, T>(&'b mut self, nbytes: usize) -> Result<&'a mut [T], Error>;
}

impl CowRw for (Cow<'_, [u8]>, usize) {
    fn write<T>(&mut self, data: &[T]) -> Result<(), Error> {
        debug_assert_eq!(::std::mem::size_of::<T>(), 1, "Size of T must be 1 byte");
    
        let slice = unsafe {
            ::std::slice::from_raw_parts(
                data.as_ptr() as *const u8,
                data.len() * ::std::mem::size_of::<T>(),
            )
        };
        
        self.0.to_mut().extend_from_slice(slice);
    
        Ok(())
    }

    fn read<'a, T>(&mut self, nbytes: usize) -> Result<&'a [T], Error> {
        debug_assert_eq!(::std::mem::size_of::<T>(), 1, "Size of T must be 1 byte");

        if self.0.len() < self.1 + nbytes {
            return Err(Error::InvalidLength { expected: nbytes, found: self.0.len() - self.1 });
        }

        let slice = &self.0[self.1..self.1 + nbytes];
        self.1 += nbytes;

        let len = slice.len() / ::std::mem::size_of::<T>();
    
        Ok(unsafe {
            ::std::slice::from_raw_parts(slice.as_ptr() as *const T, len)
        })
    }

    fn read_mut<'a, T>(&mut self, nbytes: usize) -> Result<&'a mut [T], Error> {
        debug_assert_eq!(::std::mem::size_of::<T>(), 1, "Size of T must be 1 byte");

        if self.0.len() < self.1 + nbytes {
            return Err(Error::InvalidLength { expected: nbytes, found: self.0.len() - self.1 });
        }

        let slice = &mut self.0.to_mut()[self.1..self.1 + nbytes];
        self.1 += nbytes;

        let len = slice.len() / ::std::mem::size_of::<T>();
    
        Ok(unsafe {
            ::std::slice::from_raw_parts_mut(slice.as_ptr() as *mut T, len)
        })
    }
}

/// # Structs
/// ## Next<'a>
/// A wrapper around a `Cow<'a, [u8]>` buffer, providing methods for creating and managing the buffer:
/// - `pub fn from_mut(cow: &'a mut Cow<'_, [u8]>) -> Self`:
///     - Creates a new `Next` instance from a mutable reference to a `Cow` buffer.
/// - `pub fn with_mtu(mtu: usize) -> Self`:
///     - Creates a new `Next` instance with a buffer capacity specified by `mtu`.
/// - `impl<'a> Default for Next<'a>`:
///     - Provides a default implementation that creates a `Next` instance with an empty buffer.
/// - `impl<'a, T: Into<Cow<'a, [u8]>>> From<T> for Next<'a>`:
///     - Provides an implementation that creates a `Next` instance from a value that can be converted
///       into a `Cow` buffer.
/// - `pub fn serialized(&self) -> Vec<u8>`:
///     - Returns a vector containing the serialized data from the underlying buffer.
/// - `pub fn as_slice(&'a self) -> &'a [u8]`:
///     - Returns a slice of the underlying buffer.
#[derive(Clone, Debug)]
pub struct Next<'a>{
    buf: (Cow<'a, [u8]>, usize),

    #[cfg(feature = "crossbeam")]
    stack: Stack<'a>,
}

impl<'a> Next<'a> {
    pub fn from_mut(cow: &'a mut Cow<'_, [u8]>) -> Self {
        Self {
            buf: (Cow::Borrowed(&*cow), 0),
            #[cfg(feature = "crossbeam")]
            stack: Stack::new(),
        }
    }

    pub fn with_mtu(mtu: usize) -> Self {
        Self {
            buf: (Cow::from(Vec::with_capacity(mtu)), 0),
            #[cfg(feature = "crossbeam")]
            stack: Stack::new(),
        }
    }

    #[inline(always)]
    pub fn serialized(&self) -> Vec<u8> {
        self.buf.0.to_vec()
    }

    #[inline(always)]
    pub fn as_slice(&'a self) -> &'a [u8] { 
        self.buf.0.as_ref()
    }
}

impl<'a> Default for Next<'a> {
    fn default() -> Self {
        Self {
            buf: (Cow::from(Vec::new()), 0),
            #[cfg(feature = "crossbeam")]
            stack: Stack::new(),
        }
    }
}

impl<'a, T: Into<Cow<'a, [u8]>>> From<T> for Next<'a> {
    fn from(value: T) -> Self {
        Self {
            buf: (value.into(), 0),
            #[cfg(feature = "crossbeam")]
            stack: Stack::new(),
        }
    }
}

/// The `NextTrace` struct provides middleware functionality for tracing and debugging serialization
/// and deserialization operations. It maintains a nested context to help identify and report errors
/// and their locations in the payload structure. Requires the `info` feature to be enabled.
#[cfg(feature = "info")]
#[derive(Clone, Debug)]
pub struct NextTrace<'a> {
    buf: (Cow<'a, [u8]>, usize), 
    depth: usize, 
    path: LinkedList<&'static str>,
    #[cfg(feature = "crossbeam")]
    stack: Stack<'a>
}

#[cfg(feature = "info")]
const MAX_NESTED_DEPTH: usize = 255;

#[cfg(feature = "info")]
impl<'a> NextTrace<'a> {
    pub fn from_mut(cow: &'a mut Cow<'_, [u8]>) -> Self {
        Self {
            buf: (Cow::Borrowed(&*cow), 0), 
            depth: MAX_NESTED_DEPTH, 
            path: LinkedList::new(),
            #[cfg(feature = "crossbeam")]
            stack: Stack::new(),
        }
    }

    pub fn with_mtu(mtu: usize) -> Self {
        Self {
            buf: (Cow::from(Vec::with_capacity(mtu)), 0), 
            depth: MAX_NESTED_DEPTH, 
            path: LinkedList::new(),
            #[cfg(feature = "crossbeam")]
            stack: Stack::new(),
        }
    }

    pub fn with_depth(depth: usize) -> Self {
        Self {
            buf: (Cow::from(Vec::new()), 0), 
            depth, 
            path: LinkedList::new(),
            #[cfg(feature = "crossbeam")]
            stack: Stack::new(),
        }
    }

    #[inline(always)]
    pub fn serialized(&self) -> Vec<u8> {
        self.buf.0.to_vec()
    }

    #[inline(always)]
    pub fn as_slice(&'a self) -> &'a [u8] { 
        self.buf.0.as_ref()
    }
}

#[cfg(feature = "info")]
impl<'a, T: Into<Cow<'a, [u8]>>> From<T> for NextTrace<'a> {
    fn from(value: T) -> Self {
        Self {
            buf: (value.into(), 0), 
            depth: MAX_NESTED_DEPTH, 
            path: LinkedList::new(),
            #[cfg(feature = "crossbeam")]
            stack: Stack::new(),
        }
    }
}

#[cfg(feature = "info")]
impl<'a> Default for NextTrace<'a> {
    fn default() -> Self {
        Self {
            buf: (Cow::from(Vec::new()), 0), 
            depth: MAX_NESTED_DEPTH, 
            path: LinkedList::new(),
            #[cfg(feature = "crossbeam")]
            stack: Stack::new(),
        }
    }
}

#[cfg(feature = "info")]
#[cfg(feature = "sync")]
impl<'a> Middleware<'a> for NextTrace<'a> {
    #[inline(always)]
    fn into_payload<C, T: IntoPayload<C>>(&mut self, value: &T, ctx: &mut C) -> Result<(), Error> {
        if self.path.len() > self.depth {
            return Err(Error::NestedDepthLimit(T::TYPE.to_string()))
        }

        self.path.push_back(T::TYPE);
 
        let path: Vec<&str> = self.path.iter().cloned().collect();
        println!("{}", path.join(" -> "));

        match value.into_payload(ctx, self) {
            Ok(value) => {
                self.path.pop_back();

                Ok(value)
            },
            Err(error) => {
                match error {
                    Error::Traced(_, _) => Err(error),
                    _ => {
                        let path: Vec<&str> = self.path.iter().cloned().collect();
                        Err(Error::Traced(error.to_string(), path.join(" -> ")))
                    }
                }
            }
        }
    }

    #[inline(always)]
    fn from_payload<C, T: FromPayload<'a, C>>(&mut self, ctx: &mut C) -> Result<T, Error> {
        if self.path.len() > self.depth {
            return Err(Error::NestedDepthLimit(T::TYPE.to_string()))
        }

        self.path.push_back(T::TYPE);

        let path: Vec<&str> = self.path.iter().cloned().collect();
        println!("{}", path.join(" <- "));

        match T::from_payload(ctx, self) {
            Ok(value) => {
                self.path.pop_back();

                Ok(value)
            },
            Err(error) => {
                match error {
                    Error::Traced(_, _) => Err(error),
                    _ => {
                        let path: Vec<&str> = self.path.iter().cloned().collect();
                        Err(Error::Traced(error.to_string(), path.join(" <- ")))
                    }
                }
            }
        }
    }

    #[inline(always)]
    fn write<T>(&mut self, data: &[T]) -> Result<(), Error> {
        self.buf.write(data)
    }

    #[inline(always)]
    fn read<T>(&mut self, nbytes: usize) -> Result<&'a [T], Error> {
        self.buf.read(nbytes)
    }

    #[inline(always)]
    fn read_mut<T>(&mut self, nbytes: usize) -> Result<&'a mut [T], Error> {
        self.buf.read_mut(nbytes)
    }

    #[cfg(feature = "crossbeam")]
    fn push<T: AnyBox<'a>>(&mut self, value: Box<T>) -> Result<&'a T, Error> {
        Ok(self.stack.push(value))
    }

    #[cfg(feature = "crossbeam")]
    fn push_mut<T: AnyBox<'a>>(&mut self, value: Box<T>) -> Result<&'a mut T, Error> {
        Ok(self.stack.push_mut(value))
    }

    #[cfg(feature = "crossbeam")]
    fn push_array<T: AnyBox<'a>>(&mut self, values: Box<[T]>) -> Result<&'a [T], Error> {
        Ok(self.stack.push_array(values))
    }

    #[cfg(feature = "crossbeam")]
    fn push_array_mut<T: AnyBox<'a>>(&mut self, values: Box<[T]>) -> Result<&'a mut [T], Error> {
        Ok(self.stack.push_array_mut(values))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    fn push<T: AnyBox<'a>>(&mut self, _value: Box<T>) -> Result<&'a T, Error> {
        Err(Error::Stack("References disabled".to_string()))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    fn push_mut<T: AnyBox<'a>>(&mut self, _value: Box<T>) -> Result<&'a mut T, Error> {
        Err(Error::Stack("References disabled".to_string()))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    fn push_array<T: AnyBox<'a>>(&mut self, _values: Box<[T]>) -> Result<&'a [T], Error> {
        Err(Error::Stack("References disabled".to_string()))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    fn push_array_mut<T: AnyBox<'a>>(&mut self, _values: Box<[T]>) -> Result<&'a mut [T], Error> {
        Err(Error::Stack("References disabled".to_string()))
    }
}

#[cfg(feature = "info")]
#[cfg(feature = "async")]
impl<'a> AsyncMiddleware<'a> for NextTrace<'a> {
    async fn poll_into_payload<C: Send + Sync, T: AsyncIntoPayload<C>>(
        &mut self,
        value: &T,
        ctx: &mut C
    ) -> Result<(), Error> {
        if self.path.len() > self.depth {
            return Err(Error::NestedDepthLimit(T::TYPE.to_string()));
        }

        self.path.push_back(T::TYPE);

        let path: Vec<&str> = self.path.iter().cloned().collect();
        println!("{}", path.join(" -> "));

        match value.poll_into_payload(ctx, self).await {
            Ok(value) => {
                self.path.pop_back();
                Ok(value)
            }
            Err(error) => {
                match error {
                    Error::Traced(_, _) => Err(error),
                    _ => {
                        let path: Vec<&str> = self.path.iter().cloned().collect();
                        Err(Error::Traced(error.to_string(), path.join(" -> ")))
                    }
                }
            }
        }
    }

    async fn poll_from_payload<C: Send + Sync, T: AsyncFromPayload<'a, C> + Send + Sync> (
        &mut self, 
        ctx: &mut C,
    ) -> Result<T, Error> {
        if self.path.len() > self.depth {
            return Err(Error::NestedDepthLimit(T::TYPE.to_string()));
        }

        self.path.push_back(T::TYPE);

        let path: Vec<&str> = self.path.iter().cloned().collect();
        println!("{}", path.join(" <- "));

        match T::poll_from_payload(ctx, self).await {
            Ok(value) => {
                self.path.pop_back();
                Ok(value)
            }
            Err(error) => {
                match error {
                    Error::Traced(_, _) => Err(error),
                    _ => {
                        let path: Vec<&str> = self.path.iter().cloned().collect();
                        Err(Error::Traced(error.to_string(), path.join(" <- ")))
                    }
                }
            }
        }
    }

    #[inline(always)]
    async fn poll_write<T>(&mut self, data: &[T]) -> Result<(), Error> {
        self.buf.write(data)
    }

    #[inline(always)]
    async fn poll_read<T: 'a>(&mut self, nbytes: usize) -> Result<&'a [T], Error> {
        self.buf.read(nbytes)
    }

    #[inline(always)]
    async fn poll_read_mut<T: 'a>(&mut self, nbytes: usize) -> Result<&'a mut [T], Error> {
        self.buf.read_mut(nbytes)
    }

    #[cfg(feature = "crossbeam")]
    #[inline(always)]
    async fn poll_push<T: AnyBox<'a>>(&mut self, value: Box<T>) -> Result<&'a T, Error> {
        Ok(self.stack.push(value))
    }

    #[cfg(feature = "crossbeam")]
    #[inline(always)]
    async fn poll_push_mut<T: AnyBox<'a>>(&mut self, value: Box<T>) -> Result<&'a mut T, Error> {
        Ok(self.stack.push_mut(value))
    }

    #[cfg(feature = "crossbeam")]
    #[inline(always)]
    async fn poll_push_array<T: AnyBox<'a>>(&mut self, values: Box<[T]>) -> Result<&'a [T], Error> {
        Ok(self.stack.push_array(values))
    }

    #[cfg(feature = "crossbeam")]
    #[inline(always)]
    async fn poll_push_array_mut<T: AnyBox<'a>>(&mut self, values: Box<[T]>) -> Result<&'a mut [T], Error> {
        Ok(self.stack.push_array_mut(values))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    async fn poll_push<T: AnyBox<'a>>(&mut self, _value: Box<T>) -> Result<&'a T, Error> {
        Err(Error::Stack("References disabled".to_string()))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    async fn poll_push_mut<T: AnyBox<'a>>(&mut self, _value: Box<T>) -> Result<&'a mut T, Error> {
        Err(Error::Stack("References disabled".to_string()))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    async fn poll_push_array<T: AnyBox<'a>>(&mut self, _values: Box<[T]>) -> Result<&'a [T], Error> {
        Err(Error::Stack("References disabled".to_string()))
    }

    #[cfg(not(feature = "crossbeam"))]
    #[inline(always)]
    async fn poll_push_array_mut<T: AnyBox<'a>>(&mut self, _values: Box<[T]>) -> Result<&'a mut [T], Error> {
        Err(Error::Stack("References disabled".to_string()))
    }
}