Initial Commit
This commit is contained in:
1624 files changed
+43422
No files matched your search
@@ -0,0 +1,53 @@
|
||||
# std::json
|
||||
|
||||
`std::json` reads and writes JSON for Sakura, strictly, as RFC 8259 writes it:
|
||||
any value may stand alone, text must be UTF-8, and comments, trailing commas,
|
||||
`NaN`, `Infinity`, and single quotes are errors. `json::parse` reads text into a
|
||||
`json::document`, which holds every value of it, `json::reader` gives one token
|
||||
at a time, and `json::writer` writes JSON as it is given it. A value whose type
|
||||
marks its fields with `@serial` is written as JSON and read back by those marks,
|
||||
over `std::serial`.
|
||||
|
||||
## Using it
|
||||
|
||||
Require the standard library in your blossomfile, and name the module among a
|
||||
target's `deps`, with the other modules of std it reads:
|
||||
|
||||
```yaml
|
||||
requires:
|
||||
- https://git.malunal.studio/sakura/std@v1.0.0
|
||||
|
||||
targets:
|
||||
- name: app
|
||||
type: program
|
||||
deps: [std.json, std.io]
|
||||
```
|
||||
|
||||
```sakura
|
||||
import std::io;
|
||||
import std::json;
|
||||
|
||||
def main(): void {
|
||||
val read := json::parse("{\"name\": \"sakura\", \"stars\": 5}") else (_) {
|
||||
io::println("That isn't JSON.");
|
||||
return;
|
||||
};
|
||||
if read.root.get("name") is some(name) {
|
||||
if name.as_text() is value(text) {
|
||||
io::println(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
From the standard library's root, where the conformance test finds its suite,
|
||||
`blossom test --suite std.json` runs them, or:
|
||||
|
||||
```sh
|
||||
sakurac run --lib std=. tests/main.sakura tests/json/*.sakura
|
||||
```
|
||||
|
||||
The conformance test reads each file of JSONTestSuite's `test_parsing`, in
|
||||
`tests/json/parsing`, whose license is beside it.
|
||||
@@ -0,0 +1,652 @@
|
||||
#! @file document.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the parsed document, which holds every value of JSON text as a flat
|
||||
#! array of nodes, and `json::value`, which reads one of them.
|
||||
|
||||
module std::json;
|
||||
|
||||
|
||||
#! The kinds of JSON values.
|
||||
pub enum kind: u8 {
|
||||
empty, #! `null`.
|
||||
boolean, #! `true` or `false`.
|
||||
number, #! A number.
|
||||
text, #! A string.
|
||||
array, #! A list of values, in order.
|
||||
object, #! Members, each a key and a value.
|
||||
}
|
||||
|
||||
# What a node is: the kinds of values, then a member's name.
|
||||
enum node_kind: u8 {
|
||||
empty,
|
||||
boolean,
|
||||
number,
|
||||
text,
|
||||
array,
|
||||
object,
|
||||
key,
|
||||
}
|
||||
|
||||
# One value of a document, or a member's name, in 16 bytes.
|
||||
#
|
||||
# A value's nodes follow it, so an array's elements follow it in order, and an
|
||||
# object's members do, each as its key and then its value. A container's `length`
|
||||
# is how many elements or members it holds, and its `next` is the index just past
|
||||
# everything it holds, so a value is skipped in one step. A string's `start` is
|
||||
# where its opening quote is, and its text follows that for `length` bytes, unless
|
||||
# it holds escapes: then its decoded text is in the document's buffer, from `next`.
|
||||
struct node {
|
||||
var kind: node_kind;
|
||||
var flag: u8; #! Whether a string holds escapes, or a boolean is true.
|
||||
var spare: u16;
|
||||
var start: u32; #! The byte of the text the value begins at.
|
||||
var length: u32;
|
||||
var next: u32;
|
||||
}
|
||||
|
||||
#! JSON text read whole, every value of it held as a node of a flat array.
|
||||
#!
|
||||
#! A document views the text it was parsed from, which must outlive it, and the
|
||||
#! values it gives view the document, so they are good only while it lives. A
|
||||
#! string holding escapes is decoded once, as the document is parsed, so reading
|
||||
#! any string allocates nothing.
|
||||
pub struct document : serial::decoder, moveable {
|
||||
var _text: strview;
|
||||
var _nodes: vector<node>;
|
||||
var _decoded: string; #! The text of each string that holds escapes, decoded.
|
||||
}
|
||||
|
||||
#! A value of a document, by its place in it. It is good only while the document
|
||||
#! lives and stays where it is.
|
||||
#!
|
||||
#! A value writes itself through any format, as `serial::encode` writes a typed
|
||||
#! value, so a document's values are written again whole.
|
||||
pub struct value : serial::encodable {
|
||||
var _document: *document;
|
||||
var _at: u32;
|
||||
}
|
||||
|
||||
#! A member of an object, as `value::members` gives each.
|
||||
pub struct member {
|
||||
pub var key: strview; #! The member's key, still escaped where it holds escapes.
|
||||
pub var value: value; #! Its value.
|
||||
}
|
||||
|
||||
#! Reads JSON text whole into a document.
|
||||
#! @param text The text, which must outlive the document and every value of
|
||||
#! it.
|
||||
#! @param depth How deep values may nest before parsing fails with `too_deep`.
|
||||
#! @param alloc An optional allocator for the document to take memory from.
|
||||
#! @returns The document, or why the text is not JSON, with where it fails.
|
||||
pub def parse(text: strview, depth: u32 = default_depth, alloc: maybe<&mut allocator> = nothing {}): result<document, error> {
|
||||
if text.length > 0xFFFFFFFFu {
|
||||
return error { kind = error_kind::too_long };
|
||||
}
|
||||
|
||||
var made := document {
|
||||
_text = text,
|
||||
_nodes = vector::<node>::new(alloc),
|
||||
_decoded = string::new(alloc)
|
||||
};
|
||||
|
||||
# The open objects and arrays, by their nodes.
|
||||
var open := vector::<u32>::new(alloc);
|
||||
var tokens := reader::new(text, depth);
|
||||
while tokens.next() is some(read) {
|
||||
val at := read.offset as u32;
|
||||
match read.kind {
|
||||
begin_object => {
|
||||
made.count_in(&open);
|
||||
open.append(made._nodes.length as u32);
|
||||
made._nodes.append(node { kind = node_kind::object, start = at });
|
||||
}
|
||||
begin_array => {
|
||||
made.count_in(&open);
|
||||
open.append(made._nodes.length as u32);
|
||||
made._nodes.append(node { kind = node_kind::array, start = at });
|
||||
}
|
||||
end_object, end_array => {
|
||||
val closing: u32 = open.at(open.length - 1);
|
||||
made._nodes.at(closing as u64).next = made._nodes.length as u32;
|
||||
open.remove_at(open.length - 1);
|
||||
}
|
||||
key => {
|
||||
val holder: u32 = open.at(open.length - 1);
|
||||
made._nodes.at(holder as u64).length++;
|
||||
made.add_string(node_kind::key, &read);
|
||||
}
|
||||
text => {
|
||||
made.count_in(&open);
|
||||
made.add_string(node_kind::text, &read);
|
||||
}
|
||||
number => {
|
||||
made.count_in(&open);
|
||||
made._nodes.append(node { kind = node_kind::number, start = at, length = read.view.length as u32 });
|
||||
}
|
||||
boolean => {
|
||||
made.count_in(&open);
|
||||
made._nodes.append(node { kind = node_kind::boolean, flag = read.truth ? 1 : 0, start = at });
|
||||
}
|
||||
empty => {
|
||||
made.count_in(&open);
|
||||
made._nodes.append(node { kind = node_kind::empty, start = at });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if tokens.error is some(failed) {
|
||||
return failed;
|
||||
}
|
||||
return move(made);
|
||||
}
|
||||
|
||||
#! Creates a document by taking another's nodes and decoded text, which leaves
|
||||
#! the other holding nothing.
|
||||
#! @param other The document to move from.
|
||||
#! @returns The document, which views the same text.
|
||||
pub def document::move_of(other: &mut document): document {
|
||||
return document {
|
||||
_text = other._text,
|
||||
_nodes = move(other._nodes),
|
||||
_decoded = move(other._decoded)
|
||||
};
|
||||
}
|
||||
|
||||
#! The value the text holds, which holds the rest.
|
||||
#! @param this The document to read.
|
||||
#! @returns The value.
|
||||
pub val document::root: value {
|
||||
get => value { _document = this as *document, _at = 0 };
|
||||
}
|
||||
|
||||
#! The text the document was parsed from.
|
||||
#! @param this The document to ask.
|
||||
#! @returns The text.
|
||||
pub val document::text: strview {
|
||||
get => this._text;
|
||||
}
|
||||
|
||||
#! What kind of value the value is.
|
||||
#! @param this The value to ask.
|
||||
#! @returns Its kind.
|
||||
pub val value::kind: kind {
|
||||
get => (*this._document).kind_at(this._at);
|
||||
}
|
||||
|
||||
#! Whether the value is `null`.
|
||||
#! @param this The value to ask.
|
||||
#! @returns Whether it is.
|
||||
pub val value::is_null: bool {
|
||||
get => this.kind == kind::empty;
|
||||
}
|
||||
|
||||
#! How many elements an array holds, or members an object holds, repeats
|
||||
#! included.
|
||||
#! @param this The value to measure.
|
||||
#! @returns The count, which is 0 for any other value.
|
||||
pub val value::length: u64 {
|
||||
get => (*this._document).count(this._at);
|
||||
}
|
||||
|
||||
#! Where the value begins in the text, by its line and its column.
|
||||
#! @param this The value to place.
|
||||
#! @returns Where it is.
|
||||
pub val value::place: serial::place {
|
||||
get => (*this._document).place(this._at);
|
||||
}
|
||||
|
||||
#! Finds the first member of an object with a name.
|
||||
#! @param this The object to look in, which an object is searched member by
|
||||
#! member.
|
||||
#! @param key The name to look for, as it is decoded.
|
||||
#! @returns The member's value, or `nothing` where the value is not an object or
|
||||
#! has no member of the name.
|
||||
pub def value::get(&this, key: strview): maybe<value> {
|
||||
val found := (*this._document).member(this._at, key) else { return nothing {}; };
|
||||
return value { _document = this._document, _at = found };
|
||||
}
|
||||
|
||||
#! Iterates over the values of every member of an object with a name, in the
|
||||
#! order they are written, since a name may be given more than once.
|
||||
#! @param this The object to look in.
|
||||
#! @param key The name to look for, as it is decoded.
|
||||
#! @returns An iterator over the values, which gives none where the value is not
|
||||
#! an object.
|
||||
pub def value::get_all(&this, key: strview): value::match_cursor {
|
||||
val count := (*this._document).count(this._at);
|
||||
val first: u32 = count == 0 ? 0 : this._at + 1;
|
||||
return value::match_cursor { _document = this._document, _at = first, _left = count, _key = key };
|
||||
}
|
||||
|
||||
#! Finds an element of an array by its index.
|
||||
#! @param this The array to look in.
|
||||
#! @param index The element's index, counted from 0.
|
||||
#! @returns The element, or `nothing` where the value is not an array or is
|
||||
#! shorter.
|
||||
pub def value::at(&this, index: u64): maybe<value> {
|
||||
if this.kind != kind::array || index >= this.length {
|
||||
return nothing {};
|
||||
}
|
||||
return value { _document = this._document, _at = (*this._document).element(this._at, index) };
|
||||
}
|
||||
|
||||
#! Iterates over the elements of an array, in order.
|
||||
#! @param this The array to walk.
|
||||
#! @returns An iterator over them, which gives none where the value is not an
|
||||
#! array.
|
||||
pub def value::elements(&this): value::element_cursor {
|
||||
if this.kind != kind::array {
|
||||
return value::element_cursor { _document = this._document };
|
||||
}
|
||||
return value::element_cursor { _document = this._document, _at = this._at + 1, _left = this.length };
|
||||
}
|
||||
|
||||
#! Iterates over the members of an object, in the order they are written,
|
||||
#! repeats included.
|
||||
#! @param this The object to walk.
|
||||
#! @returns An iterator over them, which gives none where the value is not an
|
||||
#! object.
|
||||
pub def value::members(&this): value::member_cursor {
|
||||
if this.kind != kind::object {
|
||||
return value::member_cursor { _document = this._document };
|
||||
}
|
||||
return value::member_cursor { _document = this._document, _at = this._at + 1, _left = this.length };
|
||||
}
|
||||
|
||||
#! Reads a boolean.
|
||||
#! @param this The value to read.
|
||||
#! @returns Its truth, or `wrong_kind` where it is not a boolean.
|
||||
pub def value::as_bool(&this): result<bool, error> {
|
||||
return (*this._document).as_bool(this._at) else (e) { return error::from(&e); };
|
||||
}
|
||||
|
||||
#! Reads a number as a signed integer, exactly.
|
||||
#! @param this The value to read.
|
||||
#! @returns The integer, or `wrong_kind` where it is not a number without a
|
||||
#! fraction, or `out_of_range` where it does not fit.
|
||||
pub def value::as_i64(&this): result<i64, error> {
|
||||
return (*this._document).as_i64(this._at) else (e) { return error::from(&e); };
|
||||
}
|
||||
|
||||
#! Reads a number as an unsigned integer, exactly.
|
||||
#! @param this The value to read.
|
||||
#! @returns The integer, or `wrong_kind` where it is not a number without a
|
||||
#! fraction, or `out_of_range` where it is negative or does not fit.
|
||||
pub def value::as_u64(&this): result<u64, error> {
|
||||
return (*this._document).as_u64(this._at) else (e) { return error::from(&e); };
|
||||
}
|
||||
|
||||
#! Reads a number as the nearest 64-bit float.
|
||||
#! @param this The value to read.
|
||||
#! @returns The float, or `wrong_kind` where it is not a number, or
|
||||
#! `out_of_range` where it is too large for 64 bits.
|
||||
pub def value::as_f64(&this): result<f64, error> {
|
||||
return (*this._document).as_f64(this._at) else (e) { return error::from(&e); };
|
||||
}
|
||||
|
||||
#! Reads a string, decoded.
|
||||
#! @param this The value to read.
|
||||
#! @returns A view of its text, good while the document lives, or `wrong_kind`
|
||||
#! where it is not a string.
|
||||
pub def value::as_text(&this): result<strview, error> {
|
||||
return (*this._document).as_text(this._at) else (e) { return error::from(&e); };
|
||||
}
|
||||
|
||||
#! Writes the value and everything it holds through a format. A number is
|
||||
#! written as an integer where it is one that fits, and as the nearest float
|
||||
#! otherwise.
|
||||
#! @param this The value to write.
|
||||
#! @param out The format to write it through.
|
||||
pub def value::encode(&this, out: &mut serial::encoder): void {
|
||||
match this.kind {
|
||||
empty => out.empty();
|
||||
boolean => out.boolean((*this._document).node_at(this._at).flag != 0);
|
||||
text => out.text((*this._document).text_at(this._at));
|
||||
number => this.encode_number(out);
|
||||
array => {
|
||||
out.begin_array(this.length);
|
||||
for item in this.elements() {
|
||||
item.encode(out);
|
||||
}
|
||||
out.end_array();
|
||||
}
|
||||
object => {
|
||||
out.begin_object(this.length);
|
||||
for each in this.members() {
|
||||
out.member(each.key);
|
||||
each.value.encode(out);
|
||||
}
|
||||
out.end_object();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Writes a number as an integer where it is one that fits, and otherwise as the
|
||||
# nearest float, or as nothing where it is too large for one, keeping the failure.
|
||||
def value::encode_number(&this, out: &mut serial::encoder): void {
|
||||
# Read once as an integer, since asking for one that is not makes an error, and
|
||||
# working out where it is reads the text up to it.
|
||||
val read := serial::integral_of((*this._document).number_at(this._at));
|
||||
val limit: u64 = read.negative ? 0x8000000000000000u : 0x7FFFFFFFFFFFFFFFu;
|
||||
if read.whole && read.fits && read.magnitude <= limit {
|
||||
out.signed(read.negative ? (0 - read.magnitude) as i64 : read.magnitude as i64);
|
||||
return;
|
||||
}
|
||||
if read.whole && read.fits && !read.negative {
|
||||
out.unsigned(read.magnitude);
|
||||
return;
|
||||
}
|
||||
match (*this._document).as_f64(this._at) {
|
||||
value(real) => out.real(real);
|
||||
error(_) => {
|
||||
out.fail(serial::error_kind::out_of_range);
|
||||
out.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! An iterator over an array's elements.
|
||||
pub struct value::element_cursor : iter<value> {
|
||||
var _document: *document;
|
||||
var _at: u32;
|
||||
var _left: u64;
|
||||
}
|
||||
|
||||
#! Gives the next element of the array.
|
||||
#! @param this The iterator to advance.
|
||||
#! @returns The next element, or `nothing` once there are no more.
|
||||
pub def value::element_cursor::next(&mut this): maybe<value> {
|
||||
if this._left == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
val made := value { _document = this._document, _at = this._at };
|
||||
this._at = (*this._document).after(this._at);
|
||||
this._left--;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! An iterator over an object's members.
|
||||
pub struct value::member_cursor : iter<member> {
|
||||
var _document: *document;
|
||||
var _at: u32; #! The next member's key.
|
||||
var _left: u64;
|
||||
}
|
||||
|
||||
#! Gives the next member of the object, in the order the text writes them.
|
||||
#! @param this The iterator to advance.
|
||||
#! @returns The next member, or `nothing` once there are no more.
|
||||
pub def value::member_cursor::next(&mut this): maybe<member> {
|
||||
if this._left == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
val made := member {
|
||||
key = (*this._document).text_at(this._at),
|
||||
value = value { _document = this._document, _at = this._at + 1 }
|
||||
};
|
||||
this._at = (*this._document).after(this._at + 1);
|
||||
this._left--;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! An iterator over the values of an object's members of one name.
|
||||
pub struct value::match_cursor : iter<value> {
|
||||
var _document: *document;
|
||||
var _at: u32; #! The next member's key.
|
||||
var _left: u64;
|
||||
var _key: strview;
|
||||
}
|
||||
|
||||
#! Gives the value of the next member of the name.
|
||||
#! @param this The iterator to advance.
|
||||
#! @returns The next value, or `nothing` once no member left has the name.
|
||||
pub def value::match_cursor::next(&mut this): maybe<value> {
|
||||
while this._left > 0 {
|
||||
val key := this._at;
|
||||
this._at = (*this._document).after(key + 1);
|
||||
this._left--;
|
||||
if (*this._document).text_at(key) == this._key {
|
||||
return value { _document = this._document, _at = key + 1 };
|
||||
}
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! What kind of value a node is.
|
||||
#! @param this The document to read.
|
||||
#! @param at The value's index.
|
||||
#! @returns Its kind.
|
||||
pub def document::kind_of(&this, at: u32): serial::kind {
|
||||
return (this.kind_at(at) as u8) as serial::kind;
|
||||
}
|
||||
|
||||
#! Finds the value of the first member of an object with a name.
|
||||
#! @param this The document to read.
|
||||
#! @param at The object's index.
|
||||
#! @param name The name to look for, as it is decoded.
|
||||
#! @returns The member's value's index, or `nothing` where there is none of the
|
||||
#! name or the value is not an object.
|
||||
pub def document::member(&this, at: u32, name: strview): maybe<u32> {
|
||||
if this.node_at(at).kind != node_kind::object {
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
var key := at + 1;
|
||||
for _ in 0..this.node_at(at).length as u64 {
|
||||
if this.text_at(key) == name {
|
||||
return key + 1;
|
||||
}
|
||||
key = this.after(key + 1);
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! How many elements an array holds, or members an object holds, repeats
|
||||
#! included.
|
||||
#! @param this The document to read.
|
||||
#! @param at The value's index.
|
||||
#! @returns The count, which is 0 for any other value.
|
||||
pub def document::count(&this, at: u32): u64 {
|
||||
val held := this.node_at(at);
|
||||
if held.kind != node_kind::array && held.kind != node_kind::object {
|
||||
return 0;
|
||||
}
|
||||
return held.length as u64;
|
||||
}
|
||||
|
||||
#! The name of the member of an object whose value is given.
|
||||
#! @param this The document to read.
|
||||
#! @param value The member's value's index.
|
||||
#! @returns The name, decoded.
|
||||
pub def document::name_of(&this, value: u32): strview {
|
||||
return this.text_at(value - 1);
|
||||
}
|
||||
|
||||
#! The element of an array, or the value of a member of an object, after
|
||||
#! another.
|
||||
#! @param this The document to read.
|
||||
#! @param at The array's or object's index.
|
||||
#! @param previous The element or value before, which must not be the last.
|
||||
#! @returns The value's index.
|
||||
pub def document::next_element(&this, at: u32, previous: u32): u32 {
|
||||
val next := this.after(previous);
|
||||
return this.node_at(at).kind == node_kind::object ? next + 1 : next;
|
||||
}
|
||||
|
||||
#! An element of an array, or the value of a member of an object, by its index.
|
||||
#! @param this The document to read.
|
||||
#! @param at The array's or object's index.
|
||||
#! @param index Which element or member, which must be less than the count.
|
||||
#! @returns The value's index.
|
||||
pub def document::element(&this, at: u32, index: u64): u32 {
|
||||
val object := this.node_at(at).kind == node_kind::object;
|
||||
var held := object ? at + 2 : at + 1;
|
||||
for _ in 0..index {
|
||||
held = this.after(held);
|
||||
if object {
|
||||
held++;
|
||||
}
|
||||
}
|
||||
return held;
|
||||
}
|
||||
|
||||
#! Reads a string's text, decoded.
|
||||
#! @param this The document to read.
|
||||
#! @param at The value's index.
|
||||
#! @returns A view of the text, or `wrong_kind` where the value is not a string.
|
||||
pub def document::as_text(&this, at: u32): result<strview, serial::error> {
|
||||
if this.node_at(at).kind != node_kind::text {
|
||||
return this.wrong(at);
|
||||
}
|
||||
return this.text_at(at);
|
||||
}
|
||||
|
||||
#! Reads a value as a signed integer, as `serial::decode` does.
|
||||
#! @param this The document to read.
|
||||
#! @param at The value's index.
|
||||
#! @returns The integer, or `wrong_kind` where the value is not a number, or
|
||||
#! `out_of_range` where it is not an integer `i64` holds.
|
||||
pub def document::as_i64(&this, at: u32): result<i64, serial::error> {
|
||||
val read := this.integral_at(at) else (e) { return e; };
|
||||
val limit: u64 = read.negative ? 0x8000000000000000u : 0x7FFFFFFFFFFFFFFFu;
|
||||
if !read.fits || read.magnitude > limit {
|
||||
return serial::error::at(serial::error_kind::out_of_range, this.place(at));
|
||||
}
|
||||
return read.negative ? (0 - read.magnitude) as i64 : read.magnitude as i64;
|
||||
}
|
||||
|
||||
#! Reads a value as an unsigned integer, as `serial::decode` does.
|
||||
#! @param this The document to read.
|
||||
#! @param at The value's index.
|
||||
#! @returns The integer, or `wrong_kind` where the value is not a number, or
|
||||
#! `out_of_range` where it is not an integer `u64` holds.
|
||||
pub def document::as_u64(&this, at: u32): result<u64, serial::error> {
|
||||
val read := this.integral_at(at) else (e) { return e; };
|
||||
if !read.fits || (read.negative && read.magnitude != 0) {
|
||||
return serial::error::at(serial::error_kind::out_of_range, this.place(at));
|
||||
}
|
||||
return read.magnitude;
|
||||
}
|
||||
|
||||
#! Reads a value as a real number, as `serial::decode` does.
|
||||
#! @param this The document to read.
|
||||
#! @param at The value's index.
|
||||
#! @returns The number, or `wrong_kind` where the value is not a number, or
|
||||
#! `out_of_range` where it is too large for an `f64`.
|
||||
pub def document::as_f64(&this, at: u32): result<f64, serial::error> {
|
||||
if this.node_at(at).kind != node_kind::number {
|
||||
return this.wrong(at);
|
||||
}
|
||||
|
||||
match real::parse::<f64>(this.number_at(at)) {
|
||||
value(read) => return read;
|
||||
error(&_) => return serial::error::at(
|
||||
serial::error_kind::out_of_range, this.place(at));
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
#! Reads a value as `true` or `false`, as `serial::decode` does.
|
||||
#! @param this The document to read.
|
||||
#! @param at The value's index.
|
||||
#! @returns The value, or `wrong_kind` where it is not a boolean.
|
||||
pub def document::as_bool(&this, at: u32): result<bool, serial::error> {
|
||||
val held := this.node_at(at);
|
||||
if held.kind != node_kind::boolean {
|
||||
return this.wrong(at);
|
||||
}
|
||||
return held.flag != 0;
|
||||
}
|
||||
|
||||
#! Where a value begins in the text, by its line and its column.
|
||||
#! @param this The document to read.
|
||||
#! @param at The value's index.
|
||||
#! @returns Where it is.
|
||||
pub def document::place(&this, at: u32): serial::place {
|
||||
return serial::place_of(this._text, this.node_at(at).start as u64);
|
||||
}
|
||||
|
||||
# Counts a value as an element of the innermost open array; an object counts its
|
||||
# members by their keys.
|
||||
def document::count_in(&mut this, open: &vector<u32>): void {
|
||||
if open.length == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
val holder: u32 = open.at(open.length - 1);
|
||||
if this._nodes.at(holder as u64).kind == node_kind::array {
|
||||
this._nodes.at(holder as u64).length++;
|
||||
}
|
||||
}
|
||||
|
||||
# Adds a string or key, decoding its escapes into the buffer where it holds any.
|
||||
def document::add_string(&mut this, kind: node_kind, read: &token): void {
|
||||
if !read.escaped {
|
||||
this._nodes.append(node { kind = kind, start = read.offset as u32, length = read.view.length as u32 });
|
||||
return;
|
||||
}
|
||||
|
||||
val from := this._decoded.length;
|
||||
unescape(read.view, &mut this._decoded);
|
||||
this._nodes.append(node {
|
||||
kind = kind,
|
||||
flag = 1,
|
||||
start = read.offset as u32,
|
||||
length = (this._decoded.length - from) as u32,
|
||||
next = from as u32
|
||||
});
|
||||
}
|
||||
|
||||
def document::node_at(&this, at: u32): &node {
|
||||
return this._nodes.at(at as u64);
|
||||
}
|
||||
|
||||
def document::kind_at(&this, at: u32): kind {
|
||||
val held := this.node_at(at).kind;
|
||||
return held == node_kind::key ? kind::text : (held as u8) as kind;
|
||||
}
|
||||
|
||||
# The index just past a value and everything it holds.
|
||||
def document::after(&this, at: u32): u32 {
|
||||
val held := this.node_at(at);
|
||||
if held.kind == node_kind::array || held.kind == node_kind::object {
|
||||
return held.next;
|
||||
}
|
||||
return at + 1;
|
||||
}
|
||||
|
||||
# A string's or key's text, decoded.
|
||||
def document::text_at(&this, at: u32): strview {
|
||||
val held := this.node_at(at);
|
||||
if held.flag != 0 {
|
||||
return this._decoded.substr(held.next as u64, held.length as u64);
|
||||
}
|
||||
return this._text.substr(held.start as u64 + 1, held.length as u64);
|
||||
}
|
||||
|
||||
# A number's text.
|
||||
def document::number_at(&this, at: u32): strview {
|
||||
val held := this.node_at(at);
|
||||
return this._text.substr(held.start as u64, held.length as u64);
|
||||
}
|
||||
|
||||
# A number read as an integer exactly, or why it is not one.
|
||||
def document::integral_at(&this, at: u32): result<serial::integral, serial::error> {
|
||||
if this.node_at(at).kind != node_kind::number {
|
||||
return this.wrong(at);
|
||||
}
|
||||
|
||||
val read := serial::integral_of(this.number_at(at));
|
||||
if !read.whole {
|
||||
return this.wrong(at);
|
||||
}
|
||||
return read;
|
||||
}
|
||||
|
||||
def document::wrong(&this, at: u32): serial::error {
|
||||
return serial::error::at(serial::error_kind::wrong_kind, this.place(at));
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
#! @file json.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains JSON's errors, and the functions that write a value as JSON and read
|
||||
#! one back by what `@serial` marks of its type, over `std::serial`.
|
||||
#!
|
||||
#! JSON is read strictly, as RFC 8259 writes it: any value may stand alone, text
|
||||
#! must be UTF-8, and comments, trailing commas, `NaN`, `Infinity`, and single
|
||||
#! quotes are errors. `json::parse` reads text into a `json::document`, which holds
|
||||
#! every value of it, `json::reader` gives one token at a time, and `json::writer`
|
||||
#! writes JSON as it is given it.
|
||||
|
||||
import std::io;
|
||||
module std::json;
|
||||
|
||||
|
||||
#! Why JSON could not be read or written.
|
||||
pub enum error_kind: u8 {
|
||||
unexpected_end, #! The text ends before the value does.
|
||||
unexpected_byte, #! A byte stands where JSON allows none of its kind.
|
||||
invalid_escape, #! A string holds an escape JSON has not, or half a surrogate pair.
|
||||
invalid_utf8, #! Text is not UTF-8.
|
||||
invalid_number, #! A number breaks JSON's grammar, as `01`, `1.`, or `.5` do.
|
||||
too_deep, #! Values nest deeper than the limit the text was read with.
|
||||
too_long, #! The text is longer than the 4 GiB a document holds.
|
||||
trailing_text, #! Something follows the value.
|
||||
not_finite, #! A number written is infinite or NaN, which JSON cannot hold.
|
||||
not_written, #! The stream the text was passed on to failed, as its own error says.
|
||||
|
||||
# What `std::serial` finds reading and writing typed values, as its own kinds say.
|
||||
wrong_kind, #! A value is of another kind than the type asked for, as text for a number.
|
||||
missing_member, #! An object lacks a member for a field that is not a `maybe`.
|
||||
unknown_member, #! An object has a member no field takes, which only strict reading refuses.
|
||||
repeated_member, #! An object has a member twice, which only strict reading refuses.
|
||||
out_of_range, #! A number does not fit the type asked for, or a name is no member's.
|
||||
not_serial, #! A value holds an enum member or union field that is not `@serial`.
|
||||
}
|
||||
|
||||
#! Why JSON could not be read or written, and where in the text.
|
||||
#!
|
||||
#! An error is plain data, so `else (e)` names it. One from writing has no
|
||||
#! place, and is at line 0.
|
||||
pub struct error {
|
||||
pub var kind: error_kind; #! What went wrong.
|
||||
pub var offset: u64; #! The byte of the text the error is at.
|
||||
pub var line: u32; #! Counted from 1.
|
||||
pub var column: u32; #! The byte within the line, counted from 1.
|
||||
}
|
||||
|
||||
#! Says what the error is, in a sentence, after where it is.
|
||||
#! @param this The error to describe.
|
||||
#! @returns The description, as `1:5: The text ends before the value does.`
|
||||
pub def error::describe(&this): string {
|
||||
if this.line == 0 {
|
||||
return string::from(describe(this.kind), nothing {});
|
||||
}
|
||||
return $"{this.line}:{this.column}: {describe(this.kind)}";
|
||||
}
|
||||
|
||||
#! Says what a kind of error is, in a sentence.
|
||||
#! @param kind The kind to describe.
|
||||
#! @returns The sentence.
|
||||
pub def describe(kind: error_kind): strview {
|
||||
return match kind {
|
||||
unexpected_end => "The text ends before the value does.",
|
||||
unexpected_byte => "A byte stands where JSON allows none of its kind.",
|
||||
invalid_escape => "A string holds an escape JSON does not have, or half of a surrogate pair.",
|
||||
invalid_utf8 => "The text is not UTF-8.",
|
||||
invalid_number => "A number does not follow JSON's grammar.",
|
||||
too_deep => "Values nest deeper than the limit the text is read with.",
|
||||
too_long => "The text is longer than the 4 GiB a document holds.",
|
||||
trailing_text => "Something follows the value.",
|
||||
not_finite => "A number is infinite or NaN, which JSON cannot hold.",
|
||||
not_written => "The stream the text was written to failed, as its own error says.",
|
||||
wrong_kind => serial::describe(serial::error_kind::wrong_kind),
|
||||
missing_member => serial::describe(serial::error_kind::missing_member),
|
||||
unknown_member => serial::describe(serial::error_kind::unknown_member),
|
||||
repeated_member => serial::describe(serial::error_kind::repeated_member),
|
||||
out_of_range => serial::describe(serial::error_kind::out_of_range),
|
||||
not_serial => serial::describe(serial::error_kind::not_serial),
|
||||
};
|
||||
}
|
||||
|
||||
#! The error JSON gives for one `std::serial` gives, at the same place.
|
||||
#! @param problem The error reading or writing a typed value gave.
|
||||
#! @returns The error.
|
||||
pub def error::from(problem: &serial::error): error {
|
||||
return error {
|
||||
kind = of_serial(problem.kind),
|
||||
offset = problem.offset,
|
||||
line = problem.line,
|
||||
column = problem.column
|
||||
};
|
||||
}
|
||||
|
||||
# The kind of JSON's error for a kind of `std::serial`'s.
|
||||
def of_serial(kind: serial::error_kind): error_kind {
|
||||
return match kind {
|
||||
wrong_kind => error_kind::wrong_kind,
|
||||
missing_member => error_kind::missing_member,
|
||||
unknown_member => error_kind::unknown_member,
|
||||
repeated_member => error_kind::repeated_member,
|
||||
out_of_range => error_kind::out_of_range,
|
||||
not_serial => error_kind::not_serial,
|
||||
};
|
||||
}
|
||||
|
||||
# An error of a kind at a byte of the text.
|
||||
def error_at(kind: error_kind, text: strview, offset: u64): error {
|
||||
val at := serial::place_of(text, offset);
|
||||
return error { kind = kind, offset = offset, line = at.line, column = at.column };
|
||||
}
|
||||
|
||||
#! Writes a typed value through a writer, by what `@serial` marks of its type,
|
||||
#! or the form of its own the type gives, among whatever else the writer is
|
||||
#! given.
|
||||
#! @tparam T The type of the value.
|
||||
#! @param value The value to write.
|
||||
#! @param out The writer to write it with.
|
||||
pub def encode<T>(value: &T, out: &mut writer): void {
|
||||
serial::encode(value, out);
|
||||
}
|
||||
|
||||
#! Writes a typed value as JSON text, by what `@serial` marks of its type.
|
||||
#! @tparam T The type of the value.
|
||||
#! @param value The value to write.
|
||||
#! @param indent Spaces for each level of nesting, or 0 to write it on one
|
||||
#! line.
|
||||
#! @param alloc An optional allocator for the text to take memory from.
|
||||
#! @returns The text, or the first failure in the value, as a number JSON cannot
|
||||
#! hold, or an enum member or union field that is not marked.
|
||||
pub def to_text<T>(value: &T, indent: u32 = 0, alloc: maybe<&mut allocator> = nothing {}): result<string, error> {
|
||||
var out := writer::indented(indent, alloc);
|
||||
serial::encode(value, &mut out);
|
||||
_ = out.finish() else (e) { return e; };
|
||||
return move(out._text);
|
||||
}
|
||||
|
||||
#! Writes a typed value as JSON text into a stream, by what `@serial` marks of
|
||||
#! its type, passing the text on as it goes rather than holding it all.
|
||||
#! @tparam T The type of the value.
|
||||
#! @param value The value to write.
|
||||
#! @param out The stream to write to, which is not flushed: whoever made it
|
||||
#! does that.
|
||||
#! @param indent Spaces for each level of nesting, or 0 to write it on one
|
||||
#! line.
|
||||
#! @returns Nothing, or the first failure in the value, or `not_written` where
|
||||
#! the stream failed, as its own error then says.
|
||||
pub def write_to<T>(value: &T, out: &mut writable, indent: u32 = 0): result<void, error> {
|
||||
var w := writer::to(out, indent);
|
||||
serial::encode(value, &mut w);
|
||||
_ = w.finish() else (e) { return e; };
|
||||
return;
|
||||
}
|
||||
|
||||
#! Reads a typed value from a value of a document, by what `@serial` marks of
|
||||
#! its type, or the form of its own the type gives.
|
||||
#! @tparam T The type to read.
|
||||
#! @param from The value to read.
|
||||
#! @param given How strictly to read: strictly, a member no field takes, and a
|
||||
#! member written more than once, are errors.
|
||||
#! @returns The value, or why it could not be read, at the value that failed.
|
||||
pub def decode<T>(from: value, given: serial::options = serial::options {}): result<T, error> where T: zeroable {
|
||||
var made := serial::decode::<T>(&from._document[0], from._at, given) else (e) { return error::from(&e); };
|
||||
return move(made);
|
||||
}
|
||||
|
||||
#! Reads a typed value from JSON text, by what `@serial` marks of its type.
|
||||
#! @tparam T The type to read.
|
||||
#! @param text The text to read.
|
||||
#! @param given How strictly to read.
|
||||
#! @returns The value, or why the text is not JSON, or could not be read as the
|
||||
#! type.
|
||||
pub def from_text<T>(text: strview, given: serial::options = serial::options {}): result<T, error> where T: zeroable {
|
||||
val read := parse(text) else (e) { return e; };
|
||||
var made := decode::<T>(read.root, given) else (e) { return e; };
|
||||
return move(made);
|
||||
}
|
||||
@@ -0,0 +1,480 @@
|
||||
#! @file reader.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the pull reader, which reads JSON one token at a time, checking it as
|
||||
#! it goes, without building anything.
|
||||
import core::swar;
|
||||
|
||||
module std::json;
|
||||
|
||||
|
||||
#! The nesting a reader allows when it is given no other limit.
|
||||
pub const default_depth: u32 = 512;
|
||||
|
||||
#! What a token is.
|
||||
pub enum token_kind: u8 {
|
||||
begin_object, #! `{`, which begins an object.
|
||||
end_object, #! `}`, which ends one.
|
||||
begin_array, #! `[`, which begins an array.
|
||||
end_array, #! `]`, which ends one.
|
||||
key, #! A member's name, whose value is the next token.
|
||||
text, #! A string.
|
||||
number, #! A number, whose text is its view.
|
||||
boolean, #! `true` or `false`, which `truth` says.
|
||||
empty, #! `null`.
|
||||
}
|
||||
|
||||
#! A piece of JSON a reader gives.
|
||||
pub struct token {
|
||||
pub var kind: token_kind; #! What the token is.
|
||||
pub var escaped: bool; #! Whether a key's or text's view holds escapes, which `unescape` decodes.
|
||||
pub var truth: bool; #! A boolean's value.
|
||||
pub var view: strview; #! A key's or text's text between its quotes, a number's text, or the literal.
|
||||
pub var offset: u64; #! The byte of the text the token begins at.
|
||||
}
|
||||
|
||||
# What a reader looks for next.
|
||||
enum reading: u8 {
|
||||
value, #! A value: the first, or one after `:` or after `,` within an array.
|
||||
first_element, #! A value or `]`, after `[`.
|
||||
first_member, #! A key or `}`, after `{`.
|
||||
member, #! A key, after `,` within an object.
|
||||
colon, #! The `:` after a key.
|
||||
after, #! A `,` or the end of what holds the value just read.
|
||||
done, #! Nothing but whitespace, after the whole value.
|
||||
failed, #! Nothing: the reader has stopped at an error.
|
||||
}
|
||||
|
||||
#! Reads JSON one token at a time, checking it as it goes: commas, colons,
|
||||
#! nesting, escapes, UTF-8, and the grammar of numbers. It stops at the first
|
||||
#! error, which `error` then gives.
|
||||
#!
|
||||
#! A reader views the text it reads, and so do its tokens, so the text outlives
|
||||
#! them. It allocates nothing unless its limit lets values nest past 512 levels.
|
||||
pub struct reader {
|
||||
var _text: strview;
|
||||
var _at: u64;
|
||||
var _state: reading;
|
||||
var _depth: u32;
|
||||
var _limit: u32;
|
||||
var _stack: u64[8]; #! A bit for each of the first 512 open values, set for an object.
|
||||
var _deeper: vector<u64>; #! The bits of those past 512.
|
||||
var _error: maybe<error>;
|
||||
}
|
||||
|
||||
#! Makes a reader of JSON text.
|
||||
#! @param text The text to read, which must outlive the reader and its
|
||||
#! tokens.
|
||||
#! @param depth How deep values may nest before reading fails with `too_deep`.
|
||||
#! @returns The reader, at the start of the text.
|
||||
pub def reader::new(text: strview, depth: u32 = default_depth): reader {
|
||||
return reader { _text = text, _limit = depth };
|
||||
}
|
||||
|
||||
#! Why reading stopped before the end of the text, where it did.
|
||||
#! @param this The reader to ask.
|
||||
#! @returns The error, or `nothing` where none has been met.
|
||||
pub val reader::error: maybe<error> {
|
||||
get => this._error;
|
||||
}
|
||||
|
||||
#! How deep the reader is among open objects and arrays.
|
||||
#! @param this The reader to ask.
|
||||
#! @returns The number of them that are open.
|
||||
pub val reader::depth: u32 {
|
||||
get => this._depth;
|
||||
}
|
||||
|
||||
#! Reads the next token.
|
||||
#! @param this The reader to read with.
|
||||
#! @returns The token, or `nothing` at the end of the text or at an error, which
|
||||
#! `error` tells apart.
|
||||
pub def reader::next(&mut this): maybe<token> {
|
||||
while true {
|
||||
this.skip_space();
|
||||
match this._state {
|
||||
value => return this.read_value();
|
||||
first_element => {
|
||||
if this.peek() != ']' {
|
||||
return this.read_value();
|
||||
}
|
||||
return this.close(token_kind::end_array);
|
||||
}
|
||||
first_member => {
|
||||
if this.peek() == '}' {
|
||||
return this.close(token_kind::end_object);
|
||||
}
|
||||
return this.read_key();
|
||||
}
|
||||
member => return this.read_key();
|
||||
colon => {
|
||||
if this.peek() != ':' {
|
||||
return this.fail(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at);
|
||||
}
|
||||
this._at++;
|
||||
this._state = reading::value;
|
||||
}
|
||||
after => {
|
||||
if this._depth == 0 {
|
||||
this._state = reading::done;
|
||||
continue;
|
||||
}
|
||||
|
||||
val byte := this.peek();
|
||||
if byte == ',' {
|
||||
this._at++;
|
||||
this._state = this.in_object() ? reading::member : reading::value;
|
||||
continue;
|
||||
}
|
||||
if byte == '}' && this.in_object() {
|
||||
return this.close(token_kind::end_object);
|
||||
}
|
||||
if byte == ']' && !this.in_object() {
|
||||
return this.close(token_kind::end_array);
|
||||
}
|
||||
return this.fail(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at);
|
||||
}
|
||||
done => {
|
||||
if this.at_end() {
|
||||
return nothing {};
|
||||
}
|
||||
return this.fail(error_kind::trailing_text, this._at);
|
||||
}
|
||||
failed => return nothing {};
|
||||
}
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Reads past the value whose first token is next, however much it holds, as
|
||||
#! after a key whose value is not wanted.
|
||||
#! @param this The reader to read with.
|
||||
#! @returns Whether the value was read whole, which it is not at an error.
|
||||
pub def reader::skip(&mut this): bool {
|
||||
val outer := this._depth;
|
||||
while this.next() is some(read) {
|
||||
if read.kind == token_kind::key {
|
||||
continue;
|
||||
}
|
||||
if this._depth == outer {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
# Reads a value: an object or array opening, a string, a number, or a literal.
|
||||
def reader::read_value(&mut this): maybe<token> {
|
||||
if this.at_end() {
|
||||
return this.fail(error_kind::unexpected_end, this._at);
|
||||
}
|
||||
|
||||
val start := this._at;
|
||||
match this._text[start] {
|
||||
'{' => return this.open(token_kind::begin_object, true);
|
||||
'[' => return this.open(token_kind::begin_array, false);
|
||||
'"' => return this.read_string(token_kind::text);
|
||||
't' => return this.read_literal("true", token_kind::boolean, true);
|
||||
'f' => return this.read_literal("false", token_kind::boolean, false);
|
||||
'n' => return this.read_literal("null", token_kind::empty, false);
|
||||
else => {
|
||||
val byte := this._text[start];
|
||||
if byte != '-' && !byte.is_digit {
|
||||
return this.fail(error_kind::unexpected_byte, start);
|
||||
}
|
||||
return this.read_number();
|
||||
}
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
# Reads a key, and the `:` after it is looked for next.
|
||||
def reader::read_key(&mut this): maybe<token> {
|
||||
if this.peek() != '"' {
|
||||
return this.fail(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at);
|
||||
}
|
||||
|
||||
val read := this.read_string(token_kind::key);
|
||||
if read is some(_) {
|
||||
this._state = reading::colon;
|
||||
}
|
||||
return read;
|
||||
}
|
||||
|
||||
# Reads a string from its opening quote, checking its escapes and its UTF-8, and
|
||||
# that it holds no control characters, which JSON writes as escapes.
|
||||
def reader::read_string(&mut this, kind: token_kind): maybe<token> {
|
||||
val start := this._at;
|
||||
var index := start + 1;
|
||||
var escaped := false;
|
||||
while true {
|
||||
index = plain_run(this._text, index);
|
||||
if index >= this._text.length {
|
||||
return this.fail(error_kind::unexpected_end, index);
|
||||
}
|
||||
|
||||
val byte := this._text[index];
|
||||
if byte == '"' {
|
||||
break;
|
||||
}
|
||||
if byte == '\\' {
|
||||
val end := escape_end(this._text, index);
|
||||
if end == 0 {
|
||||
return this.fail(error_kind::invalid_escape, index);
|
||||
}
|
||||
escaped = true;
|
||||
index = end;
|
||||
continue;
|
||||
}
|
||||
if byte < 0x20 {
|
||||
return this.fail(error_kind::unexpected_byte, index);
|
||||
}
|
||||
if byte < 0x80 {
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
|
||||
val count := serial::utf8_length(this._text, index);
|
||||
if count == 0 {
|
||||
return this.fail(error_kind::invalid_utf8, index);
|
||||
}
|
||||
index += count;
|
||||
}
|
||||
|
||||
this._at = index + 1;
|
||||
this._state = reading::after;
|
||||
return token { kind = kind, escaped = escaped, view = this._text.substr(start + 1, index - start - 1), offset = start };
|
||||
}
|
||||
|
||||
# Reads a number, which must end where a value may: at whitespace, a `,`, a closing
|
||||
# bracket, or the end of the text, so `01` and `1x` are errors of the number.
|
||||
def reader::read_number(&mut this): maybe<token> {
|
||||
val start := this._at;
|
||||
val end := number_end(this._text, start);
|
||||
if end == start || (end < this._text.length && !ends_value(this._text[end])) {
|
||||
return this.fail(error_kind::invalid_number, start);
|
||||
}
|
||||
|
||||
this._at = end;
|
||||
this._state = reading::after;
|
||||
return token { kind = token_kind::number, view = this._text.substr(start, end - start), offset = start };
|
||||
}
|
||||
|
||||
# Reads `true`, `false`, or `null`.
|
||||
def reader::read_literal(&mut this, word: strview, kind: token_kind, truth: bool): maybe<token> {
|
||||
val start := this._at;
|
||||
val found := this._text.substr(start, word.length);
|
||||
if found != word {
|
||||
# Text that ends partway through the word ends early, and anything else is wrong.
|
||||
val cut := found.length < word.length && word.starts_with(found);
|
||||
return this.fail(cut ? error_kind::unexpected_end : error_kind::unexpected_byte, start);
|
||||
}
|
||||
|
||||
this._at += word.length;
|
||||
this._state = reading::after;
|
||||
return token { kind = kind, truth = truth, view = found, offset = start };
|
||||
}
|
||||
|
||||
# Opens an object or array, nesting one level deeper.
|
||||
def reader::open(&mut this, kind: token_kind, object: bool): maybe<token> {
|
||||
val start := this._at;
|
||||
if this._depth >= this._limit {
|
||||
return this.fail(error_kind::too_deep, start);
|
||||
}
|
||||
|
||||
this.mark(this._depth, object);
|
||||
this._depth++;
|
||||
this._at++;
|
||||
this._state = object ? reading::first_member : reading::first_element;
|
||||
return token { kind = kind, view = this._text.substr(start, 1), offset = start };
|
||||
}
|
||||
|
||||
# Closes the innermost object or array, at its closing bracket.
|
||||
def reader::close(&mut this, kind: token_kind): maybe<token> {
|
||||
val start := this._at;
|
||||
this._depth--;
|
||||
this._at++;
|
||||
this._state = reading::after;
|
||||
return token { kind = kind, view = this._text.substr(start, 1), offset = start };
|
||||
}
|
||||
|
||||
# Records whether the value open at a level is an object.
|
||||
def reader::mark(&mut this, level: u32, object: bool): void {
|
||||
val bit: u64 = 1u << (level % 64) as u64;
|
||||
if level < 512 {
|
||||
val word := (level / 64) as u64;
|
||||
this._stack[word] = object ? this._stack[word] | bit : this._stack[word] & ~bit;
|
||||
return;
|
||||
}
|
||||
|
||||
val word := ((level - 512) / 64) as u64;
|
||||
while this._deeper.length <= word {
|
||||
this._deeper.append(0);
|
||||
}
|
||||
val held := this._deeper.at(word);
|
||||
this._deeper.set(word, object ? held | bit : held & ~bit);
|
||||
}
|
||||
|
||||
# Whether the innermost open value is an object.
|
||||
def reader::in_object(&this): bool {
|
||||
val level := this._depth - 1;
|
||||
val bit: u64 = 1u << (level % 64) as u64;
|
||||
if level < 512 {
|
||||
return (this._stack[(level / 64) as u64] & bit) != 0;
|
||||
}
|
||||
return (this._deeper.at(((level - 512) / 64) as u64) & bit) != 0;
|
||||
}
|
||||
|
||||
# Stops at an error, which `error` then gives.
|
||||
def reader::fail(&mut this, kind: error_kind, offset: u64): maybe<token> {
|
||||
this._error = error_at(kind, this._text, offset);
|
||||
this._state = reading::failed;
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
# Moves past the whitespace JSON allows between tokens.
|
||||
def reader::skip_space(&mut this): void {
|
||||
this._at = space_run(this._text, this._at);
|
||||
while this._at < this._text.length {
|
||||
val byte := this._text[this._at];
|
||||
if byte != ' ' && byte != '\n' && byte != '\r' && byte != '\t' {
|
||||
return;
|
||||
}
|
||||
this._at++;
|
||||
}
|
||||
}
|
||||
|
||||
# Past the bytes of a string from a place that need no looking at alone: none
|
||||
# of `"`, `\`, a control character, or a byte past ASCII, which as an `i8` is
|
||||
# below zero, so one comparison finds both. Sixteen at a time where vectors are
|
||||
# held in registers, then eight at a time as words, the last few read without
|
||||
# passing the end.
|
||||
def plain_run(text: strview, from: u64): u64 {
|
||||
var at := from;
|
||||
if lanes_held() {
|
||||
val quote := u8x16::splat('"');
|
||||
val slash := u8x16::splat('\\');
|
||||
val below := i8x16::splat(0x20);
|
||||
while at + 16 <= text.length {
|
||||
val chunk := u8x16::load(text, at);
|
||||
val stops := chunk.equal("e).bits() | chunk.equal(&slash).bits() | chunk.bits::<i8, 16>().less(&below).bits();
|
||||
return at + trailing_zeros(stops) as u64 if stops != 0;
|
||||
at += 16;
|
||||
}
|
||||
}
|
||||
val data := text.data;
|
||||
while at + 8 <= text.length {
|
||||
val stops := plain_stops(swar::load(data + at));
|
||||
return at + stops.first() if stops.any();
|
||||
at += 8;
|
||||
}
|
||||
if at < text.length {
|
||||
val stops: swar::mask8 = plain_stops(swar::load_last(data + at, text.length - at)) & swar::mask8::leading(text.length - at);
|
||||
return at + stops.first() if stops.any();
|
||||
}
|
||||
return text.length;
|
||||
}
|
||||
|
||||
# The bytes of a word a string's plain run stops at.
|
||||
def plain_stops(word: swar::bytes8): swar::mask8 {
|
||||
return word.equal('"') | word.equal('\\') | word.below(0x20) | (word & 0x8080808080808080);
|
||||
}
|
||||
|
||||
# Past the whitespace from a place, sixteen bytes at a time where vectors are
|
||||
# held in registers, then eight at a time as words where the first byte is
|
||||
# whitespace, as where lines are indented, and none otherwise.
|
||||
def space_run(text: strview, from: u64): u64 {
|
||||
var at := from;
|
||||
if lanes_held() {
|
||||
val blank := u8x16::splat(' ');
|
||||
val newline := u8x16::splat('\n');
|
||||
val ret := u8x16::splat('\r');
|
||||
val tab := u8x16::splat('\t');
|
||||
while at + 16 <= text.length {
|
||||
val chunk := u8x16::load(text, at);
|
||||
val spaces := chunk.equal(&blank).bits() | chunk.equal(&newline).bits() | chunk.equal(&ret).bits()
|
||||
| chunk.equal(&tab).bits();
|
||||
return at + trailing_zeros(~spaces) as u64 if spaces != 0xFFFF;
|
||||
at += 16;
|
||||
}
|
||||
}
|
||||
return at if at >= text.length || !is_json_space(text[at]);
|
||||
val data := text.data;
|
||||
while at + 8 <= text.length {
|
||||
val word := swar::load(data + at);
|
||||
val other: swar::mask8 = ~(word.equal(' ') | word.equal('\n') | word.equal('\r') | word.equal('\t')) & 0x8080808080808080;
|
||||
return at + other.first() if other.any();
|
||||
at += 8;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
# Whether a byte is whitespace JSON allows between tokens.
|
||||
def is_json_space(byte: u8): bool {
|
||||
return byte == ' ' || byte == '\n' || byte == '\r' || byte == '\t';
|
||||
}
|
||||
|
||||
# The byte the reader is at, or 0 at the end of the text.
|
||||
def reader::peek(&this): u8 {
|
||||
return this.at_end() ? 0 : this._text[this._at];
|
||||
}
|
||||
|
||||
def reader::at_end(&this): bool {
|
||||
return this._at >= this._text.length;
|
||||
}
|
||||
|
||||
# Whether a byte may follow a value: whitespace, a `,`, or a closing bracket.
|
||||
def ends_value(byte: u8): bool {
|
||||
return byte == ' ' || byte == '\n' || byte == '\r' || byte == '\t' || byte == ',' || byte == ']' || byte == '}';
|
||||
}
|
||||
|
||||
# Where the escape beginning at `at` ends, or 0 where it is not one JSON has: one of
|
||||
# `\" \\ \/ \b \f \n \r \t`, or `\u` and four hexadecimal digits, where a surrogate
|
||||
# is the first of a pair written as two escapes.
|
||||
def escape_end(text: strview, at: u64): u64 {
|
||||
if at + 1 >= text.length {
|
||||
return 0;
|
||||
}
|
||||
|
||||
val marker := text[at + 1];
|
||||
if marker == '"' || marker == '\\' || marker == '/' || marker == 'b' || marker == 'f'
|
||||
|| marker == 'n' || marker == 'r' || marker == 't' {
|
||||
return at + 2;
|
||||
}
|
||||
if marker != 'u' || !hex_at(text, at + 2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
val code := hex_value(text, at + 2);
|
||||
if code >= 0xDC00 && code <= 0xDFFF {
|
||||
return 0;
|
||||
}
|
||||
if code < 0xD800 || code > 0xDBFF {
|
||||
return at + 6;
|
||||
}
|
||||
|
||||
# A high surrogate is followed by a low one.
|
||||
if at + 7 >= text.length || text[at + 6] != '\\' || text[at + 7] != 'u' || !hex_at(text, at + 8) {
|
||||
return 0;
|
||||
}
|
||||
val low := hex_value(text, at + 8);
|
||||
if low < 0xDC00 || low > 0xDFFF {
|
||||
return 0;
|
||||
}
|
||||
return at + 12;
|
||||
}
|
||||
|
||||
# Whether four hexadecimal digits begin at `at`.
|
||||
def hex_at(text: strview, at: u64): bool {
|
||||
if at + 4 > text.length {
|
||||
return false;
|
||||
}
|
||||
for index in 0u..4u {
|
||||
if !text[at + index].is_hex {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
#! @file text.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what JSON's text is made of: UTF-8, the escapes of strings, and the
|
||||
#! grammar of numbers and what they read as, which the reader, the document, and
|
||||
#! the writer share.
|
||||
|
||||
module std::json;
|
||||
|
||||
|
||||
# The digits a `\u` escape is written with.
|
||||
const hex_digits: strview = "0123456789abcdef";
|
||||
|
||||
#! Writes text with JSON's escapes, as it stands between the quotes of a string:
|
||||
#! `"`, `\`, and the control characters escaped, and everything else as it is.
|
||||
#! @param text The text to escape.
|
||||
#! @param into The string to append to.
|
||||
#! @param lossy Whether each byte that breaks UTF-8 is written as the escape of
|
||||
#! U+FFFD, `\ufffd`, so the whole text is written, rather than the
|
||||
#! text being cut short at the first.
|
||||
#! @returns Whether the text is UTF-8, which JSON's text must be. Text that is
|
||||
#! not is appended only as far as its first byte that breaks UTF-8,
|
||||
#! unless the escape is lossy.
|
||||
pub def escape(text: strview, into: &mut string, lossy: bool = false): bool {
|
||||
var run: u64 = 0; # Where the bytes written as they are begin.
|
||||
var at: u64 = 0;
|
||||
var whole: bool = true;
|
||||
while at < text.length {
|
||||
val byte := text[at];
|
||||
if byte >= 0x80 {
|
||||
val count := serial::utf8_length(text, at);
|
||||
if count != 0 {
|
||||
at += count;
|
||||
continue;
|
||||
}
|
||||
into.append(text.substr(run, at - run));
|
||||
if !lossy {
|
||||
return false;
|
||||
}
|
||||
into.append("\\ufffd");
|
||||
whole = false;
|
||||
at++;
|
||||
run = at;
|
||||
continue;
|
||||
}
|
||||
if byte >= 0x20 && byte != '"' && byte != '\\' {
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
|
||||
into.append(text.substr(run, at - run));
|
||||
escape_byte(byte, into);
|
||||
at++;
|
||||
run = at;
|
||||
}
|
||||
into.append(text.substr(run, at - run));
|
||||
return whole;
|
||||
}
|
||||
|
||||
#! Decodes the escapes of a string's text as JSON writes them, where the text is
|
||||
#! as it stands between the quotes, as a reader's token views it.
|
||||
#! @param raw The text, whose escapes the reader has checked.
|
||||
#! @param into The string to append the decoded text to.
|
||||
pub def unescape(raw: strview, into: &mut string): void {
|
||||
var run: u64 = 0;
|
||||
var at: u64 = 0;
|
||||
while at < raw.length {
|
||||
if raw[at] != '\\' {
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
|
||||
into.append(raw.substr(run, at - run));
|
||||
val marker := raw[at + 1];
|
||||
at += 2;
|
||||
run = at;
|
||||
if marker != 'u' {
|
||||
into.push(unescaped(marker));
|
||||
continue;
|
||||
}
|
||||
|
||||
# A surrogate pair is two escapes, which are one character together.
|
||||
var code := hex_value(raw, at);
|
||||
at += 4;
|
||||
if code >= 0xD800 && code <= 0xDBFF {
|
||||
code = 0x10000 + ((code - 0xD800) << 10) + (hex_value(raw, at + 2) - 0xDC00);
|
||||
at += 6;
|
||||
}
|
||||
serial::append_utf8(code, into);
|
||||
run = at;
|
||||
}
|
||||
into.append(raw.substr(run, at - run));
|
||||
}
|
||||
|
||||
#! Whether text is UTF-8: no overlong forms, no surrogates, nothing past
|
||||
#! U+10FFFF, and nothing cut short.
|
||||
#! @param text The text to check.
|
||||
#! @returns Whether it is UTF-8.
|
||||
pub def is_utf8(text: strview): bool {
|
||||
return serial::is_utf8(text);
|
||||
}
|
||||
|
||||
# Where the number beginning at `at` ends, following JSON's grammar,
|
||||
# `-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?`, or `at` where none begins there
|
||||
# or it breaks the grammar.
|
||||
def number_end(text: strview, at: u64): u64 {
|
||||
var index := at;
|
||||
if index < text.length && text[index] == '-' {
|
||||
index++;
|
||||
}
|
||||
if index >= text.length {
|
||||
return at;
|
||||
}
|
||||
|
||||
if text[index] == '0' {
|
||||
index++;
|
||||
} else if text[index] >= '1' && text[index] <= '9' {
|
||||
index = digits_end(text, index);
|
||||
} else {
|
||||
return at;
|
||||
}
|
||||
|
||||
if index < text.length && text[index] == '.' {
|
||||
val digits := index + 1;
|
||||
index = digits_end(text, digits);
|
||||
if index == digits {
|
||||
return at;
|
||||
}
|
||||
}
|
||||
|
||||
if index < text.length && (text[index] == 'e' || text[index] == 'E') {
|
||||
index++;
|
||||
if index < text.length && (text[index] == '+' || text[index] == '-') {
|
||||
index++;
|
||||
}
|
||||
val digits := index;
|
||||
index = digits_end(text, digits);
|
||||
if index == digits {
|
||||
return at;
|
||||
}
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
# Where a run of decimal digits beginning at `at` ends.
|
||||
def digits_end(text: strview, at: u64): u64 {
|
||||
var index := at;
|
||||
while index < text.length && text[index].is_digit {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
# Appends the escape JSON writes for a byte it does not write as it is.
|
||||
def escape_byte(byte: u8, into: &mut string): void {
|
||||
into.push('\\');
|
||||
match byte {
|
||||
'"' => into.push('"');
|
||||
'\\' => into.push('\\');
|
||||
'\n' => into.push('n');
|
||||
'\r' => into.push('r');
|
||||
'\t' => into.push('t');
|
||||
0x08 => into.push('b');
|
||||
0x0C => into.push('f');
|
||||
else => {
|
||||
into.append("u00");
|
||||
into.push(hex_digits[(byte >> 4) as u64]);
|
||||
into.push(hex_digits[(byte & 0x0F) as u64]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# The byte a one-letter escape stands for, as `n` for a line break.
|
||||
def unescaped(marker: u8): u8 {
|
||||
return match marker {
|
||||
'b' => 0x08,
|
||||
'f' => 0x0C,
|
||||
'n' => '\n',
|
||||
'r' => '\r',
|
||||
't' => '\t',
|
||||
else => marker,
|
||||
};
|
||||
}
|
||||
|
||||
# The number four hexadecimal digits beginning at `at` write.
|
||||
def hex_value(text: strview, at: u64): u64 {
|
||||
var made: u64 = 0;
|
||||
for index in 0u..4u {
|
||||
made = made * 16 + text[at + index].digit_value;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
#! @file writer.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the writer, which writes JSON as it is given it, without building a
|
||||
#! tree first.
|
||||
|
||||
import std::io;
|
||||
module std::json;
|
||||
|
||||
|
||||
# How much text a writer passing its text on holds before it does.
|
||||
const pass_bytes: u64 = 16384;
|
||||
|
||||
# What each open object or array of a writer records.
|
||||
const level_object: u8 = 1; # It is an object.
|
||||
const level_held: u8 = 2; # It holds something already, so a comma comes before the next.
|
||||
const level_named: u8 = 4; # A member's name is written, and its value is next.
|
||||
|
||||
#! Writes JSON into a string it owns, as it is given it: commas, colons,
|
||||
#! escapes, and indentation are its own.
|
||||
#!
|
||||
#! A writer made by `writer::to` passes its text on to a stream instead,
|
||||
#! whenever it holds 16 KB and when it finishes, so a large document is never
|
||||
#! held whole. It borrows the stream, which the caller flushes and closes.
|
||||
#!
|
||||
#! Misuse stops the program, as indexing past an array does, since it is a
|
||||
#! mistake in the program rather than in its data: a member outside an object, a
|
||||
#! value within an object without its member's name, ending an array where an
|
||||
#! object is open, a second value after the first, or finishing with something
|
||||
#! still open.
|
||||
#!
|
||||
#! A failure in the data is kept, so it is checked once, when the writer
|
||||
#! finishes: a number that is infinite or NaN, or text that is not UTF-8, is
|
||||
#! written as `null` in its place, and the first such failure is what `finish`
|
||||
#! gives. A writer `set_lossy` makes lossy writes text that is not UTF-8 instead,
|
||||
#! with U+FFFD in place of each byte that breaks it, as a server must that sends
|
||||
#! whatever a file holds.
|
||||
#!
|
||||
#! The writer is a `serial::encoder`, so `json::encode` and `serial::encode`
|
||||
#! write typed values through it, among what it is given by hand, and `raw`
|
||||
#! writes JSON already written, as it is.
|
||||
pub struct writer : serial::encoder, moveable {
|
||||
pub var _text: string; #! The text written so far, which std's tests read.
|
||||
var _indent: u32; #! Spaces for each level of nesting, or 0 to write everything on one line.
|
||||
var _levels: vector<u8>; #! Each open object or array, outermost first.
|
||||
var _written: bool; #! Whether the value is begun, after which there is no other.
|
||||
var _failure: maybe<error_kind>;
|
||||
var _out: maybe<&mut writable>; #! Where the text is passed on, for a writer `to` makes.
|
||||
var _pass_at: u64; #! How much text is held before it is passed on, or 0 for never.
|
||||
var _lossy: bool; #! Whether text that is not UTF-8 is written with U+FFFD in place of what breaks it.
|
||||
}
|
||||
|
||||
#! Makes a writer that writes everything on one line.
|
||||
#! @param alloc An optional allocator for the writer to take memory from.
|
||||
#! @returns The writer, which holds no text yet.
|
||||
pub def writer::new(alloc: maybe<&mut allocator> = nothing {}): writer {
|
||||
return writer { _text = string::new(alloc), _levels = vector::<u8>::new(alloc) };
|
||||
}
|
||||
|
||||
#! Makes a writer that writes each element and member on a line of its own.
|
||||
#! @param width How many spaces each level of nesting is indented by.
|
||||
#! @param alloc An optional allocator for the writer to take memory from.
|
||||
#! @returns The writer, which holds no text yet.
|
||||
pub def writer::indented(width: u32, alloc: maybe<&mut allocator> = nothing {}): writer {
|
||||
return writer { _text = string::new(alloc), _indent = width, _levels = vector::<u8>::new(alloc) };
|
||||
}
|
||||
|
||||
#! Makes a writer that passes what it writes on to a stream, whenever it holds
|
||||
#! 16 KB and when it finishes, rather than holding it all.
|
||||
#! @param out The stream to write to, which the writer borrows, and which
|
||||
#! whoever made it flushes and closes.
|
||||
#! @param indent Spaces for each level of nesting, or 0 to write everything on
|
||||
#! one line.
|
||||
#! @param alloc An optional allocator for the writer to take memory from.
|
||||
#! @returns The writer.
|
||||
pub def writer::to(out: &mut writable, indent: u32 = 0, alloc: maybe<&mut allocator> = nothing {}): writer {
|
||||
return writer {
|
||||
_text = string::new(alloc),
|
||||
_indent = indent,
|
||||
_levels = vector::<u8>::new(alloc),
|
||||
_out = out,
|
||||
_pass_at = pass_bytes
|
||||
};
|
||||
}
|
||||
|
||||
#! Creates a writer by taking another's text and what it has open, which leaves
|
||||
#! the other holding nothing.
|
||||
#! @param other The writer to move from.
|
||||
#! @returns The writer.
|
||||
pub def writer::move_of(other: &mut writer): writer {
|
||||
val made := writer {
|
||||
_text = move(other._text),
|
||||
_indent = other._indent,
|
||||
_levels = move(other._levels),
|
||||
_written = other._written,
|
||||
_failure = other._failure,
|
||||
_out = other._out,
|
||||
_pass_at = other._pass_at,
|
||||
_lossy = other._lossy
|
||||
};
|
||||
other._written = false;
|
||||
other._failure = nothing {};
|
||||
other._out = nothing {};
|
||||
other._pass_at = 0;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Gives the text written, once the value is written whole. A writer `to` a
|
||||
#! stream passes on what it still holds, and gives an empty view.
|
||||
#! @param this The writer to finish.
|
||||
#! @returns A view of the text, good until the writer is written to, cleared, or
|
||||
#! closed, or the first failure in the data, which has no place, or
|
||||
#! `not_written` where the stream failed.
|
||||
pub def writer::finish(&mut this): result<strview, error> {
|
||||
expects(this._written && this._levels.length == 0,
|
||||
"A writer finishes once its value is written whole, with nothing left open.");
|
||||
if this._pass_at != 0 {
|
||||
this.pass();
|
||||
}
|
||||
if this._failure is some(kind) {
|
||||
return error { kind = kind };
|
||||
}
|
||||
return this._text.span;
|
||||
}
|
||||
|
||||
#! Empties the writer to write another value, keeping its memory, and whether it
|
||||
#! is lossy.
|
||||
#! @param this The writer to empty.
|
||||
pub def writer::clear(&mut this): void {
|
||||
this._text.clear();
|
||||
this._levels.clear();
|
||||
this._written = false;
|
||||
this._failure = nothing {};
|
||||
}
|
||||
|
||||
#! Makes the writer lossy, or strict again. A lossy writer writes text that is
|
||||
#! not UTF-8, in strings and members' names alike, with the escape of U+FFFD,
|
||||
#! `\ufffd`, in place of each byte that breaks UTF-8, rather than writing `null`
|
||||
#! and keeping the failure, so what it writes is JSON whatever it is given.
|
||||
#! @param this The writer to change.
|
||||
#! @param lossy Whether it is lossy.
|
||||
pub def writer::set_lossy(&mut this, lossy: bool): void {
|
||||
this._lossy = lossy;
|
||||
}
|
||||
|
||||
#! Begins an object, whose members are each written as `member` and a value.
|
||||
#! @param this The writer to write with.
|
||||
pub def writer::begin_object(&mut this): void {
|
||||
this.begin(level_object, '{');
|
||||
}
|
||||
|
||||
#! Begins an object, as `serial::encode` does, knowing how many members it
|
||||
#! holds.
|
||||
#! @param this The writer to write with.
|
||||
#! @param count How many members the object holds, which JSON need not know.
|
||||
pub def writer::begin_object(&mut this, count: u64): void {
|
||||
this.begin(level_object, '{');
|
||||
}
|
||||
|
||||
#! Writes the name of the member whose value is written next.
|
||||
#! @param this The writer to write with, within an object.
|
||||
#! @param name The name, which is escaped.
|
||||
pub def writer::member(&mut this, name: strview): void {
|
||||
expects(this._levels.length > 0 && (this.top() & level_object) != 0,
|
||||
"A member is written only within an object.");
|
||||
expects((this.top() & level_named) == 0, "A member's value is written before the next member.");
|
||||
|
||||
val top := this.top();
|
||||
if (top & level_held) != 0 {
|
||||
this._text.push(',');
|
||||
}
|
||||
this._levels.set(this._levels.length - 1, top | level_held | level_named);
|
||||
this.newline(this._levels.length);
|
||||
this._text.push('"');
|
||||
val before := this._text.length;
|
||||
if !escape(name, &mut this._text, this._lossy) && !this._lossy {
|
||||
this._text.resize(before);
|
||||
this.keep(error_kind::invalid_utf8);
|
||||
}
|
||||
this._text.append(this._indent > 0 ? "\": " : "\":");
|
||||
}
|
||||
|
||||
#! Ends the innermost object.
|
||||
#! @param this The writer to write with.
|
||||
pub def writer::end_object(&mut this): void {
|
||||
expects(this._levels.length > 0 && (this.top() & level_object) != 0,
|
||||
"An object is ended only where one is open innermost.");
|
||||
expects((this.top() & level_named) == 0, "A member's value is written before the object ends.");
|
||||
this.end('}');
|
||||
}
|
||||
|
||||
#! Begins an array.
|
||||
#! @param this The writer to write with.
|
||||
pub def writer::begin_array(&mut this): void {
|
||||
this.begin(0, '[');
|
||||
}
|
||||
|
||||
#! Begins an array, as `serial::encode` does, knowing how many elements it
|
||||
#! holds.
|
||||
#! @param this The writer to write with.
|
||||
#! @param count How many elements the array holds, which JSON need not know.
|
||||
pub def writer::begin_array(&mut this, count: u64): void {
|
||||
this.begin(0, '[');
|
||||
}
|
||||
|
||||
#! Ends the innermost array.
|
||||
#! @param this The writer to write with.
|
||||
pub def writer::end_array(&mut this): void {
|
||||
expects(this._levels.length > 0 && (this.top() & level_object) == 0,
|
||||
"An array is ended only where one is open innermost.");
|
||||
this.end(']');
|
||||
}
|
||||
|
||||
#! Writes a string.
|
||||
#! @param this The writer to write with.
|
||||
#! @param value The text, which is escaped, and must be UTF-8 unless the
|
||||
#! writer is lossy.
|
||||
pub def writer::text(&mut this, value: strview): void {
|
||||
this.before_value();
|
||||
val before := this._text.length;
|
||||
this._text.push('"');
|
||||
if !escape(value, &mut this._text, this._lossy) && !this._lossy {
|
||||
this._text.resize(before);
|
||||
this._text.append("null");
|
||||
this.keep(error_kind::invalid_utf8);
|
||||
return;
|
||||
}
|
||||
this._text.push('"');
|
||||
}
|
||||
|
||||
#! Writes a signed integer.
|
||||
#! @param this The writer to write with.
|
||||
#! @param value The integer.
|
||||
pub def writer::signed(&mut this, value: i64): void {
|
||||
this.before_value();
|
||||
if value < 0 {
|
||||
this._text.push('-');
|
||||
this.digits(0u - value as u64);
|
||||
return;
|
||||
}
|
||||
this.digits(value as u64);
|
||||
}
|
||||
|
||||
#! Writes an unsigned integer.
|
||||
#! @param this The writer to write with.
|
||||
#! @param value The integer.
|
||||
pub def writer::unsigned(&mut this, value: u64): void {
|
||||
this.before_value();
|
||||
this.digits(value);
|
||||
}
|
||||
|
||||
#! Writes a float, as the shortest text that reads back as it.
|
||||
#! @param this The writer to write with.
|
||||
#! @param value The float, which must be finite.
|
||||
pub def writer::real(&mut this, value: f64): void {
|
||||
this.before_value();
|
||||
if !(value - value == 0.0) {
|
||||
this._text.append("null");
|
||||
this.keep(error_kind::not_finite);
|
||||
return;
|
||||
}
|
||||
val written := $"{value}";
|
||||
this._text.append(written.span);
|
||||
}
|
||||
|
||||
#! Writes `true` or `false`.
|
||||
#! @param this The writer to write with.
|
||||
#! @param value The truth to write.
|
||||
pub def writer::boolean(&mut this, value: bool): void {
|
||||
this.before_value();
|
||||
this._text.append(value ? "true" : "false");
|
||||
}
|
||||
|
||||
#! Writes `null`.
|
||||
#! @param this The writer to write with.
|
||||
pub def writer::empty(&mut this): void {
|
||||
this.before_value();
|
||||
this._text.append("null");
|
||||
}
|
||||
|
||||
#! Writes JSON text already written, as it is, as a value: one written by
|
||||
#! another writer, or by another program, which is written again without being
|
||||
#! read.
|
||||
#! @param this The writer to write with.
|
||||
#! @param json The text, which must be one whole JSON value, since the writer
|
||||
#! does not read it, and which keeps its own spacing, however the
|
||||
#! writer indents.
|
||||
pub def writer::raw(&mut this, json: strview): void {
|
||||
this.before_value();
|
||||
this._text.append(json);
|
||||
}
|
||||
|
||||
#! Keeps a failure `serial::encode` finds, as the writer keeps its own, to give
|
||||
#! it when it finishes.
|
||||
#! @param this The writer to keep it.
|
||||
#! @param kind The failure.
|
||||
pub def writer::fail(&mut this, kind: serial::error_kind): void {
|
||||
this.keep(of_serial(kind));
|
||||
}
|
||||
|
||||
# Begins an object or array, as a value.
|
||||
def writer::begin(&mut this, level: u8, bracket: u8): void {
|
||||
this.before_value();
|
||||
this._text.push(bracket);
|
||||
this._levels.append(level);
|
||||
}
|
||||
|
||||
# Passes the text on to the stream, where the writer passes it on and holds enough.
|
||||
def writer::passes(&mut this): void {
|
||||
if this._pass_at != 0 && this._text.length >= this._pass_at {
|
||||
this.pass();
|
||||
}
|
||||
}
|
||||
|
||||
# Passes everything held on to the stream, and lets go of it. Once the stream has
|
||||
# failed, what is written is let go of without being passed on.
|
||||
def writer::pass(&mut this): void {
|
||||
if this._out is some(out) {
|
||||
if out.write(this._text.span) is error(_) {
|
||||
this._out = nothing {};
|
||||
this.keep(error_kind::not_written);
|
||||
}
|
||||
}
|
||||
this._text.clear();
|
||||
}
|
||||
|
||||
# Ends the innermost object or array, closing it on a line of its own where it
|
||||
# holds anything and the writer indents.
|
||||
def writer::end(&mut this, bracket: u8): void {
|
||||
this.passes();
|
||||
val held := (this.top() & level_held) != 0;
|
||||
this._levels.remove_at(this._levels.length - 1);
|
||||
if held {
|
||||
this.newline(this._levels.length);
|
||||
}
|
||||
this._text.push(bracket);
|
||||
}
|
||||
|
||||
# Readies a value: within an array, after a comma where one comes, and within an
|
||||
# object, after its member's name.
|
||||
def writer::before_value(&mut this): void {
|
||||
this.passes();
|
||||
if this._levels.length == 0 {
|
||||
expects(!this._written, "A writer writes one value; an array holds more than one.");
|
||||
this._written = true;
|
||||
return;
|
||||
}
|
||||
|
||||
val top := this.top();
|
||||
if (top & level_object) != 0 {
|
||||
expects((top & level_named) != 0, "A value within an object follows its member's name.");
|
||||
this._levels.set(this._levels.length - 1, top & ~level_named);
|
||||
return;
|
||||
}
|
||||
|
||||
if (top & level_held) != 0 {
|
||||
this._text.push(',');
|
||||
}
|
||||
this._levels.set(this._levels.length - 1, top | level_held);
|
||||
this.newline(this._levels.length);
|
||||
}
|
||||
|
||||
# Begins a line indented for a depth, where the writer indents.
|
||||
def writer::newline(&mut this, depth: u64): void {
|
||||
if this._indent == 0 {
|
||||
return;
|
||||
}
|
||||
this._text.push('\n');
|
||||
for _ in 0..depth * (this._indent as u64) {
|
||||
this._text.push(' ');
|
||||
}
|
||||
}
|
||||
|
||||
# Writes an integer's digits.
|
||||
def writer::digits(&mut this, magnitude: u64): void {
|
||||
var buffer: u8[20];
|
||||
var at: u64 = 20;
|
||||
var left := magnitude;
|
||||
while true {
|
||||
at--;
|
||||
buffer[at] = '0' + (left % 10) as u8;
|
||||
left /= 10;
|
||||
if left == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
this._text.append(strview::over(&buffer[at] as *u8, 20 - at));
|
||||
}
|
||||
|
||||
def writer::top(&this): u8 {
|
||||
return this._levels.at(this._levels.length - 1);
|
||||
}
|
||||
|
||||
# Keeps the first failure in the data.
|
||||
def writer::keep(&mut this, kind: error_kind): void {
|
||||
if this._failure is none {
|
||||
this._failure = kind;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user