alloc/boxed/convert.rs
1use core::any::Any;
2use core::error::Error;
3use core::mem;
4use core::pin::Pin;
5#[cfg(not(no_global_oom_handling))]
6use core::{fmt, ptr};
7
8use crate::alloc::Allocator;
9#[cfg(not(no_global_oom_handling))]
10use crate::borrow::Cow;
11use crate::boxed::Box;
12#[cfg(not(no_global_oom_handling))]
13use crate::raw_vec::RawVec;
14#[cfg(not(no_global_oom_handling))]
15use crate::str::from_boxed_utf8_unchecked;
16#[cfg(not(no_global_oom_handling))]
17use crate::string::String;
18#[cfg(not(no_global_oom_handling))]
19use crate::vec::Vec;
20
21#[cfg(not(no_global_oom_handling))]
22#[stable(feature = "from_for_ptrs", since = "1.6.0")]
23impl<T> From<T> for Box<T> {
24 /// Converts a `T` into a `Box<T>`
25 ///
26 /// The conversion allocates on the heap and moves `t`
27 /// from the stack into it.
28 ///
29 /// # Examples
30 ///
31 /// ```rust
32 /// let x = 5;
33 /// let boxed = Box::new(5);
34 ///
35 /// assert_eq!(Box::from(x), boxed);
36 /// ```
37 fn from(t: T) -> Self {
38 Box::new(t)
39 }
40}
41
42#[stable(feature = "pin", since = "1.33.0")]
43impl<T: ?Sized, A: Allocator> From<Box<T, A>> for Pin<Box<T, A>>
44where
45 A: 'static,
46{
47 /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
48 /// `*boxed` will be pinned in memory and unable to be moved.
49 ///
50 /// This conversion does not allocate on the heap and happens in place.
51 ///
52 /// This is also available via [`Box::into_pin`].
53 ///
54 /// Constructing and pinning a `Box` with <code><Pin<Box\<T>>>::from([Box::new]\(x))</code>
55 /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
56 /// This `From` implementation is useful if you already have a `Box<T>`, or you are
57 /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
58 fn from(boxed: Box<T, A>) -> Self {
59 Box::into_pin(boxed)
60 }
61}
62
63/// Specialization trait used for `From<&[T]>`.
64#[cfg(not(no_global_oom_handling))]
65trait BoxFromSlice<T> {
66 fn from_slice(slice: &[T]) -> Self;
67}
68
69#[cfg(not(no_global_oom_handling))]
70impl<T: Clone> BoxFromSlice<T> for Box<[T]> {
71 #[inline]
72 default fn from_slice(slice: &[T]) -> Self {
73 slice.to_vec().into_boxed_slice()
74 }
75}
76
77#[cfg(not(no_global_oom_handling))]
78impl<T: Copy> BoxFromSlice<T> for Box<[T]> {
79 #[inline]
80 fn from_slice(slice: &[T]) -> Self {
81 let len = slice.len();
82 let buf = RawVec::with_capacity(len);
83 unsafe {
84 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
85 buf.into_box(slice.len()).assume_init()
86 }
87 }
88}
89
90#[cfg(not(no_global_oom_handling))]
91#[stable(feature = "box_from_slice", since = "1.17.0")]
92impl<T: Clone> From<&[T]> for Box<[T]> {
93 /// Converts a `&[T]` into a `Box<[T]>`
94 ///
95 /// This conversion allocates on the heap
96 /// and performs a copy of `slice` and its contents.
97 ///
98 /// # Examples
99 /// ```rust
100 /// // create a &[u8] which will be used to create a Box<[u8]>
101 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
102 /// let boxed_slice: Box<[u8]> = Box::from(slice);
103 ///
104 /// println!("{boxed_slice:?}");
105 /// ```
106 #[inline]
107 fn from(slice: &[T]) -> Box<[T]> {
108 <Self as BoxFromSlice<T>>::from_slice(slice)
109 }
110}
111
112#[cfg(not(no_global_oom_handling))]
113#[stable(feature = "box_from_mut_slice", since = "1.84.0")]
114impl<T: Clone> From<&mut [T]> for Box<[T]> {
115 /// Converts a `&mut [T]` into a `Box<[T]>`
116 ///
117 /// This conversion allocates on the heap
118 /// and performs a copy of `slice` and its contents.
119 ///
120 /// # Examples
121 /// ```rust
122 /// // create a &mut [u8] which will be used to create a Box<[u8]>
123 /// let mut array = [104, 101, 108, 108, 111];
124 /// let slice: &mut [u8] = &mut array;
125 /// let boxed_slice: Box<[u8]> = Box::from(slice);
126 ///
127 /// println!("{boxed_slice:?}");
128 /// ```
129 #[inline]
130 fn from(slice: &mut [T]) -> Box<[T]> {
131 Self::from(&*slice)
132 }
133}
134
135#[cfg(not(no_global_oom_handling))]
136#[stable(feature = "box_from_cow", since = "1.45.0")]
137impl<T: Clone> From<Cow<'_, [T]>> for Box<[T]> {
138 /// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
139 ///
140 /// When `cow` is the `Cow::Borrowed` variant, this
141 /// conversion allocates on the heap and copies the
142 /// underlying slice. Otherwise, it will try to reuse the owned
143 /// `Vec`'s allocation.
144 #[inline]
145 fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
146 match cow {
147 Cow::Borrowed(slice) => Box::from(slice),
148 Cow::Owned(slice) => Box::from(slice),
149 }
150 }
151}
152
153#[cfg(not(no_global_oom_handling))]
154#[stable(feature = "box_from_slice", since = "1.17.0")]
155impl From<&str> for Box<str> {
156 /// Converts a `&str` into a `Box<str>`
157 ///
158 /// This conversion allocates on the heap
159 /// and performs a copy of `s`.
160 ///
161 /// # Examples
162 ///
163 /// ```rust
164 /// let boxed: Box<str> = Box::from("hello");
165 /// println!("{boxed}");
166 /// ```
167 #[inline]
168 fn from(s: &str) -> Box<str> {
169 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
170 }
171}
172
173#[cfg(not(no_global_oom_handling))]
174#[stable(feature = "box_from_mut_slice", since = "1.84.0")]
175impl From<&mut str> for Box<str> {
176 /// Converts a `&mut str` into a `Box<str>`
177 ///
178 /// This conversion allocates on the heap
179 /// and performs a copy of `s`.
180 ///
181 /// # Examples
182 ///
183 /// ```rust
184 /// let mut original = String::from("hello");
185 /// let original: &mut str = &mut original;
186 /// let boxed: Box<str> = Box::from(original);
187 /// println!("{boxed}");
188 /// ```
189 #[inline]
190 fn from(s: &mut str) -> Box<str> {
191 Self::from(&*s)
192 }
193}
194
195#[cfg(not(no_global_oom_handling))]
196#[stable(feature = "box_from_cow", since = "1.45.0")]
197impl From<Cow<'_, str>> for Box<str> {
198 /// Converts a `Cow<'_, str>` into a `Box<str>`
199 ///
200 /// When `cow` is the `Cow::Borrowed` variant, this
201 /// conversion allocates on the heap and copies the
202 /// underlying `str`. Otherwise, it will try to reuse the owned
203 /// `String`'s allocation.
204 ///
205 /// # Examples
206 ///
207 /// ```rust
208 /// use std::borrow::Cow;
209 ///
210 /// let unboxed = Cow::Borrowed("hello");
211 /// let boxed: Box<str> = Box::from(unboxed);
212 /// println!("{boxed}");
213 /// ```
214 ///
215 /// ```rust
216 /// # use std::borrow::Cow;
217 /// let unboxed = Cow::Owned("hello".to_string());
218 /// let boxed: Box<str> = Box::from(unboxed);
219 /// println!("{boxed}");
220 /// ```
221 #[inline]
222 fn from(cow: Cow<'_, str>) -> Box<str> {
223 match cow {
224 Cow::Borrowed(s) => Box::from(s),
225 Cow::Owned(s) => Box::from(s),
226 }
227 }
228}
229
230#[stable(feature = "boxed_str_conv", since = "1.19.0")]
231impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
232 /// Converts a `Box<str>` into a `Box<[u8]>`
233 ///
234 /// This conversion does not allocate on the heap and happens in place.
235 ///
236 /// # Examples
237 /// ```rust
238 /// // create a Box<str> which will be used to create a Box<[u8]>
239 /// let boxed: Box<str> = Box::from("hello");
240 /// let boxed_str: Box<[u8]> = Box::from(boxed);
241 ///
242 /// // create a &[u8] which will be used to create a Box<[u8]>
243 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
244 /// let boxed_slice = Box::from(slice);
245 ///
246 /// assert_eq!(boxed_slice, boxed_str);
247 /// ```
248 #[inline]
249 fn from(s: Box<str, A>) -> Self {
250 let (raw, alloc) = Box::into_raw_with_allocator(s);
251 unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
252 }
253}
254
255#[cfg(not(no_global_oom_handling))]
256#[stable(feature = "box_from_array", since = "1.45.0")]
257impl<T, const N: usize> From<[T; N]> for Box<[T]> {
258 /// Converts a `[T; N]` into a `Box<[T]>`
259 ///
260 /// This conversion moves the array to newly heap-allocated memory.
261 ///
262 /// # Examples
263 ///
264 /// ```rust
265 /// let boxed: Box<[u8]> = Box::from([4, 2]);
266 /// println!("{boxed:?}");
267 /// ```
268 fn from(array: [T; N]) -> Box<[T]> {
269 Box::new(array)
270 }
271}
272
273/// Casts a boxed slice to a boxed array.
274///
275/// # Safety
276///
277/// `boxed_slice.len()` must be exactly `N`.
278unsafe fn boxed_slice_as_array_unchecked<T, A: Allocator, const N: usize>(
279 boxed_slice: Box<[T], A>,
280) -> Box<[T; N], A> {
281 debug_assert_eq!(boxed_slice.len(), N);
282
283 let (ptr, alloc) = Box::into_raw_with_allocator(boxed_slice);
284 // SAFETY: Pointer and allocator came from an existing box,
285 // and our safety condition requires that the length is exactly `N`
286 unsafe { Box::from_raw_in(ptr as *mut [T; N], alloc) }
287}
288
289#[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
290impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
291 type Error = Box<[T]>;
292
293 /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
294 ///
295 /// The conversion occurs in-place and does not require a
296 /// new memory allocation.
297 ///
298 /// # Errors
299 ///
300 /// Returns the old `Box<[T]>` in the `Err` variant if
301 /// `boxed_slice.len()` does not equal `N`.
302 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
303 if boxed_slice.len() == N {
304 Ok(unsafe { boxed_slice_as_array_unchecked(boxed_slice) })
305 } else {
306 Err(boxed_slice)
307 }
308 }
309}
310
311#[cfg(not(no_global_oom_handling))]
312#[stable(feature = "boxed_array_try_from_vec", since = "1.66.0")]
313impl<T, const N: usize> TryFrom<Vec<T>> for Box<[T; N]> {
314 type Error = Vec<T>;
315
316 /// Attempts to convert a `Vec<T>` into a `Box<[T; N]>`.
317 ///
318 /// Like [`Vec::into_boxed_slice`], this is in-place if `vec.capacity() == N`,
319 /// but will require a reallocation otherwise.
320 ///
321 /// # Errors
322 ///
323 /// Returns the original `Vec<T>` in the `Err` variant if
324 /// `boxed_slice.len()` does not equal `N`.
325 ///
326 /// # Examples
327 ///
328 /// This can be used with [`vec!`] to create an array on the heap:
329 ///
330 /// ```
331 /// let state: Box<[f32; 100]> = vec![1.0; 100].try_into().unwrap();
332 /// assert_eq!(state.len(), 100);
333 /// ```
334 fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
335 if vec.len() == N {
336 let boxed_slice = vec.into_boxed_slice();
337 Ok(unsafe { boxed_slice_as_array_unchecked(boxed_slice) })
338 } else {
339 Err(vec)
340 }
341 }
342}
343
344impl<A: Allocator> Box<dyn Any, A> {
345 /// Attempts to downcast the box to a concrete type.
346 ///
347 /// # Examples
348 ///
349 /// ```
350 /// use std::any::Any;
351 ///
352 /// fn print_if_string(value: Box<dyn Any>) {
353 /// if let Ok(string) = value.downcast::<String>() {
354 /// println!("String ({}): {}", string.len(), string);
355 /// }
356 /// }
357 ///
358 /// let my_string = "Hello World".to_string();
359 /// print_if_string(Box::new(my_string));
360 /// print_if_string(Box::new(0i8));
361 /// ```
362 #[inline]
363 #[stable(feature = "rust1", since = "1.0.0")]
364 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
365 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
366 }
367
368 /// Downcasts the box to a concrete type.
369 ///
370 /// For a safe alternative see [`downcast`].
371 ///
372 /// # Examples
373 ///
374 /// ```
375 /// #![feature(downcast_unchecked)]
376 ///
377 /// use std::any::Any;
378 ///
379 /// let x: Box<dyn Any> = Box::new(1_usize);
380 ///
381 /// unsafe {
382 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
383 /// }
384 /// ```
385 ///
386 /// # Safety
387 ///
388 /// The contained value must be of type `T`. Calling this method
389 /// with the incorrect type is *undefined behavior*.
390 ///
391 /// [`downcast`]: Self::downcast
392 #[inline]
393 #[unstable(feature = "downcast_unchecked", issue = "90850")]
394 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
395 debug_assert!(self.is::<T>());
396 unsafe {
397 let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
398 Box::from_raw_in(raw as *mut T, alloc)
399 }
400 }
401}
402
403impl<A: Allocator> Box<dyn Any + Send, A> {
404 /// Attempts to downcast the box to a concrete type.
405 ///
406 /// # Examples
407 ///
408 /// ```
409 /// use std::any::Any;
410 ///
411 /// fn print_if_string(value: Box<dyn Any + Send>) {
412 /// if let Ok(string) = value.downcast::<String>() {
413 /// println!("String ({}): {}", string.len(), string);
414 /// }
415 /// }
416 ///
417 /// let my_string = "Hello World".to_string();
418 /// print_if_string(Box::new(my_string));
419 /// print_if_string(Box::new(0i8));
420 /// ```
421 #[inline]
422 #[stable(feature = "rust1", since = "1.0.0")]
423 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
424 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
425 }
426
427 /// Downcasts the box to a concrete type.
428 ///
429 /// For a safe alternative see [`downcast`].
430 ///
431 /// # Examples
432 ///
433 /// ```
434 /// #![feature(downcast_unchecked)]
435 ///
436 /// use std::any::Any;
437 ///
438 /// let x: Box<dyn Any + Send> = Box::new(1_usize);
439 ///
440 /// unsafe {
441 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
442 /// }
443 /// ```
444 ///
445 /// # Safety
446 ///
447 /// The contained value must be of type `T`. Calling this method
448 /// with the incorrect type is *undefined behavior*.
449 ///
450 /// [`downcast`]: Self::downcast
451 #[inline]
452 #[unstable(feature = "downcast_unchecked", issue = "90850")]
453 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
454 debug_assert!(self.is::<T>());
455 unsafe {
456 let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
457 Box::from_raw_in(raw as *mut T, alloc)
458 }
459 }
460}
461
462impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
463 /// Attempts to downcast the box to a concrete type.
464 ///
465 /// # Examples
466 ///
467 /// ```
468 /// use std::any::Any;
469 ///
470 /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
471 /// if let Ok(string) = value.downcast::<String>() {
472 /// println!("String ({}): {}", string.len(), string);
473 /// }
474 /// }
475 ///
476 /// let my_string = "Hello World".to_string();
477 /// print_if_string(Box::new(my_string));
478 /// print_if_string(Box::new(0i8));
479 /// ```
480 #[inline]
481 #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
482 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
483 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
484 }
485
486 /// Downcasts the box to a concrete type.
487 ///
488 /// For a safe alternative see [`downcast`].
489 ///
490 /// # Examples
491 ///
492 /// ```
493 /// #![feature(downcast_unchecked)]
494 ///
495 /// use std::any::Any;
496 ///
497 /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
498 ///
499 /// unsafe {
500 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
501 /// }
502 /// ```
503 ///
504 /// # Safety
505 ///
506 /// The contained value must be of type `T`. Calling this method
507 /// with the incorrect type is *undefined behavior*.
508 ///
509 /// [`downcast`]: Self::downcast
510 #[inline]
511 #[unstable(feature = "downcast_unchecked", issue = "90850")]
512 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
513 debug_assert!(self.is::<T>());
514 unsafe {
515 let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
516 Box::into_raw_with_allocator(self);
517 Box::from_raw_in(raw as *mut T, alloc)
518 }
519 }
520}
521
522#[cfg(not(no_global_oom_handling))]
523#[stable(feature = "rust1", since = "1.0.0")]
524impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
525 /// Converts a type of [`Error`] into a box of dyn [`Error`].
526 ///
527 /// # Examples
528 ///
529 /// ```
530 /// use std::error::Error;
531 /// use std::fmt;
532 /// use std::mem;
533 ///
534 /// #[derive(Debug)]
535 /// struct AnError;
536 ///
537 /// impl fmt::Display for AnError {
538 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
539 /// write!(f, "An error")
540 /// }
541 /// }
542 ///
543 /// impl Error for AnError {}
544 ///
545 /// let an_error = AnError;
546 /// assert!(0 == mem::size_of_val(&an_error));
547 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
548 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
549 /// ```
550 fn from(err: E) -> Box<dyn Error + 'a> {
551 Box::new(err)
552 }
553}
554
555#[cfg(not(no_global_oom_handling))]
556#[stable(feature = "rust1", since = "1.0.0")]
557impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
558 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
559 /// dyn [`Error`] + [`Send`] + [`Sync`].
560 ///
561 /// # Examples
562 ///
563 /// ```
564 /// use std::error::Error;
565 /// use std::fmt;
566 /// use std::mem;
567 ///
568 /// #[derive(Debug)]
569 /// struct AnError;
570 ///
571 /// impl fmt::Display for AnError {
572 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
573 /// write!(f, "An error")
574 /// }
575 /// }
576 ///
577 /// impl Error for AnError {}
578 ///
579 /// unsafe impl Send for AnError {}
580 ///
581 /// unsafe impl Sync for AnError {}
582 ///
583 /// let an_error = AnError;
584 /// assert!(0 == mem::size_of_val(&an_error));
585 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
586 /// assert!(
587 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
588 /// ```
589 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
590 Box::new(err)
591 }
592}
593
594#[cfg(not(no_global_oom_handling))]
595#[stable(feature = "rust1", since = "1.0.0")]
596impl<'a> From<String> for Box<dyn Error + Send + Sync + 'a> {
597 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
598 ///
599 /// # Examples
600 ///
601 /// ```
602 /// use std::error::Error;
603 /// use std::mem;
604 ///
605 /// let a_string_error = "a string error".to_string();
606 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
607 /// assert!(
608 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
609 /// ```
610 #[inline]
611 fn from(err: String) -> Box<dyn Error + Send + Sync + 'a> {
612 struct StringError(String);
613
614 impl Error for StringError {
615 #[allow(deprecated)]
616 fn description(&self) -> &str {
617 &self.0
618 }
619 }
620
621 impl fmt::Display for StringError {
622 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
623 fmt::Display::fmt(&self.0, f)
624 }
625 }
626
627 // Purposefully skip printing "StringError(..)"
628 impl fmt::Debug for StringError {
629 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
630 fmt::Debug::fmt(&self.0, f)
631 }
632 }
633
634 Box::new(StringError(err))
635 }
636}
637
638#[cfg(not(no_global_oom_handling))]
639#[stable(feature = "string_box_error", since = "1.6.0")]
640impl<'a> From<String> for Box<dyn Error + 'a> {
641 /// Converts a [`String`] into a box of dyn [`Error`].
642 ///
643 /// # Examples
644 ///
645 /// ```
646 /// use std::error::Error;
647 /// use std::mem;
648 ///
649 /// let a_string_error = "a string error".to_string();
650 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
651 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
652 /// ```
653 fn from(str_err: String) -> Box<dyn Error + 'a> {
654 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
655 let err2: Box<dyn Error> = err1;
656 err2
657 }
658}
659
660#[cfg(not(no_global_oom_handling))]
661#[stable(feature = "rust1", since = "1.0.0")]
662impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
663 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
664 ///
665 /// [`str`]: prim@str
666 ///
667 /// # Examples
668 ///
669 /// ```
670 /// use std::error::Error;
671 /// use std::mem;
672 ///
673 /// let a_str_error = "a str error";
674 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
675 /// assert!(
676 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
677 /// ```
678 #[inline]
679 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
680 From::from(String::from(err))
681 }
682}
683
684#[cfg(not(no_global_oom_handling))]
685#[stable(feature = "string_box_error", since = "1.6.0")]
686impl<'a> From<&str> for Box<dyn Error + 'a> {
687 /// Converts a [`str`] into a box of dyn [`Error`].
688 ///
689 /// [`str`]: prim@str
690 ///
691 /// # Examples
692 ///
693 /// ```
694 /// use std::error::Error;
695 /// use std::mem;
696 ///
697 /// let a_str_error = "a str error";
698 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
699 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
700 /// ```
701 fn from(err: &str) -> Box<dyn Error + 'a> {
702 From::from(String::from(err))
703 }
704}
705
706#[cfg(not(no_global_oom_handling))]
707#[stable(feature = "cow_box_error", since = "1.22.0")]
708impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
709 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
710 ///
711 /// # Examples
712 ///
713 /// ```
714 /// use std::error::Error;
715 /// use std::mem;
716 /// use std::borrow::Cow;
717 ///
718 /// let a_cow_str_error = Cow::from("a str error");
719 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
720 /// assert!(
721 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
722 /// ```
723 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
724 From::from(String::from(err))
725 }
726}
727
728#[cfg(not(no_global_oom_handling))]
729#[stable(feature = "cow_box_error", since = "1.22.0")]
730impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + 'a> {
731 /// Converts a [`Cow`] into a box of dyn [`Error`].
732 ///
733 /// # Examples
734 ///
735 /// ```
736 /// use std::error::Error;
737 /// use std::mem;
738 /// use std::borrow::Cow;
739 ///
740 /// let a_cow_str_error = Cow::from("a str error");
741 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
742 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
743 /// ```
744 fn from(err: Cow<'b, str>) -> Box<dyn Error + 'a> {
745 From::from(String::from(err))
746 }
747}
748
749impl dyn Error {
750 /// Attempts to downcast the box to a concrete type.
751 #[inline]
752 #[stable(feature = "error_downcast", since = "1.3.0")]
753 #[rustc_allow_incoherent_impl]
754 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
755 if self.is::<T>() {
756 unsafe {
757 let raw: *mut dyn Error = Box::into_raw(self);
758 Ok(Box::from_raw(raw as *mut T))
759 }
760 } else {
761 Err(self)
762 }
763 }
764}
765
766impl dyn Error + Send {
767 /// Attempts to downcast the box to a concrete type.
768 #[inline]
769 #[stable(feature = "error_downcast", since = "1.3.0")]
770 #[rustc_allow_incoherent_impl]
771 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
772 let err: Box<dyn Error> = self;
773 <dyn Error>::downcast(err).map_err(|s| unsafe {
774 // Reapply the `Send` marker.
775 mem::transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
776 })
777 }
778}
779
780impl dyn Error + Send + Sync {
781 /// Attempts to downcast the box to a concrete type.
782 #[inline]
783 #[stable(feature = "error_downcast", since = "1.3.0")]
784 #[rustc_allow_incoherent_impl]
785 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
786 let err: Box<dyn Error> = self;
787 <dyn Error>::downcast(err).map_err(|s| unsafe {
788 // Reapply the `Send + Sync` markers.
789 mem::transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
790 })
791 }
792}