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
100
101
102
103
104
105
106
extern crate serde;
#[cfg(feature = "chrono")]
extern crate chrono;
#[cfg(feature = "chrono")]
use chrono::{DateTime, Utc};
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct Header {
pub version: u8,
pub width: u32,
pub height: u32,
#[cfg(feature = "chrono")]
#[serde(skip_serializing_if = "Option::is_none", with = "timestamp_format")]
pub timestamp: Option<DateTime<Utc>>,
#[cfg(not(feature = "chrono"))]
#[serde(skip_serializing_if = "Option::is_none")]
pub timestamp: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub duration: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub idle_time_limit: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub command: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
}
#[cfg(feature = "chrono")]
mod timestamp_format {
use chrono::{DateTime, NaiveDateTime, Utc};
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S>(date: &Option<DateTime<Utc>>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match date {
&Some(x) => serializer.serialize_i64(x.timestamp()),
&None => serializer.serialize_none(),
}
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<DateTime<Utc>>, D::Error>
where
D: Deserializer<'de>,
{
match <i64>::deserialize(deserializer) {
Ok(timestamp) => Ok(Some(DateTime::<Utc>::from_utc(
NaiveDateTime::from_timestamp(timestamp, 0),
Utc,
))),
_ => Ok(None),
}
}
}
#[cfg(test)]
mod tests {
use serde_json;
use super::Header;
#[test]
fn test_deserializes_with_optional_data() {
let data = r#"{"version":2, "width":80, "height":40, "timestamp": null}"#;
let h: Header = serde_json::from_str(data).unwrap();
assert_eq!(
h,
Header {
version: 2,
width: 80,
height: 40,
timestamp: None,
duration: None,
idle_time_limit: None,
command: None,
title: None,
}
);
}
#[test]
fn test_serializes_with_optional_data() {
let h = Header {
version: 2,
width: 42,
height: 100,
timestamp: None,
duration: None,
idle_time_limit: None,
command: None,
title: None,
};
let result = serde_json::to_string(&h).unwrap();
assert_eq!(result, r#"{"version":2,"width":42,"height":100}"#);
}
}