web_time/time/
serde.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
//! Serde serialization and de-serialization for `SystemTime`. It aims to be
//! compatible with Serde's implementation for [`std::time::SystemTime`].
//!
//! This implementation was copied from Serde's
//! [`Deserialize`](https://github.com/serde-rs/serde/blob/v1.0.215/serde/src/de/impls.rs#L2282-L2426),
//! and
//! [`Serialize`](https://github.com/serde-rs/serde/blob/v1.0.215/serde/src/ser/impls.rs#L753-L768)
//! implementation.

#![allow(warnings)]

// CHANGED: Replaced occurrences of `tri!` macro with `?`.

extern crate alloc;

use alloc::string::String;
use core::fmt;
use core::time::Duration;

use serde::de::{Error, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use super::SystemTime;

#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl<'de> Deserialize<'de> for SystemTime {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: Deserializer<'de>,
	{
		// Reuse duration
		enum Field {
			Secs,
			Nanos,
		}

		impl<'de> Deserialize<'de> for Field {
			fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
			where
				D: Deserializer<'de>,
			{
				struct FieldVisitor;

				impl<'de> Visitor<'de> for FieldVisitor {
					type Value = Field;

					fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
						formatter.write_str("`secs_since_epoch` or `nanos_since_epoch`")
					}

					fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
					where
						E: Error,
					{
						match value {
							"secs_since_epoch" => Ok(Field::Secs),
							"nanos_since_epoch" => Ok(Field::Nanos),
							_ => Err(Error::unknown_field(value, FIELDS)),
						}
					}

					fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E>
					where
						E: Error,
					{
						match value {
							b"secs_since_epoch" => Ok(Field::Secs),
							b"nanos_since_epoch" => Ok(Field::Nanos),
							_ => {
								let value = String::from_utf8_lossy(value);
								Err(Error::unknown_field(&value, FIELDS))
							}
						}
					}
				}

				deserializer.deserialize_identifier(FieldVisitor)
			}
		}

		fn check_overflow<E>(secs: u64, nanos: u32) -> Result<(), E>
		where
			E: Error,
		{
			static NANOS_PER_SEC: u32 = 1_000_000_000;
			match secs.checked_add((nanos / NANOS_PER_SEC) as u64) {
				Some(_) => Ok(()),
				None => Err(E::custom("overflow deserializing SystemTime epoch offset")),
			}
		}

		struct DurationVisitor;

		impl<'de> Visitor<'de> for DurationVisitor {
			type Value = Duration;

			fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
				formatter.write_str("struct SystemTime")
			}

			fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
			where
				A: SeqAccess<'de>,
			{
				let secs: u64 = match seq.next_element()? {
					Some(value) => value,
					None => {
						return Err(Error::invalid_length(0, &self));
					}
				};
				let nanos: u32 = match seq.next_element()? {
					Some(value) => value,
					None => {
						return Err(Error::invalid_length(1, &self));
					}
				};
				check_overflow(secs, nanos)?;
				Ok(Duration::new(secs, nanos))
			}

			fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
			where
				A: MapAccess<'de>,
			{
				let mut secs: Option<u64> = None;
				let mut nanos: Option<u32> = None;
				while let Some(key) = map.next_key()? {
					match key {
						Field::Secs => {
							if secs.is_some() {
								return Err(<A::Error as Error>::duplicate_field(
									"secs_since_epoch",
								));
							}
							secs = Some(map.next_value()?);
						}
						Field::Nanos => {
							if nanos.is_some() {
								return Err(<A::Error as Error>::duplicate_field(
									"nanos_since_epoch",
								));
							}
							nanos = Some(map.next_value()?);
						}
					}
				}
				let secs = match secs {
					Some(secs) => secs,
					None => return Err(<A::Error as Error>::missing_field("secs_since_epoch")),
				};
				let nanos = match nanos {
					Some(nanos) => nanos,
					None => return Err(<A::Error as Error>::missing_field("nanos_since_epoch")),
				};
				check_overflow(secs, nanos)?;
				Ok(Duration::new(secs, nanos))
			}
		}

		const FIELDS: &[&str] = &["secs_since_epoch", "nanos_since_epoch"];
		let duration = deserializer.deserialize_struct("SystemTime", FIELDS, DurationVisitor)?;
		// CHANGED: Insert `Duration` directly.
		let ret = Ok(Self(duration));
		ret
	}
}

#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
impl Serialize for SystemTime {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: Serializer,
	{
		use serde::ser::SerializeStruct;
		// CHANGED: Take `Duration` directly.
		let duration_since_epoch = self.0;
		let mut state = serializer.serialize_struct("SystemTime", 2)?;
		state.serialize_field("secs_since_epoch", &duration_since_epoch.as_secs())?;
		state.serialize_field("nanos_since_epoch", &duration_since_epoch.subsec_nanos())?;
		state.end()
	}
}