Silk

silk/format

Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc.

Writer-backed value presentation, statically validated templates, and complete decimal parsing.

When to use

Use display for one value. Use format for a static template and a borrowed argument pack. Use displayWith when presentation needs explicit options. Integer parse operations and f64Value/f32Value are allocation-free inverses of their default presentation.

Details

A Formatter carries presentation policy while the ambient Writer owns byte transport. Formatter and the shipped numeric presentations do not allocate an intermediate String. Finite floats use the shortest decimal significand that parses back to identical IEEE bits, preserving negative zero as -0. Supplying precision replaces that default with exactly that many fractional digits, rounded ties-to-even against the value's exact decimal expansion; a fixed presentation is therefore not required to round-trip. Nonfinite floats display as NaN or Infinity; formats requiring finite values must check with f64.isFinite or f32.isFinite before display. Width counts Unicode scalars rather than UTF-8 bytes or terminal cells. A Writer failure preserves any prefix that the provider accepted. Formatter does not roll output back. Template parsing, field selection, and Display selection occur during compilation.

Examples

Display with defaults and explicit options

This program formats 42..+42 through a portable discard writer. Supply a native silk.os_writer.StdoutWriter at an application edge to send the bytes to stdout.

import silk.effect { Effect }

import silk.format { Alignment, Format, FormatOptions, Sign }

import silk.option { Option }

import silk.writer { Writer, WriterError }

struct DiscardWriter {}
impl Writer for DiscardWriter {
  effect fn writeAll(self: &mut Self, val: &[u8]) -> () ! WriterError ? &mut Writer {
    return ()
  }
  effect fn flush(self: &mut Self) -> () ! WriterError ? &mut Writer {
    return ()
  }
}

effect fn render() -> () ! WriterError ? &mut Writer {
  let value = 42
  run Format.display(&value)
  let options = FormatOptions {
    width: Option.some<usize>(5),
    alignment: Alignment.Right,
    fill: '.',
    sign: Sign.Always,
    alternate: false,
    zeroPad: false,
    precision: Option.none<usize>(),
    color: false,
  }
  return run Format.displayWith(&value, move options)
}

effect fn writeExample() -> () ! WriterError {
  let mut writer = DiscardWriter {}
  let completed = run render()
    |> Effect.provideMut<Writer>(&mut writer)
  return completed
}

effect fn ignoreWriteFailure(error: WriterError) -> () {
  return ()
}

pub fn main() -> i32 {
  run Effect.catchAll(writeExample(), ignoreWriteFailure)
  return 0
}

Import as Format with import silk.format { Format }.

Public declarations: 9.

Format

pub struct Format

The owner of the parsing and rendering operations.

Details

This struct carries no data and is never constructed by the library. Every operation is an inherent member declared in impl Format, reached through import silk.format { Format }.

Associated function Format.defaultOptions

pub fn defaultOptions() -> FormatOptions

Returns the canonical formatting defaults.

Details

The result has no width, default alignment, a space fill, negative-only signs, no alternate form, no zero padding, no precision, and no color permission.

Associated function Format.make

pub fn make(options: FormatOptions) -> Formatter

Starts a Formatter session with explicit options.

Associated function Format.makeDefault

pub fn makeDefault() -> Formatter

Starts a Formatter session with defaultOptions.

Associated function Format.hasWidth

pub fn hasWidth<'life0>(self: &'life0 silk/format.Formatter) -> bool

Reports whether a minimum width was supplied.

Associated function Format.width

pub fn width<'life0>(self: &'life0 silk/format.Formatter) -> usize

Returns the requested minimum width in Unicode scalars, not UTF-8 bytes or terminal cells, or zero when no width was supplied.

Associated function Format.alignment

pub fn alignment<'life0>(self: &'life0 silk/format.Formatter) -> Alignment

Returns the requested alignment.

Associated function Format.fill

pub fn fill<'life0>(self: &'life0 silk/format.Formatter) -> char

Returns the requested fill scalar.

Associated function Format.sign

pub fn sign<'life0>(self: &'life0 silk/format.Formatter) -> Sign

Returns the requested sign policy.

Associated function Format.alternate

pub fn alternate<'life0>(self: &'life0 silk/format.Formatter) -> bool

Reports whether alternate presentation is requested.

Associated function Format.zeroPad

pub fn zeroPad<'life0>(self: &'life0 silk/format.Formatter) -> bool

Reports whether integer width padding with zeroes is requested.

Details

A supplied precision disables this padding for integers. Float presentations use the fill scalar for width padding and never use zeroes.

Associated function Format.hasPrecision

