Skip to main content

right_as/
lib.rs

1#![no_std]
2#![doc = include_str!("../README.md")]
3
4#[doc = include_str!("../README.md")]
5pub trait TupleExt: Sized {
6    type Left;
7    type Right;
8    type Pack<T>;
9
10    /// Like `{*to = self.1.into(); self.0}`
11    fn right_as<D>(self, to: &mut D) -> Self::Pack<Self::Left>
12    where Self::Right: Into<D>;
13
14    /// Like `{*to = self.0.into(); self.1}`
15    fn left_as<D>(self, to: &mut D) -> Self::Pack<Self::Right>
16    where Self::Left: Into<D>;
17}
18impl<L, R> TupleExt for (L, R) {
19    type Left = L;
20    type Right = R;
21    type Pack<T> = T;
22
23    fn right_as<D>(self, to: &mut D) -> Self::Pack<Self::Left>
24    where Self::Right: Into<D>,
25    {
26        *to = self.1.into();
27        self.0
28    }
29
30    fn left_as<D>(self, to: &mut D) -> Self::Pack<Self::Right>
31    where Self::Left: Into<D>,
32    {
33        *to = self.0.into();
34        self.1
35    }
36}
37impl<L> TupleExt for [L; 2] {
38    type Left = L;
39    type Right = L;
40    type Pack<T> = T;
41
42    fn right_as<D>(self, to: &mut D) -> Self::Pack<Self::Left>
43    where Self::Right: Into<D>,
44    {
45        let [left, right] = self;
46        *to = right.into();
47        left
48    }
49
50    fn left_as<D>(self, to: &mut D) -> Self::Pack<Self::Right>
51    where Self::Left: Into<D>,
52    {
53        let [left, right] = self;
54        *to = left.into();
55        right
56    }
57}
58impl<L, R> TupleExt for Option<(L, R)> {
59    type Left = L;
60    type Right = R;
61    type Pack<T> = Option<T>;
62
63    fn right_as<D>(self, to: &mut D) -> Self::Pack<Self::Left>
64    where Self::Right: Into<D>,
65    {
66        self.map(|x| x.right_as(to))
67    }
68
69    fn left_as<D>(self, to: &mut D) -> Self::Pack<Self::Right>
70    where Self::Left: Into<D>,
71    {
72        self.map(|x| x.left_as(to))
73    }
74}
75impl<L, R, E> TupleExt for Result<(L, R), E> {
76    type Left = L;
77    type Right = R;
78    type Pack<T> = Result<T, E>;
79
80    fn right_as<D>(self, to: &mut D) -> Self::Pack<Self::Left>
81    where Self::Right: Into<D>,
82    {
83        self.map(|x| x.right_as(to))
84    }
85
86    fn left_as<D>(self, to: &mut D) -> Self::Pack<Self::Right>
87    where Self::Left: Into<D>,
88    {
89        self.map(|x| x.left_as(to))
90    }
91}