Module: libc.format

Source: ./libc/format.reef


Overview

libc.format - Number formatting and parsing (compatibility façade)

Thin wrappers over core.convert + core.str. The historical C sprintf/sscanf FFI (c_sprintf_*, c_parse_*) was never shipped in the runtime; this module reimplements the exported names in pure Reef so import libc.format links.

Prefer core.convert directly for new code (allocating APIs that return string / Result). These sprintf_* helpers keep the old buffer-filling signatures for call-site compatibility.

Buffer contract for sprintf_*:

  • buffer must be a heap-allocated mutable string (e.g. reef_alloc_string_buffer / reef_string_alloc), not a string literal.
  • Destination capacity is the heap-block length (bytes), which includes one byte for the trailing NUL. Max chars written = capacity - 1.
  • If the formatted text is longer than that, the write is truncated to fit (no OOB). Typical maxima for a 32-bit int: hex ≤ 8 digits, octal ≤ 11, prefixed hex ≤ 10, padded forms ≤ max(width, digits) — allocate generously (e.g. 64) when unsure if you need the full form.
  • Returns the number of characters actually written (not counting NUL), which may be less than the untruncated formatted length when clamped.

parse_: returns the integer on success; returns -1 on invalid input (convert's Result Err path). Prefer convert.from_ when you need Result.


Functions

fn write_into(buffer: string, formatted: string): int

Overwrites buffer with formatted and publishes str_len. Clamps to destination capacity (heap-block length minus one for NUL) so undersized buffers never OOB before set_length. Capacity is the block length field — not logical str_len — so a prior shorter write does not shrink the usable destination. Returns chars actually written.

fn sprintf_hex(buffer: string, value: int): int

Formats integer as uppercase hexadecimal (e.g., "FF")

fn sprintf_hex_lower(buffer: string, value: int): int

Formats integer as lowercase hexadecimal (e.g., "ff")

fn sprintf_hex_prefixed(buffer: string, value: int): int

Formats integer as prefixed hexadecimal (e.g., "0xFF")

fn sprintf_octal(buffer: string, value: int): int

Formats integer as octal (e.g., "377")

fn sprintf_padded(buffer: string, value: int, width: int): int

Formats integer as zero-padded decimal (e.g., "0042" with width 4) Note: convert uses zero-padding (same as the old %0Nd C path).

fn sprintf_hex_padded(buffer: string, value: int, width: int): int

Formats integer as zero-padded uppercase hex (e.g., "00FF" with width 4)

fn parse_hex(s: string): int

Parses hexadecimal string to integer (e.g., "FF" / "0xFF" -> 255). Returns -1 on invalid input.

fn parse_octal(s: string): int

Parses octal string to integer (e.g., "377" / "0o377" -> 255). Returns -1 on invalid input.

fn parse_binary(s: string): int

Parses binary string to integer (e.g., "11111111" / "0b11111111" -> 255). Returns -1 on invalid input.


Generated by reefc doc