Skip to main content

impl_more/
from.rs

1/// Implement [`From`] for a struct.
2///
3/// Declare type and const parameters before `in`.
4///
5/// # Examples
6/// With a newtype struct:
7/// ```
8/// use impl_more::impl_from;
9///
10/// struct Foo(String);
11/// impl_from!(String => Foo);
12///
13/// let foo = Foo::from("bar".to_owned());
14/// ```
15///
16/// With a named field struct with type parameters:
17/// ```
18/// use std::rc::Rc;
19/// use impl_more::impl_from;
20///
21/// struct Foo<T> { inner: Rc<T> }
22/// impl_from!(<T> in Rc<T> => Foo<T> : inner);
23///
24/// let foo = Foo::from(Rc::new("bar".to_owned()));
25/// ```
26///
27/// With type and const parameters:
28/// ```
29/// struct Array<T, const N: usize>([T; N]);
30/// impl_more::impl_from!(<T, const N: usize> in [T; N] => Array<T, N>);
31///
32/// let value = Array::from([1, 2, 3]);
33/// assert_eq!(value.0, [1, 2, 3]);
34/// ```
35///
36/// Append `in Wrapper` after the destination type or field name to call
37/// `Wrapper::new(input)`. Use a type in scope or a qualified path.
38/// ```
39/// struct Message(Box<String>);
40/// impl_more::impl_from!(String => Message in Box);
41///
42/// assert_eq!(*Message::from(String::from("hello")).0, "hello");
43///
44/// struct Batch<T, const N: usize> { items: Box<[T; N]> }
45/// impl_more::impl_from!(<T, const N: usize> in [T; N] => Batch<T, N> : items in Box);
46///
47/// assert_eq!(*Batch::from([1, 2, 3]).items, [1, 2, 3]);
48/// ```
49///
50/// The wrapper can also be a user-defined type:
51/// ```
52/// struct Label(String);
53///
54/// impl Label {
55///     fn new(input: &str) -> Self {
56///         Self(input.to_owned())
57///     }
58/// }
59///
60/// struct Message { label: Label }
61/// impl_more::impl_from!(&str => Message : label in Label);
62///
63/// assert_eq!(Message::from("hello").label.0, "hello");
64/// ```
65#[macro_export]
66macro_rules! impl_from {
67    (<$($generic:ident),+> in $($rest:tt)+) => {
68        $crate::impl_from!(@impl [$($generic),+] $($rest)+);
69    };
70
71    (<const $($rest:tt)+) => {
72        $crate::__impl_more_parse_generics!(@parse impl_from [] [] const $($rest)+);
73    };
74
75    (<$generic:ident, $($rest:tt)+) => {
76        $crate::__impl_more_parse_generics!(@parse impl_from [] [] $generic, $($rest)+);
77    };
78
79    (@impl [$($generic:tt)*] $from:ty => $this:ty $(,)?) => {
80        impl <$($generic)*> ::core::convert::From<$from> for $this {
81            fn from(from: $from) -> Self {
82                Self(from)
83            }
84        }
85    };
86
87    (@impl [$($generic:tt)*] $from:ty => $this:ty : $field:ident in $($wrapper:tt)+) => {
88        $crate::impl_from!(@wrap [$($generic)*] $from => $this : $field in $($wrapper)+);
89    };
90
91    (@impl [$($generic:tt)*] $from:ty => $this:ty : $field:ident $(,)?) => {
92        impl <$($generic)*> ::core::convert::From<$from> for $this {
93            fn from(from: $from) -> Self {
94                Self { $field: from }
95            }
96        }
97    };
98
99    // A type fragment cannot be followed by `in`. Collect the tuple struct type first.
100    (@impl [$($generic:tt)*] $from:ty => $($target:tt)+) => {
101        $crate::impl_from!(@tuple [$($generic)*] [$from] [] $($target)+);
102    };
103
104    (@tuple [$($generic:tt)*] [$from:ty] [$($this:tt)+] in $($wrapper:tt)+) => {
105        $crate::impl_from!(@wrap [$($generic)*] $from => $($this)+ : 0 in $($wrapper)+);
106    };
107
108    (@tuple [$($generic:tt)*] [$from:ty] [$($this:tt)*] $next:tt $($rest:tt)+) => {
109        $crate::impl_from!(@tuple [$($generic)*] [$from] [$($this)* $next] $($rest)+);
110    };
111
112    (@wrap [$($generic:tt)*] $from:ty => $this:ty : $field:tt in $($wrapper:tt)+) => {
113        impl <$($generic)*> ::core::convert::From<$from> for $this {
114            fn from(value: $from) -> Self {
115                Self { $field: $crate::impl_from!(@new value; $($wrapper)+) }
116            }
117        }
118    };
119
120    // Use expression paths so Rust can infer generic arguments in calls such as Box::new.
121    (@new $value:ident; $($segment:ident)::+ $(,)?) => { $($segment)::+::new($value) };
122    (@new $value:ident; ::$($segment:ident)::+ $(,)?) => { ::$($segment)::+::new($value) };
123    (@new $value:ident; $wrapper:ty $(,)?) => { <$wrapper>::new($value) };
124
125    ($from:ty => $($target:tt)+) => {
126        $crate::impl_from!(@impl [] $from => $($target)+);
127    };
128}
129
130/// Implement [`From`] for a primitive.
131///
132/// # Examples
133/// With a newtype struct:
134/// ```
135/// use impl_more::impl_from_for_primitive;
136///
137/// struct Checked(bool);
138/// impl_from_for_primitive!(Checked => bool);
139///
140/// let foo = bool::from(Checked(true));
141/// ```
142#[macro_export]
143macro_rules! impl_from_for_primitive {
144    ($from:ty => $this:ty $(,)?) => {
145        impl ::core::convert::From<$from> for $this {
146            fn from(from: $from) -> $this {
147                <$this as ::core::convert::From<_>>::from(from.0)
148            }
149        }
150    };
151}
152
153/// Implement [`From`] and [`Into`] for a newtype struct.
154///
155/// # Examples
156///
157/// ```
158/// use impl_more::impl_newtype_from_into;
159///
160/// struct Checked(bool);
161/// impl_newtype_from_into!(Checked [<=>] bool);
162///
163/// let foo = Checked::from(true);
164/// assert_eq!(foo.0, true);
165///
166/// let foo = bool::from(Checked(false));
167/// assert_eq!(foo, false);
168/// ```
169#[macro_export]
170macro_rules! impl_newtype_from_into {
171    ($newtype:ty [<=>] $inner:ty $(,)?) => {
172        impl ::core::convert::From<$inner> for $newtype {
173            fn from(from: $inner) -> $newtype {
174                Self(from)
175            }
176        }
177
178        impl ::core::convert::From<$newtype> for $inner {
179            fn from(from: $newtype) -> $inner {
180                from.0
181            }
182        }
183    };
184}
185
186/// Implement [`Into`] for a struct.
187///
188/// Declare type and const parameters before `in`.
189///
190/// # Examples
191/// With a newtype struct:
192/// ```
193/// use impl_more::impl_into;
194///
195/// struct Foo(String);
196///
197/// impl_into!(Foo => String);
198///
199/// let foo = Foo("bar".to_owned());
200/// let foo_str: String = foo.into();
201/// ```
202///
203/// With a named field struct with type parameters:
204/// ```
205/// use std::rc::Rc;
206/// use impl_more::impl_into;
207///
208/// struct Foo<T> { inner: Rc<T> }
209/// impl_into!(<T> in Foo<T> => Rc<T> : inner);
210///
211/// let foo = Foo { inner: Rc::new("bar".to_owned()) };
212/// let _: Rc<String> = foo.into();
213/// ```
214#[macro_export]
215macro_rules! impl_into {
216    (<$($generic:ident),+> in $($rest:tt)+) => {
217        $crate::impl_into!(@impl [$($generic),+] $($rest)+);
218    };
219
220    (<const $($rest:tt)+) => {
221        $crate::__impl_more_parse_generics!(@parse impl_into [] [] const $($rest)+);
222    };
223
224    (<$generic:ident, $($rest:tt)+) => {
225        $crate::__impl_more_parse_generics!(@parse impl_into [] [] $generic, $($rest)+);
226    };
227
228    (@impl [$($generic:tt)+] $this:ty => $inner:ty : $field:ident) => {
229        impl <$($generic)+> ::core::convert::Into<$inner> for $this {
230            fn into(self) -> $inner {
231                self.$field
232            }
233        }
234    };
235
236    (@impl [$($generic:tt)+] $this:ty => $inner:ty) => {
237        impl <$($generic)+> ::core::convert::Into<$inner> for $this {
238            fn into(self) -> $inner {
239                self.0
240            }
241        }
242    };
243
244    ($this:ty => $inner:ty) => {
245        impl ::core::convert::Into<$inner> for $this {
246            fn into(self) -> $inner {
247                self.0
248            }
249        }
250    };
251
252    ($this:ty => $inner:ty : $field:ident) => {
253        impl ::core::convert::Into<$inner> for $this {
254            fn into(self) -> $inner {
255                self.$field
256            }
257        }
258    };
259}
260
261#[cfg(test)]
262mod tests {
263    #![allow(clippy::from_over_into)]
264
265    use alloc::rc::Rc;
266
267    #[test]
268    fn reference_counted_fields() {
269        struct Local {
270            rc: Rc<u32>,
271        }
272        impl_from!(u32 => Local : rc in Rc);
273        impl_from!(Rc<u32> => Local : rc);
274
275        struct Shared(alloc::sync::Arc<u32>);
276        impl_from!(u32 => Shared in alloc::sync::Arc);
277
278        struct Named {
279            arc: u32,
280        }
281        impl_from!(u32 => Named : arc);
282
283        let local = Local::from(42).rc;
284        assert_eq!(*local, 42);
285        assert!(Rc::ptr_eq(&local, &Local::from(local.clone()).rc));
286        assert_eq!(*Shared::from(7).0, 7);
287        assert_eq!(Named::from(9).arc, 9);
288    }
289
290    #[test]
291    fn newtype() {
292        struct Foo(usize);
293        impl_from!(usize => Foo);
294        impl_into!(Foo => usize);
295
296        static_assertions::assert_impl_all!(Foo: From<usize>, Into<usize>);
297
298        let foo = Foo::from(42);
299        assert_eq!(foo.0, 42);
300    }
301
302    #[test]
303    fn newtype_primitive() {
304        struct Foo(usize);
305        impl_from!(usize => Foo);
306        impl_from_for_primitive!(Foo => usize);
307
308        static_assertions::assert_impl_all!(Foo: From<usize>);
309        static_assertions::assert_impl_all!(usize: From<Foo>);
310
311        let foo = Foo::from(42);
312        assert_eq!(foo.0, 42);
313    }
314
315    #[test]
316    fn newtype_generic() {
317        struct Foo<T>(Rc<T>);
318        impl_from!(<T> in Rc<T> => Foo<T>);
319        impl_into!(<T> in Foo<T> => Rc<T>);
320
321        let foo = Foo::from(Rc::new(42_usize));
322        assert_eq!(*foo.0, 42);
323    }
324
325    #[test]
326    fn named_field() {
327        struct Foo {
328            inner: usize,
329        }
330        impl_from!(usize => Foo : inner);
331        impl_into!(Foo => usize : inner);
332
333        static_assertions::assert_impl_all!(Foo: From<usize>, Into<usize>);
334
335        let foo = Foo::from(42);
336        assert_eq!(foo.inner, 42);
337
338        struct MultiFoo {
339            small: u8,
340            big: u64,
341        }
342        impl_into!(MultiFoo => u8 : small);
343        impl_into!(MultiFoo => u64 : big);
344
345        static_assertions::assert_impl_all!(MultiFoo: Into<u8>, Into<u64>);
346
347        let foo = MultiFoo { small: 4, big: 42 };
348        assert_eq!(foo.small, 4);
349        assert_eq!(foo.big, 42);
350    }
351
352    #[test]
353    fn named_field_generic() {
354        struct Foo<T> {
355            inner: Rc<T>,
356        }
357        impl_from!(<T> in Rc<T> => Foo<T> : inner);
358        impl_into!(<T> in Foo<T> => Rc<T> : inner);
359
360        let foo = Foo::from(Rc::new(42_usize));
361        assert_eq!(*foo.inner, 42);
362    }
363}