← core

core/ptr.kur

//! Raw pointer operations.
// Raw pointer helpers (`null`, `is_null`, `offset`), pointers that are
// never null, and volatile access through raw pointers.

use package as core;

use core::option::Option;
use core::mem::sizeof;

// `NonNull[T]`, below, and the volatile accesses through a raw pointer:
// `unsafe load_volatile(p)` and `unsafe store_volatile(p, v)`, the same as
// `p.load_volatile()` and `p.store_volatile(v)`.
export builtin::{NonNull, load_volatile, store_volatile};

// `NonNull[T]` is a builtin type, like `*T`: a pointer that is never null. It
// is Copy, as wide as `*T`, and compares with `==` and `!=`. `p as *T` is
// safe; the way in from a pointer is `new`, which checks, or an unsafe cast
// (`unsafe (p as NonNull[T])`), whose obligation is that `p` is not null.
// Nothing else casts to or from it.
//
// Its all-zero value is no value of the type: that is the niche of
// compiler/README.md ("Enum layout"). A struct, tuple or array holding a
// `NonNull` has the niche of its first one, so an enum of two variants, one
// with such a payload and the other zero-size, is that payload alone, the
// zero-size variant a null in it: `Option[NonNull[T]]`, `Option[Ref[T, 'k]]`
// and `List[T, 'k]` are one word. The layout follows from the types, never
// from a name.
forall T.
impl NonNull[T] {
    /// `p` as a `NonNull`, when it is not null.
    fn new(p: *T) -> Option[NonNull[T]] {
        if is_null(p) {
            Option::None
        } else {
            Option::Some.(unsafe (p as NonNull[T]))
        }
    }

    /// `p` as a `NonNull`. The C compiler is told it is not null, so a null
    /// one is undefined behavior. Caller: `p` is not null.
    unsafe fn new_unchecked(p: *T) -> NonNull[T] {
        unsafe (p as NonNull[T])
    }

    /// The pointer.
    fn as_ptr(self) -> *T {
        self as *T
    }
}

/// The null `*T`. Safe: it carries no authority, and reading or writing
/// through it, as through any raw pointer, needs its own `unsafe`.
forall T.
fn null() -> *T {
    unsafe (0usize as *T)
}

/// Whether `p` is null.
forall T.
fn is_null(p: *T) -> bool {
    p == null[T]()
}

/// The address `count` elements of `T` past `base`: integer arithmetic on
/// the address, since pointers have none of their own. Caller: the result
/// stays inside the block `base` points into; nothing checks it, and every
/// use of the result relies on it.
forall T.
unsafe fn offset(base: *T, count: usize) -> *T {
    unsafe ((unsafe (base as usize) + count * sizeof[T]()) as *T)
}