async_serialization/
lib.rs

1//! Traits for types that can be asynchronously serialized into AsyncWrites and deserialized from
2//! AsyncReads. Unlike serde's approach, the serialized data does not need to be in memory at once,
3//! and it saves a step of copying.
4#![deny(missing_docs)]
5
6#![deprecated="This was a failed attempt at finding a suitable abstraction. The async-codec crate might be what you need instead."]
7
8extern crate futures_core;
9extern crate futures_io;
10
11use std::error::Error;
12use std::fmt::{self, Display, Formatter};
13
14use futures_core::Future;
15use futures_io::{AsyncRead, AsyncWrite, Error as FutIoErr};
16
17/// Base trait for futures that write things into `AsyncWrite`s.
18///
19/// The future must yield a previously wrapped `AsyncWrite`, and the number of written bytes.
20/// If there's an error upon writing, the wrapped `AsyncWrite` is emitted together with the error.
21pub trait AsyncWriterFuture<W: AsyncWrite>
22    : Future<Item = (W, usize), Error = (W, FutIoErr)> {
23    /// Return how many bytes have already been written.
24    fn already_written(&self) -> usize;
25}
26
27/// Base trait for futures that write things into `AsyncWrite`s and can precompute the exact number
28/// of bytes to write.
29pub trait AsyncWriterFutureLen<W: AsyncWrite>: AsyncWriterFuture<W> {
30    /// Compute the exact number of bytes that will still be written by this future.
31    fn remaining_bytes(&self) -> usize;
32}
33
34/// A future that asynchronously serializes something into a wrapped AsyncWrite and then returns
35/// the wrapped AsyncWrite and how many bytes were written.
36pub trait AsyncSerialize<W: AsyncWrite>: AsyncWriterFuture<W> {
37    /// The type of values serialized.
38    type Serialized;
39
40    /// Create a new instance, consuming the value to serialize and wrapping the `AsyncWrite` to
41    /// serialize into.
42    fn from_val(writer: W, val: Self::Serialized) -> Self;
43}
44
45/// An `AsyncSerialize` that can precompute the exact number of bytes to write.
46pub trait AsyncSerializeLen<W: AsyncWrite>
47    : AsyncSerialize<W> + AsyncWriterFutureLen<W> {
48    /// Compute the exact number of bytes that would be written in total if the given value was
49    /// serialized.
50    fn total_bytes(val: &Self::Serialized) -> usize;
51}
52
53/// A future that asynchronously serializes something by reference into a wrapped AsyncWrite.
54pub trait AsyncSerializeRef<'val, W: AsyncWrite>: AsyncWriterFuture<W> {
55    /// The type of values serialized.
56    type Serialized;
57
58    /// Create a new instance, taking a reference to the value to serialize and wrapping the
59    /// `AsyncWrite` to serialize into.
60    fn from_ref(writer: W, val: &'val Self::Serialized) -> Self;
61}
62
63/// An `AsyncSerializeRef` that can precompute the exact number of bytes to write.
64pub trait AsyncSerializeRefLen<'val, W: AsyncWrite>
65    : AsyncSerializeRef<'val, W> + AsyncWriterFutureLen<W> {
66    /// Compute the exact number of bytes that would be written in total if the given value was
67    /// serialized.
68    fn total_bytes(val: &Self::Serialized) -> usize;
69}
70
71/// A future that asynchronously serializes something from a wrapped AsyncRead and then returns
72/// the wrapped AsyncRead, the deserialized value, and how many bytes were read.
73pub trait AsyncDeserialize<R: AsyncRead, S, E>
74    : Future<Item = (R, S, usize), Error = (R, DeserializeError<E>)> {
75    /// Consume a reader to create an `AsyncDeserialize`.
76    fn from_reader(reader: R) -> Self;
77
78    /// Return how many bytes have already been read.
79    fn already_read(&self) -> usize;
80}
81
82/// An error that occured during deserialization.
83#[derive(Debug)]
84pub enum DeserializeError<E> {
85    /// An error propagated from the underlying reader.
86    ReaderError(FutIoErr),
87    /// An error describing why the read data could not be deserialized into a value.
88    DataError(E),
89}
90
91impl<E: Display> Display for DeserializeError<E> {
92    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
93        match *self {
94            DeserializeError::ReaderError(ref err) => {
95                write!(f, "Deserialize reader error: {}", err)
96            }
97            DeserializeError::DataError(ref err) => write!(f, "Deserialize data error: {}", err),
98        }
99    }
100}
101
102impl<E: Error> Error for DeserializeError<E> {
103    fn description(&self) -> &str {
104        match *self {
105            DeserializeError::ReaderError(ref err) => err.description(),
106            DeserializeError::DataError(ref err) => err.description(),
107        }
108    }
109
110    fn cause(&self) -> Option<&Error> {
111        match *self {
112            DeserializeError::ReaderError(ref err) => Some(err),
113            DeserializeError::DataError(ref err) => Some(err),
114        }
115    }
116}
117
118impl<E> From<FutIoErr> for DeserializeError<E> {
119    fn from(err: FutIoErr) -> DeserializeError<E> {
120        DeserializeError::ReaderError(err)
121    }
122}