module std.ser
std.ser — serialization ([С §9], II.2, D-2100..D-2199).
encode<T> / decode<T> run the codec the compiler generates for T (a descriptor of the schema, walked by the
runtime). The default format is the OxL binary format (protobuf 3 wire encoding, §9.3); Format.Json is the
canonical protobuf JSON mapping. Repr<W> (§9.5 level 1) and Codec<T> (level 2) customise single types and
fields. Level 3 (D-7620): a user format implements Format (the interface FormatSpec), is registered with
register and passed as a type name. Format is the enum of the built-in formats (D-2104): the binary format,
JSON, MessagePack and CBOR (D-7600).
Example:
use std.ser { encode, decode, toJson, Format }
data User {
name: str
age: i32
}
fn main() io {
let bytes = encode(&User{ name: "ann", age: 31 })!
let back = decode<User>(&bytes)!
print("{back.name} {toJson(&back)!}")
}Вывод
ann {"name":"ann","age":31}Типы
interface Codec | Level 2 (§9.5): a codec for values of T, attached with @codec(C) or @codec(json |
type DecodeError | Why bytes could not be decoded into a value ([С §9.4]; declared in the prelude). |
interface Decoder | The reader of a format (§9.5), handed to Codec.decode and returned by Format.decoder. |
type EncodeError | Why a value could not be encoded (declared in the prelude; D-2115). |
interface Encoder | The writer of a format (§9.5) |
data FieldHeader | A field header read by Decoder.nextField. |
enum Format | Wire formats of encode / decode (D-2104). |
interface FormatSpec | Level 3 (§9.5): a user-defined format. |
data NativeDecoder | The reader of the built-in formats handed to a Codec (a handle of the runtime). |
data NativeEncoder | The writer of the built-in formats handed to a Codec (a handle of the runtime). |
interface Repr | Level 1 (§9.5): the type is serialized as another type W in every format and schema. |
data Schema | Description of the schema of a codec for oxl export (§9.5) |
Функции
bytesOf | The UTF-8 bytes of a string |
decode | Decodes b into a T; errors per [С §9.4]. |
encode | Encodes x (§9, II.2). |
fromHex | The bytes of a hexadecimal text (spaces are ignored). |
fromJson | Decodes canonical JSON text. |
hex | Lower-case hexadecimal text of the bytes ("0a 02 68 69" without spaces |
register | Registers the format F (a type that implements Format) so that encode(x, F) / decode<T>(b, F) accept it. |
textOf | The text of UTF-8 bytes |
toJson | Canonical JSON text of x. |