1 #[macro_use]
2 extern crate derive_builder;
3
4 use std::convert::TryFrom;
5 use std::net::{AddrParseError, IpAddr};
6 use std::str::FromStr;
7 use std::string::ToString;
8
9 #[derive(Debug, Clone, PartialEq)]
10 pub struct MyAddr(IpAddr);
11
12 impl From<IpAddr> for MyAddr {
from(v: IpAddr) -> Self13 fn from(v: IpAddr) -> Self {
14 MyAddr(v)
15 }
16 }
17
18 impl<'a> TryFrom<&'a str> for MyAddr {
19 type Error = AddrParseError;
20
try_from(v: &str) -> Result<Self, Self::Error>21 fn try_from(v: &str) -> Result<Self, Self::Error> {
22 Ok(MyAddr(v.parse()?))
23 }
24 }
25
26 #[derive(Debug, PartialEq, Builder)]
27 #[builder(try_setter, setter(into))]
28 struct Lorem {
29 pub source: MyAddr,
30 pub dest: MyAddr,
31 }
32
33 #[derive(Debug, PartialEq, Builder)]
34 #[builder(try_setter, setter(into, prefix = "set"))]
35 struct Ipsum {
36 pub source: MyAddr,
37 }
38
exact_helper() -> Result<Lorem, LoremBuilderError>39 fn exact_helper() -> Result<Lorem, LoremBuilderError> {
40 LoremBuilder::default()
41 .source(IpAddr::from_str("1.2.3.4").unwrap())
42 .dest(IpAddr::from_str("0.0.0.0").unwrap())
43 .build()
44 }
45
try_helper() -> Result<Lorem, LoremBuilderError>46 fn try_helper() -> Result<Lorem, LoremBuilderError> {
47 LoremBuilder::default()
48 .try_source("1.2.3.4")
49 .map_err(|e| e.to_string())?
50 .try_dest("0.0.0.0")
51 .map_err(|e| e.to_string())?
52 .build()
53 }
54
55 #[test]
infallible_set()56 fn infallible_set() {
57 let _ = LoremBuilder::default()
58 .source(IpAddr::from_str("1.2.3.4").unwrap())
59 .dest(IpAddr::from_str("0.0.0.0").unwrap())
60 .build();
61 }
62
63 #[test]
fallible_set()64 fn fallible_set() {
65 let mut builder = LoremBuilder::default();
66 let try_result = builder.try_source("1.2.3.4");
67 let built = try_result
68 .expect("Passed well-formed address")
69 .dest(IpAddr::from_str("0.0.0.0").unwrap())
70 .build()
71 .unwrap();
72 assert_eq!(built, exact_helper().unwrap());
73 }
74
75 #[test]
with_helper()76 fn with_helper() {
77 assert_eq!(exact_helper().unwrap(), try_helper().unwrap());
78 }
79
80 #[test]
renamed()81 fn renamed() {
82 IpsumBuilder::default()
83 .try_set_source("0.0.0.0")
84 .unwrap()
85 .build()
86 .expect("All fields were provided");
87 }
88