summaryrefslogtreecommitdiffstats
path: root/vendor/chrono/src/naive/time/serde.rs
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-05-18 02:49:50 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-05-18 02:49:50 +0000
commit9835e2ae736235810b4ea1c162ca5e65c547e770 (patch)
tree3fcebf40ed70e581d776a8a4c65923e8ec20e026 /vendor/chrono/src/naive/time/serde.rs
parentReleasing progress-linux version 1.70.0+dfsg2-1~progress7.99u1. (diff)
downloadrustc-9835e2ae736235810b4ea1c162ca5e65c547e770.tar.xz
rustc-9835e2ae736235810b4ea1c162ca5e65c547e770.zip
Merging upstream version 1.71.1+dfsg1.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vendor/chrono/src/naive/time/serde.rs')
-rw-r--r--vendor/chrono/src/naive/time/serde.rs65
1 files changed, 65 insertions, 0 deletions
diff --git a/vendor/chrono/src/naive/time/serde.rs b/vendor/chrono/src/naive/time/serde.rs
new file mode 100644
index 000000000..c7394fb57
--- /dev/null
+++ b/vendor/chrono/src/naive/time/serde.rs
@@ -0,0 +1,65 @@
+#![cfg_attr(docsrs, doc(cfg(feature = "serde")))]
+
+use super::NaiveTime;
+use core::fmt;
+use serde::{de, ser};
+
+// TODO not very optimized for space (binary formats would want something better)
+// TODO round-trip for general leap seconds (not just those with second = 60)
+
+impl ser::Serialize for NaiveTime {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: ser::Serializer,
+ {
+ serializer.collect_str(&self)
+ }
+}
+
+struct NaiveTimeVisitor;
+
+impl<'de> de::Visitor<'de> for NaiveTimeVisitor {
+ type Value = NaiveTime;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("a formatted time string")
+ }
+
+ fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
+ where
+ E: de::Error,
+ {
+ value.parse().map_err(E::custom)
+ }
+}
+
+impl<'de> de::Deserialize<'de> for NaiveTime {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: de::Deserializer<'de>,
+ {
+ deserializer.deserialize_str(NaiveTimeVisitor)
+ }
+}
+
+#[test]
+fn test_serde_serialize() {
+ super::test_encodable_json(serde_json::to_string);
+}
+
+#[test]
+fn test_serde_deserialize() {
+ super::test_decodable_json(|input| serde_json::from_str(input));
+}
+
+#[test]
+fn test_serde_bincode() {
+ // Bincode is relevant to test separately from JSON because
+ // it is not self-describing.
+ use bincode::{deserialize, serialize};
+
+ let t = NaiveTime::from_hms_nano_opt(3, 5, 7, 98765432).unwrap();
+ let encoded = serialize(&t).unwrap();
+ let decoded: NaiveTime = deserialize(&encoded).unwrap();
+ assert_eq!(t, decoded);
+}