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    ///
533    /// #[derive(Debug)]
534    /// struct AnError;
535    ///
536    /// impl fmt::Display for AnError {
537    ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
538    ///         write!(f, "An error")
539    ///     }
540    /// }
541    ///
542    /// impl Error for AnError {}
543    ///
544    /// let an_error = AnError;
545    /// assert!(0 == size_of_val(&an_error));
546    /// let a_boxed_error = Box::<dyn Error>::from(an_error);
547    /// assert!(size_of::<Box<dyn Error>>() == size_of_val(&a_boxed_error))
548    /// ```
549    fn from(err: E) -> Box<dyn Error + 'a> {
550        Box::new(err)
551    }
552}
553
554#[cfg(not(no_global_oom_handling))]
555#[stable(feature = "rust1", since = "1.0.0")]
556impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
557    /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
558    /// dyn [`Error`] + [`Send`] + [`Sync`].
559    ///
560    /// # Examples
561    ///
562    /// ```
563    /// use std::error::Error;
564    /// use std::fmt;
565    ///
566    /// #[derive(Debug)]
567    /// struct AnError;
568    ///
569    /// impl fmt::Display for AnError {
570    ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571    ///         write!(f, "An error")
572    ///     }
573    /// }
574    ///
575    /// impl Error for AnError {}
576    ///
577    /// unsafe impl Send for AnError {}
578    ///
579    /// unsafe impl Sync for AnError {}
580    ///
581    /// let an_error = AnError;
582    /// assert!(0 == size_of_val(&an_error));
583    /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
584    /// assert!(
585    ///     size_of::<Box<dyn Error + Send + Sync>>() == size_of_val(&a_boxed_error))
586    /// ```
587    fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
588        Box::new(err)
589    }
590}
591
592#[cfg(not(no_global_oom_handling))]
593#[stable(feature = "rust1", since = "1.0.0")]
594impl<'a> From<String> for Box<dyn Error + Send + Sync + 'a> {
595    /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
596    ///
597    /// # Examples
598    ///
599    /// ```
600    /// use std::error::Error;
601    ///
602    /// let a_string_error = "a string error".to_string();
603    /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
604    /// assert!(
605    ///     size_of::<Box<dyn Error + Send + Sync>>() == size_of_val(&a_boxed_error))
606    /// ```
607    #[inline]
608    fn from(err: String) -> Box<dyn Error + Send + Sync + 'a> {
609        struct StringError(String);
610
611        impl Error for StringError {
612            #[allow(deprecated)]
613            fn description(&self) -> &str {
614                &self.0
615            }
616        }
617
618        impl fmt::Display for StringError {
619            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
620                fmt::Display::fmt(&self.0, f)
621            }
622        }
623
624        // Purposefully skip printing "StringError(..)"
625        impl fmt::Debug for StringError {
626            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627                fmt::Debug::fmt(&self.0, f)
628            }
629        }
630
631        Box::new(StringError(err))
632    }
633}
634
635#[cfg(not(no_global_oom_handling))]
636#[stable(feature = "string_box_error", since = "1.6.0")]
637impl<'a> From<String> for Box<dyn Error + 'a> {
638    /// Converts a [`String`] into a box of dyn [`Error`].
639    ///
640    /// # Examples
641    ///
642    /// ```
643    /// use std::error::Error;
644    ///
645    /// let a_string_error = "a string error".to_string();
646    /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
647    /// assert!(size_of::<Box<dyn Error>>() == size_of_val(&a_boxed_error))
648    /// ```
649    fn from(str_err: String) -> Box<dyn Error + 'a> {
650        let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
651        let err2: Box<dyn Error> = err1;
652        err2
653    }
654}
655
656#[cfg(not(no_global_oom_handling))]
657#[stable(feature = "rust1", since = "1.0.0")]
658impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
659    /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
660    ///
661    /// [`str`]: prim@str
662    ///
663    /// # Examples
664    ///
665    /// ```
666    /// use std::error::Error;
667    ///
668    /// let a_str_error = "a str error";
669    /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
670    /// assert!(
671    ///     size_of::<Box<dyn Error + Send + Sync>>() == size_of_val(&a_boxed_error))
672    /// ```
673    #[inline]
674    fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
675        From::from(String::from(err))
676    }
677}
678
679#[cfg(not(no_global_oom_handling))]
680#[stable(feature = "string_box_error", since = "1.6.0")]
681impl<'a> From<&str> for Box<dyn Error + 'a> {
682    /// Converts a [`str`] into a box of dyn [`Error`].
683    ///
684    /// [`str`]: prim@str
685    ///
686    /// # Examples
687    ///
688    /// ```
689    /// use std::error::Error;
690    ///
691    /// let a_str_error = "a str error";
692    /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
693    /// assert!(size_of::<Box<dyn Error>>() == size_of_val(&a_boxed_error))
694    /// ```
695    fn from(err: &str) -> Box<dyn Error + 'a> {
696        From::from(String::from(err))
697    }
698}
699
700#[cfg(not(no_global_oom_handling))]
701#[stable(feature = "cow_box_error", since = "1.22.0")]
702impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
703    /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
704    ///
705    /// # Examples
706    ///
707    /// ```
708    /// use std::error::Error;
709    /// use std::borrow::Cow;
710    ///
711    /// let a_cow_str_error = Cow::from("a str error");
712    /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
713    /// assert!(
714    ///     size_of::<Box<dyn Error + Send + Sync>>() == size_of_val(&a_boxed_error))
715    /// ```
716    fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
717        From::from(String::from(err))
718    }
719}
720
721#[cfg(not(no_global_oom_handling))]
722#[stable(feature = "cow_box_error", since = "1.22.0")]
723impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + 'a> {
724    /// Converts a [`Cow`] into a box of dyn [`Error`].
725    ///
726    /// # Examples
727    ///
728    /// ```
729    /// use std::error::Error;
730    /// use std::borrow::Cow;
731    ///
732    /// let a_cow_str_error = Cow::from("a str error");
733    /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
734    /// assert!(size_of::<Box<dyn Error>>() == size_of_val(&a_boxed_error))
735    /// ```
736    fn from(err: Cow<'b, str>) -> Box<dyn Error + 'a> {
737        From::from(String::from(err))
738    }
739}
740
741impl dyn Error {
742    /// Attempts to downcast the box to a concrete type.
743    #[inline]
744    #[stable(feature = "error_downcast", since = "1.3.0")]
745    #[rustc_allow_incoherent_impl]
746    pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
747        if self.is::<T>() {
748            unsafe {
749                let raw: *mut dyn Error = Box::into_raw(self);
750                Ok(Box::from_raw(raw as *mut T))
751            }
752        } else {
753            Err(self)
754        }
755    }
756}
757
758impl dyn Error + Send {
759    /// Attempts to downcast the box to a concrete type.
760    #[inline]
761    #[stable(feature = "error_downcast", since = "1.3.0")]
762    #[rustc_allow_incoherent_impl]
763    pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
764        let err: Box<dyn Error> = self;
765        <dyn Error>::downcast(err).map_err(|s| unsafe {
766            // Reapply the `Send` marker.
767            mem::transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
768        })
769    }
770}
771
772impl dyn Error + Send + Sync {
773    /// Attempts to downcast the box to a concrete type.
774    #[inline]
775    #[stable(feature = "error_downcast", since = "1.3.0")]
776    #[rustc_allow_incoherent_impl]
777    pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
778        let err: Box<dyn Error> = self;
779        <dyn Error>::downcast(err).map_err(|s| unsafe {
780            // Reapply the `Send + Sync` markers.
781            mem::transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
782        })
783    }
784}