facet_core/impls/alloc/
btreemap.rs

1use alloc::{boxed::Box, collections::BTreeMap};
2
3use crate::{
4    Def, Facet, IterVTable, MapDef, MapVTable, PtrConst, PtrMut, PtrUninit, Shape, ShapeBuilder,
5    TypeNameFn, TypeNameOpts, TypeParam, VTableIndirect,
6};
7
8type BTreeMapIterator<'mem, K, V> = alloc::collections::btree_map::Iter<'mem, K, V>;
9
10unsafe fn btreemap_init_in_place_with_capacity<K, V>(
11    uninit: PtrUninit,
12    _capacity: usize,
13) -> PtrMut {
14    unsafe { uninit.put(BTreeMap::<K, V>::new()) }
15}
16
17unsafe fn btreemap_insert<K: Eq + Ord + 'static, V: 'static>(
18    ptr: PtrMut,
19    key: PtrMut,
20    value: PtrMut,
21) {
22    unsafe {
23        let map = ptr.as_mut::<BTreeMap<K, V>>();
24        let k = key.read::<K>();
25        let v = value.read::<V>();
26        map.insert(k, v);
27    }
28}
29
30unsafe fn btreemap_len<K: 'static, V: 'static>(ptr: PtrConst) -> usize {
31    unsafe { ptr.get::<BTreeMap<K, V>>().len() }
32}
33
34unsafe fn btreemap_contains_key<K: Eq + Ord + 'static, V: 'static>(
35    ptr: PtrConst,
36    key: PtrConst,
37) -> bool {
38    unsafe { ptr.get::<BTreeMap<K, V>>().contains_key(key.get()) }
39}
40
41unsafe fn btreemap_get_value_ptr<K: Eq + Ord + 'static, V: 'static>(
42    ptr: PtrConst,
43    key: PtrConst,
44) -> Option<PtrConst> {
45    unsafe {
46        ptr.get::<BTreeMap<K, V>>()
47            .get(key.get())
48            .map(|v| PtrConst::new(v as *const V))
49    }
50}
51
52unsafe fn btreemap_iter_init<K: 'static, V: 'static>(ptr: PtrConst) -> PtrMut {
53    unsafe {
54        let map = ptr.get::<BTreeMap<K, V>>();
55        let iter: BTreeMapIterator<'_, K, V> = map.iter();
56        let state = Box::new(iter);
57        PtrMut::new(Box::into_raw(state) as *mut u8)
58    }
59}
60
61unsafe fn btreemap_iter_next<K: 'static, V: 'static>(
62    iter_ptr: PtrMut,
63) -> Option<(PtrConst, PtrConst)> {
64    unsafe {
65        let state = iter_ptr.as_mut::<BTreeMapIterator<'static, K, V>>();
66        state.next().map(|(key, value)| {
67            (
68                PtrConst::new(key as *const K),
69                PtrConst::new(value as *const V),
70            )
71        })
72    }
73}
74
75unsafe fn btreemap_iter_next_back<K: 'static, V: 'static>(
76    iter_ptr: PtrMut,
77) -> Option<(PtrConst, PtrConst)> {
78    unsafe {
79        let state = iter_ptr.as_mut::<BTreeMapIterator<'static, K, V>>();
80        state.next_back().map(|(key, value)| {
81            (
82                PtrConst::new(key as *const K),
83                PtrConst::new(value as *const V),
84            )
85        })
86    }
87}
88
89unsafe fn btreemap_iter_dealloc<K, V>(iter_ptr: PtrMut) {
90    unsafe {
91        drop(Box::from_raw(
92            iter_ptr.as_ptr::<BTreeMapIterator<'_, K, V>>() as *mut BTreeMapIterator<'_, K, V>,
93        ))
94    }
95}
96
97/// Build a BTreeMap from a contiguous slice of (K, V) pairs.
98unsafe fn btreemap_from_pair_slice<K: Eq + Ord + 'static, V: 'static>(
99    uninit: PtrUninit,
100    pairs_ptr: *mut u8,
101    count: usize,
102) -> PtrMut {
103    let pairs = pairs_ptr as *mut (K, V);
104    let iter = (0..count).map(|i| unsafe {
105        let pair_ptr = pairs.add(i);
106        core::ptr::read(pair_ptr)
107    });
108    let map: BTreeMap<K, V> = iter.collect();
109    unsafe { uninit.put(map) }
110}
111
112// TODO: Debug, Hash, PartialEq, Eq, PartialOrd, Ord, for BTreeMap, BTreeSet
113unsafe impl<'a, K, V> Facet<'a> for BTreeMap<K, V>
114where
115    K: Facet<'a> + core::cmp::Eq + core::cmp::Ord + 'static,
116    V: Facet<'a> + 'static,
117{
118    const SHAPE: &'static crate::Shape = &const {
119        const fn build_map_vtable<K: Eq + Ord + 'static, V: 'static>() -> MapVTable {
120            MapVTable::builder()
121                .init_in_place_with_capacity(btreemap_init_in_place_with_capacity::<K, V>)
122                .insert(btreemap_insert::<K, V>)
123                .len(btreemap_len::<K, V>)
124                .contains_key(btreemap_contains_key::<K, V>)
125                .get_value_ptr(btreemap_get_value_ptr::<K, V>)
126                .iter_vtable(IterVTable {
127                    init_with_value: Some(btreemap_iter_init::<K, V>),
128                    next: btreemap_iter_next::<K, V>,
129                    next_back: Some(btreemap_iter_next_back::<K, V>),
130                    size_hint: None,
131                    dealloc: btreemap_iter_dealloc::<K, V>,
132                })
133                .from_pair_slice(Some(btreemap_from_pair_slice::<K, V>))
134                .pair_stride(core::mem::size_of::<(K, V)>())
135                .value_offset_in_pair(core::mem::offset_of!((K, V), 1))
136                .build()
137        }
138
139        const VTABLE: VTableIndirect = VTableIndirect::EMPTY;
140
141        const fn build_type_name<'a, K: Facet<'a>, V: Facet<'a>>() -> TypeNameFn {
142            fn type_name_impl<'a, K: Facet<'a>, V: Facet<'a>>(
143                _shape: &'static Shape,
144                f: &mut core::fmt::Formatter<'_>,
145                opts: TypeNameOpts,
146            ) -> core::fmt::Result {
147                write!(f, "BTreeMap")?;
148                if let Some(opts) = opts.for_children() {
149                    write!(f, "<")?;
150                    K::SHAPE.write_type_name(f, opts)?;
151                    write!(f, ", ")?;
152                    V::SHAPE.write_type_name(f, opts)?;
153                    write!(f, ">")?;
154                } else {
155                    write!(f, "<…>")?;
156                }
157                Ok(())
158            }
159            type_name_impl::<K, V>
160        }
161
162        ShapeBuilder::for_sized::<Self>("BTreeMap")
163            .type_name(build_type_name::<K, V>())
164            .vtable_indirect(&VTABLE)
165            .def(Def::Map(MapDef::new(
166                &const { build_map_vtable::<K, V>() },
167                K::SHAPE,
168                V::SHAPE,
169            )))
170            .type_params(&[
171                TypeParam {
172                    name: "K",
173                    shape: K::SHAPE,
174                },
175                TypeParam {
176                    name: "V",
177                    shape: V::SHAPE,
178                },
179            ])
180            .build()
181    };
182}