tap/
conv.rs

1/*! # Method-Directed Type Conversion
2
3The `std::convert` module provides traits for converting values from one type to
4another. The first of these, [`From<T>`], provides an associated function
5[`from(orig: T) -> Self`]. This function can only be called in prefix-position,
6as it does not have a `self` receiver. The second, [`Into<T>`], provides a
7method [`into(self) -> T`] which *can* be called in suffix-position; due to
8intractable problems in the type solver, this method cannot have any *further*
9method calls attached to it. It must be bound directly into a `let` or function
10call.
11
12The [`TryFrom<T>`] and [`TryInto<T>`] traits have the same properties, but
13permit failure.
14
15This module provides traits that place the conversion type parameter in the
16method, rather than in the trait, so that users can write `.conv::<T>()` to
17convert the preceding expression into `T`, without causing any failures in the
18type solver. These traits are blanket-implemented on all types that have an
19`Into<T>` implementation, which covers both the blanket implementation of `Into`
20for types with `From`, and manual implementations of `Into`.
21
22[`From<T>`]: https://doc.rust-lang.org/std/convert/trait.From.html
23[`Into<T>`]: https://doc.rust-lang.org/std/convert/trait.Into.html
24[`TryFrom<T>`]: https://doc.rust-lang.org/std/convert/trait.TryFrom.html
25[`TryInto<T>`]: https://doc.rust-lang.org/std/convert/trait.TryInto.html
26[`from(orig: T) -> Self`]: https://doc.rust-lang.org/std/convert/trait.From.html#tymethod.from
27[`into(self) -> T`]: https://doc.rust-lang.org/std/convert/trait.Into.html#tymethod.into
28!*/
29
30use core::convert::TryInto;
31
32/// Wraps `Into::<T>::into` as a method that can be placed in pipelines.
33pub trait Conv
34where
35	Self: Sized,
36{
37	/// Converts `self` into `T` using `Into<T>`.
38	///
39	/// # Examples
40	///
41	/// ```rust
42	/// use tap::conv::Conv;
43	///
44	/// let len = "Saluton, mondo!"
45	///   .conv::<String>()
46	///   .len();
47	/// ```
48	#[inline(always)]
49	fn conv<T>(self) -> T
50	where
51		Self: Into<T>,
52		T: Sized,
53	{
54		Into::<T>::into(self)
55	}
56}
57
58impl<T> Conv for T {}
59
60/// Wraps `TryInto::<T>::try_into` as a method that can be placed in pipelines.
61pub trait TryConv
62where
63	Self: Sized,
64{
65	/// Attempts to convert `self` into `T` using `TryInto<T>`.
66	///
67	/// # Examples
68	///
69	/// ```rust
70	/// use tap::conv::TryConv;
71	///
72	/// let len = "Saluton, mondo!"
73	///   .try_conv::<String>()
74	///   .unwrap()
75	///   .len();
76	/// ```
77	#[inline(always)]
78	fn try_conv<T>(self) -> Result<T, Self::Error>
79	where
80		Self: TryInto<T>,
81		T: Sized,
82	{
83		TryInto::<T>::try_into(self)
84	}
85}
86
87impl<T> TryConv for T {}