/* This Source Code Form is subject to the terms of the Mozilla Public *License,v.2.0.IfacopyoftheMPLwasnotdistributedwiththis
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
//! A replacement for `Box<[T; N]>` that cbindgen can understand.
use malloc_size_of::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps}; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; use std::ptr::NonNull; use std::{fmt, mem}; use to_shmem::{SharedMemoryBuilder, ToShmem};
/// A struct that basically replaces a `Box<[T; N]>`, but which cbindgen can /// understand. /// /// Every `OwnedArray` is allocation-backed with `N` fully-constructed /// elements; there is no empty or moved-from state. /// /// We could rely on the struct layout of `Box<[T; N]>`. Per the `Box` /// documentation, `Box<T>` has the same ABI as `*mut T`, and since `[T; N]` is /// `Sized`, that's a thin pointer (unlike `Box<[T]>`, which is fat): /// /// https://doc.rust-lang.org/std/boxed/index.html#memory-layout /// /// But handling `Box` with cbindgen both in structs and argument positions /// more generally is a bit tricky. /// /// This is useful when generated cbindgen code has circular references that /// can only be broken by indirection through boxed objects. When a type needs /// two, three, or a similar small number of such objects of the same kind, /// `OwnedArray<T, N>` is more ergonomic and efficient than holding `N` /// separate boxed values: it uses a single allocation and a single thin /// pointer instead of `N` of each. /// /// Compared to `OwnedSlice<T>`, `OwnedArray<T, N>` does not store the length /// at runtime, `N` is part of the type, so the struct is a single /// pointer-word instead of two. For types used as enum variant payloads, this /// reduces the enclosing enum's footprint. The length can also be statically /// checked, wrong-length values are unrepresentable, so consumers don't need /// need runtime length assertions. /// /// cbindgen:derive-eq=false /// cbindgen:derive-neq=false #[repr(C)] pubstruct OwnedArray<T, const N: usize> {
ptr: NonNull<T>,
_phantom: PhantomData<T>,
}
impl<T, const N: usize> Drop for OwnedArray<T, N> { #[inline] fn drop(&mutself) { unsafe {
drop(Box::from_raw(self.ptr.as_ptr() as *mut [T; N]));
}
}
}
unsafeimpl<T: Send, const N: usize> Send for OwnedArray<T, N> {} unsafeimpl<T: Sync, const N: usize> Sync for OwnedArray<T, N> {}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.