facet_core/_trait/impls/
option_impl.rs

1use core::alloc::Layout;
2
3use crate::{ConstTypeId, Def, Facet, OpaqueConst, OptionDef, OptionVTable, Shape, value_vtable};
4
5unsafe impl<T: Facet> Facet for Option<T> {
6    const SHAPE: &'static Shape = &const {
7        Shape::builder()
8            .id(ConstTypeId::of::<Self>())
9            .layout(Layout::new::<Self>())
10            .def(Def::Option(
11                OptionDef::builder()
12                    .t(T::SHAPE)
13                    .vtable(
14                        const {
15                            &OptionVTable {
16                                is_some_fn: |option| unsafe {
17                                    option.as_ref::<Option<T>>().is_some()
18                                },
19                                get_value_fn: |option| unsafe {
20                                    option
21                                        .as_ref::<Option<T>>()
22                                        .as_ref()
23                                        .map(|t| OpaqueConst::new(t as *const T))
24                                },
25                                init_some_fn: |option, value| unsafe {
26                                    option.put(Option::Some(value.read::<T>()))
27                                },
28                                init_none_fn: |option| unsafe { option.put(<Option<T>>::None) },
29                                replace_with_fn: |option, value| unsafe {
30                                    let option = option.as_mut::<Option<T>>();
31                                    match value {
32                                        Some(value) => option.replace(value.read::<T>()),
33                                        None => option.take(),
34                                    };
35                                },
36                            }
37                        },
38                    )
39                    .build(),
40            ))
41            .vtable(value_vtable!(core::option::Option<T>, |f, _opts| write!(
42                f,
43                "Option"
44            )))
45            .build()
46    };
47}