Landin library reference discuss source

Shared: available on every enabled target.

Byte cursors, validated UTF-8 views, positions and searches inside them, a scalar encoder, two text builders, formatting and parsing numbers.

Call What it does
text.from_bytes, text.valid Check that bytes are UTF-8, as a view or as a yes or no.
text.start, text.step, text.utf8_at_end, text.scalar_length Walk text a scalar at a time, keeping each scalar's byte position.
text.find, text.find_scalar and their _from forms Find where text or a scalar first occurs.
text.encode Write a scalar's UTF-8 bytes into your buffer.
text.utf8_over Make a builder that only ever holds UTF-8.
text.over, text.growing Make a builder over your buffer, or one that grows from an allocator.
text.append_text, text.append_u32 and the rest Append a piece to a builder.
text.format Append a template with each {} filled in.
text.format_onto Format a template through a buffer, handing the text to an outlet as the buffer fills.
text.parse_u32 and the rest Read a number from bytes.
text.os_string_over, text.from_os_string Make an OS string, and check that one is UTF-8.

Views and cursors

Cursors advance by bytes. Views borrow their input.

Three things check that bytes are UTF-8:

  • from_bytes validates the bytes and reports invalid_text when they are not UTF-8.
  • valid answers the same question without a view.
  • The utf8(bytes) conversion validates too, but it traps on malformed input.

A text.position indexes utf8 by byte offset, while a usize index into utf8 counts scalars. So do not index with offset(position). text.from_offset makes a position at any offset you give it and checks nothing. The positions below are always on a scalar's start.

UTF-8 equality, hashing and ordering use the encoded bytes, with no normalization and no locale collation.

Positions and searches in text

The byte cursors step one byte over []u8. Over utf8, positions step a whole scalar, so each position is where a scalar starts, or the end:

Call What it does
start(source) The first scalar's position, offset zero.
done(source, at) Whether at is at the end.
width(source, at) How many bytes, one to four, the scalar at at takes.
step(source, at) The position after the scalar at at.
find(source, sought) Where sought first begins, or mem.not_found.
find_from(source, sought, at) The same, searching from at.
find_scalar(source, scalar), find_scalar_from Where a scalar first is, or mem.not_found.

Read the scalar at a position as source[at]. Walk the text by stepping until utf8_at_end. This function walks a key that way, and checks each scalar and where it begins:

--  The key's scalars and where each begins, read by stepping.
key_steps: (key: utf8) -> (yes: bool) =
    scalars: [5]u32 = ['n', 'a', '\u{ef}', 'v', 'e']
    offsets: [5]usize = [0, 1, 2, 4, 5]
    widths: [5]usize = [1, 1, 2, 1, 1]
    yes = false
    mut at := text.start(key)
    mut index: usize = 0
    while not text.utf8_at_end(key, at) do
        return when index >= 5 or key[at] <> scalars[index]
          or text.offset(at) <> offsets[index]
          or text.scalar_length(key, at) <> widths[index]
        at = text.step(key, at)
        inc index
    end while
    yes = index == 5 and text.offset(at) == lenof key
end key_steps

step and scalar_length read the scalar at the position, so they trap where source[at] traps: at the end and inside a scalar. A search from a position inside a scalar traps too.

A match begins and ends where scalars do. The text before the match, the match and the text after it are therefore each a range of the source: utf8 with the source's origin, and nothing copied. This function splits a record at its first =:

--  The key before the first `=` and the value after it.
split: (record: utf8) -> (result: entry from record) ! mem.not_found =
    equals := try text.find_scalar(record, '=')
    value_at: usize = text.offset(text.step(record, equals))
    result = (key: record[0..<text.offset(equals)],
              value: record[value_at..<lenof record])
end split

The splitter goes on to take each field between arrows with find_from.

Three more facts about searches:

  • Empty sought text is found where the search begins, as contains finds it.
  • A surrogate is in no text, so find_scalar reports mem.not_found for one.
  • Searches are the Two-Way search that contains uses. It is linear in the two lengths, with no table and no allocation.

Encoding a scalar

encode(scalar, into) writes the scalar's UTF-8 bytes at the front of into and returns how many it wrote, one to four. To write at an offset, pass what follows the offset, buffer[at..<lenof buffer].

encode refuses in two cases, and either refusal writes nothing:

  • A surrogate, U+D800 to U+DFFF, or a value above U+10FFFF is invalid_scalar. This refusal comes first, whatever the room.
  • A scalar that does not fit is mem.out_of_memory.

OS strings

An OS string, os_string, is a path, a process argument or a directory entry's name, in the representation its system gives and takes. On Linux, Darwin and FreeBSD that representation is bytes, which need not be UTF-8. An OS string is never converted on the way through, so an argument passed on as a path reaches the system as it was given.

Call What it does
from_os_string The checked conversion to utf8, reporting invalid_text as from_bytes does.
os_string_bytes Lend its bytes.
os_string_equal Compare it with a literal.
os_string_over Make one over the caller's bytes: text.os_string_over("input.txt") for a literal path.

An OS string lends what it was made from. The NUL a C call needs is never the caller's: platform/posix adds it beneath the provider, and refuses a path that holds one.

The builder

A builder writes text into bytes a piece at a time. It is a value the caller passes inout.

Call What it does
over Make a builder over the caller's buffer, which never grows.
growing Make a builder that takes its storage from an erased allocator, text.growing(any(addr heap)). It doubles what it holds, and release gives the storage back.
used Lend what the builder holds, until the builder next changes.
length The offset the next piece begins at.
clear, truncate Empty the builder, or cut it back.

