derive_dst
Provides #[derive(DST)] for #[repr(C)] structs whose last field is an unsized slice
([T]) — the usual way to mirror a C/C++ "flexible array member" struct such as
SP_DEVICE_INTERFACE_DETAIL_DATA_W.
Why
The nomicon finishes the section on DSTs with the honest statement
(Yes, custom DSTs are a largely half-baked feature for now.)
and yet, various ffi functions make use of them.
Often this is to provide a filepath or other
string as the final field (e.g. SP_DEVICE_INTERFACE_DETAIL_DATA_W on Windows,
inotify_event on linux). Even with null-terminated strings, you still need to
allocate a buffer in advance. Sometimes it's a dynamically-sized tail of structured data
(e.g. fiemap on linux).
So do you:
- make a developer-time guess and hope your buffer is always big enough, wasting any oversizing
on every call, or ...
- find a way to allocate a DST at runtime, when you know the exact size needed?
What you get
The case which gave me the pattern for this macro:
#![feature(ptr_metadata)]
use std::io;
use derive_dst::DST;
#[repr(C)]
#[derive(Debug, DST)]
#[allow(nonstandard_style, reason = "mirroring FFI struct")]
pub struct DeviceDetails {
cbSize: u32,
DevicePath: [u16],
}
impl DeviceDetails {
pub fn new(size: usize) -> io::Result<Box<Self>> {
let (mut raw, (layout, tail_offset, _tail_count)) =
Self::new_uninit_for_size(size).map_err(io::Error::other)?;
if layout.size() != size {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"invalid buffer size",
));
}
let cbsize = (tail_offset + size_of::<u16>()).next_multiple_of(layout.align());
raw.cbSize.write(cbsize as u32);
let valid = unsafe { raw.assume_init() };
Ok(valid)
}
}
Behind the scenes this generates (an import-collision-safe version of).
The doc-comments are included in the generated code, so you can read them locally and in IDE
#[repr(C)]
#[allow(nonstandard_style, reason = "mirroring FFI struct")]
#[derive(Debug)]
struct UninitDeviceDetails
where
u16: Sized,
[u16]: Pointee<Metadata = usize>,
{
cbSize: MaybeUninit<u32>,
DevicePath: [MaybeUninit<u16>],
}
impl DeviceDetails
where
u16: Sized,
[u16]: Pointee<Metadata = usize>,
{
fn new_uninit_for_size(
size: usize,
) -> Result<
(
Box<UninitDeviceDetails>,
(Layout, usize, <[u16] as Pointee>::Metadata),
),
LayoutError,
> {
unsafe { Result::Ok(Self::new_uninit_for(Self::layout_for_size(size)?)) }
}
fn new_uninit_for_count(
count: <[u16] as Pointee>::Metadata,
) -> Result<
(
Box<UninitDeviceDetails>,
(Layout, usize, <[u16] as Pointee>::Metadata),
),
LayoutError,
> {
unsafe { Result::Ok(Self::new_uninit_for(Self::layout_for_count(count)?)) }
}
unsafe fn new_uninit_for(
(layout, offset, count): (Layout, usize, <[u16] as Pointee>::Metadata),
) -> (
Box<UninitDeviceDetails>,
(Layout, usize, <[u16] as Pointee>::Metadata),
) {
let raw = match Global::allocate_zeroed(&Global, layout) {
Result::Ok(pointer) => pointer,
Result::Err(_) => alloc::handle_alloc_error(layout),
};
let wide = ptr::from_raw_parts_mut::<UninitDeviceDetails>(raw.cast::<()>().as_ptr(), count);
let boxed = unsafe { Box::from_raw(wide) };
(boxed, (layout, offset, count))
}
fn layout_for_size(
size: usize,
) -> Result<(Layout, usize, <[u16] as Pointee>::Metadata), LayoutError> {
let header = Self::layout_header()?;
let elem_size = size_of::<u16>();
let tail_bytes = size.saturating_sub(header.size());
let count: <[u16] as Pointee>::Metadata = tail_bytes.checked_div(elem_size).unwrap_or(0);
Self::extend_with_tail(header, count)
}
fn layout_for_count(
count: <[u16] as Pointee>::Metadata,
) -> Result<(Layout, usize, <[u16] as Pointee>::Metadata), LayoutError> {
Self::extend_with_tail(Self::layout_header()?, count)
}
fn layout_header() -> Result<Layout, LayoutError> {
let mut prefix = Layout::new::<()>();
prefix = prefix.extend(Layout::new::<u32>())?.0;
Result::Ok(prefix)
}
fn extend_with_tail(
header: Layout,
count: <[u16] as Pointee>::Metadata,
) -> Result<(Layout, usize, <[u16] as Pointee>::Metadata), LayoutError> {
let tail = Layout::array::<u16>(count)?;
let (extended, offset) = header.extend(tail)?;
Result::Ok((extended.pad_to_align(), offset, count))
}
}
impl UninitDeviceDetails
where
u16: Sized,
[u16]: Pointee<Metadata = usize>,
{
unsafe fn assume_init(self: Box<Self>) -> Box<DeviceDetails> {
let raw = Box::into_raw(self);
let wide = ptr::from_raw_parts_mut::<DeviceDetails>(raw.cast::<()>(), ptr::metadata(raw));
unsafe { Box::from_raw(wide) }
}
}
Requirements
- Nightly toolchain (and
feature(ptr_metadata) not forbidden in config.toml)
#![feature(ptr_metadata)]
- DST must:
- be
#[repr(C)], no additional alignment or packing specification
- have a single` unsized field as the tail (last field) as per the nomicon
- have a slice
[T] as the unsized tail
SAFETY
We take extreme care to catch as many incorrect usages as possible at compile-time. Deliberately
or accidentally circumventing the above requirements will most likely lead to UB.
We recommend you build the docs locally via cargo doc --document-private-items to review the
requirements for assume_init
The UninitMirror type is zero-initialised and not guaranteed to be valid. All fields must
be suitably initialised, including all elements of the tail slice, before calling
assume_init.
Alternatives
- Hand-roll your own DSTs using the same pattern (if you do, please star the repo on github so I know it's useful)
- If you don't have an API that can report the required size at runtime and need to trial-and-error
grob handles growable buffers
- Create a fixed, hopefully oversized, buffer type
- If you are staying in rust just
Box the unsized type within the struct and move on with all your hair intact!