-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathassociated_type.rs
51 lines (44 loc) · 1.29 KB
/
associated_type.rs
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
// smoelius: Associated types are considered a legitimate reason to put a bound on a struct
// parameter. See:
// * https://github.com/rust-lang/rust-clippy/issues/1689
// * https://github.com/rust-lang/api-guidelines/issues/6
//
// This example is based in part on:
// https://docs.serde.rs/serde_json/#creating-json-by-serializing-data-structures
use serde::{de::DeserializeOwned, Deserialize, Serialize};
trait Serializable {
type Out: Clone + DeserializeOwned + Serialize + PartialEq + Eq;
fn serialize(&self) -> Self::Out;
}
impl<T> Serializable for T
where
T: Serialize,
{
type Out = String;
fn serialize(&self) -> Self::Out {
serde_json::to_string(self).unwrap()
}
}
#[test_fuzz::test_fuzz(generic_args = "Address", bounds = "T: Serializable")]
fn serializes_to<T>(x: &T, y: &T::Out) -> bool
where
T: Clone + DeserializeOwned + Serialize + Serializable,
{
&<T as Serializable>::serialize(x) == y
}
#[derive(Clone, Serialize, Deserialize)]
struct Address {
street: String,
city: String,
}
#[test]
fn test() {
let address = Address {
street: "10 Downing Street".to_owned(),
city: "London".to_owned(),
};
assert!(serializes_to(
&address,
&String::from("{\"street\":\"10 Downing Street\",\"city\":\"London\"}")
));
}