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
use crate::body::Body;
use std::convert::TryFrom;
use thiserror::Error;
#[derive(Debug, PartialEq, Clone)]
pub struct Trailer {
key: String,
value: String,
}
impl Trailer {
#[must_use]
pub fn new(key: &str, value: &str) -> Trailer {
Trailer {
key: String::from(key),
value: String::from(value),
}
}
}
impl From<Trailer> for String {
fn from(trailer: Trailer) -> Self {
format!("{}: {}", trailer.key, trailer.value)
}
}
impl TryFrom<Body> for Trailer {
type Error = Error;
fn try_from(body: Body) -> Result<Self, Self::Error> {
let body_value = String::from(body.clone());
let value_and_key: Vec<&str> = body_value.split(": ").collect();
let key = value_and_key
.get(0)
.ok_or_else(|| Error::NotATrailer(body.clone()))?;
let value = value_and_key.get(1).ok_or(Error::NotATrailer(body))?;
Ok(Trailer::new(key, value))
}
}
#[derive(Error, Debug)]
pub enum Error {
#[error("no colon in body line, {0} is not a trailer")]
NotATrailer(Body),
}
#[cfg(test)]
mod tests {
use super::Trailer;
use crate::body::Body;
use pretty_assertions::assert_eq;
use std::convert::TryFrom;
#[test]
fn it_can_give_me_itself_as_a_string() {
let trailer = Trailer::new("Relates-to", "#128");
assert_eq!(String::from(trailer), String::from("Relates-to: #128"))
}
#[test]
fn can_generate_itself_from_body() {
let trailer = Trailer::try_from(Body::from("Relates-to: #128"));
assert_eq!(
String::from(trailer.expect("Could not parse from string")),
String::from("Relates-to: #128")
)
}
}