| // 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_alloc::{Box as VxBox, String as VxString, TryFromUtf8Error, Vec as VxVec}; | |
| 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) }; | |
| } | |
| #[test] | |
| fn box_vec_and_string_operations_leak_free() { | |
| let before = LIVE_ALLOCS.load(Ordering::SeqCst); | |
| { | |
| let b = VxBox::try_new(1234u64).unwrap(); | |
| assert_eq!(*b, 1234); | |
| assert_eq!(VxBox::into_inner(b), 1234); | |
| let mut v: VxVec<u32> = VxVec::new(); | |
| for i in 0..32u32 { | |
| v.try_push(i * 3).unwrap(); | |
| } | |
| assert_eq!(v.len(), 32); | |
| assert_eq!(v.get(10), Some(&30)); | |
| assert_eq!(v.pop(), Some(93)); | |
| assert_eq!(v.len(), 31); | |
| let mut s = VxString::try_from_str("hello").unwrap(); | |
| s.try_push_str(" vx").unwrap(); | |
| assert_eq!(s.as_str(), "hello vx"); | |
| assert_eq!(VxString::try_from_utf8(&[0xFF]).err(), Some(TryFromUtf8Error::InvalidUtf8)); | |
| } | |
| assert_eq!(LIVE_ALLOCS.load(Ordering::SeqCst), before); | |
| } |