Files
std/tests/serial/serial.sakura
T
2026-10-27 16:22:18 -05:00

604 lines
21 KiB
Plaintext

# Tests of `std::serial`, through a small format of their own, the tape, so that
# nothing about the walk leans on JSON, and through JSON. The types are private
# to the program, so the walk sees them only by the consent `@serial` gives.
import std::io;
import std::json;
import std::serial;
import std::testing;
import std::yaml;
import std::containers;
@serial enum hue: u8 { @serial red, @serial{ name = "GREEN" } green, blue }
@serial union shape {
@serial var circle: f64;
@serial{ name = "box" } var square: i64;
var hidden: u8;
}
@serial struct point {
@serial var x: i64;
@serial{ name = "Y" } var y: i64;
var cache: i64 = 9;
}
@serial struct page<T> {
@serial var items: vector<T>;
@serial var next: maybe<string>;
}
@serial struct numbers {
@serial var a: i8;
@serial var b: i16;
@serial var c: i32;
@serial var d: i64;
@serial var e: u8;
@serial var f: u16;
@serial var g: u32;
@serial var h: u64;
@serial var i: f32;
@serial var j: f64;
@serial var k: bool;
}
@serial struct everything {
@serial var name: string;
@serial var hue: hue;
@serial var shapes: vector<shape>;
@serial var at: point;
@serial var pages: page<point>;
@serial var counts: dict<string, i64>;
@serial var plain: numbers;
@serial var heat: celsius;
}
@serial struct views {
@serial var bytes: span<u8>;
@serial var wide: span<i64>;
}
@serial struct tagged {
@serial var tags: hashset<string>;
}
# A type of its own form, written as text such as `21.5C`.
struct celsius : serial::encodable, serial::decodable { var degrees: f64; }
def celsius::encode(&this, out: &mut serial::encoder): void {
val written := $"{this.degrees}C";
out.text(written.view());
}
def celsius::decode(from: &serial::decoder, at: u32, given: serial::options): result<celsius, serial::error> {
val text := from.as_text(at) else (e) { return e; };
if !text.ends_with("C") {
return serial::error::at(serial::error_kind::wrong_kind, from.place(at));
}
return celsius { degrees = real::parse::<f64>(text.substr(0, text.length - 1)).value };
}
# A value as the tape holds it: what it is, the name of the member it is, and its
# text, number, or truth.
struct cell {
var kind: serial::kind;
var name: string;
var text: string;
var form: u8; # 0 for a signed number, 1 an unsigned one, 2 a float.
var whole: i64;
var natural: u64;
var real: f64;
var truth: bool;
var count: u64; # What an array or object holds.
var next: u32; # The cell past everything an array or object holds.
}
# A format of the tests' own: it records what it is given as cells, and as a
# transcript, and reads the cells back as a document.
struct tape : serial::encoder, serial::decoder {
var cells: vector<cell>;
var open: vector<u32>;
var pending: string; # The name of the member whose value comes next.
var transcript: string;
var failure: maybe<serial::error_kind>;
}
def tape::new(): tape {
return tape {
cells = vector::<cell>::new(),
open = vector::<u32>::new(),
pending = string::new(nothing {}),
transcript = string::new(nothing {})
};
}
def tape::add(&mut this, kind: serial::kind): u32 {
if this.open.length > 0 {
val holder: u32 = this.open.at(this.open.length - 1);
this.cells.at(holder as u64).count++;
}
this.cells.append(cell { kind = kind, name = move(this.pending), text = string::new(nothing {}) });
this.pending = string::new(nothing {});
return (this.cells.length - 1) as u32;
}
def tape::note(&mut this, text: span<u8>): void {
this.transcript.append(text);
this.transcript.push(' ');
}
def tape::begin_object(&mut this, count: u64): void {
this.open.append(this.add(serial::kind::object));
this.note($"\{{count}".view());
}
def tape::member(&mut this, name: span<u8>): void {
this.pending.append(name);
this.note($"{name}:".view());
}
def tape::end_object(&mut this): void {
this.seal();
this.note("}");
}
def tape::begin_array(&mut this, count: u64): void {
this.open.append(this.add(serial::kind::array));
this.note($"[{count}".view());
}
def tape::end_array(&mut this): void {
this.seal();
this.note("]");
}
def tape::seal(&mut this): void {
val holder: u32 = this.open.at(this.open.length - 1);
this.cells.at(holder as u64).next = this.cells.length as u32;
this.open.remove_at(this.open.length - 1);
}
def tape::text(&mut this, value: span<u8>): void {
val at := this.add(serial::kind::text);
this.cells.at(at as u64).text.append(value);
this.note($"'{value}'".view());
}
def tape::signed(&mut this, value: i64): void {
val at := this.add(serial::kind::number);
this.cells.at(at as u64).whole = value;
this.note($"{value}".view());
}
def tape::unsigned(&mut this, value: u64): void {
val at := this.add(serial::kind::number);
this.cells.at(at as u64).form = 1;
this.cells.at(at as u64).natural = value;
this.note($"{value}u".view());
}
def tape::real(&mut this, value: f64): void {
val at := this.add(serial::kind::number);
this.cells.at(at as u64).form = 2;
this.cells.at(at as u64).real = value;
this.note($"{value}f".view());
}
def tape::boolean(&mut this, value: bool): void {
val at := this.add(serial::kind::boolean);
this.cells.at(at as u64).truth = value;
this.note(value ? "true" : "false");
}
def tape::empty(&mut this): void {
_ = this.add(serial::kind::empty);
this.note("~");
}
def tape::fail(&mut this, kind: serial::error_kind): void {
if this.failure is none {
this.failure = kind;
}
}
def tape::kind_of(&this, at: u32): serial::kind {
return this.cells.at(at as u64).kind;
}
def tape::after(&this, at: u32): u32 {
val held := &this.cells.at(at as u64);
return held.kind == serial::kind::array || held.kind == serial::kind::object ? held.next : at + 1;
}
def tape::element(&this, at: u32, index: u64): u32 {
var child := at + 1;
for _ in 0..index {
child = this.after(child);
}
return child;
}
def tape::member(&this, at: u32, name: span<u8>): maybe<u32> {
if this.cells.at(at as u64).kind != serial::kind::object {
return nothing {};
}
for index in 0..this.cells.at(at as u64).count {
val child := this.element(at, index);
if this.cells.at(child as u64).name.view() == name {
return child;
}
}
return nothing {};
}
def tape::count(&this, at: u32): u64 {
return this.cells.at(at as u64).count;
}
def tape::next_element(&this, at: u32, previous: u32): u32 {
return this.after(previous);
}
def tape::name_of(&this, value: u32): strview {
return this.cells.at(value as u64).name.view();
}
def tape::as_text(&this, at: u32): result<strview, serial::error> {
val held := &this.cells.at(at as u64);
if held.kind != serial::kind::text {
return serial::error::at(serial::error_kind::wrong_kind, this.place(at));
}
return held.text.view();
}
def tape::as_i64(&this, at: u32): result<i64, serial::error> {
val held := &this.cells.at(at as u64);
if held.kind != serial::kind::number || held.form == 2 {
return serial::error::at(serial::error_kind::wrong_kind, this.place(at));
}
if held.form == 1 && held.natural > 9223372036854775807 {
return serial::error::at(serial::error_kind::out_of_range, this.place(at));
}
return held.form == 1 ? held.natural as i64 : held.whole;
}
def tape::as_u64(&this, at: u32): result<u64, serial::error> {
val held := &this.cells.at(at as u64);
if held.kind != serial::kind::number || held.form == 2 {
return serial::error::at(serial::error_kind::wrong_kind, this.place(at));
}
if held.form == 0 && held.whole < 0 {
return serial::error::at(serial::error_kind::out_of_range, this.place(at));
}
return held.form == 1 ? held.natural : held.whole as u64;
}
def tape::as_f64(&this, at: u32): result<f64, serial::error> {
val held := &this.cells.at(at as u64);
if held.kind != serial::kind::number {
return serial::error::at(serial::error_kind::wrong_kind, this.place(at));
}
return held.form == 2 ? held.real : held.form == 1 ? held.natural as f64 : held.whole as f64;
}
def tape::as_bool(&this, at: u32): result<bool, serial::error> {
val held := &this.cells.at(at as u64);
if held.kind != serial::kind::boolean {
return serial::error::at(serial::error_kind::wrong_kind, this.place(at));
}
return held.truth;
}
def tape::place(&this, at: u32): serial::place {
return serial::place { offset = at as u64 };
}
def sample(): everything {
var made := everything {
name = string::from("sample", nothing {}),
hue = hue::green,
shapes = vector::<shape>::new(),
at = point { x = 3, y = -4, cache = 100 },
pages = page::<point> { items = vector::<point>::new(), next = string::from("p2", nothing {}) },
counts = dict::<string, i64>::new(),
plain = numbers { a = -128, b = 32767, c = -5, d = 9, e = 255, f = 7, g = 4294967295, h = 18446744073709551615,
i = 1.5, j = 0.1, k = true },
heat = celsius { degrees = 21.5 }
};
made.shapes.append(shape { circle = 2.5 });
made.shapes.append(shape { square = 4 });
made.pages.items.append(point { x = 1, y = 2 });
made.counts.set(string::from("one", nothing {}), 1);
return move(made);
}
# Whether two values of `everything` hold the same, but for what is not marked.
def same(a: &everything, b: &everything): bool {
return a.name.view() == b.name.view() && a.hue == b.hue && a.shapes.length == 2 && b.shapes.length == 2
&& b.shapes.at(0).circle == 2.5 && b.shapes.at(1).square == 4 && a.at.x == b.at.x && a.at.y == b.at.y
&& b.at.cache == 9 && b.pages.items.length == 1 && b.pages.items.at(0).y == 2 && b.pages.next is some
&& b.counts.length == 1 && b.counts.get(&string::from("one", nothing {})).some == 1
&& b.plain.a == -128 && b.plain.b == 32767 && b.plain.c == -5 && b.plain.d == 9 && b.plain.e == 255
&& b.plain.f == 7 && b.plain.g == 4294967295 && b.plain.h == 18446744073709551615 && b.plain.i == 1.5
&& b.plain.j == 0.1 && b.plain.k && b.heat.degrees == 21.5;
}
# The kind of error decoding JSON text as `everything` fails with, or `nothing`.
def decode_fails<T>(text: strview, strict: bool = false): maybe<json::error_kind> where T: zeroable {
match json::from_text::<T>(text, serial::options { strict = strict }) {
value(&_) => return nothing {};
error(e) => return e.kind;
}
return nothing {};
}
@test def serial_writes_marked_fields_by_their_names(t: &mut tester): void {
var out := tape::new();
serial::encode(&point { x = 1, y = 2 }, &mut out);
t.expects(out.transcript.view() == "{2 x: 1 Y: 2 } ");
var paged := tape::new();
var p := page::<point> { items = vector::<point>::new(), next = nothing {} };
p.items.append(point { x = 5, y = 6 });
serial::encode(&p, &mut paged);
t.expects(paged.transcript.view() == "{2 items: [1 {2 x: 5 Y: 6 } ] next: ~ } ");
}
@test def serial_writes_enums_unions_and_std_types(t: &mut tester): void {
var out := tape::new();
serial::encode(&hue::green, &mut out);
serial::encode(&shape { square = 4 }, &mut out);
serial::encode(&shape { circle = 0.5 }, &mut out);
serial::encode(&numbers { a = -1, e = 2, i = 0.25, k = true }, &mut out);
t.expects(out.transcript.view() == "'GREEN' {1 box: 4 } {1 circle: 0.5f } {11 a: -1 b: 0 c: 0 d: 0 e: 2u f: 0u g: 0u h: 0u i: 0.25f j: 0f k: true } ");
t.expects(out.failure is none);
var made := views { bytes = "hi", wide = [1, 2] };
var viewed := tape::new();
serial::encode(&made, &mut viewed);
t.expects(viewed.transcript.view() == "{2 bytes: 'hi' wide: [2 1 2 ] } ");
}
@test def serial_unmarked_members_and_fields_fail(t: &mut tester): void {
var out := tape::new();
serial::encode(&hue::blue, &mut out);
serial::encode(&shape { hidden = 1 }, &mut out);
t.expects(out.transcript.view() == "~ ~ ");
t.expects(out.failure.some == serial::error_kind::not_serial);
match json::to_text(&hue::blue) {
value(&_) => t.expects(false);
error(e) => t.expects(e.kind == json::error_kind::not_serial);
}
}
@test def serial_reads_back_what_it_writes(t: &mut tester): void {
val written := sample();
var out := tape::new();
serial::encode(&written, &mut out);
t.expects(out.failure is none);
match serial::decode::<everything>(&out, 0) {
value(&read) => t.expects(same(&written, read));
error(e) => t.expects(false);
}
}
@test def serial_round_trips_through_json(t: &mut tester): void {
val written := sample();
val text := json::to_text(&written) else (e) {
t.expects(false);
return;
};
t.expects(text.view() == """
{"name":"sample","hue":"GREEN","shapes":[{"circle":2.5},{"box":4}],"at":{"x":3,"Y":-4},"pages":{"items":[{"x":1,"Y":2}],"next":"p2"},"counts":{"one":1},"plain":{"a":-128,"b":32767,"c":-5,"d":9,"e":255,"f":7,"g":4294967295,"h":18446744073709551615,"i":1.5,"j":0.1,"k":true},"heat":"21.5C"}
""".trim());
match json::from_text::<everything>(text.view()) {
value(&read) => t.expects(same(&written, read));
error(e) => t.expects(false);
}
# The same, written indented.
val pretty := json::to_text(&point { x = 1, y = 2 }, 2) else (e) {
t.expects(false);
return;
};
t.expects(pretty.view() == "{\n \"x\": 1,\n \"Y\": 2\n}");
}
@test def serial_missing_members_fail_unless_maybe(t: &mut tester): void {
t.expects(decode_fails::<point>("{\"x\": 1}").some == json::error_kind::missing_member);
t.expects(decode_fails::<point>("{\"x\": 1, \"y\": 2}").some == json::error_kind::missing_member);
t.expects(decode_fails::<page<point>>("{\"items\": []}") is none);
t.expects(decode_fails::<page<point>>("{\"items\": [], \"next\": null}") is none);
# A field left unmarked keeps its default, and one marked a `maybe` is `none`.
val read := json::from_text::<page<point>>("{\"items\": [{\"x\": 1, \"Y\": 2, \"cache\": 5}]}") else (e) {
t.expects(false);
return;
};
t.expects(read.next is none && read.items.at(0).cache == 9);
}
@test def serial_strict_reading_refuses_unknown_and_repeated_members(t: &mut tester): void {
val extra: strview = "{\"x\": 1, \"Y\": 2, \"z\": 3}";
val twice: strview = "{\"x\": 1, \"Y\": 2, \"x\": 3}";
t.expects(decode_fails::<point>(extra) is none && decode_fails::<point>(twice) is none);
t.expects(decode_fails::<point>(extra, true).some == json::error_kind::unknown_member);
t.expects(decode_fails::<point>(twice, true).some == json::error_kind::repeated_member);
# A member written twice is read from its first.
val read := json::from_text::<point>(twice) else (e) {
t.expects(false);
return;
};
t.expects(read.x == 1);
# Strictness reaches what vectors and dictionaries hold.
t.expects(decode_fails::<page<point>>("{\"items\": [{\"x\": 1, \"Y\": 2, \"w\": 0}]}", true).some == json::error_kind::unknown_member);
t.expects(decode_fails::<everything>(json::to_text(&sample()).value.view(), true) is none);
}
# A set is an array of its values, and one read holds a value written twice once.
@test def serial_writes_sets_as_arrays(t: &mut tester): void {
var out := tape::new();
var one := hashset::<i64>::new();
one.insert(7);
serial::encode(&one, &mut out);
t.expects(out.transcript.view() == "[1 7 ] ");
val read := json::from_text::<tagged>("{\"tags\": [\"b\", \"a\", \"b\"]}", serial::options { strict = true }) else (e) {
t.expects(false);
return;
};
t.expects(read.tags.length == 2 && read.tags.contains(&string::from("a", nothing {})));
t.expects(read.tags.contains(&string::from("b", nothing {})));
val text := json::to_text(&read) else (e) {
t.expects(false);
return;
};
val again := yaml::from_text::<tagged>(text.view()) else (e) {
t.expects(false);
return;
};
t.expects(again.tags == read.tags);
t.expects(decode_fails::<tagged>("{\"tags\": \"a\"}").some == json::error_kind::wrong_kind);
}
@test def serial_values_must_fit_their_types(t: &mut tester): void {
t.expects(decode_fails::<numbers>("{\"a\":-129,\"b\":0,\"c\":0,\"d\":0,\"e\":0,\"f\":0,\"g\":0,\"h\":0,\"i\":0,\"j\":0,\"k\":true}").some == json::error_kind::out_of_range);
t.expects(decode_fails::<numbers>("{\"a\":0,\"b\":0,\"c\":0,\"d\":0,\"e\":256,\"f\":0,\"g\":0,\"h\":0,\"i\":0,\"j\":0,\"k\":true}").some == json::error_kind::out_of_range);
t.expects(decode_fails::<numbers>("{\"a\":0,\"b\":0,\"c\":0,\"d\":0,\"e\":0,\"f\":0,\"g\":0,\"h\":0,\"i\":1e39,\"j\":0,\"k\":true}").some == json::error_kind::out_of_range);
t.expects(decode_fails::<numbers>("{\"a\":0,\"b\":0,\"c\":0,\"d\":1.5,\"e\":0,\"f\":0,\"g\":0,\"h\":0,\"i\":0,\"j\":0,\"k\":true}").some == json::error_kind::wrong_kind);
t.expects(decode_fails::<numbers>("{\"a\":0,\"b\":0,\"c\":0,\"d\":0,\"e\":0,\"f\":0,\"g\":-1,\"h\":0,\"i\":0,\"j\":0,\"k\":1}").some == json::error_kind::out_of_range);
t.expects(decode_fails::<numbers>("{\"a\":0,\"b\":0,\"c\":0,\"d\":0,\"e\":0,\"f\":0,\"g\":0,\"h\":0,\"i\":0,\"j\":0,\"k\":1}").some == json::error_kind::wrong_kind);
t.expects(decode_fails::<hue>("\"blue\"").some == json::error_kind::out_of_range);
t.expects(decode_fails::<hue>("\"green\"").some == json::error_kind::out_of_range);
t.expects(decode_fails::<hue>("\"GREEN\"") is none);
t.expects(decode_fails::<shape>("{\"circle\": 1, \"box\": 2}").some == json::error_kind::wrong_kind);
t.expects(decode_fails::<shape>("{\"hidden\": 1}").some == json::error_kind::out_of_range);
t.expects(decode_fails::<point>("[1, 2]").some == json::error_kind::wrong_kind);
t.expects(decode_fails::<celsius>("\"21\"").some == json::error_kind::wrong_kind);
t.expects(decode_fails::<point>("{\"x\": 1,").some == json::error_kind::unexpected_end);
}
@test def serial_errors_say_where_the_value_is(t: &mut tester): void {
match json::from_text::<page<point>>("{\"items\": [\n {\"x\": 1, \"Y\": 2},\n {\"x\": \"one\", \"Y\": 2}\n]}") {
value(&_) => t.expects(false);
error(e) => {
t.expects(e.kind == json::error_kind::wrong_kind && e.line == 3 && e.column == 9);
t.expects(e.describe().view() == "3:9: The value is not of the kind the type asks for.");
}
}
# A missing member is where the object holding it is.
match json::from_text::<page<point>>("{\"items\": [{\"x\": 1}]}") {
value(&_) => t.expects(false);
error(e) => t.expects(e.kind == json::error_kind::missing_member && e.column == 12);
}
}
@test def serial_custom_forms_write_and_read_themselves(t: &mut tester): void {
var out := tape::new();
serial::encode(&celsius { degrees = -3.25 }, &mut out);
t.expects(out.transcript.view() == "'-3.25C' ");
match serial::decode::<celsius>(&out, 0) {
value(read) => t.expects(read.degrees == -3.25);
error(e) => t.expects(false);
}
t.expects(json::from_text::<celsius>("\"100C\"").value.degrees == 100.0);
}
@test def serial_documents_are_values_of_their_own_form(t: &mut tester): void {
val doc := json::parse("{\"a\": [1, 2.5, \"x\"], \"b\": null}") else (e) {
t.expects(false);
return;
};
var out := tape::new();
serial::encode(&doc.root, &mut out);
t.expects(out.transcript.view() == "{2 a: [3 1 2.5f 'x' ] b: ~ } ");
}
@test def serial_round_trips_through_yaml(t: &mut tester): void {
val written := sample();
val text := yaml::to_text(&written) else (e) {
t.expects(false);
return;
};
t.expects(text.view() == """
name: sample
hue: GREEN
shapes:
- circle: 2.5
- box: 4
at:
x: 3
"Y": -4
pages:
items:
- x: 1
"Y": 2
next: p2
counts:
one: 1
plain:
a: -128
b: 32767
c: -5
d: 9
e: 255
f: 7
g: 4294967295
h: 18446744073709551615
i: 1.5
j: 0.1
k: true
heat: 21.5C
""");
match yaml::from_text::<everything>(text.view()) {
value(&read) => t.expects(same(&written, read));
error(e) => t.expects(false);
}
# What JSON writes is YAML, as YAML 1.2 reads it.
val as_json := json::to_text(&written) else (e) {
t.expects(false);
return;
};
match yaml::from_text::<everything>(as_json.view(), serial::options { strict = true }) {
value(&read) => t.expects(same(&written, read));
error(e) => t.expects(false);
}
}
@test def serial_reads_yaml_as_it_reads_json(t: &mut tester): void {
match yaml::from_text::<page<point>>("items:\n - x: 1\n Y: 2\n - x: one\n Y: 2\n") {
value(&_) => t.expects(false);
error(e) => t.expects(e.kind == yaml::error_kind::wrong_kind && e.line == 4 && e.column == 8);
}
match yaml::from_text::<point>("x: 1\n", serial::options { strict = true }) {
value(&_) => t.expects(false);
error(e) => t.expects(e.kind == yaml::error_kind::missing_member && e.line == 1);
}
match yaml::from_text::<point>("x: 1\nY: 2\nz: 3\n", serial::options { strict = true }) {
value(&_) => t.expects(false);
error(e) => t.expects(e.kind == yaml::error_kind::unknown_member && e.line == 3);
}
# A `string` is read from text only, so a number written plain is not one.
t.expects(yaml::from_text::<page<point>>("items: []\nnext: 1.10\n").error.kind == yaml::error_kind::wrong_kind);
t.expects(yaml::from_text::<page<point>>("items: []\nnext: \"1.10\"\n").value.next.some.view() == "1.10");
t.expects(yaml::from_text::<celsius>("100C").value.degrees == 100.0);
val doc := yaml::parse("a: [1, 2.5, x]\nb: ~\n") else (e) {
t.expects(false);
return;
};
var out := tape::new();
serial::encode(&doc.root, &mut out);
t.expects(out.transcript.view() == "{2 a: [3 1 2.5f 'x' ] b: ~ } ");
}