pub struct Writer<'o> { /* private fields */ }Expand description
A push writer: a document written one event at a time, checked as it goes.
The counterpart of Reader: where the reader pulls
Events out of text, the writer takes them in and writes text. Use it
to write a document whose shape is only known at run time, to transcode
a Reader’s events (any depth: the writer keeps an
explicit stack, never recursion), or to stream a large document to an
io::Write without holding it. For a type known at
compile time, ToJson is simpler and checked by the compiler; the two
mix, since value takes any ToJson.
Every call is checked against the grammar: a key outside an object, a
value where a key belongs, an end that does not match, or a second
top-level value is refused with a WriteError and writes nothing.
finish checks that the document is complete and passes
on the last of the output. Escaping and layout are done for you, as for
to_string_with.
Keys are not checked for repeats (that would mean keeping every key of every open object): writing the same key twice in one object is grammatical JSON that this crate’s default parser refuses, so a caller whose keys come from input should make them unique.
§Examples
use jsonx_lib::{WriteError, Writer};
let mut out = String::new();
let mut w = Writer::new(&mut out);
w.begin_object()?;
w.key("jsonrpc")?;
w.value("2.0")?;
w.key("result")?;
w.begin_array()?;
for n in 1..=3 {
w.value(&n)?;
}
w.end_array()?;
w.end_object()?;
w.finish()?;
assert_eq!(out, r#"{"jsonrpc":"2.0","result":[1,2,3]}"#);Re-indent a document of any depth, event by event:
use jsonx_lib::{Reader, Writer};
let text = r#"{"a":[1,{"b":null}]}"#;
let mut out = String::new();
let mut w = Writer::new(&mut out).pretty();
for event in Reader::new(text) {
w.event(&event?)?;
}
w.finish()?;
assert_eq!(out, jsonx_lib::to_string_pretty(&jsonx_lib::parse(text)?));Implementations§
Source§impl<'o> Writer<'o>
impl<'o> Writer<'o>
Sourcepub fn new(out: &'o mut String) -> Self
pub fn new(out: &'o mut String) -> Self
A writer that appends compact JSON to out.
§Examples
let mut out = String::from("> ");
let mut w = jsonx_lib::Writer::new(&mut out);
w.value(&true)?;
w.finish()?;
assert_eq!(out, "> true");Sourcepub fn io(out: &'o mut dyn Write) -> Self
Available on crate feature std only.
pub fn io(out: &'o mut dyn Write) -> Self
std only.A writer to an io::Write, through a buffer of a
few kilobytes: a document of any size is written in pieces as it is
produced. Call finish to write the last piece.
§Examples
let mut file = Vec::new(); // any `io::Write`
let mut w = jsonx_lib::Writer::io(&mut file);
w.begin_array()?;
for i in 0..10_000 {
w.value(&i)?;
}
w.end_array()?;
w.finish()?;
assert!(file.starts_with(b"[0,1,2,") && file.ends_with(b",9999]"));Sourcepub fn fmt(out: &'o mut dyn Write) -> Self
pub fn fmt(out: &'o mut dyn Write) -> Self
A writer to a fmt::Write (a Formatter, or
anything else that takes text), in pieces of a few kilobytes. Works
without std.
§Examples
use core::fmt;
struct Point(i32, i32);
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut w = jsonx_lib::Writer::fmt(f);
w.value(&[self.0, self.1]).map_err(|_| fmt::Error)?;
w.finish().map_err(|_| fmt::Error)
}
}
assert_eq!(Point(3, -4).to_string(), "[3,-4]");Sourcepub fn pretty(self) -> Self
pub fn pretty(self) -> Self
Switches to the indented layout of
to_string_pretty. Call before writing.
§Examples
let mut out = String::new();
let mut w = jsonx_lib::Writer::new(&mut out).pretty();
w.value(&[1, 2])?;
w.finish()?;
assert_eq!(out, "[\n 1,\n 2\n]");Sourcepub fn with_format(self, format: Format) -> Self
pub fn with_format(self, format: Format) -> Self
Switches to format. Call before writing.
§Examples
use jsonx_lib::{Format, Writer};
let mut out = String::new();
let mut w = Writer::new(&mut out).with_format(Format::compact().html_safe(true));
w.value("<b>")?;
w.finish()?;
assert_eq!(out, r#""\u003cb\u003e""#);Sourcepub fn begin_object(&mut self) -> Result<(), WriteError>
pub fn begin_object(&mut self) -> Result<(), WriteError>
Starts an object (as a value: at the top, as an array item, or after a key).
§Errors
WriteError::ExpectedKey inside an object before a key,
WriteError::DocumentComplete after the top-level value, or an
output error.
§Examples
let mut out = String::new();
let mut w = jsonx_lib::Writer::new(&mut out);
w.begin_object()?;
w.end_object()?;
w.finish()?;
assert_eq!(out, "{}");Sourcepub fn begin_array(&mut self) -> Result<(), WriteError>
pub fn begin_array(&mut self) -> Result<(), WriteError>
Starts an array; placed as begin_object.
§Errors
As begin_object.
§Examples
let mut out = String::new();
let mut w = jsonx_lib::Writer::new(&mut out);
w.begin_array()?;
w.begin_array()?;
w.end_array()?;
w.end_array()?;
w.finish()?;
assert_eq!(out, "[[]]");Sourcepub fn end_object(&mut self) -> Result<(), WriteError>
pub fn end_object(&mut self) -> Result<(), WriteError>
Ends the innermost open object.
§Errors
WriteError::MismatchedEnd if the innermost open container is not
an object, none is open, or a key is waiting for its value; or an
output error.
§Examples
use jsonx_lib::{WriteError, Writer};
let mut out = String::new();
let mut w = Writer::new(&mut out);
w.begin_array()?;
assert!(matches!(w.end_object(), Err(WriteError::MismatchedEnd)));
w.end_array()?;Sourcepub fn end_array(&mut self) -> Result<(), WriteError>
pub fn end_array(&mut self) -> Result<(), WriteError>
Ends the innermost open array.
§Errors
As end_object, for an array.
§Examples
let mut out = String::new();
let mut w = jsonx_lib::Writer::new(&mut out);
w.begin_array()?;
w.value(&"x")?;
w.end_array()?;
assert!(w.is_complete());Sourcepub fn key(&mut self, key: &str) -> Result<(), WriteError>
pub fn key(&mut self, key: &str) -> Result<(), WriteError>
Writes an object member’s key; its value comes next. A key already
written in the same object is not refused (see Writer).
§Errors
WriteError::UnexpectedKey outside an object or right after
another key, or an output error.
§Examples
use jsonx_lib::{WriteError, Writer};
let mut out = String::new();
let mut w = Writer::new(&mut out);
assert!(matches!(w.key("k"), Err(WriteError::UnexpectedKey)));
w.begin_object()?;
w.key("say \"hi\"")?;
w.value(&1)?;
w.end_object()?;
w.finish()?;
assert_eq!(out, r#"{"say \"hi\"":1}"#);Sourcepub fn value<T: ToJson + ?Sized>(&mut self, value: &T) -> Result<(), WriteError>
pub fn value<T: ToJson + ?Sized>(&mut self, value: &T) -> Result<(), WriteError>
Writes a whole value, of any type that implements ToJson: a
scalar, a Value, or your own type (placed as
begin_object).
§Errors
As begin_object.
§Examples
use jsonx_lib::{json, Writer};
let mut out = String::new();
let mut w = Writer::new(&mut out);
w.begin_array()?;
w.value(&json!({ "a": [1] }))?;
w.value(&Some(2.5))?;
w.value("three")?;
w.end_array()?;
w.finish()?;
assert_eq!(out, r#"[{"a":[1]},2.5,"three"]"#);Sourcepub fn event(&mut self, event: &Event<'_>) -> Result<(), WriteError>
pub fn event(&mut self, event: &Event<'_>) -> Result<(), WriteError>
Writes one event, as from a Reader: the start or
end of a container, a key, or a scalar.
§Errors
The error of the call the event stands for.
§Examples
use jsonx_lib::{Event, Writer};
let mut out = String::new();
let mut w = Writer::new(&mut out);
for e in [Event::StartObject, Event::Key("k".into()), Event::Null, Event::EndObject] {
w.event(&e)?;
}
w.finish()?;
assert_eq!(out, r#"{"k":null}"#);Sourcepub fn depth(&self) -> usize
pub fn depth(&self) -> usize
The number of arrays and objects open.
§Examples
let mut out = String::new();
let mut w = jsonx_lib::Writer::new(&mut out);
w.begin_array()?;
assert_eq!(w.depth(), 1);Sourcepub fn is_complete(&self) -> bool
pub fn is_complete(&self) -> bool
Whether the document’s value is complete.
§Examples
let mut out = String::new();
let mut w = jsonx_lib::Writer::new(&mut out);
assert!(!w.is_complete());
w.value(&0)?;
assert!(w.is_complete());Sourcepub fn finish(self) -> Result<(), WriteError>
pub fn finish(self) -> Result<(), WriteError>
Checks that the document is complete and passes on the rest of the
output (for io and fmt writers).
§Errors
WriteError::Incomplete with containers open or no value written,
or an output error.
§Examples
use jsonx_lib::{WriteError, Writer};
let mut out = String::new();
let mut w = Writer::new(&mut out);
w.begin_array()?;
assert!(matches!(w.finish(), Err(WriteError::Incomplete)));