← core

core/cstr.kur

//! NUL-terminated strings for C interfaces.
// core::cstr -- a NUL-terminated C string (an argv entry, a path, ...):
// distinct from `core::str::Str['k]`, which always knows its own length
// up front and is never NUL-terminated by convention.
//
// Capability-free (no `Exclusive!`/`Brand` threading): a `CStr` lives for
// the rest of the process, unchanged, so its bytes are `'static` text,
// read through `core::str::StaticRead`. `cstr_len` only reads bytes its
// caller answers for.

use package as core;

use core::cap::static_brand;
use core::ptr::offset;
use core::str::Str;

/// A borrowed, process-lifetime NUL-terminated string. Construction is
/// restricted because even measuring an arbitrary pointer would be unsafe.
struct CStr {
    ptr: *u8,
}

impl CStr {
    /// The C string at `ptr`.
    ///
    /// Caller: `ptr` addresses a NUL-terminated byte run that stays readable
    /// and unchanged for the rest of the process, as `argv` entries do.
    unsafe fn from_raw(ptr: *u8) -> CStr {
        CStr.{ ptr }
    }

    /// The raw pointer, for C interfaces. It grants no safe dereference
    /// authority.
    fn as_ptr(self) -> *u8 {
        let { ptr } = self;
        ptr
    }

    /// The number of bytes before the NUL. It scans for the NUL each time.
    fn len(self) -> usize {
        let { ptr } = self;
        // `from_raw`'s obligation: `ptr` addresses a live NUL-terminated run.
        unsafe cstr_len(ptr)
    }

    /// The bytes before the NUL, as `'static` text: they stay readable and
    /// unchanged for the rest of the process, so `StaticRead` reads them.
    fn bytes(self) -> Str['static] {
        let { ptr } = self;
        // `from_raw`'s obligation: the `len` bytes at `ptr` are readable and
        // unchanged for the rest of the process, which is what `'static`
        // promises.
        unsafe Str::from_raw_parts_branded(ptr, unsafe cstr_len(ptr), unsafe static_brand())
    }
}

/// Length of a NUL-terminated C string. The scan is unbounded: no length
/// is known ahead of it, so it walks until the NUL. Caller: `s` addresses a
/// live NUL-terminated byte run.
unsafe fn cstr_len(s: *u8) -> usize {
    var n = 0usize;
    var looping = true;
    while looping {
        let b = unsafe *(unsafe offset(s, n));
        if b == 0u8 {
            looping = false;
        } else {
            n = n + 1usize;
        }
    }
    n
}