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
use core::task::{Context, Poll};
use futures::AsyncWrite;
use crate::backend::{Format, FormatEncode};

/// Attempt to encode a data structure to an [asynchronous writer](AsyncWrite)
/// for a particular [format](FormatEncode).
pub trait Encode: Sized {
    /// The concrete [format](FormatEncode) to encode with.
    type Format: FormatEncode;
    
    /// The concrete data structure to encode.
    type Data;

    /// Initialize the internal state of the encoder.
    fn init(data: &Self::Data) -> Self;

    /// Begin encoding bytes for the indicated [format](FormatEncode) to the provided [writer](AsyncWrite).
    ///
    /// This is intended to be overriden whenever an optimized code path exists for the (usual) case where
    /// enough buffer space is available that the operation will succeed immediately without [pending](Poll).
    ///
    /// # Implementation
    /// Implementions must ensure that `start_encode` is semantically equivalent to calling
    /// `init` followed by `poll_encode`
    fn start_encode<W>(format: &Self::Format, writer: &mut W, data: &Self::Data, cx: &mut Context<'_>) -> Result<Option<Self>, <<Self as Encode>::Format as Format>::Error>
    where
        W: AsyncWrite + Unpin,
    ;

    /// Continue a [pending](Poll) [encode](FormatEncode) operation.
    fn poll_encode<W>(&mut self, format: &Self::Format, writer: &mut W, data: &Self::Data, cx: &mut Context<'_>) -> Poll<Result<(), <<Self as Encode>::Format as Format>::Error>>
    where
        W: AsyncWrite + Unpin,
    ;
}