facet_core/impls/std/
hashset.rs

1use core::hash::BuildHasher;
2use std::collections::HashSet;
3
4use crate::{PtrConst, PtrMut, PtrUninit};
5
6use crate::{
7    Def, Facet, HashProxy, IterVTable, OxPtrConst, OxPtrMut, OxRef, SetDef, SetVTable, Shape,
8    ShapeBuilder, Type, TypeNameFn, TypeNameOpts, TypeOpsIndirect, TypeParam, UserType,
9    VTableIndirect,
10};
11
12type HashSetIterator<'mem, T> = std::collections::hash_set::Iter<'mem, T>;
13
14unsafe fn hashset_init_in_place_with_capacity<T, S: Default + BuildHasher>(
15    uninit: PtrUninit,
16    capacity: usize,
17) -> PtrMut {
18    unsafe {
19        uninit.put(HashSet::<T, S>::with_capacity_and_hasher(
20            capacity,
21            S::default(),
22        ))
23    }
24}
25
26unsafe fn hashset_insert<T: Eq + core::hash::Hash + 'static>(ptr: PtrMut, item: PtrMut) -> bool {
27    unsafe {
28        let set = ptr.as_mut::<HashSet<T>>();
29        let item = item.read::<T>();
30        set.insert(item)
31    }
32}
33
34unsafe fn hashset_len<T: 'static>(ptr: PtrConst) -> usize {
35    unsafe { ptr.get::<HashSet<T>>().len() }
36}
37
38unsafe fn hashset_contains<T: Eq + core::hash::Hash + 'static>(
39    ptr: PtrConst,
40    item: PtrConst,
41) -> bool {
42    unsafe { ptr.get::<HashSet<T>>().contains(item.get()) }
43}
44
45unsafe fn hashset_iter_init<T: 'static>(ptr: PtrConst) -> PtrMut {
46    unsafe {
47        let set = ptr.get::<HashSet<T>>();
48        let iter: HashSetIterator<'_, T> = set.iter();
49        let iter_state = Box::new(iter);
50        PtrMut::new(Box::into_raw(iter_state) as *mut u8)
51    }
52}
53
54unsafe fn hashset_iter_next<T: 'static>(iter_ptr: PtrMut) -> Option<PtrConst> {
55    unsafe {
56        let state = iter_ptr.as_mut::<HashSetIterator<'static, T>>();
57        state.next().map(|value| PtrConst::new(value as *const T))
58    }
59}
60
61unsafe fn hashset_iter_dealloc<T>(iter_ptr: PtrMut) {
62    unsafe {
63        drop(Box::from_raw(
64            iter_ptr.as_ptr::<HashSetIterator<'_, T>>() as *mut HashSetIterator<'_, T>
65        ));
66    }
67}
68
69/// Extract the SetDef from a shape, returns None if not a Set
70#[inline]
71fn get_set_def(shape: &'static Shape) -> Option<&'static SetDef> {
72    match shape.def {
73        Def::Set(ref def) => Some(def),
74        _ => None,
75    }
76}
77
78/// Debug for `HashSet<T>` - delegates to inner T's debug if available
79unsafe fn hashset_debug(
80    ox: OxPtrConst,
81    f: &mut core::fmt::Formatter<'_>,
82) -> Option<core::fmt::Result> {
83    let shape = ox.shape();
84    let def = get_set_def(shape)?;
85    let ptr = ox.ptr();
86
87    let mut debug_set = f.debug_set();
88
89    // Initialize iterator
90    let iter_init = def.vtable.iter_vtable.init_with_value?;
91    let iter_ptr = unsafe { iter_init(ptr) };
92
93    // Iterate over all elements
94    loop {
95        let item_ptr = unsafe { (def.vtable.iter_vtable.next)(iter_ptr) };
96        let Some(item_ptr) = item_ptr else {
97            break;
98        };
99        let item_ox = OxRef::new(item_ptr, def.t);
100        debug_set.entry(&item_ox);
101    }
102
103    // Deallocate iterator
104    unsafe {
105        (def.vtable.iter_vtable.dealloc)(iter_ptr);
106    }
107
108    Some(debug_set.finish())
109}
110
111/// Hash for `HashSet<T>` - delegates to inner T's hash if available
112unsafe fn hashset_hash(ox: OxPtrConst, hasher: &mut HashProxy<'_>) -> Option<()> {
113    let shape = ox.shape();
114    let def = get_set_def(shape)?;
115    let ptr = ox.ptr();
116
117    use core::hash::Hash;
118
119    // Hash the length first
120    let len = unsafe { (def.vtable.len)(ptr) };
121    len.hash(hasher);
122
123    // Initialize iterator
124    let iter_init = def.vtable.iter_vtable.init_with_value?;
125    let iter_ptr = unsafe { iter_init(ptr) };
126
127    // Hash all elements
128    loop {
129        let item_ptr = unsafe { (def.vtable.iter_vtable.next)(iter_ptr) };
130        let Some(item_ptr) = item_ptr else {
131            break;
132        };
133        unsafe { def.t.call_hash(item_ptr, hasher)? };
134    }
135
136    // Deallocate iterator
137    unsafe {
138        (def.vtable.iter_vtable.dealloc)(iter_ptr);
139    }
140
141    Some(())
142}
143
144/// PartialEq for `HashSet<T>`
145unsafe fn hashset_partial_eq(a: OxPtrConst, b: OxPtrConst) -> Option<bool> {
146    let shape = a.shape();
147    let def = get_set_def(shape)?;
148
149    let a_ptr = a.ptr();
150    let b_ptr = b.ptr();
151
152    let a_len = unsafe { (def.vtable.len)(a_ptr) };
153    let b_len = unsafe { (def.vtable.len)(b_ptr) };
154
155    // If lengths differ, sets are not equal
156    if a_len != b_len {
157        return Some(false);
158    }
159
160    // Initialize iterator for set a
161    let iter_init = def.vtable.iter_vtable.init_with_value?;
162    let iter_ptr = unsafe { iter_init(a_ptr) };
163
164    // Check if all elements from a are contained in b
165    let mut all_contained = true;
166    loop {
167        let item_ptr = unsafe { (def.vtable.iter_vtable.next)(iter_ptr) };
168        let Some(item_ptr) = item_ptr else {
169            break;
170        };
171        let contained = unsafe { (def.vtable.contains)(b_ptr, item_ptr) };
172        if !contained {
173            all_contained = false;
174            break;
175        }
176    }
177
178    // Deallocate iterator
179    unsafe {
180        (def.vtable.iter_vtable.dealloc)(iter_ptr);
181    }
182
183    Some(all_contained)
184}
185
186/// Drop for HashSet<T, S>
187unsafe fn hashset_drop<T: 'static, S: 'static>(ox: OxPtrMut) {
188    unsafe {
189        core::ptr::drop_in_place(ox.as_mut::<HashSet<T, S>>());
190    }
191}
192
193/// Default for HashSet<T, S>
194unsafe fn hashset_default<T: 'static, S: Default + BuildHasher + 'static>(ox: OxPtrMut) {
195    unsafe { ox.ptr().as_uninit().put(HashSet::<T, S>::default()) };
196}
197
198unsafe impl<'a, T, S> Facet<'a> for HashSet<T, S>
199where
200    T: Facet<'a> + core::cmp::Eq + core::hash::Hash + 'static,
201    S: Facet<'a> + Default + BuildHasher + 'static,
202{
203    const SHAPE: &'static Shape = &const {
204        const fn build_set_vtable<
205            T: Eq + core::hash::Hash + 'static,
206            S: Default + BuildHasher + 'static,
207        >() -> SetVTable {
208            SetVTable::builder()
209                .init_in_place_with_capacity(hashset_init_in_place_with_capacity::<T, S>)
210                .insert(hashset_insert::<T>)
211                .len(hashset_len::<T>)
212                .contains(hashset_contains::<T>)
213                .iter_vtable(IterVTable {
214                    init_with_value: Some(hashset_iter_init::<T>),
215                    next: hashset_iter_next::<T>,
216                    next_back: None,
217                    size_hint: None,
218                    dealloc: hashset_iter_dealloc::<T>,
219                })
220                .build()
221        }
222
223        const fn build_type_name<'a, T: Facet<'a>>() -> TypeNameFn {
224            fn type_name_impl<'a, T: Facet<'a>>(
225                _shape: &'static Shape,
226                f: &mut core::fmt::Formatter<'_>,
227                opts: TypeNameOpts,
228            ) -> core::fmt::Result {
229                write!(f, "HashSet")?;
230                if let Some(opts) = opts.for_children() {
231                    write!(f, "<")?;
232                    T::SHAPE.write_type_name(f, opts)?;
233                    write!(f, ">")?;
234                } else {
235                    write!(f, "<…>")?;
236                }
237                Ok(())
238            }
239            type_name_impl::<T>
240        }
241
242        ShapeBuilder::for_sized::<Self>("HashSet")
243            .type_name(build_type_name::<T>())
244            .ty(Type::User(UserType::Opaque))
245            .def(Def::Set(SetDef::new(
246                &const { build_set_vtable::<T, S>() },
247                T::SHAPE,
248            )))
249            .type_params(&[
250                TypeParam {
251                    name: "T",
252                    shape: T::SHAPE,
253                },
254                TypeParam {
255                    name: "S",
256                    shape: S::SHAPE,
257                },
258            ])
259            .vtable_indirect(
260                &const {
261                    VTableIndirect {
262                        debug: Some(hashset_debug),
263                        hash: Some(hashset_hash),
264                        partial_eq: Some(hashset_partial_eq),
265                        ..VTableIndirect::EMPTY
266                    }
267                },
268            )
269            .type_ops_indirect(
270                &const {
271                    TypeOpsIndirect {
272                        drop_in_place: hashset_drop::<T, S>,
273                        default_in_place: Some(hashset_default::<T, S>),
274                        clone_into: None,
275                        is_truthy: None,
276                    }
277                },
278            )
279            .build()
280    };
281}
282
283#[cfg(test)]
284mod tests {
285    use alloc::string::String;
286    use core::ptr::NonNull;
287    use std::collections::HashSet;
288    use std::hash::RandomState;
289
290    use super::*;
291
292    #[test]
293    fn test_hashset_type_params() {
294        // HashSet should have a type param for both its value type
295        // and its hasher state
296        let [type_param_1, type_param_2] = <HashSet<i32>>::SHAPE.type_params else {
297            panic!("HashSet<T> should have 2 type params")
298        };
299        assert_eq!(type_param_1.shape(), i32::SHAPE);
300        assert_eq!(type_param_2.shape(), RandomState::SHAPE);
301    }
302
303    #[test]
304    fn test_hashset_vtable_1_new_insert_iter_drop() {
305        facet_testhelpers::setup();
306
307        let hashset_shape = <HashSet<String>>::SHAPE;
308        let hashset_def = hashset_shape
309            .def
310            .into_set()
311            .expect("HashSet<T> should have a set definition");
312
313        // Allocate memory for the HashSet
314        let hashset_uninit_ptr = hashset_shape.allocate().unwrap();
315
316        // Create the HashSet with a capacity of 3
317        let hashset_ptr =
318            unsafe { (hashset_def.vtable.init_in_place_with_capacity)(hashset_uninit_ptr, 3) };
319
320        // The HashSet is empty, so ensure its length is 0
321        let hashset_actual_length = unsafe { (hashset_def.vtable.len)(hashset_ptr.as_const()) };
322        assert_eq!(hashset_actual_length, 0);
323
324        // 5 sample values to insert
325        let strings = ["foo", "bar", "bazz", "fizzbuzz", "fifth thing"];
326
327        // Insert the 5 values into the HashSet
328        let mut hashset_length = 0;
329        for string in strings {
330            // Create the value
331            let mut new_value = core::mem::ManuallyDrop::new(string.to_string());
332
333            // Insert the value
334            let did_insert = unsafe {
335                (hashset_def.vtable.insert)(
336                    hashset_ptr,
337                    PtrMut::new(NonNull::from(&mut new_value).as_ptr()),
338                )
339            };
340
341            assert!(did_insert, "expected value to be inserted in the HashSet");
342
343            // Ensure the HashSet's length increased by 1
344            hashset_length += 1;
345            let hashset_actual_length = unsafe { (hashset_def.vtable.len)(hashset_ptr.as_const()) };
346            assert_eq!(hashset_actual_length, hashset_length);
347        }
348
349        // Insert the same 5 values again, ensuring they are deduplicated
350        for string in strings {
351            // Create the value
352            let mut new_value = core::mem::ManuallyDrop::new(string.to_string());
353
354            // Try to insert the value
355            let did_insert = unsafe {
356                (hashset_def.vtable.insert)(
357                    hashset_ptr,
358                    PtrMut::new(NonNull::from(&mut new_value).as_ptr()),
359                )
360            };
361
362            assert!(
363                !did_insert,
364                "expected value to not be inserted in the HashSet"
365            );
366
367            // Ensure the HashSet's length did not increase
368            let hashset_actual_length = unsafe { (hashset_def.vtable.len)(hashset_ptr.as_const()) };
369            assert_eq!(hashset_actual_length, hashset_length);
370        }
371
372        // Create a new iterator over the HashSet
373        let iter_init_with_value_fn = hashset_def.vtable.iter_vtable.init_with_value.unwrap();
374        let hashset_iter_ptr = unsafe { iter_init_with_value_fn(hashset_ptr.as_const()) };
375
376        // Collect all the items from the HashSet's iterator
377        let mut iter_items = HashSet::<&str>::new();
378        loop {
379            // Get the next item from the iterator
380            let item_ptr = unsafe { (hashset_def.vtable.iter_vtable.next)(hashset_iter_ptr) };
381            let Some(item_ptr) = item_ptr else {
382                break;
383            };
384
385            let item = unsafe { item_ptr.get::<String>() };
386
387            // Insert the item into the set of items returned from the iterator
388            let did_insert = iter_items.insert(&**item);
389
390            assert!(did_insert, "HashSet iterator returned duplicate item");
391        }
392
393        // Deallocate the iterator
394        unsafe {
395            (hashset_def.vtable.iter_vtable.dealloc)(hashset_iter_ptr);
396        }
397
398        // Ensure the iterator returned all of the strings
399        assert_eq!(iter_items, strings.iter().copied().collect::<HashSet<_>>());
400
401        // Drop the HashSet in place
402        unsafe {
403            hashset_shape
404                .call_drop_in_place(hashset_ptr)
405                .expect("HashSet<T> should have drop_in_place");
406
407            // Deallocate the memory
408            hashset_shape.deallocate_mut(hashset_ptr).unwrap();
409        }
410    }
411}