#! @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(value: &T, out: &mut encoder): void { if const T is encodable { value.encode(out); return; } if const attached::(decl_of::()).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::().kind == target::enums { for const member in members_of(decl_of::()) { if const member.kind == target::members && attached::(member).length > 0 { if value == value_of(member) { out.text(attached::(member)[0].name.length > 0 ? attached::(member)[0].name : member.name); return; } } } out.fail(error_kind::not_serial); out.empty(); return; } if const decl_of::().kind == target::unions { for const field in members_of(decl_of::()) { if const field.kind == target::fields && attached::(field).length > 0 { if value is (field) { out.begin_object(1); out.member(attached::(field)[0].name.length > 0 ? attached::(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::()) { if const field.kind == target::fields && attached::(field).length > 0 { count++; } } out.begin_object(count); for const field in members_of(decl_of::()) { if const field.kind == target::fields && attached::(field).length > 0 { out.member(attached::(field)[0].name.length > 0 ? attached::(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`, or the options ask for `defaults`, #! which leave the field at its default. 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(from: &decoder, at: u32, given: options = options {}): result where T: zeroable { if const T is decodable { return T::decode(from, at, given); } if const attached::(decl_of::()).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::().kind == target::enums { val written := from.as_text(at) else (e) { return e; }; for const member in members_of(decl_of::()) { if const member.kind == target::members && attached::(member).length > 0 { val name: strview = attached::(member)[0].name.length > 0 ? attached::(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::().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::()) { if const field.kind == target::fields && attached::(field).length > 0 { val name: strview = attached::(field)[0].name.length > 0 ? attached::(field)[0].name : field.name; if written == name { var read := decode::(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::()) { if const field.kind == target::fields && attached::(field).length > 0 { val name: strview = attached::(field)[0].name.length > 0 ? attached::(field)[0].name : field.name; if from.member(at, name) is some(found) { var read := decode::(from, found, given) else (e) { return e; }; made.(field) = move(read); } else { if const !(type_of(field) is vacant) { if !given.defaults { 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::()) { if const field.kind == target::fields && attached::(field).length > 0 { val name: strview = attached::(field)[0].name.length > 0 ? attached::(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(shortest_widened(this)); } 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 { 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 { 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 { 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 { return from.as_i64(at); } def u8::decode(from: &decoder, at: u32, given: options): result { 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 { 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 { 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 { return from.as_u64(at); } def f32::decode(from: &decoder, at: u32, given: options): result { 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 { return from.as_f64(at); } def bool::decode(from: &decoder, at: u32, given: options): result { return from.as_bool(at); } def string::encode(&this, out: &mut encoder): void { out.text(this.span); } def string::decode(from: &decoder, at: u32, given: options): result { 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::encode(&this, out: &mut encoder): void { if const size_of::() == 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::encode(&this, out: &mut encoder): void { match this { some(&held) => encode(held, out); none => out.empty(); } } def maybe::decode(from: &decoder, at: u32, given: options): result, 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::::vacant(); } var read := decode::(from, at, given) else (e) { return e; }; var made: maybe = move(read); return move(made); } def maybe::vacant(): maybe { return nothing {}; } def vector::encode(&this, out: &mut encoder): void { out.begin_array(this.length); for &item in this { encode(item, out); } out.end_array(); } def vector::decode(from: &decoder, at: u32, given: options): result, 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::::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::(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::encode(&this, out: &mut encoder): void { if const !(K is spannable) { 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(K::span_of(&entry.key)); encode(&entry.value, out); } out.end_object(); } def dict::decode(from: &decoder, at: u32, given: options): result, 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::::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::(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::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::decode(from: &decoder, at: u32, given: options): result, 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::::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::(from, item, given) else (e) { return e; }; made.insert(move(read)); } return move(made); } # The `f64` an `f32` is written as: the one its shortest text reads as, which # reads back as the same `f32`, where widening it would write every digit of # the `f64`, as `0.10000000149011612` for `0.1`. Infinity and NaN, which have no # such text, are widened. def shortest_widened(value: f32): f64 { val text := $"{value}"; val read := real::parse::(text.span) else (_) { return value as f64; }; return read; } # A signed integer read exactly, within bounds. def signed_within(from: &decoder, at: u32, low: i64, high: i64): result { 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 { 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; }