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 /// For allocation behavior, see [`Vec::into_boxed_slice`].
287 ///
288 /// # Errors
289 ///
290 /// Returns the original `Vec<T>` in the `Err` variant if
291 /// `vec.len()` does not equal `N`.
292 ///
293 /// # Examples
294 ///
295 /// This can be used with [`vec!`] to create an array on the heap:
296 ///
297 /// ```
298 /// let state: Box<[f32; 100]> = vec![1.0; 100].try_into().unwrap();
299 /// assert_eq!(state.len(), 100);
300 /// ```
301 fn try_from(vec: Vec<T, A>) -> Result<Self, Self::Error> {
302 if vec.len() == N {
303 let boxed_slice = vec.into_boxed_slice();
304 // SAFETY: Checked length.
305 Ok(unsafe { boxed_slice_as_array_unchecked(boxed_slice) })
306 } else {
307 Err(vec)
308 }
309 }
310}
311
312impl<T: ?Sized + 'static, A: Allocator> Box<T, A> {
313 fn downcast_any<Dst: 'static>(this: Self) -> Result<Box<Dst, A>, Self> {
314 if T::type_id(&this) == core::any::TypeId::of::<Dst>() {
315 // SAFETY: The type is correct
316 Ok(unsafe { Self::cast_unchecked(this) })
317 } else {
318 Err(this)
319 }
320 }
321}
322impl<T: ?Sized, A: Allocator> Box<T, A> {
323 /// Casts a box by converting to a raw pointer and back, whatever that means
324 /// in the given context.
325 unsafe fn cast_unchecked<Dst>(this: Self) -> Box<Dst, A> {
326 // SAFETY: Caller ensures the cast is correct
327 unsafe {
328 let (raw, alloc) = Box::into_raw_with_allocator(this);
329 Box::from_raw_in(raw.cast(), alloc)
330 }
331 }
332}
333
334impl<A: Allocator> Box<dyn Any, A> {
335 /// Attempts to downcast the box to a concrete type.
336 ///
337 /// # Examples
338 ///
339 /// ```
340 /// use std::any::Any;
341 ///
342 /// fn print_if_string(value: Box<dyn Any>) {
343 /// if let Ok(string) = value.downcast::<String>() {
344 /// println!("String ({}): {}", string.len(), string);
345 /// }
346 /// }
347 ///
348 /// let my_string = "Hello World".to_string();
349 /// print_if_string(Box::new(my_string));
350 /// print_if_string(Box::new(0i8));
351 /// ```
352 #[inline]
353 #[stable(feature = "rust1", since = "1.0.0")]
354 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
355 Self::downcast_any(self)
356 }
357
358 /// Downcasts the box to a concrete type.
359 ///
360 /// For a safe alternative see [`downcast`].
361 ///
362 /// # Examples
363 ///
364 /// ```
365 /// #![feature(downcast_unchecked)]
366 ///
367 /// use std::any::Any;
368 ///
369 /// let x: Box<dyn Any> = Box::new(1_usize);
370 ///
371 /// unsafe {
372 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
373 /// }
374 /// ```
375 ///
376 /// # Safety
377 ///
378 /// The contained value must be of type `T`. Calling this method
379 /// with the incorrect type is *undefined behavior*.
380 ///
381 /// [`downcast`]: Self::downcast
382 #[inline]
383 #[unstable(feature = "downcast_unchecked", issue = "90850")]
384 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
385 debug_assert!(self.is::<T>());
386 // SAFETY: Caller ensures the type is correct.
387 unsafe { Self::cast_unchecked(self) }
388 }
389}
390
391impl<A: Allocator> Box<dyn Any + Send, A> {
392 /// Attempts to downcast the box to a concrete type.
393 ///
394 /// # Examples
395 ///
396 /// ```
397 /// use std::any::Any;
398 ///
399 /// fn print_if_string(value: Box<dyn Any + Send>) {
400 /// if let Ok(string) = value.downcast::<String>() {
401 /// println!("String ({}): {}", string.len(), string);
402 /// }
403 /// }
404 ///
405 /// let my_string = "Hello World".to_string();
406 /// print_if_string(Box::new(my_string));
407 /// print_if_string(Box::new(0i8));
408 /// ```
409 #[inline]
410 #[stable(feature = "rust1", since = "1.0.0")]
411 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
412 Self::downcast_any(self)
413 }
414
415 /// Downcasts the box to a concrete type.
416 ///
417 /// For a safe alternative see [`downcast`].
418 ///
419 /// # Examples
420 ///
421 /// ```
422 /// #![feature(downcast_unchecked)]
423 ///
424 /// use std::any::Any;
425 ///
426 /// let x: Box<dyn Any + Send> = Box::new(1_usize);
427 ///
428 /// unsafe {
429 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
430 /// }
431 /// ```
432 ///
433 /// # Safety
434 ///
435 /// The contained value must be of type `T`. Calling this method
436 /// with the incorrect type is *undefined behavior*.
437 ///
438 /// [`downcast`]: Self::downcast
439 #[inline]
440 #[unstable(feature = "downcast_unchecked", issue = "90850")]
441 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
442 debug_assert!(self.is::<T>());
443 // SAFETY: Caller ensures the type is correct.
444 unsafe { Self::cast_unchecked(self) }
445 }
446}
447
448impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
449 /// Attempts to downcast the box to a concrete type.
450 ///
451 /// # Examples
452 ///
453 /// ```
454 /// use std::any::Any;
455 ///
456 /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
457 /// if let Ok(string) = value.downcast::<String>() {
458 /// println!("String ({}): {}", string.len(), string);
459 /// }
460 /// }
461 ///
462 /// let my_string = "Hello World".to_string();
463 /// print_if_string(Box::new(my_string));
464 /// print_if_string(Box::new(0i8));
465 /// ```
466 #[inline]
467 #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
468 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
469 Self::downcast_any(self)
470 }
471
472 /// Downcasts the box to a concrete type.
473 ///
474 /// For a safe alternative see [`downcast`].
475 ///
476 /// # Examples
477 ///
478 /// ```
479 /// #![feature(downcast_unchecked)]
480 ///
481 /// use std::any::Any;
482 ///
483 /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
484 ///
485 /// unsafe {
486 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
487 /// }
488 /// ```
489 ///
490 /// # Safety
491 ///
492 /// The contained value must be of type `T`. Calling this method
493 /// with the incorrect type is *undefined behavior*.
494 ///
495 /// [`downcast`]: Self::downcast
496 #[inline]
497 #[unstable(feature = "downcast_unchecked", issue = "90850")]
498 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
499 debug_assert!(self.is::<T>());
500 // SAFETY: Caller ensures the type is correct.
501 unsafe { Self::cast_unchecked(self) }
502 }
503}
504
505#[cfg(not(no_global_oom_handling))]
506#[stable(feature = "rust1", since = "1.0.0")]
507impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
508 /// Converts a type of [`Error`] into a box of dyn [`Error`].
509 ///
510 /// # Examples
511 ///
512 /// ```
513 /// use std::error::Error;
514 /// use std::fmt;
515 ///
516 /// #[derive(Debug)]
517 /// struct AnError;
518 ///
519 /// impl fmt::Display for AnError {
520 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
521 /// write!(f, "An error")
522 /// }
523 /// }
524 ///
525 /// impl Error for AnError {}
526 ///
527 /// let an_error = AnError;
528 /// assert!(0 == size_of_val(&an_error));
529 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
530 /// assert!(size_of::<Box<dyn Error>>() == size_of_val(&a_boxed_error))
531 /// ```
532 fn from(err: E) -> Box<dyn Error + 'a> {
533 Box::new(err)
534 }
535}
536
537#[cfg(not(no_global_oom_handling))]
538#[stable(feature = "rust1", since = "1.0.0")]
539impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
540 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
541 /// dyn [`Error`] + [`Send`] + [`Sync`].
542 ///
543 /// # Examples
544 ///
545 /// ```
546 /// use std::error::Error;
547 /// use std::fmt;
548 ///
549 /// #[derive(Debug)]
550 /// struct AnError;
551 ///
552 /// impl fmt::Display for AnError {
553 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
554 /// write!(f, "An error")
555 /// }
556 /// }
557 ///
558 /// impl Error for AnError {}
559 ///
560 /// unsafe impl Send for AnError {}
561 ///
562 /// unsafe impl Sync for AnError {}
563 ///
564 /// let an_error = AnError;
565 /// assert!(0 == size_of_val(&an_error));
566 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
567 /// assert!(
568 /// size_of::<Box<dyn Error + Send + Sync>>() == size_of_val(&a_boxed_error))
569 /// ```
570 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
571 Box::new(err)
572 }
573}
574
575#[cfg(not(no_global_oom_handling))]
576#[stable(feature = "rust1", since = "1.0.0")]
577impl<'a> From<String> for Box<dyn Error + Send + Sync + 'a> {
578 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
579 ///
580 /// # Examples
581 ///
582 /// ```
583 /// use std::error::Error;
584 ///
585 /// let a_string_error = "a string error".to_string();
586 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
587 /// assert!(
588 /// size_of::<Box<dyn Error + Send + Sync>>() == size_of_val(&a_boxed_error))
589 /// ```
590 #[inline]
591 fn from(err: String) -> Box<dyn Error + Send + Sync + 'a> {
592 struct StringError(String);
593
594 impl Error for StringError {}
595
596 impl fmt::Display for StringError {
597 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
598 fmt::Display::fmt(&self.0, f)
599 }
600 }
601
602 // Purposefully skip printing "StringError(..)"
603 impl fmt::Debug for StringError {
604 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
605 fmt::Debug::fmt(&self.0, f)
606 }
607 }
608
609 Box::new(StringError(err))
610 }
611}
612
613#[cfg(not(no_global_oom_handling))]
614#[stable(feature = "string_box_error", since = "1.6.0")]
615impl<'a> From<String> for Box<dyn Error + 'a> {
616 /// Converts a [`String`] into a box of dyn [`Error`].
617 ///
618 /// # Examples
619 ///
620 /// ```
621 /// use std::error::Error;
622 ///
623 /// let a_string_error = "a string error".to_string();
624 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
625 /// assert!(size_of::<Box<dyn Error>>() == size_of_val(&a_boxed_error))
626 /// ```
627 fn from(str_err: String) -> Box<dyn Error + 'a> {
628 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
629 let err2: Box<dyn Error> = err1;
630 err2
631 }
632}
633
634#[cfg(not(no_global_oom_handling))]
635#[stable(feature = "rust1", since = "1.0.0")]
636impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
637 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
638 ///
639 /// [`str`]: prim@str
640 ///
641 /// # Examples
642 ///
643 /// ```
644 /// use std::error::Error;
645 ///
646 /// let a_str_error = "a str error";
647 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
648 /// assert!(
649 /// size_of::<Box<dyn Error + Send + Sync>>() == size_of_val(&a_boxed_error))
650 /// ```
651 #[inline]
652 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
653 From::from(String::from(err))
654 }
655}
656
657#[cfg(not(no_global_oom_handling))]
658#[stable(feature = "string_box_error", since = "1.6.0")]
659impl<'a> From<&str> for Box<dyn Error + 'a> {
660 /// Converts a [`str`] into a box of dyn [`Error`].
661 ///
662 /// [`str`]: prim@str
663 ///
664 /// # Examples
665 ///
666 /// ```
667 /// use std::error::Error;
668 ///
669 /// let a_str_error = "a str error";
670 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
671 /// assert!(size_of::<Box<dyn Error>>() == size_of_val(&a_boxed_error))
672 /// ```
673 fn from(err: &str) -> Box<dyn Error + 'a> {
674 From::from(String::from(err))
675 }
676}
677
678#[cfg(not(no_global_oom_handling))]
679#[stable(feature = "cow_box_error", since = "1.22.0")]
680impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
681 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
682 ///
683 /// # Examples
684 ///
685 /// ```
686 /// use std::error::Error;
687 /// use std::borrow::Cow;
688 ///
689 /// let a_cow_str_error = Cow::from("a str error");
690 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
691 /// assert!(
692 /// size_of::<Box<dyn Error + Send + Sync>>() == size_of_val(&a_boxed_error))
693 /// ```
694 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
695 From::from(String::from(err))
696 }
697}
698
699#[cfg(not(no_global_oom_handling))]
700#[stable(feature = "cow_box_error", since = "1.22.0")]
701impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + 'a> {
702 /// Converts a [`Cow`] into a box of dyn [`Error`].
703 ///
704 /// # Examples
705 ///
706 /// ```
707 /// use std::error::Error;
708 /// use std::borrow::Cow;
709 ///
710 /// let a_cow_str_error = Cow::from("a str error");
711 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
712 /// assert!(size_of::<Box<dyn Error>>() == size_of_val(&a_boxed_error))
713 /// ```
714 fn from(err: Cow<'b, str>) -> Box<dyn Error + 'a> {
715 From::from(String::from(err))
716 }
717}
718
719impl<T: Error + ?Sized + 'static, A: Allocator> Box<T, A> {
720 fn downcast_error<Dst: 'static>(this: Self) -> Result<Box<Dst, A>, Self> {
721 if core::error::error_type_id::<T>(&this) == core::any::TypeId::of::<Dst>() {
722 // SAFETY: The type is correct
723 Ok(unsafe { Self::cast_unchecked(this) })
724 } else {
725 Err(this)
726 }
727 }
728}
729
730impl dyn Error {
731 /// Attempts to downcast the box to a concrete type.
732 #[inline]
733 #[stable(feature = "error_downcast", since = "1.3.0")]
734 #[rustc_allow_incoherent_impl]
735 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
736 Box::downcast_error(self)
737 }
738}
739
740impl dyn Error + Send {
741 /// Attempts to downcast the box to a concrete type.
742 #[inline]
743 #[stable(feature = "error_downcast", since = "1.3.0")]
744 #[rustc_allow_incoherent_impl]
745 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
746 Box::downcast_error(self)
747 }
748}
749
750impl dyn Error + Send + Sync {
751 /// Attempts to downcast the box to a concrete type.
752 #[inline]
753 #[stable(feature = "error_downcast", since = "1.3.0")]
754 #[rustc_allow_incoherent_impl]
755 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
756 Box::downcast_error(self)
757 }
758}