Logo JDeck

Encoding Guide

An encoder is defined as:

type Encoder<'T> = 'T -> MessagePackValue

Encode provides encoders for the same primitive set as the decoders: string, boolean, char, guid, binary, numeric widths, decimal, dateTime, dateTimeOffset, and timeSpan.

Maps are the default record form. Encode.entryMap builds a map from string keys. Encode.array builds one positional array. Encode.sequence encodes each element of a sequence with one encoder.

type Coord = { X: int; Y: int } with

  static member Encoder: Encoder<Coord> =
    fun coord -> Encode.array [| Encode.int coord.X; Encode.int coord.Y |]

type Person = { name: string; age: int } with

  static member Encoder: Encoder<Person> =
    fun person ->
      Encode.entryMap [
        "name", Encode.string person.name
        "age", Encode.int person.age
      ]

let encodedPerson = Person.Encoder { name = "Ada"; age = 36 }
printfn $"Kind: %A{encodedPerson.Kind}"

let encodedCoord = Coord.Encoder { X = 3; Y = 4 }
printfn $"Coord kind: %A{encodedCoord.Kind}"

Wire Forms

The library uses the same native forms as the automatic serializer, so manual and automatic code agree on one choice per type:

Decoders stay lenient: guid, decimal, dateTime, and dateTimeOffset also read their old invariant string forms, and decimal also reads a 16-byte binary value with the same DECIMAL layout.

For default serializers this costs nothing and needs no action. One exception matters: guid and decimal use serializer-reserved codes. Remapping LibraryExtensionTypeCodes on your serializer changes those codes, and manual payloads then stop matching that serializer. Keep the default codes when you mix manual and automatic paths.

The value then travels through MessagePackSerializer as one MessagePackValue.

Inspecting Payloads

MessagePackSerializer.ConvertToJson prints real bytes as JSON, which shows the native forms above without guessing at raw bytes:

let inspectSerializer = MessagePackSerializer()

let inspectShape =
  ReflectionTypeShapeProvider.Default.GetTypeShape<MessagePackValue>()

let mutable inspectOutgoing = Encode.decimal 1234.56m
let inspectBytes: byte array = inspectSerializer.Serialize(&inspectOutgoing, inspectShape)
printfn "%s" (inspectSerializer.ConvertToJson(System.ReadOnlyMemory(inspectBytes)))

F# Values to Bytes

Serializing is the byte-level counterpart of Decoding. Three paths cover the F# serialization cases:

Every path returns byte array. Serializing.toStream and Serializing.autoToStream write to a stream. Pass a serializer as the first argument when codecs or custom settings apply.

type Reading = { Name: string; Value: int }

let autoBytes = Serializing.auto { Name = "temp"; Value = 21 }
printfn $"Auto bytes: %d{autoBytes.Length}"

let manualBytes =
  Serializing.toBytes(
    { name = "Ada"; age = 36 },
    fun person ->
      Encode.entryMap [
        "name", Encode.string person.name
        "age", Encode.int person.age
      ]
  )

printfn $"Manual bytes: %d{manualBytes.Length}"

let manualBack = Decoding.fromBytes (manualBytes, fun value -> decode {
  let! name = Required.Map.get ("name", Required.string) value
  and! age = Required.Map.get ("age", Required.int) value
  return name, age
})

printfn $"Manual round-trip: %A{manualBack}"
namespace System
namespace Nerdbank
namespace Nerdbank.MessagePack
namespace PolyType
namespace PolyType.ReflectionProvider
namespace JDeck
namespace JDeck.MessagePack
type Encoder<'T> = 'T -> MessagePackValue
'T
Multiple items
type MessagePackValue = new: value: byte -> unit + 16 overloads member Equals: other: MessagePackValue -> bool + 1 overload member GetHashCode: unit -> int member StructuralEquals: other: MessagePackValue -> bool member ToString: unit -> string static member op_Explicit: token: MessagePackValue -> byte + 17 overloads static member op_Implicit: value: byte -> MessagePackValue + 17 overloads static val Nil: MessagePackValue member Kind: MessagePackValueKind member ValueAsArray: ReadOnlyMemory<MessagePackValue> ...
<summary> A variant type that can represent any of the MessagePack primitives. </summary>

