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 are the allocation-free inverse of their default presentation.

Details

A Formatter carries presentation policy while the ambient Writer owns byte transport. Formatter and the shipped integer presentations do not allocate an intermediate String. 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 width-driven integer zero padding is requested. A supplied precision disables that padding when presenting an integer.

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 minimum digit count, or zero when no numeric precision was supplied. For integers, a supplied precision disables width-driven zero padding.

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<'env> fn write<'life0: 'env, 'life1: 'env, 'env>(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<'env> fn writeText<'life0: 'env, 'life1: 'env, 'env>(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<'env> fn display<T: 'env, 'life1: 'env, 'env>(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<'env> fn displayWith<T: 'env, 'life1: 'env, 'env>(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 disables width-driven zero padding. Alternate form and color do not change integer 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<'env> fn format<Args: 'env, 'life1: 'env, 'env>(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 09 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.MINi64.MAX is OutOfRange.

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.MINi8.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.MINi16.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.MINi32.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.MINi64.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. Alternate form and color do not change integer 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 minimum digit count for numeric presentations. For integers, supplying precision disables width-driven zero padding.

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<'env> fn display<'life0: 'env, 'life1: 'env, 'env>(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 string<'text>

impl Display for string<'text>

Operation display

display = string.impl@10.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.zeroPadAssociated function Format.hasPrecisionAssociated function Format.precisionAssociated 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.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 precisionField 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 string<'text>Operation displayDetails