Grav v1.14.0

MessagePack

import "std/data" (included in import "std") · namespace std.data

MessagePack: the same data as JSON in a compact binary form, for caches, queues and messages between services. It is read into, and written from, the same JsonValue as JSON.

grav
import "std"

fn main() {
    let doc = Json.parse("{\"id\": 7, \"name\": \"Ada\", \"tags\": [\"admin\"], \"score\": 1.5}")
    let bytes = MsgPack.encode(doc)
    print("${doc.toJson().length} bytes as JSON, ${bytes.size()} as MessagePack")
    print(bytes.toHex())
    print(MsgPack.decode(bytes).toJson())
}
Output
50 bytes as JSON, 41 as MessagePack
84a2696407a46e616d65a3416461a47461677391a561646d696ea573636f7265cb3ff8000000000000
{"id":7,"name":"Ada","tags":["admin"],"score":1.5}
  • Writing picks the smallest form for each integer, writes floats as float64, strings as str, and arrays and maps as such. MsgPack.encodeAny(x) writes any value (objects as JsonMap writes them).
  • Reading takes every form, float32 included. A bin becomes Base64 text, an ext an object {"ext": type, "data": Base64}, and a map key that is not a string its text. Malformed or truncated input, or bytes after the value, is a ValueError.
  • Speed. Both directions run in C over the value's storage: writing is about five times faster than writing JSON, reading about one and a half. The bytes are the same as Python's msgpack writes.

API

class MsgPack

Static members

  • static fn encode(v: JsonValue) -> Bytes — The MessagePack bytes of a JSON value.
  • static fn encodeAny(x: any) -> Bytes — The MessagePack bytes of any value (objects as JsonMap writes them).
  • static fn decode(b: Bytes) -> JsonValue — The value MessagePack bytes hold (all of them: trailing bytes are an error).

class MsgPackReader

Reads MessagePack bytes (the scalars in C, straight into the containers).

Constructors

  • new MsgPackReader(b: Bytes)

Methods

  • fn document() -> JsonValue

Edit this page on GitHub