BinaryFormat.Choice

Last updated 5 months ago

BinaryFormat.Choice

Returns a binary format that chooses the next binary format based on a value that has already been read.

function (binaryFormat as function, chooseFunction as function, optional type as nullable any, optional combineFunction as nullable function) as function

Description

Returns a binary format that chooses the next binary format based on a value that has already been read. The binary format value produced by this function works in stages:

The binary format specified by the binaryFormat parameter is used to read a value.

The value is passed to the choice function specified by the chooseFunction parameter.

The choice function inspects the value and returns a second binary format.

The second binary format is used to read a second value.

If the combine function is specified, then the first and second values are passed to the combine function, and the resulting value is returned.

If the combine function is not specified, the second value is returned.

The second value is returned.

Category

Binary Formats.Controlling what comes next

Examples

Read a list of bytes where the number of elements is determined by the first byte.

let
binaryData = #binary({2, 3, 4, 5}),
listFormat = BinaryFormat.Choice(
BinaryFormat.Byte,
(length) => BinaryFormat.List(BinaryFormat.Byte, length))
in
listFormat(binaryData)

{3, 4}

Read a list of bytes where the number of elements is determined by the first byte, and preserve the first byte read.

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)

[ length = 2, list = {3, 4} ]

Read a list of bytes where the number of elements is determined by the first byte using a streaming list.

let
binaryData = #binary({2, 3, 4, 5}),
listFormat = BinaryFormat.Choice(
BinaryFormat.Byte,
(length) => BinaryFormat.List(BinaryFormat.Byte, length),
type list)
in
listFormat(binaryData)

{3, 4}