An append, and format, may be given the builder's own bytes, text.used(line) or a part of it. What is written is what they held when the call began, though the builder grew and moved while it wrote. The view is still not to be used after the call.

Each append writes its whole piece, or reports mem.out_of_memory and leaves the builder as it was:

Append Writes
append bytes as they are
append_byte one byte
append_text a utf8
append_scalar a scalar's UTF-8 bytes, as encode writes them, or invalid_scalar
append_os_string an OS string's bytes
append_u32, append_u64, append_usize decimal
append_i32, append_i64, append_isize decimal, with a - before a negative value
append_hex_u32, append_hex_u64, append_hex_usize lower-case hexadecimal with no 0x

Each append takes exactly its own type, and nothing widens at the call: passing a u8 to append_u32 is refused. Convert a narrower integer explicitly, text.append_u32(line, u32(byte)).

Width and padding apply to whatever was written since an earlier length:

  • align_right puts a fill byte before the piece until the piece is as wide as the field.
  • align_left puts the fill byte after the piece.

The fill goes before a sign too, so a zero fill suits an unsigned value.

To right-align a number in a column, note where it starts, append it and align what was appended. The fill is a byte, so a space is u8(' '):

--- Append `value` to `line` in decimal, right-aligned in a field `width`
--- bytes wide.
append_right: (inout line: text.builder, value: u64, width: usize)
              -> none ! mem.out_of_memory =
    start: usize = text.length(line)
    try text.append_u64(line, value)
    try text.align_right(line, start, width, u8(' '))
end append_right

A builder over mut buffer: [64]u8 = zeroed is text.over(buffer), and io.put(out, text.used(line)) prints what the builder holds.

The UTF-8 builder

A builder holds bytes, which need not be UTF-8, because append takes any bytes. A utf8_builder holds only UTF-8, because it takes only text, scalars and numbers. utf8_over(buffer) makes one over your buffer.

Call What it does
utf8_append_text, utf8_append_scalar Append text or a scalar.
utf8_append_u32 and the other number appends Append a number, as the builder's call without utf8_ does.
utf8_used Lend the text written as one utf8, until it next changes; nothing is scanned.
utf8_bytes Lend the same as bytes.
utf8_length, utf8_capacity, utf8_clear As the builder's.
utf8_truncate Cut back to a length, never inside a scalar.

Each append writes its whole piece, or reports mem.out_of_memory and leaves the builder as it was. A cut inside a scalar keeps only the scalars before the cut. A utf8_builder has no byte append, no alignment and no format into it, since each of those can write any bytes.

Formatting

format appends a template to a builder. Each {} is replaced by the next of an array of any formattable values, and {{ and }} are written as braces. A placeholder takes nothing else: width, padding and hexadecimal are the typed calls.

The values are an array literal written at the call, which lends the array as a slice: text.format(line, "{} {}\n", [any(addr count), any(addr name)]).

formattable has one entry, append, which writes a value into a builder through a pointer to the value. The library supplies it for these types, and a program declares it for a type of its own:

  • the ten integer types, in decimal;
  • bool, as true or false;
  • utf8, []u8 and OS strings.

Floats, f32 and f64, are not formattable yet.

Nothing runs at compile time, so the template is checked against the values when format runs:

  • A different number of placeholders, or a brace that is neither part of {} nor doubled, is invalid_format, and nothing is written.
  • A builder that fills partway is put back before mem.out_of_memory is reported.

format_onto formats text that may be longer than its buffer. It formats through a buffer of the caller's, and hands the text to an outlet each time the buffer fills and once at the end. io.write_format is format_onto over a file. An outlet has one entry, take, which takes the bytes whole or reports mem.out_of_memory.

How a value passes through the buffer:

  • A value that fits the buffer is formatted whole into it, so a conformance's length and alignments see its own piece.
  • A library value longer than the whole buffer is handed on in pieces as it is written.
  • The buffer must still hold the largest piece a value asks room for at once. Twenty bytes hold every integer the library formats. A conformance of the program's own that asks for more than the buffer has fails with mem.out_of_memory.

A conformance of the program's own may be writing a value longer than the whole buffer, a row with a long name in it. Its offsets still hold:

  • length counts the bytes already handed on, so an offset taken before a piece was handed on names the same byte after.
  • align_left fills after its piece wherever the piece began.
  • align_right needs the whole piece still in the buffer, and room there for the fill. When some of the piece has been handed on, nothing can go before it, and the call fails with mem.out_of_memory. Through io.write_format that is io_failed, after the text before it was written. A column that must hold a long value right-aligned is built in a builder of the program's own that is long enough, and written whole.
  • truncate cuts what the buffer still holds. What was handed on stays written.

To print a float, scale it to an integer and print the parts. Converting a float to an integer truncates toward zero, and traps when the value does not fit. So this function adds a half to round, and takes the sign off first so that a negative value rounds the same way:

--- Append `value` with two decimals, rounded half away from zero.  Floats
--- are not formattable, so this scales the value to whole hundredths and
--- writes the integer part, a point and the two digits after it.
append_hundredths: (inout line: text.builder, value: f64)
                   -> none ! mem.out_of_memory =
    mut magnitude: f64 = value
    if value < 0.0 then
        magnitude = -value
    end if
    --  The conversion truncates toward zero, so adding a half rounds.
    hundredths: u64 = u64(magnitude * 100.0 + 0.5)
    if value < 0.0 and hundredths > 0 then
        try text.append_byte(line, u8('-'))
    end if
    try text.append_u64(line, hundredths / 100)
    try text.append_byte(line, u8('.'))
    start: usize = text.length(line)
    try text.append_u64(line, hundredths % 100)
    try text.align_right(line, start, 2, u8('0'))
end append_hundredths

The 0 fill writes five hundredths as 05, so 2.05 never prints as 2.5. A value that rounds to zero prints without a sign, 0.00. A value too large for a u64 once scaled, a NaN or an infinity traps at the conversion.

No locale is consulted anywhere. The same values give the same bytes everywhere, on Cortex-M0 as on a hosted system.

Parsing numbers

Parsing is the mirror of the appends. It reads a byte slice, which need not be UTF-8:

Parse Reads
parse_u8 to parse_u64, parse_usize nonempty ASCII digits
parse_i8 to parse_i64, parse_isize an optional - before them, never a +, since no append writes one
parse_hex_u32, parse_hex_u64, parse_hex_usize hexadecimal digits of either case, with no 0x
to_u32 parse_u32 over a utf8 view

A parse fails in two ways. The scan goes from the left and reports whichever it meets first:

  • Any input other than what the table allows, a space included, is invalid_number.
  • A value outside the type, above its maximum or below a signed minimum, is number_overflow.

usize and isize are the target's, 32 bits on Cortex-M.

The builder's appends are the library's one decimal writer, and these parses are its one parser: core/net reads the numbers of its addresses through them.

Items

formattable

concept core/text/format.ldn:22 ↑ index
public formattable: type = concept (item: type)

Append the value's text, or report mem.out_of_memory and leave the builder as it was.

    append: (self: ptr item, inout into: builder) -> none ! mem.out_of_memory
end formattable

A value that writes its own text into a builder, which format fills a placeholder with. The library supplies it for the ten integer types in decimal, bool as true or false, utf8, []u8 and host strings as their bytes. Floats, f32 and f64, are not formattable yet: scale one to an integer and append the parts, as this module's reference program does for two decimals. A type of the program's own conforms with a function that appends its text. For a different reading of a supplied type, hexadecimal for one, call a typed append routine, or declare a distinct wrapper with its own conformance [1280].

public outlet: type = concept (item: type)

Take all of bytes, or report mem.out_of_memory.

    take: (self: ptr mut item, bytes: []u8) -> none ! mem.out_of_memory
end outlet

Where format_onto hands the text it formats, a piece at a time. An outlet is a value the caller keeps. It takes each piece whole or reports mem.out_of_memory, and keeps its own reason for the caller, since a builder's appends fail with nothing else. io.write_format makes one over a file. Only a program that builds an erased outlet links any outlet's routines (D374).

public builder: type = builder_value

Text being built: the bytes written so far, in a buffer the caller gave over or in storage that growing takes from an allocator. It is a value the caller keeps and edits, passing it inout to every append; used lends what it holds. It is bytes, not utf8: an append of bytes or of a host string writes them as they are. A utf8_builder holds only text.

public os_string: type = os_string_value

A host string: a path, a process argument or a directory entry's name, in the representation its system gives and takes, and not converted on the way through. On Linux, Darwin and FreeBSD it is bytes, which need not be UTF-8. from_os_string is the checked conversion to utf8, os_string_bytes the conversion to bytes, and os_string_equal compares one with a literal. It lends what it was made from: an argument lends the process's storage, an entry its directory's buffer, and os_string_over the caller's bytes. A NUL cannot be in a path or an argument, and the system refuses one when it is given a host string holding one.

public os_variable: type = struct
    name: os_string
    value: os_string
end os_variable

One environment variable: its name and its value, host strings as the system keeps them. core/io's environments lend it, and platform/posix reads and passes it, which is why it is declared here, below both (D1951).

public position: type = position_value

Opaque byte offset for scanning. It does not retain or validate a source; when used to index UTF-8 it must identify a codepoint boundary.

public utf8_builder: type = utf8_builder_value

Text being built that is always UTF-8: a builder over a buffer the caller gave utf8_over, which takes text, scalars and numbers and nothing else, since bytes or a host string could be anything. Each call is the byte builder's with utf8_ before it, and writes the same bytes: whole, or mem.out_of_memory and the builder left as it was.

invalid_format

atom core/text/format.ldn:10 ↑ index
public invalid_format: atom

The template does not fit its values: its {} placeholders and the values differ in number, or a brace is neither part of a {} nor doubled.

invalid_number

atom core/text/text.ldn:22 ↑ index
public invalid_number: atom

The bytes are empty or are not the digits the parse reads: a byte other than a digit, a sign where none is read, or a - without digits.

invalid_scalar

atom core/text/text.ldn:28 ↑ index
public invalid_scalar: atom

The value is not a Unicode scalar: it is a surrogate, U+D800 to U+DFFF, or above U+10FFFF, and so has no UTF-8 encoding.

invalid_text

atom core/text/text.ldn:19 ↑ index
public invalid_text: atom

The supplied bytes are not well-formed UTF-8.

number_overflow

atom core/text/text.ldn:25 ↑ index
public number_overflow: atom

The parsed value is outside the type it is parsed into: above its maximum, or for a signed type below its minimum.

public nowhere: position = (offset: 0)

