docs

You are reading the docs for v0.1.2. Nabi 0.1.2 is no longer supported. Latest release: v0.1.3 →

#1.3. MaybeUninit<T> - uninitialized memory

On this page

The bare::mem module defines a wrapper for handling uninitialized memory safely, along with the associated ops. Whereas an ordinary T is always guaranteed to be initialized, MaybeUninit<T> expresses initialization status explicitly at the type level.

#1.3.1. Motivation - reading uninitialized memory is UB

Reading uninitialized memory is UB, even for integer types. It is not merely that a "garbage value" comes out; the compiler may assume anything about the value and transform the code accordingly.

c
// C
int x;            // uninit
if (x == 0) { ... }   // the compiler may assume any value for x; either branch may become dead code

T itself therefore cannot represent the uninitialized state, and a separate wrapper is needed.

#1.3.2. MaybeUninit<T>

nabi
struct MaybeUninit<T> { /* same size + align as T, but possibly uninitialized */ }

impl<T> MaybeUninit<T> {
    fn uninit() -> MaybeUninit<T>;          // uninitialized slot
    fn zeroed() -> MaybeUninit<T>;          // filled with 0
    fn new(value: T) -> MaybeUninit<T>;     // initialized slot

    fn write(ref self, value: T);           // write value

    fn as_ptr(self) -> ConstPtr<T>;
    fn as_mut_ptr(ref self) -> Ptr<T>;

    unsafe fn assume_init(self) -> T;
    // SAFETY: only when initialization is guaranteed by write / an external mechanism

}

as_ptr / as_mut_ptr need the receiver to be a place: the pointer points at that variable, not at a copy. uninit() may be implemented as zeroed().

#Example - separating the initialization step

A typical pattern: wait for FFI to fill a buffer, then take the value out.

nabi
let buf: MaybeUninit<[u8; 1024]> = MaybeUninit::uninit();
let p: Ptr<u8> = buf.as_mut_ptr().cast::<u8>();

unsafe {
    read_from_kernel(p, 1024);              // FFI fills buf
    let initialized: [u8; 1024] = buf.assume_init();
}

#Using after write

write only stores the value; it returns no reference (Nabi has no ref returns). After writing, take the value out with assume_init.

nabi
let slot: MaybeUninit<Big> = MaybeUninit::uninit();
slot.write(big_value());
let v: Big = unsafe { slot.assume_init() };
process(v);

#1.3.3. The Pod trait

nabi
unsafe trait Pod { /* marker */ }

Short for Plain Old Data: a type for which every bit pattern is valid. The reinterpret of 1.2.5 requires this marker. It is an unsafe trait (4.15.4): #[derive(Pod)] writes the impl, and a hand-written one is unsafe impl Pod for T {}. Either way a struct's layout, fields and Drop are checked as below.

