Hy,
I did recently read how the from_box
for Arc
is implemented,
mainly how it is implemented for DST since rust 1.21 (link to std src).
And I'm wondering about a few parts. First is how size_of_val
actually works. (It's a compiler intrinsic which can determine the
size of a dynamic typed value at runtime).
If I would guess it either magically knows about the two types of
DST pointers (pointer+size / pointer+vtable) or it asks the
allocator about the size of the memory slice allocated in
for the given ptr (or correct the slicee size minus the offset
of the pointer to the start of the slice ). Not sure if the later
is even possible. And if it is the former will there be a
mechanism in the future to "tell" rust the size for
less usual DST's?.
Also from the way pointers to ArcInner
are handled
I guess that a pointers to a "wrapper"/"composition"
DST like ArcInner
will automatiacally be fatpointer
of the same structure (and with the same meta data)
than a pointer to the structs only DST field?
Is there a way to tell the compiler "no do not store/keep
the meta information for this DST field and just have
thin pointers to me". E.g. if I have a lot of references
to a small amount of slices I seldom access moving
the slice length into the slice through a wrapper
type containing a filed with the length and a DST
field with the slice could be a nice memory
optimization.
Lastly how can Layout::from_val
work even
through we give it a reference to ArcInner
from a pointer which we "just" casted from
*const T
to *mut ArcInner<T>
...
I mean the fake ptr points to a struct
which is smaller by the size of two
atomic counters and their padding..
Wups, that's a lot of text so thanks
for reading it and more so for
answering it
EDIT:
thinks which I think I now how they work now:
- fat ptr to a struct containing a DST seem use the same type of fat ptr and the same "meta data" as the DST they contain
-
size_of_val
(and in extensionLayout
) seem know about the different types of fat pointers and use (only) the fat pointers meta data to determine the size - in extension to 1. this means that the size in a ptr to a containing a slice is the size of the slice, not the struct, is kinda obvious if spelled out, but it explains why
Layout::from_val
works with a "wrong" pointer (*mut T as *mut ArcInner<T>
) as it "just" uses metadata, which will stay the same.
EDIT2:
I wasn't clear about it, but a lot of the DST talk is about DST which should be possible in future rust but aren't really now, through then even in nightly rust you can't create a DST without relying on compiler implementation details (mainly that the first usize integer of a fat pointer is the pointer to the underlying data)