The zero-offset position sentinel. It has the same offset as first; it is not a separate invalid-position tag.

advance

function core/text/text.ldn:77 ↑ index
public advance: (inout cursor: position) -> none

Advance the cursor by one byte in place. Does not validate the source or skip a whole UTF-8 scalar.

align_left

function core/text/builder.ldn:628 ↑ index
public align_left: (inout into: builder, start: usize, width: usize,
                    fill: u8) -> none ! mem.out_of_memory

Left-align the piece written since start in a field width bytes wide: fill goes after it until the field is full. A piece as wide as the field or wider is left as it is. The fill follows the piece wherever its start now is, handed on by format_onto or not.

align_right

function core/text/builder.ldn:603 ↑ index
public align_right: (inout into: builder, start: usize, width: usize,
                     fill: u8) -> none ! mem.out_of_memory

Right-align the piece written since start, an earlier length, in a field width bytes wide: fill goes before it until the field is full. A piece as wide as the field or wider is left as it is. The fill goes before the whole piece, a sign included, so a zero fill suits an unsigned value. A start past the length is a checked-range trap, as a slice's would be. The piece has to be in the builder still: where format_onto has handed any of it on, or has to hand it on to make room for the fill, nothing can go before it and the call reports mem.out_of_memory (D1123).

public append: (inout into: builder, bytes: []u8) -> none ! mem.out_of_memory

Append bytes as they are.

append_byte

function core/text/builder.ldn:359 ↑ index
public append_byte: (inout into: builder, value: u8)
                    -> none ! mem.out_of_memory

Append one byte.

append_hex_u32

function core/text/builder.ldn:535 ↑ index
public append_hex_u32: (inout into: builder, value: u32)
                       -> none ! mem.out_of_memory

Append a u32 in hexadecimal: lower-case digits, as few as the value needs, and no 0x, which is a piece of its own.

append_hex_u64

function core/text/builder.ldn:555 ↑ index
public append_hex_u64: (inout into: builder, value: u64)
                       -> none ! mem.out_of_memory

Append a u64 in hexadecimal, as append_hex_u32 does.

append_hex_usize

function core/text/builder.ldn:575 ↑ index
public append_hex_usize: (inout into: builder, value: usize)
                         -> none ! mem.out_of_memory

Append a usize in hexadecimal, as append_hex_u32 does.

append_i32

function core/text/builder.ldn:484 ↑ index
public append_i32: (inout into: builder, value: i32)
                   -> none ! mem.out_of_memory

Append an i32 in decimal: a - before a negative value's digits and nothing before any other's. Write i8 and i16 through it.

append_i64

function core/text/builder.ldn:500 ↑ index
public append_i64: (inout into: builder, value: i64)
                   -> none ! mem.out_of_memory

Append an i64 in decimal, signed as append_i32 is.

append_isize

function core/text/builder.ldn:516 ↑ index
public append_isize: (inout into: builder, value: isize)
                     -> none ! mem.out_of_memory

Append an isize in decimal, signed as append_i32 is.

append_os_string

function core/text/builder.ldn:375 ↑ index
public append_os_string: (inout into: builder, value: os_string)
                         -> none ! mem.out_of_memory

Append a host string's bytes, as the system gave them: a name that is not UTF-8 is written as it is. Check it with from_os_string first where the output must be text.

append_scalar

function core/text/builder.ldn:384 ↑ index
public append_scalar: (inout into: builder, scalar: u32)
                      -> none ! mem.out_of_memory | invalid_scalar

Append the UTF-8 encoding of scalar, one to four bytes, as encode writes it. A surrogate or a value above U+10FFFF reports invalid_scalar, before a scalar that does not fit reports mem.out_of_memory, and either leaves the builder as it was.

append_text

function core/text/builder.ldn:367 ↑ index
public append_text: (inout into: builder, value: utf8)
                    -> none ! mem.out_of_memory

Append text's encoded bytes.

append_u32

function core/text/builder.ldn:465 ↑ index
public append_u32: (inout into: builder, value: u32)
                   -> none ! mem.out_of_memory

Append a u32 in decimal: its digits, with no sign, padding or separator. Write u8 and u16 through it.

append_u64

function core/text/builder.ldn:471 ↑ index
public append_u64: (inout into: builder, value: u64)
                   -> none ! mem.out_of_memory

Append a u64 in decimal.

append_usize

function core/text/builder.ldn:477 ↑ index
public append_usize: (inout into: builder, value: usize)
                     -> none ! mem.out_of_memory

Append a usize in decimal, at the target's width.

public at_end: (source: []u8, cursor: position) -> (yes: bool)

Return whether the byte offset is at or beyond the source length.

public byte: (source: []u8, cursor: position)
             -> (value: u8) ! mem.out_of_bounds

Read one source byte at the cursor. Reports mem.out_of_bounds before reading outside the source.

public bytes: (source: utf8) -> (result: []u8 from source)

Lend the encoded bytes of a UTF-8 view without copying or allocating.

public capacity: (source: builder) -> (count: usize)

How many bytes the builder holds before it next fills: its buffer's length, which grows for a builder from growing.

public clear: (inout target: builder) -> none

Forget everything written, keeping the buffer for the next text.

contains

function core/text/text.ldn:307 ↑ index
public contains: (source: utf8, sought: utf8) -> (yes: bool)

Test whether the sought UTF-8 byte sequence occurs in the source. Empty text matches; no normalization or allocation is performed.

