tokio_fmt_encoder/
lib.rs

1//! Encode items that implement formatting traits like `Debug` and `Display`.
2//!
3//! To encode an item that implements `Debug`:
4//!
5//! ```
6//! extern crate bytes;
7//! extern crate tokio_fmt_encoder;
8//! extern crate tokio_io;
9//!
10//! fn main() {
11//!     use bytes::BytesMut;
12//!     use std::fmt::Formatter;
13//!     use tokio_fmt_encoder::DebugEncoder;
14//!     use tokio_io::codec::Encoder;
15//!
16//!     let to_encode = Some(10);
17//!     let mut buffer = BytesMut::with_capacity(64);
18//!     let mut encoder: DebugEncoder<Option<usize>> = Default::default();
19//!     encoder.encode(to_encode, &mut buffer).unwrap();
20//!     assert_eq!(&buffer.take(), &"Some(10)\n");
21//! }
22//! ```
23//!
24//! To encode an item that implements `Display`:
25//!
26//! ```
27//! extern crate bytes;
28//! extern crate tokio_fmt_encoder;
29//! extern crate tokio_io;
30//!
31//! fn main() {
32//!     use bytes::BytesMut;
33//!     use std::fmt::Formatter;
34//!     use tokio_fmt_encoder::DisplayEncoder;
35//!     use tokio_io::codec::Encoder;
36//!
37//!     let to_encode = String::from("hello");
38//!     let mut buffer = BytesMut::with_capacity(64);
39//!     let mut encoder: DisplayEncoder<String> = Default::default();
40//!     encoder.encode(to_encode, &mut buffer).unwrap();
41//!     assert_eq!(&buffer.take(), &"hello\n");
42//! }
43//! ```
44//!
45#![deny(warnings)]
46#![allow(deprecated)]
47extern crate bytes;
48extern crate tokio_io;
49
50use bytes::BytesMut;
51use std::fmt::{Debug, Display, Write};
52use std::marker::PhantomData;
53use tokio_io::codec::Encoder;
54
55
56#[derive(Debug)]
57pub enum Error {
58    Fmt(std::fmt::Error),
59    Io(std::io::Error),
60}
61
62impl From<std::io::Error> for Error {
63    fn from(e: std::io::Error) -> Self {
64        Error::Io(e)
65    }
66}
67
68/// Encode items that implement `Debug`, separated by newlines.
69pub struct DebugEncoder<I> {
70    _i: PhantomData<I>, // TODO can this be removed?
71}
72
73impl<I> Default for DebugEncoder<I> {
74    fn default() -> Self {
75        Self { _i: PhantomData }
76    }
77}
78
79impl<I: Debug> Encoder for DebugEncoder<I> {
80    type Item = I;
81    type Error = Error;
82
83    fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
84        writeln!(dst, "{:?}", item).map_err(Error::Fmt)
85    }
86}
87
88/// Encode items that implement `Display`, separated by newlines.
89pub struct DisplayEncoder<I> {
90    _i: PhantomData<I>, // TODO can this be removed?
91}
92
93impl<I> Default for DisplayEncoder<I> {
94    fn default() -> Self {
95        Self { _i: PhantomData }
96    }
97}
98
99impl<I: Display> Encoder for DisplayEncoder<I> {
100    type Item = I;
101    type Error = Error;
102
103    fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> {
104        writeln!(dst, "{}", item).map_err(Error::Fmt)
105    }
106}