blob: 6185c0b99a2e5e5c5f53576a00cf8977c4bfd664 [file]
// Copyright 2026 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::alloc::{Layout, alloc, dealloc};
use std::sync::atomic::{AtomicUsize, Ordering};
use vx_std::collections::{HashMap, HashSet};
use vx_std::string::String as VxString;
static LIVE_ALLOCS: AtomicUsize = AtomicUsize::new(0);
#[unsafe(no_mangle)]
pub unsafe extern "C" fn __vx_alloc(size: usize, align: usize) -> *mut u8 {
let Ok(layout) = Layout::from_size_align(size, align) else {
return core::ptr::null_mut();
};
// SAFETY: `size > 0` and `align` is a valid power of two checked by `Layout::from_size_align`.
let ptr = unsafe { alloc(layout) };
if !ptr.is_null() {
LIVE_ALLOCS.fetch_add(1, Ordering::SeqCst);
}
ptr
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn __vx_dealloc(ptr: *mut u8, size: usize, align: usize) {
if ptr.is_null() {
return;
}
let layout = Layout::from_size_align(size, align).expect("valid dealloc layout");
LIVE_ALLOCS.fetch_sub(1, Ordering::SeqCst);
// SAFETY: Caller passes a live allocation previously returned by `__vx_alloc`.
unsafe { dealloc(ptr, layout) };
}
#[unsafe(no_mangle)]
pub extern "C" fn __vx_hash_seed() -> u64 {
0x1234_5678_9abc_def0
}
#[test]
fn hash_map_and_hash_set_operations_leak_free() {
let before = LIVE_ALLOCS.load(Ordering::SeqCst);
{
let mut map: HashMap<u64, u32> = HashMap::new();
for k in 0..40u64 {
assert_eq!(map.try_insert(k, (k as u32) * 10).unwrap(), None);
}
assert_eq!(map.len(), 40);
assert_eq!(map.try_insert(5, 999).unwrap(), Some(50));
assert_eq!(map.get(&5), Some(&999));
assert_eq!(map.remove(&5), Some(999));
assert!(!map.contains_key(&5));
assert_eq!(map.len(), 39);
let mut smap: HashMap<VxString, u32> = HashMap::new();
smap.try_insert(VxString::try_from_str("alpha").unwrap(), 1).unwrap();
smap.try_insert(VxString::try_from_str("beta").unwrap(), 2).unwrap();
assert_eq!(smap.get("alpha"), Some(&1));
assert_eq!(smap.remove("beta"), Some(2));
assert_eq!(smap.get("beta"), None);
let mut set: HashSet<u64> = HashSet::new();
assert!(set.try_insert(7).unwrap());
assert!(!set.try_insert(7).unwrap());
assert!(set.contains(&7));
assert!(set.remove(&7));
assert!(!set.contains(&7));
}
assert_eq!(LIVE_ALLOCS.load(Ordering::SeqCst), before);
}