Two-Way search uses a critical split of the sought bytes. Its two lexicographic passes and the search each take linear time; only scalar counters are kept, so neither a table nor a caller allocator is needed.

public copied: (cursor: position) -> (result: position)

Copy a position out of aggregate storage without borrowing that storage. This matters to scanners that retain the token start while advancing the cursor field from which it was read.

public encode: (scalar: u32, into: []mut u8)
               -> (count: usize) ! invalid_scalar | mem.out_of_memory

Encode scalar as UTF-8 at the front of into and say how many bytes, one to four, it took; encode at an offset by passing what follows it, buffer[at..<lenof buffer]. A surrogate, U+D800 to U+DFFF, or a value above U+10FFFF reports invalid_scalar, before a scalar whose bytes do not fit reports mem.out_of_memory; either refusal writes nothing, so into is as it was. The builders' append_scalar and utf8_append_scalar write the same bytes.

public equal: (left: utf8, right: utf8) -> (yes: bool)

Compare UTF-8 values by their encoded bytes. Does not normalize Unicode spelling.

Equality and containment are exact encoded-byte operations. Valid UTF-8 has one shortest-form encoding per scalar sequence, so neither operation needs normalization or locale authority.

public find: (source: utf8, sought: utf8)
             -> (found: position) ! mem.not_found

The position where sought first occurs in source, or mem.not_found. Empty text is found at the start, as contains finds it. The match begins and ends on scalar boundaries, so source[text.offset(found)..< text.offset(found) + lenof sought] is the match and the parts either side of it are text too, each a view of source with nothing copied.

find_from

function core/text/text.ldn:471 ↑ index
public find_from: (source: utf8, sought: utf8, at: position)
                  -> (found: position) ! mem.not_found

The position where sought first occurs in source at or after at, or mem.not_found: the match after one find returned is found from the position past it. Empty text is found at at. A position inside a scalar or past the end traps, as a range of source from it does. contains's Two-Way search, in time linear in the two lengths and with no table.

find_scalar

function core/text/text.ldn:479 ↑ index
public find_scalar: (source: utf8, scalar: u32) -> (found: position)
                    ! mem.not_found

The position of the first scalar of source equal to scalar, or mem.not_found, which a surrogate or a value above U+10FFFF always is, since no text holds one.

find_scalar_from

function core/text/text.ldn:487 ↑ index
public find_scalar_from: (source: utf8, scalar: u32, at: position)
                         -> (found: position) ! mem.not_found

The position of the first scalar of source equal to scalar at or after at, or mem.not_found. A position inside a scalar or past the end traps, as find_from's does.

public first: (source: []u8) -> (result: position)

Return a cursor at byte offset zero, including for an empty source.

public format: (inout into: builder, template: utf8,
                values: []any formattable)
               -> none ! mem.out_of_memory | invalid_format

Append template with each {} replaced by the next of values, in order, written by its own formattable conformance; {{ writes { and }} writes }. A placeholder takes nothing else: width, padding and hexadecimal are the typed append and align calls. The template is checked first, so invalid_format writes nothing, and a builder that fills partway is put back as it was before mem.out_of_memory is reported. No locale is consulted: the text is the same everywhere. The template and the values may be views of the builder's own bytes, text.used(into) or parts of it: each is written as it was when the call began, since a growing builder that moves while the call writes keeps the block they view until the call ends (D1122).

The values are an array literal of erased addresses, which the call lends as a slice: text.format(line, "{} {}\n", [any(addr count), any(addr name)]).

format_onto

function core/text/format.ldn:216 ↑ index
public format_onto: (provider: type is outlet, store: []mut u8,
                     onto: provider, template: utf8,
                     values: []any formattable)
                    -> none ! mem.out_of_memory | invalid_format

Format template with values, as format does, through store, a buffer of the caller's, handing the text to onto each time the store fills and once at the end: text that fits the store is handed on in one piece, and text of any length in several. The template is checked first, so invalid_format hands on nothing. A value that fits the store is formatted whole into it; one longer than the whole store is handed on in pieces as it is written, and a library value's longest piece goes to onto as it is. mem.out_of_memory is the outlet's refusal, or a conformance of the program's own asking for more room at once than the store has, or right-aligning a piece that has been handed on (D1123). Twenty bytes hold every integer the library formats. io.write_format is this over a file.

from_bytes

function core/text/text.ldn:186 ↑ index
public from_bytes: (source: []u8)
                   -> (result: utf8 from source) ! invalid_text

Validate a byte slice and lend it as UTF-8. Reports invalid_text when the bytes are not well-formed UTF-8; the utf8(bytes) conversion traps on them instead.

The result is a view of source: nothing is allocated or copied. The caller keeps the bytes alive and valid for as long as the view is used.

public from_c: (source: cstring)
               -> (result: utf8 from source) ! invalid_text

Validate a terminated C string and lend it as UTF-8. The pointer must remain readable through its terminator; invalid UTF-8 reports invalid_text.

from_offset

function core/text/text.ldn:64 ↑ index
public from_offset: (source: []u8, offset: usize) -> (result: position)

Construct a position at a byte offset into source. Does not check bounds or UTF-8 boundaries; later operations enforce their own requirements. The source names the coordinate space, although the position stores only the offset.

from_os_string

function core/text/text.ldn:256 ↑ index
public from_os_string: (source: os_string)
                       -> (result: utf8 from source) ! invalid_text

