402 lines
14 KiB
Plaintext
402 lines
14 KiB
Plaintext
#! @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.view();
|
|
}
|
|
|
|
#! 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.view());
|
|
}
|
|
|
|
#! 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.view()) 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;
|
|
}
|
|
}
|