BinaryFormat.Choice
BinaryReturns a binary format that chooses the next binary format based on a value that has already been read.
Syntax
BinaryFormat.Choice(binaryFormat as function, chooseFunction as function, optional type as nullable type, optional combineFunction as nullable function) as functionParameters
| Name | Type | Required | Description |
|---|---|---|---|
binaryFormat | function | Yes | The binary format used to read the initial value that determines the choice. |
chooseFunction | function | Yes | A function that receives the initial value and returns a second binary format to use for reading the next value. |
type | nullable type | No | The expected type of binary format returned by the choice function. Can be type any, type list, or type binary. Using type list or type binary may enable streaming. |
combineFunction | nullable function | No | A function that receives both the first and second values and returns a combined result. If not specified, the second value is returned. |
Return Value
function — A binary format function that dynamically selects parsing logic based on a previously read value.
Remarks
BinaryFormat.Choice returns a binary format that dynamically determines how to parse binary data based on an initial value. It works in stages:
1. The binaryFormat parameter reads an initial value from the binary stream. 2. That value is passed to chooseFunction, which inspects it and returns a second binary format. 3. The second binary format reads the next value from the stream. 4. If combineFunction is provided, both values are passed to it and the combined result is returned. Otherwise, only the second value is returned.
The optional type parameter (type any, type list, or type binary) hints at the return type of the choice function. Using type list or type binary may allow the system to return streaming values instead of buffered ones, reducing memory usage.
This is essential for parsing binary formats where the structure depends on header values, type tags, or length prefixes.
Examples
Example 1: Read a list of bytes with a length prefix
let
binaryData = #binary({2, 3, 4, 5}),
listFormat = BinaryFormat.Choice(
BinaryFormat.Byte,
(length) => BinaryFormat.List(BinaryFormat.Byte, length)
)
in
listFormat(binaryData)Example 2: Preserve the first value using a record
let
binaryData = #binary({2, 3, 4, 5}),
listFormat = BinaryFormat.Choice(
BinaryFormat.Byte,
(length) => BinaryFormat.Record([
length = length,
list = BinaryFormat.List(BinaryFormat.Byte, length)
])
)
in
listFormat(binaryData)