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