pub fn hasPrecision<'life0>(self: &'life0 silk/format.Formatter) -> bool

Reports whether a numeric precision was supplied.

Associated function Format.precision

pub fn precision<'life0>(self: &'life0 silk/format.Formatter) -> usize

Returns the requested digit count, or zero when no numeric precision was supplied.

Details

For integers this is a minimum digit count and disables width-driven zero padding. For floats it is the exact number of fractional digits.

Associated function Format.color

pub fn color<'life0>(self: &'life0 silk/format.Formatter) -> bool

Reports whether a presentation may emit balanced ANSI styling.

Associated function Format.write

pub effect<'life0 & 'life1> fn write<'life0, 'life1>(self: &'life0 mut silk/format.Formatter, bytes: &'life1 [u8]) -> () ! WriterError ? &mut Writer

Writes one byte sequence through the ambient Writer.

Gotchas

If Writer fails, this returns the original WriterError; any prefix accepted before the failure remains written.

Associated function Format.writeText

pub effect<'life0 & 'life1> fn writeText<'life0, 'life1>(self: &'life0 mut silk/format.Formatter, text: string<'life1>) -> () ! WriterError ? &mut Writer

Writes valid UTF-8 content without applying width policy.

Gotchas

If Writer fails, this returns the original WriterError; any prefix accepted before the failure remains written.

Associated function Format.writePadding

pub effect<'life0> fn writePadding<'life0>(self: &'life0 mut silk/format.Formatter, count: usize) -> () ! WriterError ? &mut Writer

Writes count copies of the session's fill scalar in bounded chunks.

Gotchas

If Writer fails, this returns the original WriterError; any fill accepted before the failure remains written.

Associated function Format.leadingPadding

pub fn leadingPadding<'life0>(self: &'life0 silk/format.Formatter, contentWidth: usize) -> usize

Returns the number of fill scalars before content with this visible width.

Details

A user-defined Display can use this together with writeLeadingPadding and writeTrailingPadding so ANSI control bytes never count toward the visible content width. Alignment.Default and Alignment.Right put all extra fill before the content; Alignment.Left puts Option.none there. Alignment.Center puts half there, rounding an odd extra scalar down so the trailing side receives the remainder. No padding is returned when the requested width does not exceed contentWidth.

Associated function Format.trailingPadding

pub fn trailingPadding<'life0>(self: &'life0 silk/format.Formatter, contentWidth: usize) -> usize

Returns the number of fill scalars after content with this visible width.

Details

Alignment.Default and Alignment.Right put no extra fill after the content; Alignment.Left puts all extra fill there. Alignment.Center puts half there, rounding an odd extra scalar up. No padding is returned when the requested width does not exceed contentWidth.

Associated function Format.writeLeadingPadding

pub effect<'life0> fn writeLeadingPadding<'life0>(self: &'life0 mut silk/format.Formatter, contentWidth: usize) -> () ! WriterError ? &mut Writer

Emits all fill required before content whose width is the supplied Unicode-scalar count, not a byte or terminal-cell count.

Gotchas

If Writer fails, this returns the original WriterError; any leading fill accepted before the failure remains written.

Associated function Format.writeTrailingPadding

pub effect<'life0> fn writeTrailingPadding<'life0>(self: &'life0 mut silk/format.Formatter, contentWidth: usize) -> () ! WriterError ? &mut Writer

Emits all fill required after content whose width is the supplied Unicode-scalar count, not a byte or terminal-cell count.

Gotchas

If Writer fails, this returns the original WriterError; any trailing fill accepted before the failure remains written.

Associated function Format.display

pub effect<'life1> fn display<T: 'life1, 'life1>(value: &'life1 T) -> () ! WriterError ? &mut Writer

Displays one value with canonical defaults through the ambient mutable Writer.

Details

This operation uses defaultOptions and does not require Allocator. If Writer fails, an accepted prefix remains written and the original WriterError is preserved.

Associated function Format.displayWith

pub effect<'life1> fn displayWith<T: 'life1, 'life1>(value: &'life1 T, options: FormatOptions) -> () ! WriterError ? &mut Writer

Displays one value with explicit options through the ambient mutable Writer.

Details

Width counts Unicode scalars. For integers, precision is a minimum digit count and disables width-driven zero padding. For floats, precision is the exact number of fractional digits rounded ties-to-even, replacing the shortest round-tripping default; float padding always uses the fill scalar. Alternate form and color do not change numeric output. This operation does not require Allocator. If Writer fails, an accepted prefix remains written and the original WriterError is preserved.

Associated function Format.format

