-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathduration.rs
193 lines (175 loc) · 6.07 KB
/
duration.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
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
//! Serde support for `chrono::Duration` using the ISO 8601 duration format.
//!
//! **Note**: Years and months are not supported.
//!
//! ```
//! use chrono::Duration;
//! use serde::{Serialize, Deserialize};
//! use editoast_schemas::primitives::duration;
//!
//! #[derive(Serialize, Deserialize)]
//! struct MyStruct {
//! #[serde(with = "editoast_schemas::primitives::duration")] // <- Add this line
//! duration: Duration
//! }
//!
//! let s = r#"{"duration":"PT1H"}"#; // 1 hour
//! let my_struct: MyStruct = serde_json::from_str(s).unwrap();
//! assert_eq!(my_struct.duration.num_seconds(), 3600);
//! assert_eq!(r#"{"duration":"PT3600S"}"#, serde_json::to_string(&my_struct).unwrap());
//!
//! let err_s = r#"{"duration":"P1M"}"#; // 1 month
//! assert!(serde_json::from_str::<MyStruct>(err_s).is_err());
//! ```
use std::ops::Deref;
use std::str::FromStr;
use chrono::Duration as ChronoDuration;
use iso8601::Duration as IsoDuration;
use serde::Deserialize;
use serde::Serialize;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum PositiveDurationError {
#[error("Negative duration provided")]
NegativeDuration,
}
/// Wrapper for `chrono::Duration` to use with Serde.
/// This is useful to serialize `chrono::Duration` using the ISO 8601 duration format.
///
/// ```
/// use serde::{Serialize, Deserialize};
/// use editoast_schemas::primitives::PositiveDuration;
///
/// #[derive(Serialize, Deserialize)]
/// struct MyStruct {
/// duration: PositiveDuration
/// }
///
/// let s = r#"{"duration":"PT1H"}"#; // 1 hour
/// let my_struct: MyStruct = serde_json::from_str(s).unwrap();
/// assert_eq!(my_struct.duration.num_seconds(), 3600);
/// assert_eq!(r#"{"duration":"PT3600S"}"#, serde_json::to_string(&my_struct).unwrap());
///
/// let err_s = r#"{"duration":"P1M"}"#; // 1 month
/// assert!(serde_json::from_str::<MyStruct>(err_s).is_err());
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct PositiveDuration(ChronoDuration);
impl TryFrom<ChronoDuration> for PositiveDuration {
type Error = PositiveDurationError;
/// Create PositiveDuration from `chrono::Duration``
/// This function errors when the given duration is negative
/// The created PositiveDuration is limited to 1 millisecond
fn try_from(duration: ChronoDuration) -> Result<Self, PositiveDurationError> {
let milli_sec = duration.num_milliseconds();
if milli_sec < 0 {
return Err(PositiveDurationError::NegativeDuration);
}
Ok(PositiveDuration(ChronoDuration::milliseconds(milli_sec)))
}
}
impl From<PositiveDuration> for ChronoDuration {
fn from(duration: PositiveDuration) -> Self {
duration.0
}
}
impl Deref for PositiveDuration {
type Target = ChronoDuration;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Serialize for PositiveDuration {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serialize(&self.0, serializer)
}
}
impl<'de> Deserialize<'de> for PositiveDuration {
fn deserialize<D>(deserializer: D) -> Result<PositiveDuration, D::Error>
where
D: serde::Deserializer<'de>,
{
deserialize(deserializer).map(PositiveDuration)
}
}
/// Serialize a `chrono::Duration` using the ISO 8601 duration format.
pub fn serialize<S>(duration: &ChronoDuration, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(&duration.to_string())
}
/// Deserialize a `chrono::Duration` from an ISO 8601 duration string.
pub fn deserialize<'de, D>(deserializer: D) -> Result<ChronoDuration, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
let iso_dur = IsoDuration::from_str(&s).map_err(serde::de::Error::custom)?;
Ok(match iso_dur {
IsoDuration::YMDHMS {
year,
month,
day,
hour,
minute,
second,
millisecond,
} => {
if year != 0 || month != 0 {
return Err(serde::de::Error::custom(
"years and months are not supported",
));
}
ChronoDuration::try_days(day as i64)
.ok_or_else(|| serde::de::Error::custom("value for days is not valid"))?
+ ChronoDuration::try_hours(hour as i64)
.ok_or_else(|| serde::de::Error::custom("value for hours is not valid"))?
+ ChronoDuration::try_minutes(minute as i64)
.ok_or_else(|| serde::de::Error::custom("value for minutes is not valid"))?
+ ChronoDuration::try_seconds(second as i64)
.ok_or_else(|| serde::de::Error::custom("value for seconds is not valid"))?
+ ChronoDuration::try_milliseconds(millisecond as i64)
.ok_or_else(|| serde::de::Error::custom("value for millisecond is not valid"))?
}
IsoDuration::Weeks(weeks) => ChronoDuration::try_weeks(weeks as i64)
.ok_or_else(|| serde::de::Error::custom("value for weeks is not valid"))?,
})
}
#[cfg(test)]
mod tests {
use serde::Deserialize;
use serde::Serialize;
use serde_json::from_str;
use serde_json::to_string;
use super::PositiveDuration;
#[derive(Serialize, Deserialize)]
struct MyStruct {
duration: PositiveDuration,
}
/// Test the deserialization
#[test]
fn test_deserialize() {
let s = r#"{"duration":"PT1H"}"#; // 1 hour
let my_struct: MyStruct = from_str(s).unwrap();
assert_eq!(my_struct.duration.num_seconds(), 3600);
}
/// Test the serialization
#[test]
fn test_serialize() {
let s = r#"{"duration":"PT3600S"}"#; // 1 hour
let my_struct = MyStruct {
duration: chrono::Duration::hours(1).try_into().unwrap(),
};
assert_eq!(s, to_string(&my_struct).unwrap());
}
/// Test invalid deserialization
#[test]
fn test_invalid_deserialize() {
let s = r#"{"duration":"P1M"}"#; // 1 month
assert!(from_str::<MyStruct>(s).is_err());
}
}