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