The host string as UTF-8 text, lent: the checked conversion, which reports invalid_text when its bytes are not UTF-8, as from_bytes does. A host string that is not text is still a working path or argument; it is only not utf8.

public growing: (memory: any mem.allocator) -> (result: builder from memory)

An empty builder that takes its storage from memory as it needs it, doubling what it holds, and reports mem.out_of_memory only when the allocator refuses. Build the erased allocator from the address of its handle's binding, text.growing(any(addr heap)), and keep the handle and its state alive while the builder is used. release gives the storage back: there are no destructors, so a builder dropped without it keeps its storage.

public hash: (value: utf8, seed: cmp.hash_seed) -> (result: u64)

Hash UTF-8 encoded bytes keyed by seed, consistently with equal and the byte-slice hash. No Unicode normalization or cryptographic guarantee is provided.

utf8 is a map key and sortable as it stands: equality, hash and order are over the encoded bytes, which valid UTF-8 makes unique per scalar sequence. The hash is cmp.hash_bytes of those bytes, SipHash-1-3.

public length: (source: builder) -> (count: usize)

How many bytes have been written: the offset the next piece begins at, which align_left and align_right take as a piece's start and truncate as where to cut. It is the length of used, except in the builder format_onto hands a conformance while it writes a value longer than its whole store: there it also counts the bytes already handed on, so an offset taken earlier still names the same byte (D1123).

public less: (left: utf8, right: utf8) -> (yes: bool)

Order UTF-8 values by their encoded bytes, lexicographically, with a shorter equal prefix sorting first.

For valid UTF-8 this is scalar order. It is not locale-aware collation.

public next: (cursor: position) -> (result: position)

Return a cursor one byte later. This is byte traversal, not Unicode-scalar traversal; offset overflow follows ordinary checked arithmetic.

public offset: (cursor: position) -> (bytes: usize)

Return the byte offset stored in a position. Index utf8 with the position itself: a usize index into utf8 counts scalars, not bytes.

os_string_bytes

function core/text/text.ldn:239 ↑ index
public os_string_bytes: (source: os_string) -> (result: []u8 from source)

The host string's bytes, as the system gave them, lent. Nothing is validated or copied.

os_string_equal

function core/text/text.ldn:264 ↑ index
public os_string_equal: (value: os_string, literal: utf8) -> (yes: bool)

Whether the host string spells exactly the text literal, compared as the system stores it, with no normalization: --verbose against an argument, for one.

os_string_over

function core/text/text.ldn:233 ↑ index
public os_string_over: (source: []u8) -> (result: os_string from source)

A host string over the caller's bytes, which it lends. Any bytes are one; the system says whether it accepts them when it is given them. A literal path is text.os_string_over("input.txt").

public over: (buffer: []mut u8) -> (result: builder from buffer)

A builder over the caller's buffer, empty, which never grows: an append that does not fit reports mem.out_of_memory. The buffer's earlier contents are overwritten as pieces are appended.

parse_hex_u32

function core/text/numbers.ldn:203 ↑ index
public parse_hex_u32: (source: []u8)
                      -> (result: u32) ! invalid_number | number_overflow

Parse nonempty hexadecimal digits from bytes into u32: 0 to 9 and a to f in either case, with no 0x, sign or space. Refuses any other byte or an empty slice with invalid_number and a value above u32's maximum with number_overflow, whichever the scan meets first.

parse_hex_u64

function core/text/numbers.ldn:218 ↑ index
public parse_hex_u64: (source: []u8)
                      -> (result: u64) ! invalid_number | number_overflow

Parse hexadecimal digits from bytes into u64, as parse_hex_u32 does.

parse_hex_usize

function core/text/numbers.ldn:233 ↑ index
public parse_hex_usize: (source: []u8)
                        -> (result: usize) ! invalid_number | number_overflow

Parse hexadecimal digits from bytes into usize, as parse_hex_u32 does, at the target's width.

public parse_i16: (source: []u8)
                  -> (result: i16) ! invalid_number | number_overflow

Parse an i16 from bytes, as parse_i8 does, within -32,768 to 32,767.

public parse_i32: (source: []u8)
                  -> (result: i32) ! invalid_number | number_overflow

Parse an i32 from bytes, as parse_i8 does, within i32's range.

public parse_i64: (source: []u8)
                  -> (result: i64) ! invalid_number | number_overflow

Parse an i64 from bytes, as parse_i8 does, within i64's range.

public parse_i8: (source: []u8)
                 -> (result: i8) ! invalid_number | number_overflow

Parse an i8 from bytes: an optional - and nonempty ASCII decimal digits. Refuses an empty slice, a lone -, a +, whitespace and any other byte with invalid_number, and a value outside -128 to 127 with number_overflow, whichever the scan meets first.

parse_isize

function core/text/numbers.ldn:171 ↑ index
public parse_isize: (source: []u8)
                    -> (result: isize) ! invalid_number | number_overflow

Parse an isize from bytes, as parse_i8 does, within the target's isize range, so the same digits can parse on a 64-bit target and overflow on a 32-bit one.

public parse_u16: (source: []u8)
                  -> (result: u16) ! invalid_number | number_overflow

Parse nonempty ASCII decimal digits from bytes into u16, refusing as parse_u32 does, with number_overflow above 65,535.

parse_u32

function core/text/numbers.ldn:56 ↑ index
public parse_u32: (source: []u8)
                  -> (result: u32) ! invalid_number | number_overflow

