Hi guys:
I'm trying to initialize an enum variant, which is a struct in my case, using Box::new_uninit_in
and ptr::addr_of_mut!
. However, I'm struggling to access the right field. Can someone help me with this problem?
#![feature(allocator_api)]
use std::alloc::Allocator;
use std::mem::MaybeUninit;
use core::ptr::{self, NonNull};
fn main() {}
enum Node<K, V> {
LeafNode {
size: u16,
keys: [MaybeUninit<K>; 10],
vals: [MaybeUninit<V>; 10],
prev: Option<NonNull<Node<K, V>>>,
next: Option<NonNull<Node<K, V>>>,
},
InternalNode {
size: u16,
keys: [MaybeUninit<K>; 10],
vals: [MaybeUninit<NonNull<Node<K, V>>>; 11],
},
}
impl<K, V> Node<K, V> {
unsafe fn init(this: *mut Self) {
unsafe {
// 1. How do I access the fields of the struct within the enum?
// 2. How can I initialize the enum as either the LeafNode variant or the InternalNode variant?
ptr::addr_of_mut!((*this).size).write(0);
}
}
fn new<A: Allocator + Clone>(alloc: A) -> Box<Self, A> {
unsafe {
let mut node = Box::new_uninit_in(alloc);
Node::init(node.as_mut_ptr());
node.assume_init()
}
}
}