Files
std/serial/walk.sakura
T
2026-10-28 00:51:45 -05:00

429 lines
15 KiB
Plaintext

#! @file walk.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains `serial::encode` and `serial::decode`, which walk a value by what
#! `@serial` marks of its type, and the forms of the types std gives: numbers,
#! `bool`, strings, views, `maybe`, vectors, sets, and dictionaries keyed by
#! text.
import std::containers;
module std::serial;
# A type whose value is left out where it is missing, as `maybe` is, rather than
# the missing member being an error.
trait vacant {
def vacant(): self;
}
# A key read from a member's name, as a dictionary's `string` keys are.
trait named {
def from(text: strview, alloc: maybe<&mut allocator>): self;
}
#! Writes a value through a format.
#!
#! A type of its own form, one implementing `encodable`, writes itself, as std's
#! numbers, strings, and containers do. Otherwise the type must be `@serial`:
#! - a struct is written as an object of its marked fields, named as they are or
#! by the `name` of their marks;
#! - an enum as the name of its member, which must be marked;
#! - a union as an object of one member, the marked field it holds.
#! A value holding an unmarked member or field is written as nothing, and the
#! format keeps `not_serial` as its failure.
#! @tparam T The type of the value.
#! @param value The value to write.
#! @param out The format to write it through.
pub def encode<T>(value: &T, out: &mut encoder): void {
if const T is encodable {
value.encode(out);
return;
}
if const attached::<serial>(decl_of::<T>()).length == 0 {
compile_error("The type is not `@serial`, so it is not written. Mark it, and each field to write, with `@serial`.");
}
if const decl_of::<T>().kind == target::enums {
for const member in members_of(decl_of::<T>()) {
if const member.kind == target::members && attached::<serial>(member).length > 0 {
if value == value_of(member) {
out.text(attached::<serial>(member)[0].name.length > 0 ? attached::<serial>(member)[0].name : member.name);
return;
}
}
}
out.fail(error_kind::not_serial);
out.empty();
return;
}
if const decl_of::<T>().kind == target::unions {
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<serial>(field).length > 0 {
if value is (field) {
out.begin_object(1);
out.member(attached::<serial>(field)[0].name.length > 0 ? attached::<serial>(field)[0].name : field.name);
encode(&value.(field), out);
out.end_object();
return;
}
}
}
out.fail(error_kind::not_serial);
out.empty();
return;
}
var count: u64 = 0;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<serial>(field).length > 0 {
count++;
}
}
out.begin_object(count);
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<serial>(field).length > 0 {
out.member(attached::<serial>(field)[0].name.length > 0 ? attached::<serial>(field)[0].name : field.name);
encode(&value.(field), out);
}
}
out.end_object();
}
#! Reads a value a format has read.
#!
#! A type of its own form, one implementing `decodable`, reads itself, as std's
#! numbers, strings, and containers do. Otherwise the type must be `@serial`,
#! and is read as `encode` writes it. A struct starts at its zero value, with
#! its fields at their defaults, and each marked field is read from its member,
#! so a field left unmarked keeps its default.
#!
#! A member missing for a marked field is a `missing_member` error, unless the
#! field is a `maybe`, which is then `none`. A member no field takes is ignored,
#! and so is a member written again after its first, unless the options are
#! strict.
#! @tparam T The type to read, which is `zeroable`, so a field left unread
#! has a value.
#! @param from The document the format read.
#! @param at The value to read, by its index in the document.
#! @param given How strictly to read.
#! @returns The value, or why it could not be read, at the value that failed.
pub def decode<T>(from: &decoder, at: u32, given: options = options {}): result<T, error> where T: zeroable {
if const T is decodable {
return T::decode(from, at, given);
}
if const attached::<serial>(decl_of::<T>()).length == 0 {
compile_error("The type is not `@serial`, so it is not read. Mark it, and each field to read, with `@serial`.");
}
if const decl_of::<T>().kind == target::enums {
val written := from.as_text(at) else (e) { return e; };
for const member in members_of(decl_of::<T>()) {
if const member.kind == target::members && attached::<serial>(member).length > 0 {
val name: strview = attached::<serial>(member)[0].name.length > 0 ? attached::<serial>(member)[0].name : member.name;
if written == name {
return value_of(member);
}
}
}
return error::at(error_kind::out_of_range, from.place(at));
}
if const decl_of::<T>().kind == target::unions {
if from.kind_of(at) != kind::object || from.count(at) != 1 {
return error::at(error_kind::wrong_kind, from.place(at));
}
val inner := from.element(at, 0);
val written := from.name_of(inner);
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<serial>(field).length > 0 {
val name: strview = attached::<serial>(field)[0].name.length > 0 ? attached::<serial>(field)[0].name : field.name;
if written == name {
var read := decode::<type_of(field)>(from, inner, given) else (e) { return e; };
var made: T;
made.(field) = move(read);
return move(made);
}
}
}
return error::at(error_kind::out_of_range, from.place(inner));
}
if from.kind_of(at) != kind::object {
return error::at(error_kind::wrong_kind, from.place(at));
}
var made: T;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<serial>(field).length > 0 {
val name: strview = attached::<serial>(field)[0].name.length > 0 ? attached::<serial>(field)[0].name : field.name;
if from.member(at, name) is some(found) {
var read := decode::<type_of(field)>(from, found, given) else (e) { return e; };
made.(field) = move(read);
} else {
if const !(type_of(field) is vacant) {
return error::at(error_kind::missing_member, from.place(at));
}
}
}
}
# Strictly, every member is one a field takes, and is the first of its name.
if given.strict {
var item: u32 = 0;
for index in 0..from.count(at) {
item = index == 0 ? from.element(at, 0) : from.next_element(at, item);
val written := from.name_of(item);
var known := false;
for const field in members_of(decl_of::<T>()) {
if const field.kind == target::fields && attached::<serial>(field).length > 0 {
val name: strview = attached::<serial>(field)[0].name.length > 0 ? attached::<serial>(field)[0].name : field.name;
known = known || written == name;
}
}
if !known {
return error::at(error_kind::unknown_member, from.place(item));
}
val first := from.member(at, written) else { continue; };
if first != item {
return error::at(error_kind::repeated_member, from.place(item));
}
}
}
return move(made);
}
def i8::encode(&this, out: &mut encoder): void { out.signed(this as i64); }
def i16::encode(&this, out: &mut encoder): void { out.signed(this as i64); }
def i32::encode(&this, out: &mut encoder): void { out.signed(this as i64); }
def i64::encode(&this, out: &mut encoder): void { out.signed(this); }
def u8::encode(&this, out: &mut encoder): void { out.unsigned(this as u64); }
def u16::encode(&this, out: &mut encoder): void { out.unsigned(this as u64); }
def u32::encode(&this, out: &mut encoder): void { out.unsigned(this as u64); }
def u64::encode(&this, out: &mut encoder): void { out.unsigned(this); }
def f32::encode(&this, out: &mut encoder): void { out.real(this as f64); }
def f64::encode(&this, out: &mut encoder): void { out.real(this); }
def bool::encode(&this, out: &mut encoder): void { out.boolean(this); }
def i8::decode(from: &decoder, at: u32, given: options): result<i8, error> {
val read := signed_within(from, at, -128, 127) else (e) { return e; };
return read as i8;
}
def i16::decode(from: &decoder, at: u32, given: options): result<i16, error> {
val read := signed_within(from, at, -32768, 32767) else (e) { return e; };
return read as i16;
}
def i32::decode(from: &decoder, at: u32, given: options): result<i32, error> {
val read := signed_within(from, at, -2147483648, 2147483647) else (e) { return e; };
return read as i32;
}
def i64::decode(from: &decoder, at: u32, given: options): result<i64, error> {
return from.as_i64(at);
}
def u8::decode(from: &decoder, at: u32, given: options): result<u8, error> {
val read := unsigned_within(from, at, 255) else (e) { return e; };
return read as u8;
}
def u16::decode(from: &decoder, at: u32, given: options): result<u16, error> {
val read := unsigned_within(from, at, 65535) else (e) { return e; };
return read as u16;
}
def u32::decode(from: &decoder, at: u32, given: options): result<u32, error> {
val read := unsigned_within(from, at, 4294967295) else (e) { return e; };
return read as u32;
}
def u64::decode(from: &decoder, at: u32, given: options): result<u64, error> {
return from.as_u64(at);
}
def f32::decode(from: &decoder, at: u32, given: options): result<f32, error> {
val read := from.as_f64(at) else (e) { return e; };
if read > 3.4028234663852886e38 || read < -3.4028234663852886e38 {
return error::at(error_kind::out_of_range, from.place(at));
}
return read as f32;
}
def f64::decode(from: &decoder, at: u32, given: options): result<f64, error> {
return from.as_f64(at);
}
def bool::decode(from: &decoder, at: u32, given: options): result<bool, error> {
return from.as_bool(at);
}
def string::encode(&this, out: &mut encoder): void {
out.text(this.view());
}
def string::decode(from: &decoder, at: u32, given: options): result<string, error> {
val read := from.as_text(at) else (e) { return e; };
return string::from(read, nothing {});
}
# A view of one-byte integers is text, and any other view an array, since a view of
# text cannot be told apart from one of bytes by its type.
def span<T>::encode(&this, out: &mut encoder): void {
if const size_of::<T>() == 1 && T is integer {
out.text(strview::over(this.data as *u8, this.length));
return;
}
out.begin_array(this.length);
for &item in this {
encode(item, out);
}
out.end_array();
}
def maybe<T>::encode(&this, out: &mut encoder): void {
match this {
some(&held) => encode(held, out);
none => out.empty();
}
}
def maybe<T>::decode(from: &decoder, at: u32, given: options): result<maybe<T>, error> {
if const !(T is zeroable) {
compile_error("What a `maybe` holds is read from its zero value, so it is `zeroable`.");
}
if from.kind_of(at) == kind::empty {
return maybe::<T>::vacant();
}
var read := decode::<T>(from, at, given) else (e) { return e; };
var made: maybe<T> = move(read);
return move(made);
}
def maybe<T>::vacant(): maybe<T> {
return nothing {};
}
def vector<T>::encode(&this, out: &mut encoder): void {
out.begin_array(this.length);
for &item in this {
encode(item, out);
}
out.end_array();
}
def vector<T>::decode(from: &decoder, at: u32, given: options): result<vector<T>, error> {
if const !(T is zeroable) {
compile_error("A vector's elements are each read from their zero value, so they are `zeroable`.");
}
if from.kind_of(at) != kind::array {
return error::at(error_kind::wrong_kind, from.place(at));
}
val count := from.count(at);
var made := vector::<T>::new(count, nothing {});
var item: u32 = 0;
for index in 0..count {
item = index == 0 ? from.element(at, 0) : from.next_element(at, item);
var read := decode::<T>(from, item, given) else (e) { return e; };
made.append(move(read));
}
return move(made);
}
# A dictionary is an object, so its keys are text.
def dict<K, V>::encode(&this, out: &mut encoder): void {
if const !(K is viewable<u8>) {
compile_error("A dictionary is written as an object, whose members are named, so its keys are text.");
}
out.begin_object(this.length);
for &entry in this {
out.member(entry.key.view());
encode(&entry.value, out);
}
out.end_object();
}
def dict<K, V>::decode(from: &decoder, at: u32, given: options): result<dict<K, V>, error> {
if const !(K is named) {
compile_error("A dictionary is read from an object, whose members are named, so its keys are `string`s.");
}
if const !(V is zeroable) {
compile_error("A dictionary's values are each read from their zero value, so they are `zeroable`.");
}
if from.kind_of(at) != kind::object {
return error::at(error_kind::wrong_kind, from.place(at));
}
# A member written again is read from its first, as a struct's is.
val count := from.count(at);
var made := dict::<K, V>::new(count, nothing {});
var item: u32 = 0;
for index in 0..count {
item = index == 0 ? from.element(at, 0) : from.next_element(at, item);
var key := K::from(from.name_of(item), nothing {});
if made.get(&key) is some(_) {
if given.strict {
return error::at(error_kind::repeated_member, from.place(item));
}
continue;
}
var read := decode::<V>(from, item, given) else (e) { return e; };
made.set(move(key), move(read));
}
return move(made);
}
# A set is an array of its values, in no particular order.
def hashset<T>::encode(&this, out: &mut encoder): void {
out.begin_array(this.length);
for &item in this {
encode(item, out);
}
out.end_array();
}
# A value written twice is held once, as a set holds every value.
def hashset<T>::decode(from: &decoder, at: u32, given: options): result<hashset<T>, error> {
if const !(T is zeroable) {
compile_error("A set's values are each read from their zero value, so they are `zeroable`.");
}
if from.kind_of(at) != kind::array {
return error::at(error_kind::wrong_kind, from.place(at));
}
val count := from.count(at);
var made := hashset::<T>::new(count, nothing {});
var item: u32 = 0;
for index in 0..count {
item = index == 0 ? from.element(at, 0) : from.next_element(at, item);
var read := decode::<T>(from, item, given) else (e) { return e; };
made.insert(move(read));
}
return move(made);
}
# A signed integer read exactly, within bounds.
def signed_within(from: &decoder, at: u32, low: i64, high: i64): result<i64, error> {
val read := from.as_i64(at) else (e) { return e; };
if read < low || read > high {
return error::at(error_kind::out_of_range, from.place(at));
}
return read;
}
# An unsigned integer read exactly, within a bound.
def unsigned_within(from: &decoder, at: u32, high: u64): result<u64, error> {
val read := from.as_u64(at) else (e) { return e; };
if read > high {
return error::at(error_kind::out_of_range, from.place(at));
}
return read;
}