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
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};

use crate::{UUID_SIZE, Uuid};

impl Serialize for Uuid {
    #[inline]
    fn serialize<SER: Serializer>(&self, ser: SER) -> Result<SER::Ok, SER::Error> {
        match ser.is_human_readable() {
            true => ser.serialize_str(&self.to_str()),
            false => {
                use serde::ser::SerializeTuple;

                let mut data = ser.serialize_tuple(UUID_SIZE)?;
                for byt in self.data.iter() {
                    data.serialize_element(byt)?;
                }
                data.end()
            }
        }
    }
}

struct StrVisitor;

impl<'de> serde::de::Visitor<'de> for StrVisitor {
    type Value = Uuid;

    #[inline(always)]
    fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
        formatter.write_str("a uuid string")
    }

    #[inline]
    fn visit_str<E: serde::de::Error>(self, input: &str) -> Result<Self::Value, E> {
        Uuid::parse_str(input).map_err(|err| serde::de::Error::custom(format_args!("Not a valid uuid: {}", err)))
    }

    #[inline]
    fn visit_bytes<E: serde::de::Error>(self, input: &[u8]) -> Result<Self::Value, E> {
        Uuid::parse_ascii_bytes(input).map_err(|err| serde::de::Error::custom(format_args!("Not a valid uuid: {}", err)))
    }
}

struct BytesVisitor;

impl<'de> serde::de::Visitor<'de> for BytesVisitor {
    type Value = Uuid;

    #[inline(always)]
    fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
        formatter.write_str("raw uuid bytes with size 16")
    }

    #[inline]
    fn visit_seq<S: serde::de::SeqAccess<'de>>(self, mut seq: S) -> Result<Self::Value, S::Error> {
        let bytes = [
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(0, &self)),
            },
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(1, &self)),
            },
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(2, &self)),
            },
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(3, &self)),
            },
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(4, &self)),
            },
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(5, &self)),
            },
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(6, &self)),
            },
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(7, &self)),
            },
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(8, &self)),
            },
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(9, &self)),
            },
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(10, &self)),
            },
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(11, &self)),
            },
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(12, &self)),
            },
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(13, &self)),
            },
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(14, &self)),
            },
            match seq.next_element()? {
                Some(val) => val,
                None => return Err(serde::de::Error::invalid_length(15, &self)),
            },
        ];

        Ok(Self::Value::from_bytes(bytes))
    }
}

impl<'de> Deserialize<'de> for Uuid {
    #[inline]
    fn deserialize<D: Deserializer<'de>>(des: D) -> Result<Self, D::Error> {
        match des.is_human_readable() {
            true => des.deserialize_str(StrVisitor),
            false => des.deserialize_tuple(UUID_SIZE, BytesVisitor),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::Uuid;

    use serde::de::Deserialize;
    use serde::de::value::{BorrowedStrDeserializer, SeqDeserializer, Error as ValueError};

    #[cfg(feature = "osrng")]
    #[test]
    fn serialize_and_deserialize() {
        let uuid = Uuid::v4();
        let uuid_str = uuid.to_str();
        let des = BorrowedStrDeserializer::<ValueError>::new(uuid_str.as_str());
        let res = Uuid::deserialize(des).expect("Unexpected fail");
        assert_eq!(res, uuid);
    }

    #[test]
    fn deserialize_str() {
        let uuid = Uuid::parse_str("60ecb7b6-ba34-5aad-a9ef-9020b1ea210a").unwrap();
        let des = BorrowedStrDeserializer::<ValueError>::new("60ecb7b6-ba34-5aad-a9ef-9020b1ea210a");
        let res = Uuid::deserialize(des).expect("Unexpected fail");
        assert_eq!(res, uuid);

        let uuid = Uuid::parse_str("60ecb7b6ba345aada9ef9020b1ea210a").unwrap();
        let des = BorrowedStrDeserializer::<ValueError>::new("60ecb7b6ba345aada9ef9020b1ea210a");
        let res = Uuid::deserialize(des).expect("Unexpected fail");
        assert_eq!(res, uuid);
    }

    #[test]
    fn deserialize_array_as_human_format() {
        let uuid = Uuid::parse_str("60ecb7b6-ba34-5aad-a9ef-9020b1ea210a").unwrap();
        let uuid_bytes = uuid.bytes();

        let des = SeqDeserializer::<_, ValueError>::new(uuid_bytes.iter().map(|byt| *byt));
        Uuid::deserialize(des).unwrap_err();
    }

    #[test]
    fn deserialize_array_bincode() {
        let uuid = Uuid::parse_str("60ecb7b6-ba34-5aad-a9ef-9020b1ea210a").unwrap();
        let serialized = bincode::serialize(&uuid).unwrap();

        let res: Uuid = bincode::deserialize(&serialized).expect("Unexpected fail");
        assert_eq!(res, uuid);
    }

    #[test]
    fn deserialize_bincode_invalid_len() {
        let bytes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
        bincode::deserialize::<Uuid>(&bytes).unwrap_err();
    }
}