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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
//! Converting values to another type.
/// Extention trait that enables `.into_type::<T>()` syntax. Also works for
/// [`cinto`](Cinto),
/// [`try_into`](TryInto),
/// [`saturating_into`](SaturatingInto).
///
/// When you replace unchecked type casts (e.g. `number as u32`) with an infallible conversion
/// (`number.into()`) or a fallible conversion (`number.try_into()?`), you may often encounter
/// type inference errors if the context doesn't have enough information about the target type:
/// ```
/// fn f1(input: u32) -> u64 {
/// 10 + (input as u64) // Compiles
/// }
/// ```
/// ```compile_fail
/// fn f1(input: u32) -> Result<u64, std::num::TryFromIntError> {
/// let a = 10 + input.try_into()?; // Doesn't compile
/// Ok(a)
/// }
/// ```
/// The easiest way to solve it in `std` is to use `From` or `TryFrom` instead
/// so that you can specify the target type:
/// ```
/// fn f1(input: u32) -> Result<u64, std::num::TryFromIntError> {
/// let a = 10 + u64::try_from(input)?; // Compiles
/// Ok(a)
/// }
/// ```
/// This can cause unnecessary friction because it requires some rearrangement of the code and reduces its
/// readability. The `IntoType` trait provides an alternative way to do it:
/// ```
/// use cadd::convert::IntoType;
/// fn f1(input: u32) -> Result<u64, std::num::TryFromIntError> {
/// let a = 10 + input.try_into_type::<u64>()?; // Compiles
/// Ok(a)
/// }
/// ```
///
/// This trait is implemented for all types. However, each method has its own type bound that requires
/// the corresponding conversion trait to be implemented.
/// Checked conversion from `Input` to `Self`.
///
/// This is semantically the same as [`TryFrom`]. However, `Cfrom`
/// aims to provide a rich error message, as opposed to many implementations of `TryFrom` in `std`
/// that provide minimal informations in errors.
///
/// [`Cinto`] trait provides an alternative way to do the same conversion.
/// Similar to `TryFrom`, it's recommended to always implement `Cfrom` instead of [`Cinto`].
/// The corresponding `Cinto` implementation will be covered by the blanket impl.
///
/// # Comparison with `std` alternatives
/// ```
/// # fn test1() -> Result<(), Box<dyn std::error::Error>> {
/// let a: i32 = -50;
/// // Reinterpretation cast: never fails, but produces a different value
/// // when the input value is out of bounds.
/// let b = a as u32;
///
/// // Returns an uninformative error: `TryFromIntError(())`;
/// // requires type annotation on the left side.
/// let b2: u32 = a.try_into()?;
///
/// // Returns an informative error:
/// // `failed to convert value -50 from i32 to u32: value is out of bounds`.
/// // Still requires type annotation on the left side.
/// use cadd::convert::Cinto;
///
/// let b3: u32 = a.cinto()?;
///
/// // Same error as above, and output type can be specified in the call.
/// use cadd::convert::IntoType;
///
/// let b4 = a.cinto_type::<u32>()?;
/// # Ok(())
/// # }
/// # fn main() {
/// # test1().unwrap_err();
/// # }
/// ```
///
/// # Notable implementations
///
/// * Fallible conversions between integer types:
/// ```
/// use cadd::convert::{Cfrom, Cinto, IntoType};
///
/// // Output type can be inferred from context:
/// let a = 15_i32;
/// let b: u32 = a.cinto().unwrap();
/// assert_eq!(b, 15);
///
/// // It's also possible to specify output type explicitly:
/// let c = a.cinto_type::<u32>().unwrap();
/// assert_eq!(c, 15);
///
/// // The error contains the input value, input type and output type:
/// let d = -15_i32;
/// let err = d.cinto_type::<u32>().unwrap_err();
/// assert!(err.to_string().contains(
/// "failed to convert value -15 from i32 to u32: value is out of bounds"
/// ));
///
/// // Using `Cfrom` directly:
/// let e = u32::cfrom(a).unwrap();
/// assert_eq!(e, 15);
/// ```
/// * Conversions from slices to fixed arrays:
/// ```
/// # use cadd::convert::{Cfrom, Cinto, IntoType};
/// let a: &[u32] = &[1, 2, 3, 4];
/// let b: &[u32; 4] = a.cinto().unwrap();
/// assert!(
/// a.cinto_type::<&[u32; 5]>().unwrap_err().to_string().contains(
/// "expected 5 items, got [1, 2, 3, 4] (4 items)"
/// )
/// );
/// ```
/// * Conversions from `CString`, `&CStr`, `OsString`, `&OsStr`, `PathBuf`, `&Path` to `String` and `&str`:
/// ```
/// # use {cadd::convert::{Cfrom, Cinto, IntoType}, std::ffi::CString};
/// let a = CString::from_vec_with_nul(vec![104, 101, 108, 108, 111, 0]).unwrap();
/// assert_eq!(a.cinto_type::<String>().unwrap(), "hello");
///
/// let a2 = CString::from_vec_with_nul(vec![104, 128, 108, 108, 111, 0]).unwrap();
/// assert!(
/// a2.clone().cinto_type::<String>().unwrap_err().to_string().contains(
/// "failed to convert bytes to string: \
/// invalid utf-8 sequence of 1 bytes from index 1; \
/// input: [104, 128, 108, 108, 111] (5 bytes); \
/// input as lossy utf-8: \"h�llo\""
/// )
/// );
/// ```
/// Checked conversion from `Self` to `Output`.
///
/// This trait is automatically implemented when `Output` implements <code>[Cfrom]<Self></code>.
///
/// In order to help with type inference,
/// the [`IntoType`] extension trait provides `.cinto_type::<T>()` syntax.
///
/// **See [`Cfrom`] for main documentation.**
/// Saturating conversion of a number from `Input` to `Self`.
///
/// If the value being converted is out of bounds for the target type,
/// the closest representable value is returned. Consequently, if the value is out of bounds,
/// this conversion always returns `Self::MIN` or `Self::MAX`.
/// ```
/// use cadd::convert::SaturatingFrom;
///
/// assert_eq!(u8::saturating_from(300_u32), 255);
/// assert_eq!(u8::saturating_from(200_u32), 200);
/// assert_eq!(u8::saturating_from(-300_i32), 0);
/// assert_eq!(i8::saturating_from(-300_i32), -128);
/// ```
/// [`SaturatingInto`] trait provides an alternative way to do the same conversion.
/// Similar to [`TryFrom`], it's recommended to always implement
/// `SaturatingFrom` instead of [`SaturatingInto`](Cinto).
/// The corresponding `SaturatingInto` implementation will be covered by the blanket impl.
///
/// In order to help with type inference,
/// the [`IntoType`] extension trait provides `.saturating_into_type::<T>()` syntax.
/// Saturating conversion of a number from `Self` to `Output`.
///
/// This trait is automatically implemented when `Output` implements <code>[SaturatingFrom]<Self></code>.
/// Similar to [`TryInto`], it's recommended to always implement
/// `SaturatingFrom` instead of [`SaturatingInto`](Cinto).
///
/// In order to help with type inference,
/// the [`IntoType`] extension trait provides `.saturating_into_type::<T>()` syntax.
///
/// **See [`SaturatingFrom`] for main documentation.**
///
/// # Examples
/// ```
/// use cadd::convert::{SaturatingInto, IntoType};
///
/// let v: u8 = 300_u32.saturating_into();
/// assert_eq!(v, 255);
/// // Or with `IntoType` extension trait:
/// assert_eq!(300_u32.saturating_into_type::<u8>(), 255);
///
/// // More examples:
/// assert_eq!(200_u32.saturating_into_type::<u8>(), 200);
/// assert_eq!((-300_i32).saturating_into_type::<u8>(), 0);
/// assert_eq!((-300_i32).saturating_into_type::<i8>(), -128);
/// ```
/// Conversion from an integer type to the corresponding [`NonZero`](core::num::NonZero) type.
///
/// If the value is zero, it returns an error with a backtrace.
///
/// [`non_zero`] provides an alternative way to do the same conversion.
///
/// # Examples
/// ```
/// use cadd::convert::ToNonZero;
/// use std::num::NonZero;
///
/// let x: u32 = 5;
/// let y = x.to_non_zero().unwrap();
/// assert_eq!(y, NonZero::new(5).unwrap());
///
/// let x2: u32 = 0;
/// assert!(
/// x2.to_non_zero().unwrap_err().to_string().contains("unexpected zero value")
/// );
/// ```
/// Returns [`NonZero`](core::num::NonZero) value equal to `value`, returning an error if `value` is 0.
///
/// See also: [`ToNonZero`].
impl_to_non_zero!;