OxL Справочник OxL
РусскийEnglish

interface Codec

Level 2 (§9.5): a codec for values of T, attached with @codec(C) or @codec(json: C1, oxl: C2).

Example:

oxl✓ проверяется в CI
use std.ser { Codec, Encoder, Decoder, Schema, encode, decode, hex, EncodeError, DecodeError }

/// Stores names upper-cased in every format.
data Upper {}

impl Codec<str> for Upper {
  static fn encode(x: &str, w: &var Encoder) -> () | EncodeError {
    w.writeStr(x.upper())
  }
  static fn decode(r: &var Decoder) -> str | DecodeError {
    match r.readStr() {
      str s => s.lower()
      DecodeError e => fail e
    }
  }
  static fn schema() -> Schema => Schema{ proto: "string" }
}

data Tag {
  @codec(Upper) name: str
}

fn main() io {
  let b = encode(&Tag{ name: "abc" })!
  print("{hex(&b)} {decode<Tag>(&b)!.name}")
}
Вывод
0a03414243 abc
@explicit pub(api) interface Codec<T>

С версии. 1.0.0-beta

Методы

encode(x: &T, w: &var Encoder) -> () | EncodeError
Writes x to the encoder w as a sequence of events (writeStr, writeI64, ...).
decode(r: &var Decoder) -> T | DecodeError
Reads a value of T from the decoder r with calls of readStr, readI64, ...
schema() -> Schema
The protobuf type text of the codec's representation, recorded in oxl.schema.lock and used by oxl export.

Определено в: std/ser/ser.oxl:250

См. также