pub effect<'life1> fn format<Args: 'life1, 'life1>(static template: string<'static>, args: &'life1 Args) -> () ! WriterError ? &mut Writer

Writes a statically validated template with values from one borrowed tuple or record.

When to use

Use when the template is static and each replacement value has a Display implementation.

Details

{} selects tuple fields in order. {name} selects visible record fields. {{ and }} write literal braces. The operation borrows args and does not allocate an intermediate String.

Gotchas

A template cannot mix positional and named placeholders. A positional template must use every tuple field one time. Malformed templates and unavailable fields stop compilation. A Writer failure preserves the prefix that the provider accepted.

Examples

Write a named argument pack

This program formats Hello, Julia. Age: 31 through a portable discard writer.

import silk.effect { Effect }

import silk.format { Format }

import silk.writer { Writer, WriterError }

struct DiscardWriter {}
impl Writer for DiscardWriter {
  effect fn writeAll(self: &mut Self, val: &[u8]) -> () ! WriterError ? &mut Writer {
    return ()
  }
  effect fn flush(self: &mut Self) -> () ! WriterError ? &mut Writer {
    return ()
  }
}

effect fn render() -> () ! WriterError ? &mut Writer {
  let args = .{name: "Julia", age: 31}
  return run Format.format("Hello, {name}. Age: {age}", &args)
}

effect fn writeExample() -> () ! WriterError {
  let mut writer = DiscardWriter {}
  return run render()
    |> Effect.provideMut<Writer>(&mut writer)
}

effect fn ignoreWriteFailure(error: WriterError) -> () {
  return ()
}

pub fn main() -> i32 {
  run Effect.catchAll(writeExample(), ignoreWriteFailure)
  return 0
}

Associated function Format.unsignedValue

pub fn unsignedValue<'life0>(text: string<'life0>) -> silk/result.Result<u64, silk/format.ParseError>

Reads complete decimal text as an unsigned value.

Details

Empty text, a leading sign, and any byte outside 0–9 are NotANumber at the offset that stopped the read. A value above u64.MAX is OutOfRange, detected before the overflow rather than after it.

Associated function Format.signedValue

pub fn signedValue<'life0>(text: string<'life0>) -> silk/result.Result<i64, silk/format.ParseError>

Reads complete decimal text as a signed value, accepting one leading -.

Details

Digits accumulate negatively, so text naming i64.MIN reads like any other value. A leading + is not accepted. A value outside i64.MIN–i64.MAX is OutOfRange.

Associated function Format.f64Value

pub fn f64Value<'life0>(text: string<'life0>) -> silk/result.Result<f64, silk/format.ParseError>

Reads a complete finite decimal spelling, rounding directly to IEEE binary64.

Details

An optional sign, decimal point, and e exponent are accepted. NaN and Infinity are rejected. Overflow rounds to infinity and underflow rounds to signed zero. The fallback compares exact decimal values with binary64 rounding boundaries, including subnormals and ties to even; no intermediate floating-point multiplication decides the result.

Associated function Format.f32Value

pub fn f32Value<'life0>(text: string<'life0>) -> silk/result.Result<f32, silk/format.ParseError>

Reads a complete finite decimal spelling, rounding directly to IEEE binary32.

Details

The decimal is never rounded through binary64, avoiding double rounding. Overflow produces infinity and underflow preserves the sign of zero.

Associated function Format.u8Value

pub fn u8Value<'life0>(text: string<'life0>) -> silk/result.Result<u8, silk/format.ParseError>

Reads complete decimal text as a u8, rejecting a value above u8.MAX.

Associated function Format.u16Value

pub fn u16Value<'life0>(text: string<'life0>) -> silk/result.Result<u16, silk/format.ParseError>

Reads complete decimal text as a u16, rejecting a value above u16.MAX.

Associated function Format.u32Value

pub fn u32Value<'life0>(text: string<'life0>) -> silk/result.Result<u32, silk/format.ParseError>

Reads complete decimal text as a u32, rejecting a value above u32.MAX.

Associated function Format.u64Value

pub fn u64Value<'life0>(text: string<'life0>) -> silk/result.Result<u64, silk/format.ParseError>

Reads complete decimal text as a u64, rejecting a value above u64.MAX.

Associated function Format.usizeValue

pub fn usizeValue<'life0>(text: string<'life0>) -> silk/result.Result<usize, silk/format.ParseError>

Reads complete decimal text as a usize, rejecting a value the target's pointer width cannot hold.

Associated function Format.i8Value

pub fn i8Value<'life0>(text: string<'life0>) -> silk/result.Result<i8, silk/format.ParseError>