Parse nonempty ASCII decimal digits from bytes into u32. Rejects an empty slice, signs, whitespace and any other byte with invalid_number, and a value above u32's maximum with number_overflow, whichever the scan meets first. The bytes need not be UTF-8: a digit is one byte. Leading zeros are accepted, and a refusal reads no byte past the one that caused it.

parse_u64

function core/text/numbers.ldn:63 ↑ index
public parse_u64: (source: []u8)
                  -> (result: u64) ! invalid_number | number_overflow

Parse nonempty ASCII decimal digits from bytes into u64. Refuses as parse_u32 does, with number_overflow above u64's maximum.

public parse_u8: (source: []u8)
                 -> (result: u8) ! invalid_number | number_overflow

Parse nonempty ASCII decimal digits from bytes into u8, refusing as parse_u32 does, with number_overflow above 255.

parse_usize

function core/text/numbers.ldn:72 ↑ index
public parse_usize: (source: []u8)
                    -> (result: usize) ! invalid_number | number_overflow

Parse nonempty ASCII decimal digits from bytes into usize. Refuses as parse_u32 does, with number_overflow above the target's usize maximum, so the same digits can parse on a 64-bit target and overflow on a 32-bit one.

public release: (inout target: builder) -> none

Give a growing builder's storage back to its allocator and leave it empty; it grows again from nothing if appended to. A builder over a caller's buffer has nothing to give back and is only cleared. End every use of used first.

scalar_length

function core/text/text.ldn:444 ↑ index
public scalar_length: (source: utf8, at: position) -> (count: usize)

How many bytes, one to four, encode the scalar at at. Traps at the end and on a continuation byte, as source[at] does.

public slice: (source: []u8, begins: position, ends: position)
              -> (result: []u8 from source)

Lend bytes between two cursor offsets, with an exclusive end. Requires an ordered interval within the source; invalid ranges follow the language's checked range behavior.

public start: (source: utf8) -> (at: position)

The position of the first scalar of source, or of its end when it is empty: byte offset zero. Step through the text with step until utf8_at_end, reading each scalar as source[at].

public step: (source: utf8, at: position) -> (after: position)

The position just past the scalar at at: the next scalar's, or the end. Traps where scalar_length does, so it never steps into a scalar.

public to_u32: (source: utf8)
               -> (result: u32) ! invalid_number | number_overflow

Parse the decimal digits of UTF-8 text into u32, as parse_u32 parses its bytes.

public truncate: (inout target: builder, count: usize) -> none

Keep only the first count bytes written; a count at or past the length changes nothing. A formattable conformance that appends several pieces puts the builder back with this, to an earlier length, when a later piece reports mem.out_of_memory. Bytes format_onto has already handed on cannot be taken back: a count before them cuts everything the builder still holds and nothing else (D1123).

public used: (source: builder) -> (bytes: []u8 from source)

The bytes written so far, lent from the builder until it is next changed.

utf8_append_hex_u32

function core/text/builder.ldn:759 ↑ index
public utf8_append_hex_u32: (inout into: utf8_builder, value: u32)
                            -> none ! mem.out_of_memory

Append a u32 in lower-case hexadecimal, as append_hex_u32 does.

utf8_append_hex_u64

function core/text/builder.ldn:765 ↑ index
public utf8_append_hex_u64: (inout into: utf8_builder, value: u64)
                            -> none ! mem.out_of_memory

Append a u64 in lower-case hexadecimal.

utf8_append_hex_usize

function core/text/builder.ldn:771 ↑ index
public utf8_append_hex_usize: (inout into: utf8_builder, value: usize)
                              -> none ! mem.out_of_memory

Append a usize in lower-case hexadecimal.

utf8_append_i32

function core/text/builder.ldn:741 ↑ index
public utf8_append_i32: (inout into: utf8_builder, value: i32)
                        -> none ! mem.out_of_memory

Append an i32 in decimal, with a - before a negative value.

utf8_append_i64

function core/text/builder.ldn:747 ↑ index
public utf8_append_i64: (inout into: utf8_builder, value: i64)
                        -> none ! mem.out_of_memory

Append an i64 in decimal, signed as utf8_append_i32 is.

utf8_append_isize

function core/text/builder.ldn:753 ↑ index
public utf8_append_isize: (inout into: utf8_builder, value: isize)
                          -> none ! mem.out_of_memory

Append an isize in decimal, signed as utf8_append_i32 is.

utf8_append_scalar

function core/text/builder.ldn:717 ↑ index
public utf8_append_scalar: (inout into: utf8_builder, scalar: u32)
                           -> none ! mem.out_of_memory | invalid_scalar

Append the UTF-8 encoding of scalar, as append_scalar does.

utf8_append_text

function core/text/builder.ldn:711 ↑ index
public utf8_append_text: (inout into: utf8_builder, value: utf8)
                         -> none ! mem.out_of_memory

Append text.

utf8_append_u32

function core/text/builder.ldn:723 ↑ index
public utf8_append_u32: (inout into: utf8_builder, value: u32)
                        -> none ! mem.out_of_memory

Append a u32 in decimal, as append_u32 does.

utf8_append_u64

function core/text/builder.ldn:729 ↑ index
public utf8_append_u64: (inout into: utf8_builder, value: u64)
                        -> none ! mem.out_of_memory

Append a u64 in decimal.

utf8_append_usize

function core/text/builder.ldn:735 ↑ index
public utf8_append_usize: (inout into: utf8_builder, value: usize)
                          -> none ! mem.out_of_memory

