Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add unsizing for {Arc,Rc}Box
To avoid the unstable traits this uses a helper crate that provides the
necessary checks and mechanisms for the raw pointer conversion while
opting into them via a trait implemented for the smart pointers here.
  • Loading branch information
197g committed Apr 15, 2021
commit 91d57b893fa335650ff7000eb0999efd00ee941c
10 changes: 10 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions crates/rc-box/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,7 @@ slice-dst = { version = "1.4.0", optional = true }
version = "1.0.0"
path = "../erasable"
optional = true

[dependencies.unsize]
version = "1.1"
optional = true
44 changes: 44 additions & 0 deletions crates/rc-box/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -634,6 +634,50 @@ then the data will be pinned in memory and unable to be moved."),

#[cfg(feature = "std")]
impl<T: ?Sized> UnwindSafe for $RcBox<T> where Box<T>: UnwindSafe {}

#[cfg(feature = "unsize")]
doc_comment! {
concat!("Unsizes a pointer using the `unsize` crate.
# Usage

```
# use rc_box::*;
use unsize::{Coercion, CoerceUnsize};

let unique = ", stringify!($RcBox), "::new(|| 42u32);
let unique:", stringify!($RcBox), r"<dyn Fn() -> u32> =
unique.unsize(Coercion::<_, dyn Fn() -> u32>::to_fn());

let value = (*unique)();
assert_eq!(value, 42);
```

Another common usage would be to create an `dyn Any`.

fn print_if_string(value: ", stringify!($RcBox), r#"<dyn Any>) {
if let Ok(string) = value.downcast::<String>() {
println!("String ({}): {}", string.len(), string);
}
}

let my_string = "Hello World".to_string();
let my_string: "#, stringify!($RcBox), "<dyn Any> = ", stringify!($RcBox), "::new(my_string).unsize(Coercion::to_any());
print_if_string(my_string);
let my_number: ", stringify!($RcBox), "<dyn Any> = ", stringify!($RcBox), "::new(0i8).unsize(Coercion::to_any());
print_if_string(my_number);
```"),
unsafe impl<T, U: ?Sized> unsize::CoerciblePtr<U> for $RcBox<T> {
type Pointee = T;
type Output = $RcBox<U>;
fn as_sized_ptr(&mut self) -> *mut T {
$RcBox::as_raw(self).as_ptr()
}
unsafe fn replace_ptr(self, new: *mut U) -> $RcBox<U> {
let new = $RcBox::into_raw(self).replace_ptr(new);
$RcBox::from_raw(new.as_ptr() as *const U)
}
}
}
)*};
}

Expand Down