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_iter_init<K, V>(ptr: PtrConst) -> PtrMut {
54 unsafe {
55 let map = ptr.get::<HashMap<K, V>>();
56 let iter: HashMapIterator<'_, K, V> = map.iter();
57 let iter_state = Box::new(iter);
58 PtrMut::new(Box::into_raw(iter_state) as *mut u8)
59 }
60}
61
62unsafe fn hashmap_iter_next<K, V>(iter_ptr: PtrMut) -> Option<(PtrConst, PtrConst)> {
63 unsafe {
64 let ptr = iter_ptr.as_mut_ptr::<HashMapIterator<'_, K, V>>();
70 let state = &mut *ptr;
71 state.next().map(|(key, value)| {
72 (
73 PtrConst::new(NonNull::from(key).as_ptr()),
74 PtrConst::new(NonNull::from(value).as_ptr()),
75 )
76 })
77 }
78}
79
80unsafe fn hashmap_iter_dealloc<K, V>(iter_ptr: PtrMut) {
81 unsafe {
82 drop(Box::from_raw(
83 iter_ptr.as_ptr::<HashMapIterator<'_, K, V>>() as *mut HashMapIterator<'_, K, V>,
84 ));
85 }
86}
87
88unsafe fn hashmap_drop<K, V, S>(ox: crate::OxPtrMut) {
89 unsafe {
90 core::ptr::drop_in_place(ox.as_mut::<HashMap<K, V, S>>());
91 }
92}
93
94unsafe impl<'a, K, V, S> Facet<'a> for HashMap<K, V, S>
96where
97 K: Facet<'a> + core::cmp::Eq + core::hash::Hash,
98 V: Facet<'a>,
99 S: 'a + Default + BuildHasher,
100{
101 const SHAPE: &'static Shape = &const {
102 const fn build_map_vtable<K: Eq + core::hash::Hash, V, S: Default + BuildHasher>()
103 -> MapVTable {
104 MapVTable::builder()
105 .init_in_place_with_capacity(hashmap_init_in_place_with_capacity::<K, V, S>)
106 .insert(hashmap_insert::<K, V>)
107 .len(hashmap_len::<K, V>)
108 .contains_key(hashmap_contains_key::<K, V>)
109 .get_value_ptr(hashmap_get_value_ptr::<K, V>)
110 .iter_vtable(IterVTable {
111 init_with_value: Some(hashmap_iter_init::<K, V>),
112 next: hashmap_iter_next::<K, V>,
113 next_back: None,
114 size_hint: None,
115 dealloc: hashmap_iter_dealloc::<K, V>,
116 })
117 .build()
118 }
119
120 const fn build_type_name<'a, K: Facet<'a>, V: Facet<'a>>() -> TypeNameFn {
121 fn type_name_impl<'a, K: Facet<'a>, V: Facet<'a>>(
122 _shape: &'static Shape,
123 f: &mut core::fmt::Formatter<'_>,
124 opts: TypeNameOpts,
125 ) -> core::fmt::Result {
126 write!(f, "HashMap")?;
127 if let Some(opts) = opts.for_children() {
128 write!(f, "<")?;
129 K::SHAPE.write_type_name(f, opts)?;
130 write!(f, ", ")?;
131 V::SHAPE.write_type_name(f, opts)?;
132 write!(f, ">")?;
133 } else {
134 write!(f, "<…>")?;
135 }
136 Ok(())
137 }
138 type_name_impl::<K, V>
139 }
140
141 ShapeBuilder::for_sized::<Self>("HashMap")
142 .type_name(build_type_name::<K, V>())
143 .ty(Type::User(UserType::Opaque))
144 .def(Def::Map(MapDef {
145 vtable: &const { build_map_vtable::<K, V, S>() },
146 k: K::SHAPE,
147 v: V::SHAPE,
148 }))
149 .type_params(&[
150 TypeParam {
151 name: "K",
152 shape: K::SHAPE,
153 },
154 TypeParam {
155 name: "V",
156 shape: V::SHAPE,
157 },
158 ])
159 .vtable_indirect(&VTableIndirect::EMPTY)
160 .type_ops_indirect(
161 &const {
162 TypeOpsIndirect {
163 drop_in_place: hashmap_drop::<K, V, S>,
164 default_in_place: None,
165 clone_into: None,
166 is_truthy: None,
167 }
168 },
169 )
170 .build()
171 };
172}
173
174unsafe impl Facet<'_> for RandomState {
175 const SHAPE: &'static Shape = &const {
176 const VTABLE: VTableDirect = VTableDirect::empty();
177
178 ShapeBuilder::for_sized::<Self>("RandomState")
179 .ty(Type::User(UserType::Opaque))
180 .def(Def::Scalar)
181 .vtable_direct(&VTABLE)
182 .build()
183 };
184}