Append a usize in decimal, at the target's width.

utf8_at_end

function core/text/text.ldn:438 ↑ index
public utf8_at_end: (source: utf8, at: position) -> (yes: bool)

Whether no scalar begins at at: it is at the end of source, or past it.

utf8_bytes

function core/text/builder.ldn:662 ↑ index
public utf8_bytes: (source: utf8_builder) -> (bytes: []u8 from source)

The text written so far, as bytes, lent from the builder until it is next changed. They are UTF-8 however the builder was used.

utf8_capacity

function core/text/builder.ldn:684 ↑ index
public utf8_capacity: (source: utf8_builder) -> (count: usize)

How many bytes the builder holds before it fills: its buffer's length.

utf8_clear

function core/text/builder.ldn:689 ↑ index
public utf8_clear: (inout target: utf8_builder) -> none

Forget everything written, keeping the buffer for the next text.

utf8_length

function core/text/builder.ldn:679 ↑ index
public utf8_length: (source: utf8_builder) -> (count: usize)

How many bytes have been written: the offset the next piece begins at, which is always a scalar's start.

public utf8_over: (buffer: []mut u8) -> (result: utf8_builder from buffer)

A utf8_builder over the caller's buffer, empty, which never grows, as over's builder does not.

utf8_truncate

function core/text/builder.ldn:697 ↑ index
public utf8_truncate: (inout target: utf8_builder, count: usize) -> none

Keep the whole scalars of the first count bytes written: a count inside a scalar keeps only the scalars before it, so the text stays UTF-8, and a count at or past the length changes nothing. A count an earlier utf8_length gave is always a scalar's start.

public utf8_used: (source: utf8_builder) -> (result: utf8 from source)

The text written so far, lent from the builder until it is next changed. Nothing is scanned: every append wrote whole scalars and every cut kept them, so the bytes are UTF-8 already.

public valid: (source: []u8) -> (yes: bool)

Report whether the bytes are well-formed UTF-8: shortest-form encodings of Unicode scalars, with no surrogate and nothing above U+10FFFF. This is the check from_bytes makes; the utf8(bytes) conversion makes it too but traps instead of reporting.

Example program

The program prints a price list: each item's name aligned left, its count right-aligned under its heading, and its price, an f64, with two decimals.

This complete program is one of the compiler's runtime tests. View source.

compiler/tests/fixtures/runtime/library-text-columns/main.ldn82 lines
--  A price list in columns: each count right-aligned under its heading,
--  and each price, a float, with two decimals.
import core/io
import core/mem
import core/text
import hosted/blocking

item: type = struct
    name: utf8
    count: u64
    price: f64
end item

--- Append `value` to `line` in decimal, right-aligned in a field `width`
--- bytes wide.
append_right: (inout line: text.builder, value: u64, width: usize)
              -> none ! mem.out_of_memory =
    start: usize = text.length(line)
    try text.append_u64(line, value)
    try text.align_right(line, start, width, u8(' '))
end append_right

--- Append `value` with two decimals, rounded half away from zero.  Floats
--- are not formattable, so this scales the value to whole hundredths and
--- writes the integer part, a point and the two digits after it.
append_hundredths: (inout line: text.builder, value: f64)
                   -> none ! mem.out_of_memory =
    mut magnitude: f64 = value
    if value < 0.0 then
        magnitude = -value
    end if
    --  The conversion truncates toward zero, so adding a half rounds.
    hundredths: u64 = u64(magnitude * 100.0 + 0.5)
    if value < 0.0 and hundredths > 0 then
        try text.append_byte(line, u8('-'))
    end if
    try text.append_u64(line, hundredths / 100)
    try text.append_byte(line, u8('.'))
    start: usize = text.length(line)
    try text.append_u64(line, hundredths % 100)
    try text.align_right(line, start, 2, u8('0'))
end append_hundredths

--- Write `one` into `line` as a row: its name, then its count and its
--- price right-aligned under their headings.
write_row: (inout line: text.builder, one: item) -> none ! mem.out_of_memory =
    text.clear(line)
    try text.append_text(line, one.name)
    try text.align_left(line, 0, 8, u8(' '))
    try append_right(line, one.count, 6)
    start: usize = text.length(line)
    try append_hundredths(line, one.price)
    try text.align_right(line, start, 8, u8(' '))
    try text.append_byte(line, u8('\n'))
end write_row

public main: () -> (code: i32) =
    host := blocking.new()
    mut storage: [256]u8 = zeroed
    mut out := io.buffered_over(host, io.out(host), storage)
    defer io.flush(out) else none
    code = 1
    items: [4]item = [(name: "bolts", count: 1200, price: 0.125),
                      (name: "nuts", count: 950, price: 0.08),
                      (name: "washers", count: 75, price: 0.0625),
                      (name: "refund", count: 1, price: -2.5)]
    io.put(out, "item     count   price\n") else none
    mut buffer: [64]u8 = zeroed
    mut line := text.over(buffer)
    for one in items do
        write_row(line, one) else begin
            return
        end
        io.put(out, text.used(line)) else begin
            return
        end
    end for
    io.flush(out) else begin
        return
    end
    code = 0
end main
in a terminalprints on standard output
$ refine compile main.ldn -o text-columns && ./text-columns
item     count   price
bolts     1200    0.13
nuts       950    0.08
washers     75    0.06
refund       1   -2.50