Reads complete decimal text as an i8, rejecting a value outside i8.MIN–i8.MAX.

Associated function Format.i16Value

pub fn i16Value<'life0>(text: string<'life0>) -> silk/result.Result<i16, silk/format.ParseError>

Reads complete decimal text as an i16, rejecting a value outside i16.MIN–i16.MAX.

Associated function Format.i32Value

pub fn i32Value<'life0>(text: string<'life0>) -> silk/result.Result<i32, silk/format.ParseError>

Reads complete decimal text as an i32, rejecting a value outside i32.MIN–i32.MAX.

Associated function Format.i64Value

pub fn i64Value<'life0>(text: string<'life0>) -> silk/result.Result<i64, silk/format.ParseError>

Reads complete decimal text as an i64, rejecting a value outside i64.MIN–i64.MAX.

Associated function Format.isizeValue

pub fn isizeValue<'life0>(text: string<'life0>) -> silk/result.Result<isize, silk/format.ParseError>

Reads complete decimal text as an isize, rejecting a value the target's pointer width cannot hold.

Alignment

pub enum Alignment

Alignment of content within a requested minimum width.

Default

Default = 0

Requests default alignment. The shared padding helpers and integers use right alignment.

Left

Left = 1

Emits all required fill after the content.

Center

Center = 2

Splits fill around the content, placing an odd remainder on the right.

Right = 3

Emits all required fill before the content.

Sign

pub enum Sign

Sign policy available to numeric presentation implementations.

NegativeOnly

NegativeOnly = 0

Emits a sign only for negative values.

Always

Always = 1

Emits - for negative values and + otherwise.

Space

Space = 2

Emits - for negative values and one space otherwise.

FormatOptions

pub struct FormatOptions

Explicit policy for one formatting session.

Details

defaultOptions uses no width, default alignment, a space fill, negative-only signs, no alternate form, no zero padding, no precision, and no color. Width counts Unicode scalars. For integers, precision disables width-driven zero padding. For floats, precision selects fixed fractional digits instead of the shortest round-tripping form. Alternate form and color do not change numeric output.

Field width

pub width: silk/option.Option<usize>

Optional minimum visible width in Unicode scalars, not UTF-8 bytes or terminal cells.

Field alignment

pub alignment: Alignment

Alignment inside the requested minimum width. Default is right alignment for the shared padding helpers and shipped integer presentations.

Field fill

pub fill: char

One Unicode scalar repeated for ordinary padding.

Field sign

pub sign: Sign

Numeric sign policy.

Field alternate

pub alternate: bool

Permission for a separately documented presentation to use an alternate form.

Field zeroPad

pub zeroPad: bool

Whether integer width padding uses zeroes after the sign. A supplied precision disables this width-driven zero padding.

Field precision

pub precision: silk/option.Option<usize>

Optional digit count for numeric presentations.

Details

For integers, this is a minimum digit count and disables width-driven zero padding. For floats, it is the exact number of fractional digits, rounded ties-to-even. This replaces the shortest round-tripping default, so the output may not parse back to the original bits. Nonfinite floats ignore it.

Field color

pub color: bool

Permission, not a requirement, to emit balanced ANSI styling.

Formatter

pub struct Formatter

Mutable presentation policy that does not store, select, or replace a Writer provider.

Display

pub interface Display

Static human-readable presentation contract for Writer-backed output.

Details

An implementation reads presentation policy from Formatter and writes through the ambient mutable Writer. The contract does not require Allocator. If Writer fails, an accepted prefix remains written and the original WriterError is preserved.

Operation display

effect<'life0 & 'life1> fn display<'life0, 'life1>(self: &'life0 Self, formatter: &'life1 mut silk/format.Formatter) -> () ! WriterError ? &mut Writer

Emits one presentation through the ambient mutable Writer.

Details

This operation reads policy from formatter. It does not require Allocator. If Writer fails, an accepted prefix remains written and the original WriterError is preserved.

NotANumber

pub struct NotANumber

The byte offset where complete decimal parsing cannot continue.

Field offset

pub offset: usize

The offset where reading stopped. It can equal the byte length when a digit was required.

OutOfRange

pub struct OutOfRange

A well-formed decimal number whose value does not fit the requested type.

ParseError

pub struct ParseError

Why decimal text did not produce a value, narrowed with match.

Field reason

pub reason: silk/format.NotANumber | silk/format.OutOfRange

The reason the text was rejected.

Implementation Display for u8

impl Display for u8

Operation display

display = u8.impl@0.display

Implementation Display for u16

impl Display for u16

Operation display

