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
193unsafe impl<'a, T, S> Facet<'a> for HashSet<T, S>
194where
195    T: Facet<'a> + core::cmp::Eq + core::hash::Hash + 'static,
196    S: Facet<'a> + Default + BuildHasher + 'static,
197{
198    const SHAPE: &'static Shape = &const {
199        const fn build_set_vtable<
200            T: Eq + core::hash::Hash + 'static,
201            S: Default + BuildHasher + 'static,
202        >() -> SetVTable {
203            SetVTable::builder()
204                .init_in_place_with_capacity(hashset_init_in_place_with_capacity::<T, S>)
205                .insert(hashset_insert::<T>)
206                .len(hashset_len::<T>)
207                .contains(hashset_contains::<T>)
208                .iter_vtable(IterVTable {
209                    init_with_value: Some(hashset_iter_init::<T>),
210                    next: hashset_iter_next::<T>,
211                    next_back: None,
212                    size_hint: None,
213                    dealloc: hashset_iter_dealloc::<T>,
214                })
215                .build()
216        }
217
218        const fn build_type_name<'a, T: Facet<'a>>() -> TypeNameFn {
219            fn type_name_impl<'a, T: Facet<'a>>(
220                _shape: &'static Shape,
221                f: &mut core::fmt::Formatter<'_>,
222                opts: TypeNameOpts,
223            ) -> core::fmt::Result {
224                write!(f, "HashSet")?;
225                if let Some(opts) = opts.for_children() {
226                    write!(f, "<")?;
227                    T::SHAPE.write_type_name(f, opts)?;
228                    write!(f, ">")?;
229                } else {
230                    write!(f, "<…>")?;
231                }
232                Ok(())
233            }
234            type_name_impl::<T>
235        }
236
237        ShapeBuilder::for_sized::<Self>("HashSet")
238            .type_name(build_type_name::<T>())
239            .ty(Type::User(UserType::Opaque))
240            .def(Def::Set(SetDef::new(
241                &const { build_set_vtable::<T, S>() },
242                T::SHAPE,
243            )))
244            .type_params(&[
245                TypeParam {
246                    name: "T",
247                    shape: T::SHAPE,
248                },
249                TypeParam {
250                    name: "S",
251                    shape: S::SHAPE,
252                },
253            ])
254            .vtable_indirect(
255                &const {
256                    VTableIndirect {
257                        debug: Some(hashset_debug),
258                        hash: Some(hashset_hash),
259                        partial_eq: Some(hashset_partial_eq),
260                        ..VTableIndirect::EMPTY
261                    }
262                },
263            )
264            .type_ops_indirect(
265                &const {
266                    TypeOpsIndirect {
267                        drop_in_place: hashset_drop::<T, S>,
268                        default_in_place: None,
269                        clone_into: None,
270                        is_truthy: None,
271                    }
272                },
273            )
274            .build()
275    };
276}
277
278#[cfg(test)]
279mod tests {
280    use alloc::string::String;
281    use core::ptr::NonNull;
282    use std::collections::HashSet;
283    use std::hash::RandomState;
284
285    use super::*;
286
287    #[test]
288    fn test_hashset_type_params() {
289        // HashSet should have a type param for both its value type
290        // and its hasher state
291        let [type_param_1, type_param_2] = <HashSet<i32>>::SHAPE.type_params else {
292            panic!("HashSet<T> should have 2 type params")
293        };
294        assert_eq!(type_param_1.shape(), i32::SHAPE);
295        assert_eq!(type_param_2.shape(), RandomState::SHAPE);
296    }
297
298    #[test]
299    fn test_hashset_vtable_1_new_insert_iter_drop() {
300        facet_testhelpers::setup();
301
302        let hashset_shape = <HashSet<String>>::SHAPE;
303        let hashset_def = hashset_shape
304            .def
305            .into_set()
306            .expect("HashSet<T> should have a set definition");
307
308        // Allocate memory for the HashSet
309        let hashset_uninit_ptr = hashset_shape.allocate().unwrap();
310
311        // Create the HashSet with a capacity of 3
312        let hashset_ptr =
313            unsafe { (hashset_def.vtable.init_in_place_with_capacity)(hashset_uninit_ptr, 3) };
314
315        // The HashSet is empty, so ensure its length is 0
316        let hashset_actual_length = unsafe { (hashset_def.vtable.len)(hashset_ptr.as_const()) };
317        assert_eq!(hashset_actual_length, 0);
318
319        // 5 sample values to insert
320        let strings = ["foo", "bar", "bazz", "fizzbuzz", "fifth thing"];
321
322        // Insert the 5 values into the HashSet
323        let mut hashset_length = 0;
324        for string in strings {
325            // Create the value
326            let mut new_value = core::mem::ManuallyDrop::new(string.to_string());
327
328            // Insert the value
329            let did_insert = unsafe {
330                (hashset_def.vtable.insert)(
331                    hashset_ptr,
332                    PtrMut::new(NonNull::from(&mut new_value).as_ptr()),
333                )
334            };
335
336            assert!(did_insert, "expected value to be inserted in the HashSet");
337
338            // Ensure the HashSet's length increased by 1
339            hashset_length += 1;
340            let hashset_actual_length = unsafe { (hashset_def.vtable.len)(hashset_ptr.as_const()) };
341            assert_eq!(hashset_actual_length, hashset_length);
342        }
343
344        // Insert the same 5 values again, ensuring they are deduplicated
345        for string in strings {
346            // Create the value
347            let mut new_value = core::mem::ManuallyDrop::new(string.to_string());
348
349            // Try to insert the value
350            let did_insert = unsafe {
351                (hashset_def.vtable.insert)(
352                    hashset_ptr,
353                    PtrMut::new(NonNull::from(&mut new_value).as_ptr()),
354                )
355            };
356
357            assert!(
358                !did_insert,
359                "expected value to not be inserted in the HashSet"
360            );
361
362            // Ensure the HashSet's length did not increase
363            let hashset_actual_length = unsafe { (hashset_def.vtable.len)(hashset_ptr.as_const()) };
364            assert_eq!(hashset_actual_length, hashset_length);
365        }
366
367        // Create a new iterator over the HashSet
368        let iter_init_with_value_fn = hashset_def.vtable.iter_vtable.init_with_value.unwrap();
369        let hashset_iter_ptr = unsafe { iter_init_with_value_fn(hashset_ptr.as_const()) };
370
371        // Collect all the items from the HashSet's iterator
372        let mut iter_items = HashSet::<&str>::new();
373        loop {
374            // Get the next item from the iterator
375            let item_ptr = unsafe { (hashset_def.vtable.iter_vtable.next)(hashset_iter_ptr) };
376            let Some(item_ptr) = item_ptr else {
377                break;
378            };
379
380            let item = unsafe { item_ptr.get::<String>() };
381
382            // Insert the item into the set of items returned from the iterator
383            let did_insert = iter_items.insert(&**item);
384
385            assert!(did_insert, "HashSet iterator returned duplicate item");
386        }
387
388        // Deallocate the iterator
389        unsafe {
390            (hashset_def.vtable.iter_vtable.dealloc)(hashset_iter_ptr);
391        }
392
393        // Ensure the iterator returned all of the strings
394        assert_eq!(iter_items, strings.iter().copied().collect::<HashSet<_>>());
395
396        // Drop the HashSet in place
397        unsafe {
398            hashset_shape
399                .call_drop_in_place(hashset_ptr)
400                .expect("HashSet<T> should have drop_in_place");
401
402            // Deallocate the memory
403            hashset_shape.deallocate_mut(hashset_ptr).unwrap();
404        }
405    }
406}