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
/// For implementing [`FromStructural`],
/// and delegating the implementation of [`TryFromStructural`] to it.
///
/// [`FromStructural`]: ./convert/trait.FromStructural.html
/// [`TryFromStructural`]: ./convert/trait.TryFromStructural.html
///
/// # Example
///
/// This example demonstrates how you can implement `FromStructural` in a
/// more general way than necessary,
///
/// ```rust
/// use structural::{FP, IntoField, Structural, StructuralExt, fp, make_struct};
///
/// use std::borrow::Cow;
///
/// {
///     let this = make_struct!{
///         encoding: "utf8",
///         contents: &[0,1,2,3,4][..],
///     };
///     assert_eq!(
///         this.into_struc::<Message>(),
///         Message{encoding: "utf8".to_string(), contents: vec![0,1,2,3,4]}
///     );
/// }
/// {
///     let this = HttpMessage{
///         encoding: Cow::from("utf16"),
///         contents: Cow::from(vec![5,7,8]),
///         valid_until: 0o40002,
///     };
///     assert_eq!(
///         this.into_struc::<Message>(),
///         Message{encoding: "utf16".to_string(), contents: vec![5,7,8]}
///     );
/// }
///
/// #[derive(Structural, Debug)]
/// #[struc(no_trait, public, access="move")]
/// pub struct HttpMessage<'a> {
///     encoding: Cow<'a,str>,
///     contents: Cow<'a,[u8]>,
///     valid_until: u32,
/// }
///
/// #[derive(Structural, Debug, PartialEq)]
/// #[struc(no_trait, public, access="move")]
/// pub struct Message {
///     encoding: String,
///     contents: Vec<u8>,
/// }
///
/// // This macro generates the TryFromStructural impl based on the passed
/// // FromStructural implementation.
/// structural::z_impl_from_structural! {
///     impl[F, E, C] FromStructural<F> for Message
///     where[
///         // The bounds here would usually just be `F: Message_SI`
///         // (Message_SI being a trait generated by the Structural derive,
///         //  aliasing the accessor traits implemented by Message),
///         // but I decided to make this example different.
///         F: IntoField<FP!(encoding), Ty = C>,
///         F: IntoField<FP!(contents), Ty = E>,
///         C: Into<String>,
///         E: Into<Vec<u8>>,
///     ]{
///         fn from_structural(this){
///             let (encoding, contents) = this.into_fields(fp!(encoding, contents));
///             Self {
///                 encoding: encoding.into(),
///                 contents: contents.into(),
///             }
///         }
///     }
/// }
///
/// ```
#[macro_export]
macro_rules! z_impl_from_structural {
    (
        impl[ $($impl_params:tt)* ] FromStructural<$from:ident> for $self:ty
        where [ $($where_preds:tt)* ]
        {
            fn from_structural($from_var:ident){
                $($code:tt)*
            }
        }
    ) => {
        impl< $($impl_params)* > $crate::pmr::FromStructural<$from> for $self
        where
            $($where_preds)*
        {
            fn from_structural($from_var: $from) -> Self {
                $($code)*
            }
        }

        impl< $($impl_params)*> $crate::pmr::TryFromStructural<$from> for $self
        where
            $($where_preds)*
        {
            type Error = $crate::pmr::Infallible;

            #[inline(always)]
            fn try_from_structural(
                $from_var: $from,
            ) -> Result<Self, $crate::pmr::TryFromError<$from,$crate::pmr::Infallible>> {
                Ok(<Self as $crate::pmr::FromStructural<$from>>::from_structural($from_var))
            }
        }
    };
}

