#! @file writer.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the writer, which writes YAML in block style as it is given it, without #! building a tree first. import std::io; module std::yaml; # How much text a writer passing its text on holds before it does. const pass_bytes: u64 = 16384; # The longest key written plain or quoted on its line, past which it is written after # `?`, as YAML limits implicit keys. const key_limit: u64 = 1024; # What the next value follows. const after_nothing: u8 = 0; # It begins a document. const after_key: u8 = 1; # A key's `:`, after which it is on the same line or begins below. const after_dash: u8 = 2; # A sequence's `-`, after which it begins on the same line. # Each open mapping or sequence of a writer. struct level { var mapping: bool; var column: u64; #! Where its entries begin. var count: u64; #! How many entries are begun. var after: u8; #! What it follows. var named: bool; #! Whether a mapping's key is written, and its value is next. } #! Writes YAML in block style into a string it owns, as it is given it: #! indentation, dashes, colons, quotes, and block scalars are its own. #! #! Text is written plain where it reads back as the same text, as a literal #! block where it holds line breaks, and double-quoted with escapes otherwise. #! Each level of nesting is indented by two spaces, or as many as `writer::new` #! is given, with a sequence indented under its key, and an empty collection #! written `{}` or `[]`. #! #! A writer made by `writer::to` passes its text on to a stream instead, #! whenever it holds 16 KB and when it finishes. It borrows the stream, which #! the caller flushes and closes. #! #! Misuse stops the program, as indexing past an array does: a member outside a #! mapping, a value within a mapping without its key, ending a sequence where a #! mapping is open, a second value in a document, or finishing with something #! still open. Text that is not UTF-8 is written as `null` in its place, and #! `finish` gives `invalid_utf8`. #! #! The writer is a `serial::encoder`, so `yaml::encode` and `serial::encode` #! write typed values through it, among what it is given by hand. pub struct writer : serial::encoder, moveable { pub var _text: string; #! The text written so far, which std's tests read. var _indent: u64; #! Spaces for each level of nesting. var _levels: vector; var _pending: u8; #! What the next value follows. var _written: bool; #! Whether the document's value is begun, after which there is no other. var _failure: maybe; 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. } #! Makes a writer. #! @param indent Spaces for each level of nesting, from 1 to 9. #! @param alloc An optional allocator for the writer to take memory from. #! @returns The writer, which holds no text yet. pub def writer::new(indent: u32 = 2, alloc: maybe<&mut allocator> = nothing {}): writer { expects(indent >= 1 && indent <= 9, "A writer indents each level by 1 to 9 spaces."); return writer { _text = string::new(alloc), _indent = indent as u64, _levels = vector::::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, from 1 to 9. #! @param alloc An optional allocator for the writer to take memory from. #! @returns The writer. pub def writer::to(out: &mut writable, indent: u32 = 2, alloc: maybe<&mut allocator> = nothing {}): writer { expects(indent >= 1 && indent <= 9, "A writer indents each level by 1 to 9 spaces."); return writer { _text = string::new(alloc), _indent = indent as u64, _levels = vector::::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), _pending = other._pending, _written = other._written, _failure = other._failure, _out = other._out, _pass_at = other._pass_at }; other._written = false; other._failure = nothing {}; other._out = nothing {}; other._pass_at = 0; return made; } #! Gives the text written, once each document's 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, which has no place, or `not_written` #! where the stream failed. pub def writer::finish(&mut this): result { 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(); } #! Ends the document written, and begins another after a `---` line. #! @param this The writer to write with, whose document's value is written #! whole. pub def writer::document(&mut this): void { expects(this._written && this._levels.length == 0, "A document ends once its value is written whole, with nothing left open."); this._text.append("---\n"); this._written = false; } #! Empties the writer to write another stream, keeping its memory. #! @param this The writer to empty. pub def writer::clear(&mut this): void { this._text.clear(); this._levels.clear(); this._pending = after_nothing; this._written = false; this._failure = nothing {}; } #! Begins a mapping, 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.open(true); } #! Begins a mapping, as `serial::encode` does, knowing how many members it #! holds. #! @param this The writer to write with. #! @param count How many members the mapping holds, which YAML need not know. pub def writer::begin_object(&mut this, count: u64): void { this.open(true); } #! Writes the key of the member whose value is written next. #! @param this The writer to write with, within a mapping. #! @param name The key's text, which is quoted where it would read as #! something else. pub def writer::member(&mut this, name: strview): void { expects(this._levels.length > 0 && this.top().mapping, "A member is written only within a mapping."); expects(!this.top().named, "A member's value is written before the next member."); this.entry(); val start := this._text.length; if !this.append_key(name) { this._text.resize(start); this._text.append("null"); this.keep(error_kind::invalid_utf8); } # A key too long to be implicit is written after `?`, with its `:` on a line below. if this._text.length - start > key_limit { val key := string::from(this._text.view().substr(start, this._text.length - start), nothing {}); this._text.resize(start); this._text.append("? "); this._text.append(key.view()); this._text.push('\n'); this.spaces(this.top().column); } this._text.push(':'); this.top().named = true; this._pending = after_key; } #! Ends the innermost mapping. #! @param this The writer to write with. pub def writer::end_object(&mut this): void { expects(this._levels.length > 0 && this.top().mapping, "A mapping is ended only where one is open innermost."); expects(!this.top().named, "A member's value is written before the mapping ends."); this.close("{}"); } #! Begins a sequence. #! @param this The writer to write with. pub def writer::begin_array(&mut this): void { this.open(false); } #! Begins a sequence, as `serial::encode` does, knowing how many elements it #! holds. #! @param this The writer to write with. #! @param count How many elements the sequence holds, which YAML need not #! know. pub def writer::begin_array(&mut this, count: u64): void { this.open(false); } #! Ends the innermost sequence. #! @param this The writer to write with. pub def writer::end_array(&mut this): void { expects(this._levels.length > 0 && !this.top().mapping, "A sequence is ended only where one is open innermost."); this.close("[]"); } #! Writes text: plain where it reads back as the same text, as a literal block #! where it holds line breaks, and double-quoted otherwise. #! @param this The writer to write with. #! @param value The text, which must be UTF-8. pub def writer::text(&mut this, value: strview): void { this.before_value(); if plain_writes(value) { this.scalar(value); return; } if literal_writes(value) && this.literal(value) { return; } this.lead(); val start := this._text.length; if !append_double(value, &mut this._text) { this._text.resize(start); this._text.append("null"); this.keep(error_kind::invalid_utf8); } this._text.push('\n'); this._pending = after_nothing; } #! 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(); this.scalar($"{value}".view()); } #! 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.scalar($"{value}".view()); } #! Writes a float, as the shortest text that reads back as it, and infinity and #! NaN as `.inf`, `-.inf`, and `.nan`. #! @param this The writer to write with. #! @param value The float. pub def writer::real(&mut this, value: f64): void { this.before_value(); if value != value { this.scalar(".nan"); return; } if value - value != 0.0 { this.scalar(value > 0.0 ? ".inf" : "-.inf"); return; } # A whole float is written so it reads back as a float. val written := $"{value}"; if is_integer(written.view()) { this.scalar($"{written}.0".view()); return; } this.scalar(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.scalar(value ? "true" : "false"); } #! Writes `null`. #! @param this The writer to write with. pub def writer::empty(&mut this): void { this.before_value(); this.scalar("null"); } #! 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 a mapping or sequence, as a value. Nothing is written until its first entry # is, since an empty one is written `{}` or `[]` where it stands. def writer::open(&mut this, mapping: bool): void { this.before_value(); var column: u64 = 0; if this._levels.length > 0 { column = this.top().column + this._indent; } this._levels.append(level { mapping = mapping, column = column, after = this._pending }); this._pending = after_nothing; } # Ends the innermost mapping or sequence, writing it `{}` or `[]` where it is empty. def writer::close(&mut this, empty: strview): void { this.passes(); val ended: level = this.top(); this._levels.remove_at(this._levels.length - 1); if ended.count > 0 { return; } if ended.after != after_nothing { this._text.push(' '); } this._text.append(empty); this._text.push('\n'); } # Readies a value: within a sequence, after its `-`, and within a mapping, after its # member's key. def writer::before_value(&mut this): void { this.passes(); if this._levels.length == 0 { expects(!this._written, "A writer writes one value a document; a sequence holds more than one."); this._written = true; return; } val top := &mut this.top(); if top.mapping { expects(top.named, "A value within a mapping follows its member's key."); top.named = false; return; } this.entry(); this._text.push('-'); this._pending = after_dash; } # Begins an entry of the innermost collection: on the line its key or `-` is on, for # its first entry, and on a line of its own, indented, for any other. def writer::entry(&mut this): void { val top := &mut this.top(); if top.count == 0 { if top.after == after_key { this._text.push('\n'); this.spaces(top.column); } else if top.after == after_dash { this.spaces(this._indent - 1); } } else { this.spaces(top.column); } top.count++; } # Writes what comes before a value on the line its key or `-` is on. def writer::lead(&mut this): void { if this._pending != after_nothing { this._text.push(' '); } } # Writes a scalar as it is, ending its line. def writer::scalar(&mut this, written: strview): void { this.lead(); this._text.append(written); this._text.push('\n'); this._pending = after_nothing; } # Writes text as a literal block, its lines indented past what holds it, with the # indicators its first line and its final line breaks need, or gives `false` where it # cannot be, as text holding nothing but line breaks cannot. def writer::literal(&mut this, value: strview): bool { var trailing: u64 = 0; while trailing < value.length && value[value.length - 1 - trailing] == '\n' { trailing++; } val body := value.substr(0, value.length - trailing); if body.length == 0 { return false; } # Where the lines begin, and where what holds the scalar is, as an indentation # indicator counts from it. var parent: i64 = -1; if this._levels.length > 0 { parent = this.top().column as i64; } val column := (parent + this._indent as i64) as u64; # The first line holding anything begins with a space, so the indentation is # written, since it could not be found from that line. var first: u64 = 0; while first < body.length && body[first] == '\n' { first++; } val indicated := body[first] == ' '; val indicator := column as i64 - parent; if indicated && indicator > 9 { return false; } this.lead(); this._text.push('|'); if indicated { this._text.push(('0' as u64 + indicator as u64) as u8); } if trailing == 0 { this._text.push('-'); } else if trailing > 1 { this._text.push('+'); } this._text.push('\n'); var start: u64 = 0; while start <= body.length { var end := start; while end < body.length && body[end] != '\n' { end++; } if end > start { this.spaces(column); this._text.append(body.substr(start, end - start)); } this._text.push('\n'); start = end + 1; } for _ in 1..trailing { this._text.push('\n'); } this._pending = after_nothing; return true; } # Appends a key: plain where it reads back as the same text, and double-quoted # otherwise, giving whether it is UTF-8. def writer::append_key(&mut this, name: strview): bool { if plain_writes(name) { this._text.append(name); return true; } return append_double(name, &mut this._text); } def writer::spaces(&mut this, count: u64): void { for _ in 0..count { this._text.push(' '); } } def writer::top(&mut this): &mut level { return this._levels.at(this._levels.length - 1); } # Keeps the first failure. def writer::keep(&mut this, kind: error_kind): void { if this._failure is none { this._failure = kind; } } # 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(); }