sync_guid/
serde_support.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5use std::fmt;
6
7use serde::{
8    de::{self, Deserialize, Deserializer, Visitor},
9    ser::{Serialize, Serializer},
10};
11
12use crate::Guid;
13
14struct GuidVisitor;
15impl Visitor<'_> for GuidVisitor {
16    type Value = Guid;
17    #[inline]
18    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
19        formatter.write_str("a sync guid")
20    }
21    #[inline]
22    fn visit_str<E: de::Error>(self, s: &str) -> Result<Self::Value, E> {
23        Ok(Guid::from_slice(s.as_ref()))
24    }
25}
26
27impl<'de> Deserialize<'de> for Guid {
28    #[inline]
29    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
30    where
31        D: Deserializer<'de>,
32    {
33        deserializer.deserialize_str(GuidVisitor)
34    }
35}
36
37impl Serialize for Guid {
38    #[inline]
39    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
40        serializer.serialize_str(self.as_str())
41    }
42}
43
44#[cfg(test)]
45mod test {
46    use super::*;
47    #[test]
48    fn test_ser_de() {
49        let guid = Guid::from("asdffdsa12344321");
50        assert_eq!(
51            serde_json::to_value(guid).unwrap(),
52            serde_json::json!("asdffdsa12344321")
53        );
54
55        let guid = Guid::from("");
56        assert_eq!(serde_json::to_value(guid).unwrap(), serde_json::json!(""));
57
58        let guid = Guid::from(&b"abcd43211234"[..]);
59        assert_eq!(
60            serde_json::to_value(guid).unwrap(),
61            serde_json::json!("abcd43211234")
62        );
63    }
64}