/// For implementing [`TryFromStructural`],
/// and delegating the implementation of [`FromStructural`] to it.
///
/// The implementation of [`FromStructural`] inherits all the constraints of the
/// [`TryFromStructural`] impl.
///
/// In order to implement [`FromStructural`],
/// this macro assumes that the [`TryFromStructural`] implementation written by users:
///
/// - Matches on all the variants of the enum
///
/// - Returns `Ok` for all the variants of the enum that were matches by name.
///
/// [`FromStructural`]: ./convert/trait.FromStructural.html
/// [`TryFromStructural`]: ./convert/trait.TryFromStructural.html
///
/// # Example
///
/// ```rust
/// use structural::{
///     convert::{EmptyTryFromError, FromStructural, TryFromError, TryFromStructural},
///     Structural, StructuralExt, switch,
/// };
///
/// use std::cmp::Ordering;
///
///
/// assert_eq!(
///     EnumAAAA::Foo([9,8,7,6,5,4,3,2,1,0]).try_into_struc::<Variants>(),
///     Ok(Variants::Foo(9)),
/// );
///
/// assert_eq!(
///     EnumAAAA::Bar{heh: true}.try_into_struc::<Variants>(),
///     Ok(Variants::Bar),
/// );
///
/// assert_eq!(
///     EnumAAAA::Baz{foom: "hi", uh: Ordering::Less}.try_into_struc::<Variants>(),
///     Ok(Variants::Baz{foom: "hi"}),
/// );
///
/// assert_eq!(
///     EnumAAAA::Qux.try_into_struc::<Variants>(),
///     Err(TryFromError::with_empty_error(EnumAAAA::Qux)),
/// );
///
///
/// #[derive(Structural, Copy, Clone, Debug, PartialEq)]
/// #[struc(no_trait)]
/// enum EnumAAAA {
///     // This delegates the `*VariantField` accessor traits to the array,
///     // meaning that `.field_(fp!(::Foo.0))` would access the 0th element,
///     // `.field_(fp!(::Foo.4))` would access the 4th element of the array,
///     // etcetera.
///     //
///     // If this enum had a `EnumAAAA_SI` trait alias (generated by the `Structural` derive),
///     // this variant would only have the `IsVariant<TS!(Foo)>` bound in the trait alias.
///     #[struc(newtype)]
///     Foo([u8;10]),
///     Bar{ heh: bool },
///     Baz {
///         foom: &'static str,
///         uh: Ordering,
///     },
///     Qux,
/// }
///  
/// #[derive(Structural, Copy, Clone, Debug, PartialEq)]
/// enum Variants {
///     Foo(u8),
///     Bar,
///     Baz { foom: &'static str },
/// }
///  
///
/// structural::z_impl_try_from_structural_for_enum!{
///     impl[F] TryFromStructural<F> for Variants
///     where[
///         // `Variants_SI` was generated by the `Structural` derive for `Variants`
///         // aliasing its accessor trait impls,
///         // and allows `F` to have more variants than `Foo`,`Bar`,and `Baz`.
///         F: Variants_SI,
///     ]{
///         type Error = EmptyTryFromError;
///
///         fn try_from_structural(this) {
///             switch! {this;
///                 Foo(x) => Ok(Self::Foo(x)),
///                 Bar => Ok(Self::Bar),
///                 Baz{foom} => Ok(Self::Baz{foom}),
///                 _ => Err(TryFromError::with_empty_error(this)),
///             }
///         }
///     }
///
///     // `Variants_ESI` is like `Variants_SI` with the additional requirement that `F`
///     // only has the `Foo`,`Bar`,and `Baz` variants.
///     FromStructural
///     where[ F: Variants_ESI, ]
/// }
///
/// ```
#[macro_export]
macro_rules! z_impl_try_from_structural_for_enum {
    (
        impl[ $($impl_params:tt)* ] TryFromStructural<$from:ident> for $self:ty
        where [ $($where_preds:tt)* ]
        {
            type Error= $err:ty;
            fn try_from_structural($from_var:ident){
                $($code:tt)*
            }
        }

        FromStructural
        where [ $($from_where_preds:tt)* ]
    ) => {
        impl< $($impl_params)* > $crate::pmr::FromStructural<$from> for $self
        where
            $($where_preds)*
            $($from_where_preds)*
        {
            #[inline]
            fn from_structural(from_var: $from) -> Self {
                let res=<Self as $crate::pmr::TryFromStructural<$from>>::try_from_structural(
                    from_var
                );
                match res {
                    Ok(x) => x,
                    Err(e) => unreachable!(
                        "expected type to implement `TryFromStructural::try_from_structural`
                         such that it doesn't return an error in `FromStructural`.\n\
                        type:\n\t{}\n\
                        error:\n\t{}\n",
                        $crate::std_::any::type_name::<Self>(),
                        e.error,
                    ),
                }
            }
        }

        impl< $($impl_params)*> $crate::pmr::TryFromStructural<$from> for $self
        where
            $($where_preds)*
        {
            type Error = $err;

            #[inline(always)]
            fn try_from_structural(
                $from_var: $from,
            ) -> Result<Self, $crate::pmr::TryFromError<$from,$err>> {
                $($code)*
            }
        }
    };
}