Convert text to numbers, handle missing values, and choose byte operations for your file format. Start with the text example, then use the tables to find a helper.
Install Topaz. Save each example in its own .tpz file and run it from that folder.
Parse and transform values
Save this as core-everyday.tpz.
import std.io
function parseAll(values: Array<string>) -> Array<Option<int>> {
return values.map(value => value.toInt())
}
let scalars = "토파즈".scalars()
let parsed = parseAll(["1", "x", "3"])
io.writeLine("{scalars.length}:{parsed}")Run topaz run --language-version 5.21 core-everyday.tpz.
3:[Some(1), None, Some(3)]string.toInt() converts "1" and "3" successfully. It returns None for "x", so map keeps that missing value in the result. Change "x" to "2" to get Some(2) in the middle.
"토파즈" contains three Unicode scalar values. A scalar is one Unicode code point outside the surrogate range. scalars() returns an array of these values as strings. Its length counts scalars, which can differ from bytes or visible characters.
io.writeLine takes a string. Interpolation inside {...} converts the values to text before printing.
Choose the everyday helper
| Task | Call | Return type |
|---|---|---|
| Print one line | io.writeLine(text) | () |
| Read all text supplied for this run | io.readStdin() | string |
| Parse an integer | text.toInt() | Option<int> |
| Parse with a radix from 2 through 36 | text.toIntRadix(radix) | Option<int> |
| Convert an integer to a floating-point number | value.toFloat() | float |
| Create a scalar from its code point | value.toCodePoint() | Option<string> |
| Split text into scalar strings | text.scalars() | Array<string> |
| Transform, select, or accumulate elements | items.map, items.filter, items.reduce | A new value |
io.readStdin() returns the same complete text on each call during a run. The environment must provide input and output support for io.readStdin and io.writeLine.
int.toFloat() takes an int. For text containing an integer, parse with string.toInt() first. Use interpolation to turn values into text and .length on an array to count elements. The free names toString, len, println, and type_of are unavailable.
Round a float to an integer
The receiver is evaluated once before the written arguments.
| Method | Result |
|---|---|
float.trunc(), float.floor(), float.ceil(), float.round() | int |
float.abs(), float.sin(), float.cos(), float.tan() | float |
float.sqrt() | Result<float, string> |
float.isNaN(), float.isFinite() | bool |
float.atMost(b: float), float.atLeast(b: float) | float |
string.parseFloat() | Result<float, string> |
trunc rounds toward zero, floor toward negative infinity, and ceil toward positive infinity. round chooses the nearest integer and sends an exact tie away from zero. Each returns int, so 3.7.floor() + 2 is 5.
The rounded integer must satisfy −2^63 ≤ n < 2^63. Negative zero becomes 0. NaN, infinity, and a rounded value outside this range raise TPZ4004 at the call. A constant expression reports TPZ5001.
sqrt returns Err for a negative value or NaN, and preserves negative zero in Ok. atMost and atLeast return the second operand when the comparison is false, including equal values and NaN. Text parsing trims whitespace and returns Err for invalid text or a nonfinite result.
Transform Option and Result
Some and None construct Option. Ok and Err construct Result. If the compiler cannot infer all type arguments, add a type annotation. This can happen with None, Ok, Err, or an empty collection.
| Method | Signature | Behavior |
|---|---|---|
option.okOr | (error: E) -> Result<T, E> | Evaluates error before the call |
option.okOrElse | (f: () -> E) -> Result<T, E> | Calls f when the value is None |
option.map | (f: (T) -> U) -> Option<U> | Transforms the value inside Some |
option.flatMap | (f: (T) -> Option<U>) -> Option<U> | Returns the Option from f without nesting it |
result.map | (f: (T) -> U) -> Result<U, E> | Transforms the value inside Ok |
result.flatMap | (f: (T) -> Result<U, E>) -> Result<U, E> | Returns the Result from f without nesting it |
result.mapErr | (f: (E) -> F) -> Result<T, F> | Transforms the value inside Err |
result.unwrapOr | (default: T) -> T | Evaluates the default eagerly |
The map and flatMap methods preserve None or Err without calling f. Result.mapErr calls f for an Err payload and preserves Ok. Its callback expression is evaluated normally. unwrapOr evaluates its default before the call and returns the value inside Ok or that default. These methods do not catch faults.
Work with integer bits
int.and(other), or(other), xor(other), and shift(count) operate on 64-bit two's-complement patterns. A positive shift moves left and discards high bits. A negative shift moves right with sign extension. The count is −63 through 63. 1.shift(63) is −9223372036854775808, and (-1).shift(-1) is −1. A count outside the range raises TPZ4004 with integer shift count must be between -63 and 63 at the call. A constant expression reports TPZ5001.
Assemble bytes in place
Save this as core-byte-buffer.tpz.
import std.io
let mut row = ByteBuffer.allocate(8)
row.fill(0, 8, 255)
row.set(0, 137)
let mut frame = ByteBuffer.allocate(12)
frame.copy(row, 0, 2, 8)
let payload = frame.toBytes()
io.writeLine(payload.toHex())Run topaz run core-byte-buffer.tpz.
000089ffffffffffffff0000row holds eight bytes. fill sets them to 255, and set replaces the first with 137. copy puts those eight bytes into frame, starting at index 2. The remaining bytes stay zero.
ByteBuffer.allocate(length, value = 0) creates a fixed-length buffer. set, fill, and copy need a receiver declared with let mut. They check all ranges and byte values before writing. Invalid arguments cause a fault and leave the target unchanged.
Assignment shares the same buffer. ByteBuffer.fromBytes makes a copy, and toBytes() creates an immutable snapshot. A ByteBuffer cannot be compared, used as a Map key or Set element, rendered as text or JSON, or passed through a Web export.
Compute a CRC-32 integrity field
Save this as core-crc32.tpz.
import std.io
let checksum = "123456789".encodeUtf8().crc32()
io.writeLine("{checksum}")Run topaz run core-crc32.tpz.
3421780262data.crc32() returns a CRC-32/ISO-HDLC checksum as an int in 0..4294967295. Use this checksum for file-format integrity fields. It does not authenticate data or protect against deliberate tampering.
Produce fixed DEFLATE
Save this as core-deflate.tpz.
import std.io
match "hello".encodeUtf8().deflateFixedCompress() {
case Ok(compressed) => io.writeLine(compressed.toHex())
case Err(error) => io.writeLine(error)
}Run topaz run core-deflate.tpz.
cb48cdc9c90700Bytes.deflateFixedCompress produces one raw DEFLATE block using fixed Huffman codes. The same input produces the same bytes. The output has no zlib or gzip header or checksum. Input above 256 MiB returns Err.
Produce fixed zlib
Save this as core-zlib.tpz.
import std.io
match "hello".encodeUtf8().zlibFixedCompress() {
case Ok(compressed) => io.writeLine(compressed.toHex())
case Err(error) => io.writeLine(error)
}Run topaz run core-zlib.tpz.
7801cb48cdc9c90700062c0215Bytes.zlibFixedCompress adds a 78 01 header and an Adler-32 checksum to the fixed-Huffman compressed data. The same input produces the same bytes. Input above 256 MiB returns Err.
This function has no decompression, compression-level, dictionary, or streaming options. It does not expose a separate Adler-32 calculation.
Add Reed–Solomon protection bytes
Save this as core-reed-solomon.tpz.
import std.io
match "hello".encodeUtf8().reedSolomon255223Protect() {
case Ok(protected) => io.writeLine("{protected.length()}")
case Err(error) => io.writeLine(error)
}Run topaz run core-reed-solomon.tpz.
255The function splits input into 223-byte blocks and adds 32 parity bytes to each block, producing RS(255,223) codewords. It fills the final short block with zeros. Keep the original input length separately to distinguish data from padding.
Empty input or input requiring more than 65,535 blocks returns Err. The function generates protection bytes. Detecting or repairing damaged data needs a decoder.
Related operations
Use std.json.parse, std.json.stringify, and std.json.parseAs<T> for JSON boundaries. Use JSONValue.decode<T>() to decode a parsed value. Both typed calls require one explicit, fully known type. Data errors retain their $ path. std.test.assert uses the test profile.
string.encodeUtf8() creates bytes. Bytes receivers provide hashing and compression. hmacSha256(message) uses the receiver as its key, and zstdCompress(level = 3) preserves its default. CLI helpers are methods of Array<string>. Path, Regex, URL, Date, BigInt, and Decimal retain their constructors and value methods. Use int.toBigInt() and int.toDecimal() for integer conversion. BigInt toString(radix) and Decimal rounding modes retain their existing arguments. CSV and TOML format functions live in std.csv and std.toml. Use TOMLValue.toJson() for an already parsed value.
Use Collection Methods for iterable values and Null, Option, Result & Faults for error handling. Runtime Behavior explains numeric results. Standard Library Overview lists other tasks.
Typed JSON and boundary checks
Native and Web builds support json.parse and json.stringify through namespace aliases, selected imports and function-value aliases. Named arguments retain their ordinary call behavior.
json.parseAs<T> and JSONValue.decode<T>() resolve imported nominal declarations supplied as explicit type arguments. The declared type still needs the required JSON conformance.
Date.fromYmd validates the day before calendar arithmetic. Bytes.get and JSONValue.at return None for an index outside the target platform range, including values too large for a 32-bit index.