docs

您正在閱讀 v0.1.2 的文件。Nabi 0.1.2 已停止支援。 最新版本:v0.1.3 →

本頁尚未翻譯,以下為英文原文。

#1.4. raw allocation - alloc / dealloc / realloc

本頁內容

The bare::alloc module provides an API for allocating and freeing memory directly in a region outside the GC's control. Ordinary Nabi code is managed by the GC, but this module is used where the GC is not a good fit: handing memory to the C side across an FFI boundary, large buffers, mmap and the like.

#1.4.1. API

If alloc fails, or the size is 0, it returns CPtr::null(); it does not abort, so the caller must check and handle the result. alloc_array also returns CPtr::null() when n elements overflow usize. Layout's fields are private: read them with size() / align(). array throws LayoutError when n elements overflow usize, from_size_align when align is not a power of two; message() says which.

#1.4.2. Example

nabi
let layout = try Layout::array::<u32>(1000);
let p: CPtr<u8> = unsafe { bare::alloc::alloc(layout) };

match p.as_ptr() {
    raw: Ptr<u8> => {
        let typed: Ptr<u32> = bare::ptr_cast::<u32>(raw);
        // use
        unsafe {
            for i in 0u32..1000u32 { typed.add(i as usize).write(i); }
        }
        unsafe { bare::alloc::dealloc(raw, layout) };
    }
    none => panic("alloc failed"),
}

With a using block, cleanup takes RAII form.

nabi
using buf = try bare::alloc::Allocation::<u32>::new(1000) {
    // buf.as_ptr() is usable
}     // ← automatic dealloc

Here Allocation<T> is the RAII wrapper included in this module.

nabi
struct Allocation<T> { /* private: pointer + length */ }

impl<T> Allocation<T> {
    fn new(n: usize) throws (LayoutError) -> Allocation<T>;   // n zeroed Ts
    fn as_ptr(self) -> Ptr<T>;
    fn as_many(self) -> ManyPtr<T>;
    fn len(self) -> usize;
}

impl<T> Drop for Allocation<T> { /* frees the block */ }

new throws LayoutError when the size overflows usize or the system has no memory (message() is "out of memory"). Allocation implements Drop, so it is affine (2.13.4): let b = a moves it, and its block is freed where its last owner releases it (the end of a using block or the owner leaving scope).

#1.4.3. Relationship with the GC

RegionAllocation / deallocationGC-managed?
Ordinary objects (List<i32>)GC TLAB bump✓
bare::alloc::allocsystem malloc✗ (manual)
FFI mallocC malloc✗
Large object (≥8KB)LOS (non-moving mark-sweep)✓ (but non-moving)

If a GC-managed raw buffer is needed, use bare::mem::GcBuf<T> (2.9.12) instead of this module.

Regions outside the GC are not traced by it, so cleanup is the user's responsibility. Since objects there do not move, however, a Ptr<T> stays valid without a separate pin guard.

#1.4.4. Runtime linkage

The body of bare::alloc::alloc lowers to a wrapper the Nabi runtime provides over system malloc, ultimately calling libc::malloc / libc::free / libc::realloc.

Found a mistake? Edit this page on GitHub. Last updated