Bytes.Encode

Bytes

Build Bytes from integers, floats, strings, and nested encoders.

BEAM-target encoders for OTP binaries.

Types

Encoder

type Encoder = Encoder

Describes how to produce a byte sequence. Snap pieces together with sequence, then call encode.

Examples

Bytes.width (encode (unsignedInt8 7)) == 1

Values

encode

encode : Encoder -> Bytes

Turn an encoder into Bytes.

Examples

Bytes.width (encode (unsignedInt8 7)) == 1
Bytes.width (encode (unsignedInt16 BE 7)) == 2
Bytes.width (encode (unsignedInt16 LE 7)) == 2

signedInt8

signedInt8 : Int -> Encoder

Encode an integer from -128 to 127 in one byte.

Examples

Bytes.width (encode (signedInt8 -3)) == 1

signedInt16

signedInt16 : Endianness -> Int -> Encoder

Encode an integer from -32768 to 32767 in two bytes.

Examples

Bytes.width (encode (signedInt16 BE -3)) == 2

signedInt32

signedInt32 : Endianness -> Int -> Encoder

Encode an integer from -2147483648 to 2147483647 in four bytes.

Examples

Bytes.width (encode (signedInt32 BE -3)) == 4

unsignedInt8

unsignedInt8 : Int -> Encoder

Encode an integer from 0 to 255 in one byte.

Examples

Bytes.width (encode (unsignedInt8 255)) == 1

unsignedInt16

unsignedInt16 : Endianness -> Int -> Encoder

Encode an integer from 0 to 65535 in two bytes.

Examples

Bytes.width (encode (unsignedInt16 LE 7)) == 2

unsignedInt32

unsignedInt32 : Endianness -> Int -> Encoder

Encode an integer from 0 to 4294967295 in four bytes.

Examples

Bytes.width (encode (unsignedInt32 BE 7)) == 4

float32

float32 : Endianness -> Float -> Encoder

Encode a 32-bit float in four bytes.

Examples

Bytes.width (encode (float32 BE 1.5)) == 4

float64

float64 : Endianness -> Float -> Encoder

Encode a 64-bit float in eight bytes.

Examples

Bytes.width (encode (float64 BE 1.5)) == 8

bytes

bytes : Bytes -> Encoder

Copy existing bytes into the encoder (no length prefix).

Examples

png imageData =
    sequence
        [ unsignedInt32 BE (Bytes.width imageData)
        , bytes imageData
        ]

string

string : String -> Encoder

Encode a string as UTF-8 bytes (no length prefix).

Examples

Bytes.width (encode (string "hi")) == 2
Bytes.width (encode (string "hello")) == 5

getStringWidth

getStringWidth : String -> Int

UTF-8 byte width of a string (for length prefixes in your protocol).

Examples

getStringWidth "hi" == 2
getStringWidth "hello" == 5
getStringWidth "$20" == 3

sequence

sequence : List Encoder -> Encoder

Concatenate encoders in order.

Examples

type alias Ball =
    { x : Float
    , y : Float
    , z : Float
    }

ball : Ball -> Encoder
ball { x, y, z } =
    sequence
        [ float32 BE x
        , float32 BE y
        , float32 BE z
        ]

Bytes.width (encode (sequence [ unsignedInt8 1, unsignedInt8 2 ])) == 2