--------------------
MessagePackValue ()
   (+0 other overloads)
MessagePackValue(value: byte) : MessagePackValue
   (+0 other overloads)
MessagePackValue(value: sbyte) : MessagePackValue
   (+0 other overloads)
MessagePackValue(value: uint16) : MessagePackValue
   (+0 other overloads)
MessagePackValue(value: int16) : MessagePackValue
   (+0 other overloads)
MessagePackValue(value: uint32) : MessagePackValue
   (+0 other overloads)
MessagePackValue(value: int) : MessagePackValue
   (+0 other overloads)
MessagePackValue(value: uint64) : MessagePackValue
   (+0 other overloads)
MessagePackValue(value: int64) : MessagePackValue
   (+0 other overloads)
MessagePackValue(value: bool) : MessagePackValue
   (+0 other overloads)
Coord.X: int
Multiple items
val int: value: 'T -> int (requires member op_Explicit)

--------------------
type int = int32

--------------------
type int<'Measure> = int
Coord.Y: int
type Coord = { X: int Y: int } static member Encoder: Encoder<Coord>
val coord: Coord
module Encode from JDeck.MessagePack.Encoding
val array: values: MessagePackValue array -> MessagePackValue
val int: value: int -> MessagePackValue
Multiple items
val string: value: 'T -> string

--------------------
type string = String
type Person = { name: string age: int } static member Encoder: Encoder<Person>
val person: Person
val entryMap: values: (string * MessagePackValue) seq -> MessagePackValue
val string: value: string -> MessagePackValue
Person.name: string
Person.age: int
val encodedPerson: MessagePackValue
property Person.Encoder: Encoder<Person> with get
val printfn: format: Printf.TextWriterFormat<'T> -> 'T
property MessagePackValue.Kind: MessagePackValueKind with get
<summary> Gets the type of the MessagePack token. </summary>
val encodedCoord: MessagePackValue
property Coord.Encoder: Encoder<Coord> with get
val inspectSerializer: MessagePackSerializer
Multiple items

--------------------
MessagePackSerializer() : MessagePackSerializer
val inspectShape: PolyType.ITypeShape<MessagePackValue>
type ReflectionTypeShapeProvider = interface ITypeShapeProvider member GetTypeShape<'T> : unit -> ITypeShape<'T> + 1 overload static member Create: options: ReflectionTypeShapeProviderOptions -> ReflectionTypeShapeProvider member Options: ReflectionTypeShapeProviderOptions static member Default: ReflectionTypeShapeProvider
<summary> Provides a <see cref="T:PolyType.ITypeShapeProvider" /> implementation that uses reflection. </summary>
property ReflectionTypeShapeProvider.Default: ReflectionTypeShapeProvider with get
<summary> Gets the default provider instance using configuration supported by the current platform. </summary>
ReflectionTypeShapeProvider.GetTypeShape<'T>() : PolyType.ITypeShape<'T>
ReflectionTypeShapeProvider.GetTypeShape(``type`` : Type) : PolyType.ITypeShape
val mutable inspectOutgoing: MessagePackValue
val decimal: value: decimal -> MessagePackValue
val inspectBytes: byte array
Multiple items
val byte: value: 'T -> byte (requires member op_Explicit)

--------------------
type byte = Byte

--------------------
type byte<'Measure> = byte
type 'T array = 'T array
(extension) MessagePackSerializer.Serialize<'T>(value: inref<'T>, ?cancellationToken: Threading.CancellationToken) : byte array
   (+0 other overloads)
