Skip to main content

alloc/boxed/
convert.rs

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