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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#[allow(unused_imports)]
#[macro_use]
extern crate destruct_derive;
#[allow(unused_imports)]
#[cfg(test)]
#[macro_use]
extern crate err_derive;
#[macro_use]
extern crate derive_new;

use std::marker::PhantomData;

pub trait Destruct: Sized {
    /// The destructed object type
    ///
    /// If your struct is:
    /// ```rust,no-run
    /// #[derive(Destruct)]
    /// struct YourStruct {
    ///     field: YourField,
    ///     field2: YourField2,
    /// }
    /// ```
    /// Then the DestructType is:
    ///
    /// DestructBegin<Fields, m>
    ///     where Fields = DestructField<YourField, NextField, m1>
    ///           NextField = DestructField<YourField2, End, m2>
    ///           End = DestructEnd<m>
    ///     where m is some generated type implementing `trait DestructMetadata`
    ///           m1 is the metadata for `field`, implementing `trait DestructFieldMetadata`
    ///           m2 is the metadata for `field2`, implementing `trait DestructFieldMetadata`
    /// }
    type DestructType: From<Self> + Into<Self>;

    /// Destruct self to destruct type
    fn destruct(self) -> Self::DestructType;

    /// Construct self from destruct type
    fn construct(d: Self::DestructType) -> Self;
}

pub trait DestructMetadata {
    fn struct_name() -> &'static str;
    fn named_fields() -> bool;
}

#[derive(new, Debug, PartialEq, Eq)]
pub struct DestructBegin<T, M: DestructMetadata + 'static> {
    pub fields: T,
    #[new(default)]
    meta: PhantomData<&'static M>,
}

pub trait DestructFieldMetadata: DestructMetadata + 'static {
    fn field_name() -> &'static str;
    fn field_index() -> usize;
}

impl<T, M: DestructMetadata + 'static> DestructBegin<T, M> {
    pub fn struct_name(&self) -> &'static str {
        M::struct_name()
    }
}

#[derive(new, Debug, PartialEq, Eq)]
pub struct DestructField<H, T, M: DestructFieldMetadata + 'static> {
    pub head: H,
    pub tail: T,
    #[new(default)]
    meta: PhantomData<&'static M>,
}

impl<H, T, M: DestructFieldMetadata + 'static> DestructField<H, T, M> {
    pub fn struct_name(&self) -> &'static str {
        M::struct_name()
    }
    pub fn field_name(&self) -> &'static str {
        M::field_name()
    }
    pub fn field_index(&self) -> usize {
        M::field_index()
    }
}

#[derive(new, Debug, PartialEq, Eq)]
pub struct DestructEnd<M: DestructMetadata + 'static> {
    #[new(default)]
    meta: PhantomData<&'static M>,
}

impl<M: DestructMetadata + 'static> DestructEnd<M> {
    pub fn struct_name(&self) -> &'static str {
        M::struct_name()
    }
}

pub trait DestructEnumMetadata {
    fn enum_name() -> &'static str;
}

#[derive(new, Debug, PartialEq, Eq)]
pub struct DestructEnumBegin<T, M: DestructEnumMetadata + 'static> {
    pub variants: T,
    #[new(default)]
    meta: PhantomData<&'static M>,
}

pub trait DestructEnumVariantMetadata: DestructEnumMetadata + 'static {
    fn variant_name() -> &'static str;
    fn variant_index() -> usize;
}

impl<T, M: DestructEnumMetadata + 'static> DestructEnumBegin<T, M> {
    pub fn enum_name() -> &'static str {
        M::enum_name()
    }
}

#[derive(new, Debug, PartialEq, Eq)]
pub enum DestructEnumVariant<H, T, M: DestructEnumVariantMetadata + 'static> {
    Head(H, #[new(default)] PhantomData<&'static M>),
    Tail(T, #[new(default)] PhantomData<&'static M>),
}

impl<H, T, M: DestructEnumVariantMetadata + 'static> DestructEnumVariant<H, T, M> {
    pub fn enum_name() -> &'static str {
        M::enum_name()
    }
    pub fn variant_name() -> &'static str {
        M::variant_name()
    }
    pub fn variant_index() -> usize {
        M::variant_index()
    }
}

