1use core::hash::BuildHasher;
2use core::ptr::NonNull;
3use std::collections::HashMap;
4use std::hash::RandomState;
5
6use crate::{PtrConst, PtrMut, PtrUninit};
7
8use crate::{
9 Def, Facet, IterVTable, MapDef, MapVTable, Shape, ShapeBuilder, Type, TypeNameFn, TypeNameOpts,
10 TypeOpsIndirect, TypeParam, UserType, VTableDirect, VTableIndirect,
11};
12
13type HashMapIterator<'mem, K, V> = std::collections::hash_map::Iter<'mem, K, V>;
14
15unsafe fn hashmap_init_in_place_with_capacity<K, V, S: Default + BuildHasher>(
16 uninit: PtrUninit,
17 capacity: usize,
18) -> PtrMut {
19 unsafe {
20 uninit.put(HashMap::<K, V, S>::with_capacity_and_hasher(
21 capacity,
22 S::default(),
23 ))
24 }
25}
26
27unsafe fn hashmap_insert<K: Eq + core::hash::Hash, V>(ptr: PtrMut, key: PtrMut, value: PtrMut) {
28 let map = unsafe { ptr.as_mut::<HashMap<K, V>>() };
29 let key = unsafe { key.read::<K>() };
30 let value = unsafe { value.read::<V>() };
31 map.insert(key, value);
32}
33
34unsafe fn hashmap_len<K, V>(ptr: PtrConst) -> usize {
35 unsafe { ptr.get::<HashMap<K, V>>().len() }
36}
37
38unsafe fn hashmap_contains_key<K: Eq + core::hash::Hash, V>(ptr: PtrConst, key: PtrConst) -> bool {
39 unsafe { ptr.get::<HashMap<K, V>>().contains_key(key.get()) }
40}
41
42unsafe fn hashmap_get_value_ptr<K: Eq + core::hash::Hash, V>(
43 ptr: PtrConst,
44 key: PtrConst,
45) -> Option<PtrConst> {
46 unsafe {
47 ptr.get::<HashMap<K, V>>()
48 .get(key.get())
49 .map(|v| PtrConst::new(NonNull::from(v).as_ptr()))
50 }
51}
52
53unsafe fn hashmap_from_pair_slice<K: Eq + core::hash::Hash, V, S: Default + BuildHasher>(
57 uninit: PtrUninit,
58 pairs_ptr: *mut u8,
59 count: usize,
60) -> PtrMut {
61 let pairs = pairs_ptr as *mut (K, V);
63 let iter = (0..count).map(|i| unsafe {
64 let pair_ptr = pairs.add(i);
65 core::ptr::read(pair_ptr)
66 });
67
68 let map: HashMap<K, V, S> = iter.collect();
70 unsafe { uninit.put(map) }
71}
72
73unsafe fn hashmap_iter_init<K, V>(ptr: PtrConst) -> PtrMut {
74 unsafe {
75 let map = ptr.get::<HashMap<K, V>>();
76 let iter: HashMapIterator<'_, K, V> = map.iter();
77 let iter_state = Box::new(iter);
78 PtrMut::new(Box::into_raw(iter_state) as *mut u8)
79 }
80}
81
82unsafe fn hashmap_iter_next<K, V>(iter_ptr: PtrMut) -> Option<(PtrConst, PtrConst)> {
83 unsafe {
84 let ptr = iter_ptr.as_mut_ptr::<HashMapIterator<'_, K, V>>();
90 let state = &mut *ptr;
91 state.next().map(|(key, value)| {
92 (
93 PtrConst::new(NonNull::from(key).as_ptr()),
94 PtrConst::new(NonNull::from(value).as_ptr()),
95 )
96 })
97 }
98}
99
100unsafe fn hashmap_iter_dealloc<K, V>(iter_ptr: PtrMut) {
101 unsafe {
102 drop(Box::from_raw(
103 iter_ptr.as_ptr::<HashMapIterator<'_, K, V>>() as *mut HashMapIterator<'_, K, V>,
104 ));
105 }
106}
107
108unsafe fn hashmap_drop<K, V, S>(ox: crate::OxPtrMut) {
109 unsafe {
110 core::ptr::drop_in_place(ox.as_mut::<HashMap<K, V, S>>());
111 }
112}
113
114unsafe impl<'a, K, V, S> Facet<'a> for HashMap<K, V, S>
116where
117 K: Facet<'a> + core::cmp::Eq + core::hash::Hash,
118 V: Facet<'a>,
119 S: 'a + Default + BuildHasher,
120{
121 const SHAPE: &'static Shape = &const {
122 const fn build_map_vtable<K: Eq + core::hash::Hash, V, S: Default + BuildHasher>()
123 -> MapVTable {
124 MapVTable::builder()
125 .init_in_place_with_capacity(hashmap_init_in_place_with_capacity::<K, V, S>)
126 .insert(hashmap_insert::<K, V>)
127 .len(hashmap_len::<K, V>)
128 .contains_key(hashmap_contains_key::<K, V>)
129 .get_value_ptr(hashmap_get_value_ptr::<K, V>)
130 .iter_vtable(IterVTable {
131 init_with_value: Some(hashmap_iter_init::<K, V>),
132 next: hashmap_iter_next::<K, V>,
133 next_back: None,
134 size_hint: None,
135 dealloc: hashmap_iter_dealloc::<K, V>,
136 })
137 .from_pair_slice(Some(hashmap_from_pair_slice::<K, V, S>))
138 .pair_stride(core::mem::size_of::<(K, V)>())
139 .value_offset_in_pair(core::mem::offset_of!((K, V), 1))
140 .build()
141 }
142
143 const fn build_type_name<'a, K: Facet<'a>, V: Facet<'a>>() -> TypeNameFn {
144 fn type_name_impl<'a, K: Facet<'a>, V: Facet<'a>>(
145 _shape: &'static Shape,
146 f: &mut core::fmt::Formatter<'_>,
147 opts: TypeNameOpts,
148 ) -> core::fmt::Result {
149 write!(f, "HashMap")?;
150 if let Some(opts) = opts.for_children() {
151 write!(f, "<")?;
152 K::SHAPE.write_type_name(f, opts)?;
153 write!(f, ", ")?;
154 V::SHAPE.write_type_name(f, opts)?;
155 write!(f, ">")?;
156 } else {
157 write!(f, "<…>")?;
158 }
159 Ok(())
160 }
161 type_name_impl::<K, V>
162 }
163
164 ShapeBuilder::for_sized::<Self>("HashMap")
165 .type_name(build_type_name::<K, V>())
166 .ty(Type::User(UserType::Opaque))
167 .def(Def::Map(MapDef {
168 vtable: &const { build_map_vtable::<K, V, S>() },
169 k: K::SHAPE,
170 v: V::SHAPE,
171 }))
172 .type_params(&[
173 TypeParam {
174 name: "K",
175 shape: K::SHAPE,
176 },
177 TypeParam {
178 name: "V",
179 shape: V::SHAPE,
180 },
181 ])
182 .vtable_indirect(&VTableIndirect::EMPTY)
183 .type_ops_indirect(
184 &const {
185 TypeOpsIndirect {
186 drop_in_place: hashmap_drop::<K, V, S>,
187 default_in_place: None,
188 clone_into: None,
189 is_truthy: None,
190 }
191 },
192 )
193 .build()
194 };
195}
196
197unsafe impl Facet<'_> for RandomState {
198 const SHAPE: &'static Shape = &const {
199 const VTABLE: VTableDirect = VTableDirect::empty();
200
201 ShapeBuilder::for_sized::<Self>("RandomState")
202 .ty(Type::User(UserType::Opaque))
203 .def(Def::Scalar)
204 .vtable_direct(&VTABLE)
205 .build()
206 };
207}