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
use std::fmt;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};

use serde::{de, Deserialize, Deserializer, Serialize, Serializer};

impl Serialize for crate::raw::HaxeDate {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_i64(chrono::NaiveDateTime::from(*self).timestamp())
    }
}

impl<'de> Deserialize<'de> for crate::raw::HaxeDate {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let timestamp: i64 = Deserialize::deserialize(deserializer)?;
        crate::raw::HaxeDate::try_from_timestamp(timestamp).ok_or_else(|| {
            de::Error::invalid_value(de::Unexpected::Signed(timestamp), &"valid timestamp")
        })
    }
}

macro_rules! declare_markers {
    ($vis:vis enum $marker_enum:ident($marker_prefix:expr) {
        $(
            $(#[$adapter_meta:meta])*
            $marker_name:ident($adapter_vis:vis $adapter_name:ident($module:ident))
        ),* $(,)?
    }) => {
        #[derive(Debug, Copy, Clone, Eq, PartialEq)]
        $vis enum $marker_enum {
            $($marker_name,)*
            Unknown
        }

        impl $marker_enum {
            $vis fn parse(string: &str) -> Option<Self> {
                if !string.starts_with($marker_prefix) {
                    return None;
                }
                match &string[$marker_prefix.len()..] {
                    $(stringify!($marker_name) => Some(Self::$marker_name),)*
                    _ => Some(Self::Unknown)
                }
            }

            #[allow(clippy::wrong_self_convention)]
            $vis fn to_str(&self) -> &'static str {
                match *self {
                    $(Self::$marker_name => concat!($marker_prefix, stringify!($marker_name)),)*
                    Self::Unknown => concat!($marker_prefix, "unknown")
                }
            }
        }

        $(declare_markers!(
            @declare_adapter $(#[$adapter_meta])*
            $adapter_vis struct $adapter_name($module) => $marker_enum::$marker_name
        );)*

    };
    (@declare_adapter $(#[$meta:meta])* $vis:vis struct $adapter:ident($module:ident) => $marker:path) => {

        $(#[$meta])*
        $vis mod $module {
            #![allow(dead_code)]
            use super::$adapter;
            use serde::{ Serialize, Serializer, Deserialize, Deserializer };

            pub fn serialize<T: Serialize, S: Serializer>(value: &T, ser: S) -> Result<S::Ok, S::Error> {
                $adapter(value).serialize(ser)
            }

            pub fn deserialize<'de, T: Deserialize<'de>, D: Deserializer<'de>>(de: D) -> Result<T, D::Error> {
                let val: $adapter<T> = Deserialize::deserialize(de)?;
                Ok(val.0)
            }
        }

        $(#[$meta])*
        #[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
        #[repr(transparent)]
        $vis struct $adapter<T>($vis T);

        impl<T: fmt::Display> fmt::Display for $adapter<T> {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                self.0.fmt(f)
            }
        }

        impl<T> From<T> for $adapter<T> {
            fn from(inner: T) -> Self { Self(inner) }
        }

        impl<T> Deref for $adapter<T> {
            type Target = T;
            fn deref(&self) -> &T { &self.0 }
        }

        impl<T> DerefMut for $adapter<T> {
            fn deref_mut(&mut self) -> &mut T { &mut self.0 }
        }

        impl<T: Serialize> Serialize for $adapter<T> {
            fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
                ser.serialize_newtype_struct($marker.to_str(), &self.0)
            }
        }

        impl<'de, T: Deserialize<'de>> Deserialize<'de> for $adapter<T> {
            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                let vis = AdapterVisitor {
                    kind: $marker,
                    _marker: PhantomData::<T>,
                    _lifetime: PhantomData::<&'de ()>,
                };
                deserializer.deserialize_newtype_struct($marker.to_str(), vis)
                    .map($adapter)
            }
        }
    }
}

struct AdapterVisitor<'de, T> {
    kind: AdapterMarker,
    _marker: PhantomData<T>,
    _lifetime: PhantomData<&'de ()>,
}

impl<'de, T: Deserialize<'de>> de::Visitor<'de> for AdapterVisitor<'de, T> {
    type Value = T;
    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "adapter struct {:?}", self.kind)
    }

    fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<T, A::Error> {
        match seq.next_element()? {
            None => Err(<A::Error as de::Error>::invalid_length(0, &self)),
            Some(value) => Ok(value),
        }
    }

    fn visit_newtype_struct<D: Deserializer<'de>>(self, de: D) -> Result<T, D::Error> {
        T::deserialize(de)
    }
}

declare_markers! { pub(super) enum AdapterMarker("\0haxeformat::") {
    /// Forces Haxe `Date` representation.
    /// Accepts integers (as timestamps).
    Date(pub DateAdapter(date)),
    /// Forces Haxe `Array` representation (the default for sequences).
    /// Accepts sequences, tuples and tuple structs.
    Array(pub ArrayAdapter(array)),
    /// Forces Haxe `List` representation.
    /// Accepts sequences, tuples and tuple structs.
    List(pub ListAdapter(list)),
    /// Forces Haxe `struct` representation (the default for maps).
    /// Accepts only structs and maps, with string keys.
    Struct(pub StructAdapter(struct_obj)),
    /// Forces Haxe `StringMap` representation.
    /// Accepts only maps, with string keys.
    StringMap(pub StringMapAdapter(string)),
    /// Forces Haxe `IntMap` representation.
    /// Accepts only maps, with integer keys.
    IntMap(pub IntMapAdapter(int)),
    /// Forces Haxe `ObjectMap` representation.
    /// Accepts only maps, with arbitrary keys.
    ObjectMap(pub ObjectMapAdapter(object)),
    /// Forces Haxe `class` representation.
    /// Accepts only structs.
    Class(pub ClassAdapter(class)),
    /// Forces Haxe `Class<T>` representation.
    /// Accepts only strings.
    ClassDef(pub ClassDefAdapter(class_def)),
    /// Forces Haxe `Enum<T>` representation.
    /// Accepts only strings.
    EnumDef(pub EnumDefAdapter(enum_def)),
    // TODO: add serde support for CustomAdapter
    Custom(CustomAdapter(custom)),
    /// Forces Haxe `exception` representation (throws on deserialization).
    /// Accepts any value.
    Exception(pub ExceptionAdapter(exception)),
}}