How to create a DST type?

DST (Dynamicically Sized Types) is now available in Rust. I used them successfully, with a flexible last member known to the compiler (for example, [u8] ).

However, I want to create a custom DST. Say for example:

 struct Known<S> { dropit: fn (&mut S) -> (), data: S, } struct Unknown { dropit: fn (&mut ()) -> (), data: (), } 

With the expected use of Box<Known<S>> => Box<Unknown> => Box<Known<S>> , where the middleware does not need to know the specific types.

Note: yes, I know about Any , and no, I'm not interested in using it.

I am open to suggestions in the layout of both Known and Unknown , however:

  • size_of::<Box<Known>>() = size_of::<Box<Unknown>>() = size_of::<Box<u32>>() ; that is, it must be a thin pointer.
  • dropping Box<Unknown> reduces its contents
  • cloning Box<Unknown> (assuming the cloned S ), clones its contents
  • Ideally, fn dup(u: &Unknown) -> Box<Unknown> { box u.clone() } works

I have special difficulties with (3) and (4), I could solve (3) with manual memory allocation (not using box , but directly calling malloc ), but I would prefer to provide an idiomatic experience for the user.

I could not find the documentation on how to tell the box right size to place.

+7
rust
source share
1 answer

Currently, there are exactly two types of non-serialized objects: slices ( [T] ), where it adds an element of length; and object objects ( Trait , Trait + Send , & c.), where it adds a vtable, including a destructor that knows how large the object is being freed.

There is currently no mechanism for declaring your own variety of uncertified objects.

+3
source share

All Articles