enum Format
Wire formats of encode / decode (D-2104). std.ser.formats has the lower-case names of the standard.
Example:
use std.ser { encode, Format, hex }
fn main() io {
let a = encode(&300, Format.Oxl)!
let b = encode(&300, Format.Json)!
print("{hex(&a)} {Utf8.decode(b)!}")
}Вывод
08ac02 "300"
Примеры#
Один тип — несколько форматов: родной, JSON, MessagePack, CBOR.
Сравнение форматов#
encode(&x, Format.…) и decode(&bytes, Format.…) принимают формат параметром. Компактные двоичные форматы (Msgpack, Cbor) заметно короче JSON.
use std.ser { encode, decode, hex, Format }
data Point { x: i64; y: i64 }
fn main() io {
let p = Point{ x: 1, y: -2 }
let native = encode(&p, Format.Oxl)! // родной компактный двоичный формат
let json = encode(&p, Format.Json)! // тот же тип в другом формате
let pack = encode(&p, Format.Msgpack)!
let cbor = encode(&p, Format.Cbor)!
print("oxl {native.len()}, json {json.len()}, msgpack {pack.len()}, cbor {cbor.len()} bytes")
print("{hex(&native)} {Utf8.decode(json)!}")
let back: Point = decode(&json, Format.Json)!
print("{back.x} {back.y}")
let again: Point = decode(&pack, Format.Msgpack)!
print("{again == back}")
}Вывод
oxl 13, json 18, msgpack 7, cbor 7 bytes
080110feffffffffffffffff01 {"x":"1","y":"-2"}
1 -2
truepub(api) enum FormatС версии. 1.0.0-beta
Варианты
Oxl | The OxL binary format (protobuf 3 wire encoding). |
Json | Canonical protobuf JSON. |
Msgpack | MessagePack. |
Cbor | CBOR (RFC 8949). |
Определено в: std/ser/ser.oxl:85