Skip to content

Instantly share code, notes, and snippets.

@lovely-error
Created October 29, 2024 14:07
Show Gist options
  • Save lovely-error/c6b490bf10e87c03259becd9ee0eaf07 to your computer and use it in GitHub Desktop.
Save lovely-error/c6b490bf10e87c03259becd9ee0eaf07 to your computer and use it in GitHub Desktop.
(Almost) How to desugar dynsized values in rust
#![feature(ptr_metadata)]
// use libc; // 0.2.159
use std::alloc::Layout;
use std::ptr::copy_nonoverlapping;
use std::mem::forget;
use std::ptr::metadata;
use std::ptr::DynMetadata;
fn main() {
// let ptr: fn() -> impl Iterator<Item=usize> = ff;
// let mut iter = ptr();
// let item = iter.next().unwrap();
let item = call_dynsized() ;
println!("{item}!");
assert!(item == 42);
}
fn call_dynsized() -> usize {
let (desc, pro) = ff_equiv_rw_1();
// let sptr1 = libc::alloca(mtd.size_of());
let mut sptr1 = [0usize;32];
let ptr = (&raw mut sptr1) as *mut usize;
pro(ptr.cast());
let iter: *mut dyn Iterator<Item=usize> = core::ptr::from_raw_parts_mut(ptr, desc);
let item = unsafe { (&mut *iter).next().unwrap() };
unsafe { iter.drop_in_place() };
return item
}
fn ff_equiv_rw_1() -> (DynMetadata<dyn Iterator<Item=usize>>, impl FnOnce(*mut u8)) {
let result = ff();
let desc = metadata(&result as &dyn Iterator<Item=usize>);
(desc, move |ptr| unsafe {
copy_nonoverlapping((&raw const result) as *mut u8, ptr, desc.size_of());
forget(result);
})
}
fn ff() -> impl Iterator<Item=usize> {
core::iter::from_fn(||{
return Some(42usize);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment