use std::io;
use bytes::BytesMut;
use encoding::{DecoderTrap, EncoderTrap, EncodingRef};
use encoding::label::encoding_from_whatwg_label;
use tokio_io::codec::{Decoder, Encoder};
use error;
pub struct LineCodec {
encoding: EncodingRef,
}
impl LineCodec {
pub fn new(label: &str) -> error::Result<LineCodec> {
encoding_from_whatwg_label(label)
.map(|enc| LineCodec { encoding: enc })
.ok_or_else(|| io::Error::new(
io::ErrorKind::InvalidInput,
&format!("Attempted to use unknown codec {}.", label)[..],
).into())
}
}
impl Decoder for LineCodec {
type Item = String;
type Error = error::IrcError;
fn decode(&mut self, src: &mut BytesMut) -> error::Result<Option<String>> {
if let Some(n) = src.as_ref().iter().position(|b| *b == b'\n') {
let line = src.split_to(n + 1);
match self.encoding.decode(line.as_ref(), DecoderTrap::Replace) {
Ok(data) => Ok(Some(data)),
Err(data) => Err(
io::Error::new(
io::ErrorKind::InvalidInput,
&format!("Failed to decode {} as {}.", data, self.encoding.name())[..],
).into(),
),
}
} else {
Ok(None)
}
}
}
impl Encoder for LineCodec {
type Item = String;
type Error = error::IrcError;
fn encode(&mut self, msg: String, dst: &mut BytesMut) -> error::Result<()> {
let data: error::Result<Vec<u8>> = self.encoding
.encode(&msg, EncoderTrap::Replace)
.map_err(|data| {
io::Error::new(
io::ErrorKind::InvalidInput,
&format!("Failed to encode {} as {}.", data, self.encoding.name())[..],
).into()
});
dst.extend(&data?);
Ok(())
}
}