(extension) MessagePackSerializer.Serialize<'T,'TProvider>(value: inref<'T>, ?cancellationToken: Threading.CancellationToken) : byte array
   (+0 other overloads)
MessagePackSerializer.Serialize<'T,'TProvider (requires 'TProvider :> PolyType.IShapeable<'T>)>(value: inref<'T>, ?cancellationToken: Threading.CancellationToken) : byte array
   (+0 other overloads)
MessagePackSerializer.Serialize<'T (requires 'T :> PolyType.IShapeable<'T>)>(value: inref<'T>, ?cancellationToken: Threading.CancellationToken) : byte array
   (+0 other overloads)
(extension) MessagePackSerializer.Serialize<'T>(writer: byref<MessagePackWriter>, value: inref<'T>, ?cancellationToken: Threading.CancellationToken) : unit
   (+0 other overloads)
(extension) MessagePackSerializer.Serialize<'T>(writer: Buffers.IBufferWriter<byte>, value: inref<'T>, ?cancellationToken: Threading.CancellationToken) : unit
   (+0 other overloads)
(extension) MessagePackSerializer.Serialize<'T>(stream: IO.Stream, value: inref<'T>, ?cancellationToken: Threading.CancellationToken) : unit
   (+0 other overloads)
(extension) MessagePackSerializer.Serialize<'T,'TProvider>(writer: byref<MessagePackWriter>, value: inref<'T>, ?cancellationToken: Threading.CancellationToken) : unit
   (+0 other overloads)
(extension) MessagePackSerializer.Serialize<'T,'TProvider>(writer: Buffers.IBufferWriter<byte>, value: inref<'T>, ?cancellationToken: Threading.CancellationToken) : unit
   (+0 other overloads)
(extension) MessagePackSerializer.Serialize<'T,'TProvider>(stream: IO.Stream, value: inref<'T>, ?cancellationToken: Threading.CancellationToken) : unit
   (+0 other overloads)
MessagePackSerializer.ConvertToJson(msgpack: inref<Buffers.ReadOnlySequence<byte>>, ?options: Nullable<MessagePackSerializer.JsonOptions>) : string
MessagePackSerializer.ConvertToJson(msgpack: ReadOnlyMemory<byte>, ?options: Nullable<MessagePackSerializer.JsonOptions>) : string
MessagePackSerializer.ConvertToJson(reader: byref<MessagePackReader>, jsonWriter: IO.TextWriter, ?options: Nullable<MessagePackSerializer.JsonOptions>) : unit
Multiple items
type ReadOnlyMemory<'T> = new: array: 'T array -> unit + 1 overload member CopyTo: destination: Memory<'T> -> unit member Equals: obj: obj -> bool + 1 overload member GetHashCode: unit -> int member Pin: unit -> MemoryHandle member Slice: start: int -> ReadOnlyMemory<'T> + 1 overload member ToArray: unit -> 'T array member ToString: unit -> string member TryCopyTo: destination: Memory<'T> -> bool static member op_Implicit: segment: ArraySegment<'T> -> ReadOnlyMemory<'T> + 1 overload ...
<summary>Represents a contiguous region of memory, similar to <see cref="T:System.ReadOnlySpan`1" />. Unlike <see cref="T:System.ReadOnlySpan`1" />, it is not a byref-like type.</summary>
<typeparam name="T">The object type from which the contiguous region of memory will be read.</typeparam>


--------------------
ReadOnlyMemory ()
ReadOnlyMemory(array: 'T array) : ReadOnlyMemory<'T>
ReadOnlyMemory(array: 'T array, start: int, length: int) : ReadOnlyMemory<'T>
type Reading = { Name: string Value: int }
val autoBytes: byte array
type Serializing = static member auto: value: 'T -> byte array + 1 overload static member autoToStream: stream: Stream * value: 'T -> unit + 1 overload static member autoWithShape: shape: ITypeShape<'T> * value: 'T -> byte array + 1 overload static member toBytes: value: 'T * encoder: Encoder<'T> -> byte array + 1 overload static member toStream: stream: Stream * value: 'T * encoder: Encoder<'T> -> unit + 1 overload
<summary> Serializes F# values and manual encoder output to MessagePack bytes. Automatic members use a PolyType shape. Manual members run one encoder to a MessagePackValue, then write that value with the serializer. </summary>
static member Serializing.auto: value: 'T -> byte array
static member Serializing.auto: serializer: MessagePackSerializer * value: 'T -> byte array
property Array.Length: int with get
<summary>Gets the total number of elements in all the dimensions of the <see cref="T:System.Array" />.</summary>
<exception cref="T:System.OverflowException">The array is multidimensional and contains more than <see cref="F:System.Int32.MaxValue">Int32.MaxValue</see> elements.</exception>
<returns>The total number of elements in all the dimensions of the <see cref="T:System.Array" />; zero if there are no elements in the array.</returns>
val manualBytes: byte array
static member Serializing.toBytes: value: 'T * encoder: Encoder<'T> -> byte array
static member Serializing.toBytes: serializer: MessagePackSerializer * value: 'T * encoder: Encoder<'T> -> byte array
val manualBack: Result<(string * int),DecodeError>
type Decoding = static member auto: bytes: byte array -> Result<'TResult,DecodeError> + 3 overloads static member autoFromMemory: serializer: MessagePackSerializer * buffer: ReadOnlyMemory<byte> -> Result<'TResult,DecodeError> static member autoWithShape: shape: ITypeShape<'TResult> * bytes: byte array -> Result<'TResult,DecodeError> + 1 overload static member fromBytes: bytes: byte array * decoder: Decoder<'TResult> -> Result<'TResult,DecodeError> static member fromBytesCol: bytes: byte array * decoder: CollectErrorsDecoder<'TResult> -> Result<'TResult,DecodeError list> static member fromMemory: buffer: ReadOnlyMemory<byte> * decoder: Decoder<'TResult> -> Result<'TResult,DecodeError> static member fromMemoryCol: buffer: ReadOnlyMemory<byte> * decoder: CollectErrorsDecoder<'TResult> -> Result<'TResult,DecodeError list> static member fromSequence: buffer: ReadOnlySequence<byte> * decoder: Decoder<'TResult> -> Result<'TResult,DecodeError> static member fromSequenceCol: buffer: ReadOnlySequence<byte> * decoder: CollectErrorsDecoder<'TResult> -> Result<'TResult,DecodeError list> static member fromStream: stream: Stream * decoder: Decoder<'TResult> -> Result<'TResult,DecodeError> ...
<summary> Decodes MessagePack payloads with JDeck decoders or automatic shapes. There is no fromString: MessagePack is a binary format. </summary>
static member Decoding.fromBytes: bytes: byte array * decoder: Decoder<'TResult> -> Result<'TResult,DecodeError>
val value: MessagePackValue
val decode: DecodeBuilder
val name: string
module Required from JDeck.MessagePack.Decode
<summary> Required decoders fail when the value is missing or has the wrong kind. </summary>
type Map = static member array: key: string * decoder: Decoder<'TResult> -> Decoder<'TResult array> + 1 overload static member dict: key: string * decoder: Decoder<'TValue> -> Decoder<Dictionary<string,'TValue>> + 1 overload static member get: key: string * decoder: Decoder<'TResult> -> Decoder<'TResult> + 1 overload static member list: key: string * decoder: Decoder<'TResult> -> Decoder<'TResult list> + 1 overload static member map: key: string * decoder: Decoder<'TValue> -> Decoder<Map<string,'TValue>> + 1 overload static member seq: key: string * decoder: Decoder<'TResult> -> Decoder<'TResult seq> + 1 overload
<summary> Reads entries of a Map value by string key. </summary>
static member Required.Map.get: key: string * decoder: CollectErrorsDecoder<'TResult> -> (MessagePackValue -> Result<'TResult,DecodeError list>)
static member Required.Map.get: key: string * decoder: Decoder<'TResult> -> Decoder<'TResult>
val string: Decoder<string>
val age: int
val int: Decoder<int>

Type something to start searching.