Automatic implNot applied
All integers (i*, u*)Ptr<T> (provenance)
All floating-point (f*)User structs (explicit #[derive(Pod)])
[T; N] (T:Pod)enum (variant tag, niche)
tuples of up to 4 elements, all Pod
c_charbool, char (most bit patterns are not values)

#What Pod guarantees

Pod guarantees three things at once.

  1. Reading any bit pattern is safe: no uninit exposure.
  2. Deterministic layout: #[repr(C)] or #[repr(transparent)] is required.
  3. No Drop: if Drop is implemented, Pod is automatically rejected.
nabi
#[derive(Pod)]
#[repr(C)]
struct Vec3 { x: f32; y: f32; z: f32; }
// → reinterpret OK, ffi safe, etc.

#1.3.4. raw mem ops - read / write

The free functions for low-level memory manipulation are:

nabi
unsafe fn read<T>(src: ConstPtr<T>) -> T;
unsafe fn write<T>(dst: Ptr<T>, value: T);

unsafe fn copy<T>(src: ConstPtr<T>, dst: Ptr<T>, count: usize);
                                               // memmove (overlap OK)
unsafe fn copy_nonoverlapping<T>(src: ConstPtr<T>, dst: Ptr<T>, count: usize);
                                               // memcpy (overlap UB, faster)

unsafe fn write_bytes<T>(dst: Ptr<T>, value: u8, count: usize);
                                               // memset (every byte = value)

unsafe fn swap<T>(a: Ptr<T>, b: Ptr<T>);
unsafe fn replace<T>(dst: Ptr<T>, value: T) -> T;     // read existing + write
unsafe fn drop_in_place<T>(p: Ptr<T>);               // runs the drop glue (does not free memory)

Most of these are also exposed as methods of Ptr<T> (1.1.2); the free functions of this module serve as an ergonomic alternative. Volatile accesses are bare::volatile::read / write (1.5), their one path.

drop_in_place runs the drop glue: the type's own drop, then its fields' in reverse declaration order (2.13.4).

#1.3.5. transmute_unchecked - escape hatch

It is the function described in 1.2.6. It is defined in this module; bare::transmute_unchecked is its re-export at the tier root.

nabi
unsafe fn transmute_unchecked<A, B>(a: A) -> B;        // no size check

#1.3.6. align / size util

nabi
fn align_of<T>() -> usize;                  // T::align()
fn size_of<T>() -> usize;                   // T::size()

These are not unsafe. They are the bare-tier forms of T::size() / T::align() from the Reflect trait (2.12 reflect): bare code has no Reflect. They are defined here and nowhere else. There are no value forms: the size of what a value holds at run time (a sum's member, the content of an any) is x.size_of_val() (2.12.2); bare code only has static types.

#1.3.7. intrinsic mapping

The correspondence between each item and compiler intrinsics is:

Itemintrinsic
MaybeUninit::as_ptr / as_mut_ptrnabi.addr_of (assume_init is a plain field read)
ptr::addr_of / many_addr_ofnabi.addr_of
Pod(marker, derived automatically)
read / writenabi.ptr.read / nabi.ptr.write (through the Ptr / ConstPtr methods)
copy / copy_nonoverlappingnone: a loop of element read / write (copy runs backward when dst is above src)
write_bytesnone: a loop of byte writes
drop_in_placenabi.drop_in_place
size_of / align_ofnabi.size_of / nabi.align_of
buf_new / buf_get / buf_set / buf_samenabi.buf_new / nabi.buf_get / nabi.buf_set / nabi.buf_same

#1.3.8. Comparison with other languages

AspectCRustZigNabi
Uninitialized representationT x; (silent)MaybeUninit<T>undefinedMaybeUninit<T>
Pod / safe transmutenonebytemuck::Pod (lib)@bitCastPod + reinterpret
Uninitialized read UBallowedUBUBUB
memcpy / memmovememcpyptr::copy*@memcpybare::mem::copy*

#1.3.9. GcBuf<T> and the buf_* primitives

GcBuf<T>, the compiler-known GC buffer that collections are built on, is defined in this module. Its semantics are those of 2.9.12, where core::collections::raw re-exports it.

nabi
struct GcBuf<T> { /* one GC reference to a run of Ts */ }

impl<T> GcBuf<T> {
    unsafe fn new(len: usize) -> GcBuf<T>;     // = buf_new(len)
    unsafe fn get(self, i: usize) -> T;        // = buf_get(self, i)
    unsafe fn set(self, i: usize, v: T);       // = buf_set(self, i, v)
}
impl<T> Clone for GcBuf<T>;                    // the same handle: the clone shares the buffer

unsafe fn buf_new<T>(len: usize) -> GcBuf<T>;      // zeroed
unsafe fn buf_get<T>(buf: GcBuf<T>, i: usize) -> T;        // no bounds check
unsafe fn buf_set<T>(buf: GcBuf<T>, i: usize, v: T);       // no bounds check
fn buf_same<T>(a: GcBuf<T>, b: GcBuf<T>) -> bool;  // identity, not contents; pins nothing

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