#[derive(new, Debug, PartialEq, Eq)]
pub struct DestructEnumEnd<M: DestructEnumMetadata + 'static> {
    #[new(default)]
    meta: PhantomData<&'static M>,
}

impl<M: DestructEnumMetadata + 'static> DestructEnumEnd<M> {
    pub fn enum_name() -> &'static str {
        M::enum_name()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::ParseError::IOError;
    use std::io::Error;
    use std::io::Read;

    use crate as destruct;

    trait Parser: Sized {
        type Error;

        fn parse<R: Read>(r: &mut R) -> Result<Self, Self::Error>;
    }

    #[derive(Debug, Error)]
    pub enum ParseError {
        #[error(display = "io error: {:?}", 0)]
        IOError(std::io::Error),
    }

    impl From<std::io::Error> for ParseError {
        fn from(e: Error) -> Self {
            IOError(e)
        }
    }

    struct AA();

    /// Test for simple bincode
    impl Parser for u8 {
        type Error = ParseError;

        fn parse<R: Read>(r: &mut R) -> Result<Self, Self::Error> {
            let mut b = [0; 1];
            r.read_exact(&mut b)?;
            Ok(b[0])
        }
    }

    impl<M: DestructMetadata> Parser for DestructEnd<M> {
        type Error = ParseError;

        fn parse<R: Read>(_: &mut R) -> Result<Self, Self::Error> {
            Ok(DestructEnd::new())
        }
    }

    impl<
            H: Parser<Error = ParseError>,
            T: Parser<Error = ParseError>,
            M: DestructFieldMetadata,
        > Parser for DestructField<H, T, M>
    {
        type Error = ParseError;

        fn parse<R: Read>(r: &mut R) -> Result<Self, Self::Error> {
            Ok(DestructField::new(H::parse(r)?, T::parse(r)?))
        }
    }

    impl<Fields: Parser<Error = ParseError>, M: DestructMetadata> Parser for DestructBegin<Fields, M> {
        type Error = ParseError;

        fn parse<R: Read>(r: &mut R) -> Result<Self, Self::Error> {
            Ok(DestructBegin::new(Fields::parse(r)?))
        }
    }

    #[derive(Destruct, Clone, Debug, PartialEq, Eq)]
    struct A {
        first: u8,
        second: u8,
        third: u8,
    }

    #[derive(Destruct, Clone, Debug, PartialEq, Eq)]
    struct B(u8, u8);

    #[test]
    fn test_meta() {
        let a = A {
            first: b'a',
            second: b'b',
            third: b'c',
        };
        let d = a.destruct();
        let name = d.struct_name();
        assert_eq!(name, "A");
        let name = d.fields.field_name();
        assert_eq!(name, "first");
        let name = d.fields.tail.field_name();
        assert_eq!(name, "second");
        let name = d.fields.tail.tail.field_name();
        assert_eq!(name, "third");
    }

    #[test]
    fn test_parse_struct() {
        let mut src = b"abc" as &[u8];
        let a: A = <A as Destruct>::DestructType::parse(&mut src)
            .unwrap()
            .into();
        assert_eq!(
            a,
            A {
                first: b'a',
                second: b'b',
                third: b'c'
            }
        )
    }

    #[test]
    fn test_parse_unnamed_struct() {
        let mut src = b"ab" as &[u8];
        let b: B = <B as Destruct>::DestructType::parse(&mut src)
            .unwrap()
            .into();
        assert_eq!(b, B(b'a', b'b'))
    }

    #[derive(Debug, Destruct, PartialEq, Eq)]
    enum TestEnum {
        A,
        B,
        C,
    }

    #[test]
    fn test_enum() {
        let e = TestEnum::construct(TestEnum::A.destruct());
        assert_eq!(e, TestEnum::A);
        let e = TestEnum::construct(TestEnum::B.destruct());
        assert_eq!(e, TestEnum::B);
    }

}