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

use super::Id;
use std::hash::{Hash, Hasher};

#[derive(Debug)]
pub enum AnonymizableId<T> {
    Anonymized,
    Id(Id<T>),
}

impl<T> Clone for AnonymizableId<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for AnonymizableId<T> {}

impl<'de, T> Deserialize<'de> for AnonymizableId<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(Id::deserialize(deserializer).map_or(Self::Anonymized, Self::Id))
    }
}

impl<T> Eq for AnonymizableId<T> {}

impl<T> PartialEq for AnonymizableId<T> {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Anonymized, Self::Anonymized) => true,
            (Self::Id(id), Self::Id(other_id)) => id == other_id,
            (_, _) => false,
        }
    }
}

impl<T> Hash for AnonymizableId<T> {
    fn hash<U: Hasher>(&self, state: &mut U) {
        match self {
            Self::Anonymized => state.write_u64(0),
            Self::Id(id) => state.write_u64(id.value.get()),
        }
    }
}

impl<T> Serialize for AnonymizableId<T> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Anonymized => serializer.serialize_newtype_struct("AnonymizableId", "0"),
            Self::Id(id) => serializer.serialize_newtype_struct("AnonymizableId", &id.to_string()),
        }
    }
}