Skip to content

Introduction#

MxPack is a modern Java library for reading and writing the MessagePack serialization format.

The Kotlin examples on this website use MxPack's Kotlin integration.

Example#

The following code writes a string and number to path, then reads them back:

var out = FileChannel.open(path, WRITE, CREATE);
try (var writer = MessageWriter.of(out)) { //(1)
  writer.write("Hello, MxPack!");          //(2)
  writer.write(42);                        //(3)
}

var in = FileChannel.open(path);
try (var reader = MessageReader.of(in)) {  //(4)
  var string = reader.readString();        //(5)
  var number = reader.readInt();           //(6)
}
  1. Creates a MessageWriter that writes to out. The try block ensures that the writer is always closed and not used thereafter.
  2. Encodes string "Hello, MxPack!" and writes it to out.
  3. Encodes number 42 and writes it to out.
  4. Creates a MessageReader that reads from in. The try block ensures that the reader is always closed and not used thereafter.
  5. Reads a string from in and decodes it to "Hello, MxPack!".
  6. Reads a number from in and decodes it to 42.
val out = FileChannel.open(path, WRITE, CREATE)
MessageWriters.of(out).use { writer -> //(1)
  writer.write("Hello, MxPack!")       //(2)
  writer.write(42)                     //(3)
}

val ch = FileChannel.open(path)
MessageReaders.of(ch).use { reader ->  //(4)
  val string = reader.readString()     //(5)
  val number = reader.readInt()        //(6)
}
  1. Creates a MessageWriter that writes to out. The preferred Kotlin way to create a writer is MessageWriters.of() (note the plural form). The use {} block ensures that the writer is always closed and not used thereafter.
  2. Encodes string "Hello, MxPack!" and writes it to out.
  3. Encodes number 42 and writes it to out.
  4. Creates a MessageReader that reads from in. The preferred Kotlin way to create a reader is MessageReaders.of() (note the plural form). The use {} block ensures that the reader is always closed and not used thereafter.
  5. Reads a string from in and decodes it to "Hello, MxPack!".
  6. Reads a number from in and decodes it to 42.

License#

Copyright 2024 the MxPack project authors

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.