serde_traitobject icon indicating copy to clipboard operation
serde_traitobject copied to clipboard

I need s_to::Box into_raw, from_raw and from Box<dyn .. >

Open TrionProg opened this issue 4 years ago • 3 comments

Hello. I need to use raw pointers for optimization(to avoid incrementation of ref counter). I need to serialize *const dyn MyTrait almost as Box<dyn MyTrait>. That is why I create Box<dyn MyTrait> via from_raw, and not I need to convert it to s_to::Box<dyn MyTrait>, serialize and later mem::forget

TrionProg avatar Jan 22 '20 21:01 TrionProg

Serializing a trait object without boxing it is possible, see here for an example: https://github.com/alecmocatta/serde_traitobject/blob/d1a59ffa47f8945976cafb1f86ed9703dd96acac/tests/test.rs#L77-L81

Though that doesn't work for deserializing, which does need to create a Box.

alecmocatta avatar Jan 22 '20 22:01 alecmocatta

Thank you for example but:

Though that doesn't work for deserializing, which does need to create a Box.

Is not good for me.

I've added several lines:

impl<T: ?Sized> Box<T> {
	/// Convert to a regular `std::Boxed::Box<T>`. Coherence rules prevent currently prevent `impl Into<std::boxed::Box<T>> for Box<T>`.
	pub fn into_box(self) -> boxed::Box<T> {
		self.0
	}

	pub fn from_box(inner: boxed::Box<T> ) -> Self {
		Self(inner)
	}

	pub unsafe fn from_raw(raw: *mut T) -> Self {
        Self(boxed::Box::from_raw(raw))
    }

    pub fn into_raw(self) -> *mut T {
        boxed::Box::into_raw(self.0)
    }
}

TrionProg avatar Jan 23 '20 02:01 TrionProg

Ah, I see what you mean. I think this is possible without adding any lines:

// from raw to st::Box
let raw: *mut T = ...;
let st_box: st::Box<T> = std::boxed::Box::from_raw(raw).into();
// from st::Box to raw
let st_box: st::Box<T> = ...;
let raw = std::boxed::Box::into_raw(box.into_box());

But I'd be happy to accept a PR adding these (or any other of Box/Rc/Arc's methods)!

alecmocatta avatar Jan 24 '20 10:01 alecmocatta