pipe_drop/
lib.rs

1#![no_std]
2#![doc = include_str!("../doc/lib.md")]
3
4use core::{
5    borrow::{Borrow, BorrowMut},
6    ops::{Deref, DerefMut},
7};
8
9#[doc = include_str!("../doc/lib.md")]
10pub trait PipeDrop: Sized {
11    /// Apply `f` on `&self` and then drop `self`.
12    fn pipe_ref_drop<F, Y>(self, f: F) -> Y
13    where
14        F: FnOnce(&Self) -> Y,
15    {
16        f(&self)
17    }
18
19    /// Apply `f` on `&mut self` and then drop `self`.
20    fn pipe_mut_drop<F, Y>(mut self, f: F) -> Y
21    where
22        F: FnOnce(&mut Self) -> Y,
23    {
24        f(&mut self)
25    }
26
27    /// Apply `f` on `self.as_ref()` and then drop `self`.
28    fn pipe_as_ref_drop<F, X, Y>(self, f: F) -> Y
29    where
30        Self: AsRef<X>,
31        X: ?Sized,
32        F: FnOnce(&X) -> Y,
33    {
34        f(self.as_ref())
35    }
36
37    /// Apply `f` on `self.as_mut()` and then drop `self`.
38    fn pipe_as_mut_drop<F, X, Y>(mut self, f: F) -> Y
39    where
40        Self: AsMut<X>,
41        X: ?Sized,
42        F: FnOnce(&mut X) -> Y,
43    {
44        f(self.as_mut())
45    }
46
47    /// Apply `f` on `&self` and then drop `self`.
48    fn pipe_deref_drop<F, X, Y>(self, f: F) -> Y
49    where
50        Self: Deref<Target = X>,
51        X: ?Sized,
52        F: FnOnce(&X) -> Y,
53    {
54        f(&self)
55    }
56
57    /// Apply `f` on `&mut self` and then drop `self`.
58    fn pipe_deref_mut_drop<F, X, Y>(mut self, f: F) -> Y
59    where
60        Self: DerefMut<Target = X>,
61        X: ?Sized,
62        F: FnOnce(&X) -> Y,
63    {
64        f(&mut self)
65    }
66
67    /// Apply `f` on `self.borrow()` and then drop `self`.
68    fn pipe_borrow_drop<F, X, Y>(self, f: F) -> Y
69    where
70        Self: Borrow<X>,
71        X: ?Sized,
72        F: FnOnce(&X) -> Y,
73    {
74        f(self.borrow())
75    }
76
77    /// Apply `f` on `self.borrow_mut()` and then drop `self`.
78    fn pipe_borrow_mut_drop<F, X, Y>(mut self, f: F) -> Y
79    where
80        Self: BorrowMut<X>,
81        X: ?Sized,
82        F: FnOnce(&X) -> Y,
83    {
84        f(self.borrow_mut())
85    }
86}
87
88impl<X> PipeDrop for X {}