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
use crate::Encodable;
use std::io::{Result as IoResult, Write};
pub struct Encoder<W> {
writer: W,
}
impl<W> std::fmt::Debug for Encoder<W> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Encoder").finish()
}
}
impl<W> Encoder<W>
where
W: Write,
{
pub fn new(writer: W) -> Self {
Self { writer }
}
pub fn into_inner(self) -> W {
self.writer
}
pub fn encode<M>(&mut self, msg: M) -> IoResult<()>
where
M: Encodable,
{
msg.encode(&mut self.writer)?;
self.writer.flush()
}
}
impl<W> Clone for Encoder<W>
where
W: Clone,
{
fn clone(&self) -> Self {
Self {
writer: self.writer.clone(),
}
}
}
impl<W> Write for Encoder<W>
where
W: Write,
{
fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
self.writer.write(buf)
}
fn flush(&mut self) -> IoResult<()> {
self.writer.flush()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::commands::join;
#[test]
fn encoder() {
let mut encoder = Encoder::new(vec![]);
encoder.encode(join("#museun")).unwrap();
encoder.encode(join("#shaken_bot")).unwrap();
let out = encoder.into_inner();
let s = std::str::from_utf8(&out).unwrap();
assert_eq!(s, "JOIN #museun\r\nJOIN #shaken_bot\r\n");
}
#[test]
fn encodable_builtin() {
fn check<T>(input: &T)
where
T: Encodable + AsRef<[u8]> + ?Sized,
{
let mut output = vec![];
let mut encoder = Encoder::new(&mut output);
encoder.encode(input).unwrap();
assert_eq!(output, input.as_ref());
}
let input = "hello world\r\n";
check(&input);
check(&input.to_string());
check(&input.as_bytes());
check(&input.as_bytes().to_vec());
}
}