tuplities_try_from/lib.rs
1//! [tuplities](https://github.com/lucacappelletti94/tuplities) suite crate providing the `TupleTryFrom` and `TupleTryInto` traits.
2
3#[tuplities_derive::impl_tuple_try_from]
4/// A trait for fallibly converting from one tuple type to another.
5///
6/// This trait allows converting between tuples where each element can be converted
7/// using the standard `TryFrom` trait. The error type `E` must implement `From` for
8/// each individual `TryFrom` error in the tuple, allowing error accumulation.
9///
10/// Part of the [`tuplities`](https://docs.rs/tuplities/latest/tuplities/) crate.
11pub trait TupleTryFrom<T, E> {
12 /// Attempts to convert from `T` into `Self`.
13 ///
14 /// # Errors
15 ///
16 /// Returns an error of type `E` if any element conversion fails.
17 ///
18 /// # Examples
19 ///
20 /// ```rust
21 /// use tuplities_try_from::TupleTryFrom;
22 ///
23 /// let source = (1u32, 2u32);
24 /// let target: Result<(u8, u8), _> = TupleTryFrom::<_, std::num::TryFromIntError>::tuple_try_from(source);
25 /// assert_eq!(target, Ok((1, 2)));
26 ///
27 /// let invalid = (300u32, 2u32); // 300 is too big for u8
28 /// let result: Result<(u8, u8), _> = TupleTryFrom::<_, std::num::TryFromIntError>::tuple_try_from(invalid);
29 /// assert!(result.is_err());
30 /// ```
31 fn tuple_try_from(value: T) -> Result<Self, E>
32 where
33 Self: Sized;
34}
35
36/// A trait for fallibly converting a tuple into another tuple type.
37///
38/// This trait allows converting tuples into other tuple types where each element can be converted
39/// using the standard `TryFrom` trait. The error type `E` must implement `From` for
40/// each individual `TryFrom` error in the tuple, allowing error accumulation.
41///
42/// Part of the [`tuplities`](https://docs.rs/tuplities/latest/tuplities/) crate.
43pub trait TupleTryInto<T, E> {
44 /// Attempts to convert `self` into `T`.
45 ///
46 /// # Errors
47 ///
48 /// Returns an error of type `E` if any element conversion fails.
49 ///
50 /// # Examples
51 ///
52 /// ```rust
53 /// use tuplities_try_from::TupleTryInto;
54 ///
55 /// let source = (1u32, 2u32);
56 /// let target: Result<(u8, u8), _> = TupleTryInto::<(u8, u8), std::num::TryFromIntError>::tuple_try_into(source);
57 /// assert_eq!(target, Ok((1, 2)));
58 ///
59 /// let invalid = (300u32, 2u32); // 300 is too big for u8
60 /// let result: Result<(u8, u8), _> = TupleTryInto::<(u8, u8), std::num::TryFromIntError>::tuple_try_into(invalid);
61 /// assert!(result.is_err());
62 /// ```
63 fn tuple_try_into(self) -> Result<T, E>;
64}
65
66// Blanket implementation of TupleTryInto based on TupleTryFrom
67impl<T, U, E> TupleTryInto<T, E> for U
68where
69 T: TupleTryFrom<U, E>,
70{
71 fn tuple_try_into(self) -> Result<T, E> {
72 T::tuple_try_from(self)
73 }
74}