Alpha.16 · standard library

UTF-8

Decode bytes to text with an explicit error location and category.

These pages describe alpha.16. Host I/O requires the native toolchain; browser capabilities are limited. Browse the stdlib guides.

All standard library modules

Decode bytes to text with an explicit error location and category.

Import

import stdlib/encoding/utf8 as utf8

decode()

pure decode(data: Bytes): Result[Str,Utf8Error]

Parameters

  • data: Bytes — complete byte sequence to decode.

Returns: Result[Str,Utf8Error].

Pure and usable from ordinary or async code. Never silently replaces invalid bytes. A truncated final sequence is an error: when processing streamed input, retain incomplete sequences or assemble a bounded complete buffer first. Encoding in the other direction uses the pure text.encode_utf8(): Bytes method.

Errors: The error identifies a zero-based byte offset and one of the categories below.

Utf8Error

record Utf8Error { offset: Nat, kind: Utf8ErrorKind }
enum Utf8ErrorKind {
  InvalidLeadingByte, InvalidContinuationByte, TruncatedSequence,
  OverlongEncoding, SurrogateCodePoint, CodePointOutOfRange
}

offset is the offending continuation byte, or otherwise the start of the invalid sequence. This pure error contains no host error.

Utf8Error.render()

pure render(): Str

Parameters

None.

Returns: Str, a human-readable explanation of this error, including the zero-based byte offset.

Pure. Use the structured error fields for control flow; the wording is diagnostic text and must not be parsed.

Example

The console input program decodes a bounded complete buffer and reports invalid input.

Implementation: view source on GitHub.

Keep exploring

Explore Panackelty.