1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
use Any;
use crateCastIdentityBorrowed;
/// Attempt to cast owned `T` to `U`.
///
/// Returns `None` if they are not the same type.
///
/// ```rust
/// fn only_string<T: 'static>(t: T) -> Option<String> {
/// specializer::cast_identity::<T, String>(t)
/// }
///
/// assert!(only_string(()).is_none());
/// assert!(only_string(1).is_none());
/// assert!(only_string("Hello").is_none());
/// assert_eq!(only_string("Hello".to_string()).as_deref(), Some("Hello"));
/// ```
/// Attempt to cast `&T` to `&U`.
///
/// Returns `None` if they are not the same type.
///
/// ```rust
/// fn only_string<T: 'static>(t: &T) -> Option<&String> {
/// specializer::cast_identity_ref::<T, String>(t)
/// }
///
/// assert!(only_string(&()).is_none());
/// assert!(only_string(&1).is_none());
/// assert!(only_string(&"Hello").is_none());
/// assert_eq!(
/// only_string(&"Hello".to_string()).map(|x| x.as_str()),
/// Some("Hello"),
/// );
/// ```
/// Attempt to cast `&mut T` to `&mut U`.
///
/// Returns `None` if they are not the same type.
///
/// ```rust
/// fn only_string<T: 'static>(t: &mut T) -> Option<&mut String> {
/// specializer::cast_identity_mut::<T, String>(t)
/// }
///
/// assert!(only_string(&mut ()).is_none());
/// assert!(only_string(&mut 1).is_none());
/// assert!(only_string(&mut "Hello").is_none());
/// assert_eq!(
/// only_string(&mut "Hello".to_string()),
/// Some(&mut "Hello".to_string()),
/// );
/// ```
/// Attempt to cast borrowed `T` to `U`.
///
/// ```rust
/// fn only_string_ref<T: 'static>(t: &T) -> Option<&String> {
/// specializer::cast_identity_borrowed::<&T, &String>(t)
/// }
///
/// assert!(only_string_ref(&()).is_none());
/// assert!(only_string_ref(&1).is_none());
/// assert!(only_string_ref(&"Hello").is_none());
/// assert_eq!(
/// only_string_ref(&"Hello".to_string()).map(|x| x.as_str()),
/// Some("Hello"),
/// );
///
/// fn only_string_mut<T: 'static>(t: &mut T) -> Option<&mut String> {
/// specializer::cast_identity_borrowed::<&mut T, &mut String>(t)
/// }
///
/// assert!(only_string_mut(&mut ()).is_none());
/// assert!(only_string_mut(&mut 1).is_none());
/// assert!(only_string_mut(&mut "Hello").is_none());
/// assert_eq!(
/// only_string_mut(&mut "Hello".to_string()),
/// Some(&mut "Hello".to_string()),
/// );
/// ```