docs

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

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

#1.2. cast operations - explicitly named casts

本頁內容

Conversions between pointers and types exist only as named functions. There is no cast module: ptr_cast, align_cast, align_cast_unchecked and const_cast are defined in bare::ptr, reinterpret and transmute_unchecked in bare::mem, and the bare root re-exports all six (bare::ptr_cast) together with Pod (1.2.5). The reason as casts in C and Rust are so dangerous is that the conversion happens silently; to avoid that pitfall, Nabi requires every cast to carry an explicit name.

#1.2.1. The 4 cast functions

The four basic functions are:

FunctionMeaningRisk
ptr_cast<U>(p: Ptr<T>)Changes the type only (provenance/address kept)alignment is the caller's
align_cast<T>(p: Ptr<u8>)Alignment up-castchecked (none when misaligned)
const_cast<T>(p: ConstPtr<T>)Removes constvery high (caller guarantees)
reinterpret<A: Pod, B: Pod>(a: A) -> Bbit-level cast (Pod only)low (guaranteed by the Pod marker)

In addition, there is one escape hatch for when a deeper bypass is needed.

FunctionMeaningRisk
transmute_unchecked<A,B>(a: A) -> Bbit cast without Pod checking (caller's responsibility)highest

The compiler rejects the as keyword on pointers, so users necessarily use named casts.

#1.2.2. ptr_cast<U> - pointer type conversion

nabi
fn ptr_cast<U, T>(p: Ptr<T>) -> Ptr<U>;

This function keeps address and provenance intact and changes only the type tag. Alignment is therefore the caller's responsibility. It takes Ptr only (Nabi has no overloading); ConstPtr and ManyPtr retype the same way with their own cast method (1.1): p.cast::<U>().

nabi
let p: Ptr<u32> = ...;        // 4-byte aligned
let q: Ptr<u8> = bare::ptr_cast::<u8>(p);    // safe (down-align)
let r: Ptr<u64> = bare::ptr_cast::<u64>(p);  // dangerous: u64 needs 8-byte
                                                 // r.read() may SIGBUS (ARM)

No alignment check is inserted, in any build: reading or writing through a misaligned result is UB. Check first with align_cast (1.2.3) or is_aligned (1.1.2).

#Safe cast - type-equivalent

Conversion between two structs with identical layout is safe.

nabi
struct A { x: u32 }
struct B { x: u32 }       // same layout as A

let pa: Ptr<A> = ...;
let pb: Ptr<B> = bare::ptr_cast::<B>(pa);    // safe if layout matches

The compiler does not verify that the layouts really match, however; the caller must bear that guarantee.

#1.2.3. align_cast<T> - alignment check

nabi
fn align_cast<T>(p: Ptr<u8>) -> Ptr<T> | none;

When turning a Ptr<u8> (1-byte align) into a Ptr<T> of larger alignment, the conversion happens only after the actual alignment is verified.

nabi
let bytes: ManyPtr<u8> = ...;
let p: Ptr<u8> = bytes.add(offset).as_one();

if let aligned: Ptr<u32> = bare::align_cast::<u32>(p) {
    let v = unsafe { aligned.read() };       // safe (verified)
} else {
    panic("not 4-byte aligned");
}

align_cast returns T | none, not Result, because the latter of the two forms is lighter.

#unchecked variant

nabi
fn align_cast_unchecked<T>(p: Ptr<u8>) -> Ptr<T>;     // without checking

Use it only where alignment has already been verified just before the call. This variant performs no check even in debug builds.

#1.2.4. const_cast<T> - const removal

nabi
fn const_cast<T>(p: ConstPtr<T>) -> Ptr<T>;

This function strips const. The danger is obvious: if the original lives in a read-only region (immortal const), writing there segfaults immediately.

nabi
use bare::ptr::{Ptr, ConstPtr, const_cast};

let s: str = "hello";              // immortal const
let p: ConstPtr<u8> = s.as_ptr();
let m: Ptr<u8> = const_cast(p);
unsafe { m.write(72u8) };          // 'H': SEGFAULT (write to immortal const)

It is exactly isomorphic to C's const_cast<T*>. Its use is limited to temporarily wrapping a read-only API where mutability is required; ordinary code must not use it.

#1.2.5. reinterpret<A: Pod, B: Pod> - bit cast (safe)

nabi
unsafe trait Pod { /* marker: Plain Old Data */ }

fn reinterpret<A: Pod, B: Pod>(a: A) -> B;

For types with the Pod (Plain Old Data) marker, safe transmute is guaranteed, because:

  • Every bit pattern of a Pod type is valid, so uninit can never be exposed.
  • Conversion is allowed only between equal sizes. A where size_of bound has no compile-time form, so the size condition is checked when reinterpret runs (a mismatch panics).
  • It is a value conversion, so alignment is naturally guaranteed.
nabi
let f: f32 = 3.14;
let bits: u32 = bare::reinterpret(f);     // OK: both Pod, 4 bytes
let f2: f32 = bare::reinterpret(bits);    // round-trip OK

#Automatic Pod derive

The standard library automatically gives Pod to these types:

nabi
unsafe impl Pod for i8, i16, i32, i64, u8, u16, u32, u64, usize, isize { }
unsafe impl Pod for f32, f64 { }
unsafe impl Pod for c_char { }
unsafe impl<T: Pod, const N: usize> Pod for [T; N] { }
unsafe impl<A: Pod> Pod for (A,) { }
unsafe impl<A: Pod, B: Pod> Pod for (A, B) { }
unsafe impl<A: Pod, B: Pod, C: Pod> Pod for (A, B, C) { }
unsafe impl<A: Pod, B: Pod, C: Pod, D: Pod> Pod for (A, B, C, D) { }

bool and char are not Pod: most of their bit patterns are not values (bool is 0 or 1, char a Unicode scalar). Reinterpret to u8 / u32 and convert with a check (b != 0u8, char::from_u32).

Pod is an unsafe trait (4.15.4): its impl promises that every bit pattern is a value, which the compiler cannot check, so a hand-written impl is unsafe impl Pod for T {}. #[derive(Pod)] writes it.

The following are not given it automatically:

  • Ptr<T> carries separate provenance information and cannot be represented by bits alone.
  • User structs must opt in explicitly with #[derive(Pod)].
nabi
#[derive(Pod)]
#[repr(C)]
struct Vec3 { x: f32; y: f32; z: f32; }

let v: Vec3 = Vec3 { x: 1.0, y: 2.0, z: 3.0 };
let bytes: [u8; 12] = bare::reinterpret(v);
let v2: Vec3 = bare::reinterpret(bytes);

This design follows the Project Safe Transmute (Rust RFC 2835) model and the bytemuck crate pattern.

#1.2.6. transmute_unchecked<A, B> - escape hatch

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

This function moves bits as is, without even Pod checking. As the name says, it is the most dangerous cast, so it is an unsafe fn: uninit exposure, size mismatch, alignment problems and the GC references inside are all the caller's responsibility. It panics mem::transmute_unchecked: out of memory when the scratch block cannot be allocated. A size mismatch is not rejected; the value goes through a zeroed scratch block as large as the larger type, so the bytes past the source's size read as zero.

Its use is limited to the lowest layer inside the standard library, only for cases that cannot be expressed with any other tool, such as writing a Pod impl itself. Ordinary user code must never use it.

nabi
// example inside the standard library
unsafe impl Pod for SomeNewtype {
    // empty marker
}

let s: SomeNewtype = ...;
let bits: u64 = unsafe { bare::transmute_unchecked(s) };   // code where SomeNewtype guarantees size 8

#1.2.7. Where as casts apply

as is a numeric cast (refs-lang 2.14.2): it is allowed between any two of the integer types, the floating-point types, bool, char and c_char, with the target restrictions refs-lang gives, and gives the same result as .wrapping_into(). A lossy pair wraps (integers) or truncates toward zero and saturates (float to integer). Only pointers are rejected.

ExpressionResult
i32 as i64OK (lossless widening)
i64 as i32OK, wraps (try_into / saturating_into to check or saturate)
f32 as f64OK (lossless)
i32 as f32OK, rounds to the nearest f32
u32 as i32OK, the same bits (0xFFFF_FFFF is -1)
Ptr<T> as Ptr<U>Compile error: bare::ptr_cast::<U>
Ptr<T> as usizeCompile error: .addr() or expose_provenance
usize as Ptr<T>Compile error: from_exposed_provenance

See 2.11 conversion for the full conversion matrix.

#1.2.8. Policy summary

The cast policy of this chapter comes down to four points.

  • as casts are numeric only; pointers never go through as, and a non-numeric bit reinterpretation goes through reinterpret.
  • The four functions bare::ptr_cast / align_cast / const_cast / reinterpret are the channels for explicit casts.
  • The Pod marker trait provides the safety condition for bit reinterpretation.
  • transmute_unchecked is exposed only as an escape hatch.

With this policy Nabi avoids both C's cumbersome type conversions and Rust's as pitfalls on pointers.

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