display = u16.impl@1.display

Implementation Display for u32

impl Display for u32

Operation display

display = u32.impl@2.display

Implementation Display for u64

impl Display for u64

Operation display

display = u64.impl@3.display

Implementation Display for usize

impl Display for usize

Operation display

display = usize.impl@4.display

Implementation Display for i8

impl Display for i8

Operation display

display = i8.impl@5.display

Implementation Display for i16

impl Display for i16

Operation display

display = i16.impl@6.display

Implementation Display for i32

impl Display for i32

Operation display

display = i32.impl@7.display

Implementation Display for i64

impl Display for i64

Operation display

display = i64.impl@8.display

Implementation Display for isize

impl Display for isize

Operation display

display = isize.impl@9.display

Implementation Display for f64

impl Display for f64

Operation display

display = f64.impl@10.display

Writes the shortest decimal that parses back to these exact bits, or fixed fractional digits when precision is supplied.

Details

The default presentation is the shortest significand whose correctly rounded parse returns the original bits, so f64Value recovers the value exactly. Negative zero displays as -0. A supplied precision instead emits exactly that many fractional digits, rounded ties-to-even against the value's exact decimal expansion, which is not required to round-trip.

Gotchas

NaN and Infinity ignore precision and width-driven zero padding; only the sign policy applies, and it applies to Infinity alone. Float padding always uses the fill scalar.

Implementation Display for f32

impl Display for f32

Operation display

display = f32.impl@11.display

Writes the shortest decimal that parses back to these exact bits, or fixed fractional digits when precision is supplied.

Details

Rounding reads the binary32 expansion, so the result can differ from the binary64 nearest to the same literal. Negative zero displays as -0. A supplied precision emits exactly that many fractional digits, rounded ties-to-even, which is not required to round-trip.

Gotchas

NaN and Infinity ignore precision and width-driven zero padding; only the sign policy applies, and it applies to Infinity alone. Float padding always uses the fill scalar.

Implementation Display for string<'text>

impl Display for string<'text>

Operation display

display = string.impl@12.display

Writes the string's UTF-8 bytes through the ambient mutable Writer.

Details

This operation borrows the string and does not allocate an intermediate String. If Writer fails, an accepted prefix remains written and the original WriterError is preserved.

On this page

When to useDetailsExamplesDisplay with defaults and explicit optionsFormatDetailsAssociated function Format.defaultOptionsDetailsAssociated function Format.makeAssociated function Format.makeDefaultAssociated function Format.hasWidthAssociated function Format.widthAssociated function Format.alignmentAssociated function Format.fillAssociated function Format.signAssociated function Format.alternateAssociated function Format.zeroPadDetailsAssociated function Format.hasPrecisionAssociated function Format.precisionDetailsAssociated function Format.colorAssociated function Format.writeGotchasAssociated function Format.writeTextGotchasAssociated function Format.writePaddingGotchasAssociated function Format.leadingPaddingDetailsAssociated function Format.trailingPaddingDetailsAssociated function Format.writeLeadingPaddingGotchasAssociated function Format.writeTrailingPaddingGotchasAssociated function Format.displayDetailsAssociated function Format.displayWithDetailsAssociated function Format.formatWhen to useDetailsGotchasExamplesWrite a named argument packAssociated function Format.unsignedValueDetailsAssociated function Format.signedValueDetailsAssociated function Format.f64ValueDetailsAssociated function Format.f32ValueDetailsAssociated function Format.u8ValueAssociated function Format.u16ValueAssociated function Format.u32ValueAssociated function Format.u64ValueAssociated function Format.usizeValueAssociated function Format.i8ValueAssociated function Format.i16ValueAssociated function Format.i32ValueAssociated function Format.i64ValueAssociated function Format.isizeValueAlignmentDefaultLeftCenterRightSignNegativeOnlyAlwaysSpaceFormatOptionsDetailsField widthField alignmentField fillField signField alternateField zeroPadField precisionDetailsField colorFormatterDisplayDetailsOperation displayDetailsNotANumberField offsetOutOfRangeParseErrorField reasonImplementation Display for u8Operation displayImplementation Display for u16Operation displayImplementation Display for u32Operation displayImplementation Display for u64Operation displayImplementation Display for usizeOperation displayImplementation Display for i8Operation displayImplementation Display for i16Operation displayImplementation Display for i32Operation displayImplementation Display for i64Operation displayImplementation Display for isizeOperation displayImplementation Display for f64Operation displayDetailsGotchasImplementation Display for f32Operation displayDetailsGotchasImplementation Display for string<'text>Operation displayDetails