serde_json_v8/
ser.rs

1//! Serialize a Rust data structure into JSON data.
2
3use std::io;
4
5use serde_json::error::Result;
6use serde::ser::Serialize;
7
8pub use serde_json::ser::Formatter;
9
10/// A structure for serializing Rust values into JSON.
11#[allow(non_snake_case)]
12pub mod Serializer {
13    use super::{io, Formatter, CompactV8Formatter, PrettyV8Formatter};
14
15    /// Creates a new JSON serializer.
16    #[inline]
17    pub fn new<W>(writer: W) -> serde_json::ser::Serializer<W, CompactV8Formatter>
18        where
19          W: io::Write,
20    {
21        with_formatter(writer, CompactV8Formatter)
22    }
23
24
25    /// Creates a new JSON pretty print serializer.
26    #[inline]
27    pub fn pretty<'a, W>(writer: W) -> serde_json::ser::Serializer<W, PrettyV8Formatter<'a>>
28        where
29          W: io::Write,
30    {
31        with_formatter(writer, PrettyV8Formatter::new())
32    }
33
34    /// Creates a new JSON visitor whose output will be written to the writer
35    /// specified.
36    #[inline]
37    pub fn with_formatter<W, F>(writer: W, formatter: F) -> serde_json::ser::Serializer<W, F>
38        where
39          W: io::Write,
40          F: Formatter,
41    {
42        serde_json::ser::Serializer::with_formatter(writer, formatter)
43    }
44}
45
46/// This structure compacts a JSON value with no extra whitespace.
47#[derive(Clone, Debug)]
48pub struct CompactV8Formatter;
49
50impl Formatter for CompactV8Formatter {
51    #[inline]
52    fn write_f32<W: ?Sized>(&mut self, writer: &mut W, value: f32) -> io::Result<()>
53        where
54          W: io::Write,
55    {
56        let mut buffer = ryu_js::Buffer::new();
57        let s = buffer.format(f64::from(value));
58        writer.write_all(s.as_bytes())
59    }
60
61    #[inline]
62    fn write_f64<W: ?Sized>(&mut self, writer: &mut W, value: f64) -> io::Result<()>
63        where
64          W: io::Write,
65    {
66        let mut buffer = ryu_js::Buffer::new();
67        let s = buffer.format(value);
68        writer.write_all(s.as_bytes())
69    }
70}
71
72
73/// This structure pretty prints a JSON value to make it human readable.
74#[derive(Clone, Debug)]
75pub struct PrettyV8Formatter<'a> {
76    inner: serde_json::ser::PrettyFormatter<'a>
77}
78
79impl<'a> PrettyV8Formatter<'a> {
80    /// Construct a pretty printer formatter that defaults to using two spaces for indentation.
81    pub fn new() -> Self {
82        PrettyV8Formatter {
83            inner: serde_json::ser::PrettyFormatter::new()
84        }
85    }
86
87    /// Construct a pretty printer formatter that uses the `indent` string for indentation.
88    pub fn with_indent(indent: &'a [u8]) -> Self {
89        PrettyV8Formatter {
90            inner: serde_json::ser::PrettyFormatter::with_indent(indent)
91        }
92    }
93}
94
95impl<'a> Default for PrettyV8Formatter<'a> {
96    fn default() -> Self {
97        PrettyV8Formatter::new()
98    }
99}
100
101impl<'a> Formatter for PrettyV8Formatter<'a> {
102    #[inline]
103    fn write_f32<W: ?Sized>(&mut self, writer: &mut W, value: f32) -> io::Result<()>
104        where
105          W: io::Write,
106    {
107        let mut buffer = ryu_js::Buffer::new();
108        let s = buffer.format(f64::from(value));
109        writer.write_all(s.as_bytes())
110    }
111
112    #[inline]
113    fn write_f64<W: ?Sized>(&mut self, writer: &mut W, value: f64) -> io::Result<()>
114        where
115          W: io::Write,
116    {
117        let mut buffer = ryu_js::Buffer::new();
118        let s = buffer.format(value);
119        writer.write_all(s.as_bytes())
120    }
121
122    #[inline]
123    fn begin_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()>
124        where
125          W: io::Write,
126    {
127        self.inner.begin_array(writer)
128    }
129
130    #[inline]
131    fn end_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()>
132        where
133          W: io::Write,
134    {
135        self.inner.end_array(writer)
136    }
137
138    #[inline]
139    fn begin_array_value<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
140        where
141          W: io::Write,
142    {
143        self.inner.begin_array_value(writer, first)
144    }
145
146    #[inline]
147    fn end_array_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()>
148        where
149          W: io::Write,
150    {
151        self.inner.end_array_value(writer)
152    }
153
154    #[inline]
155    fn begin_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()>
156        where
157          W: io::Write,
158    {
159        self.inner.begin_object(writer)
160    }
161
162    #[inline]
163    fn end_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()>
164        where
165          W: io::Write,
166    {
167        self.inner.end_object(writer)
168    }
169
170    #[inline]
171    fn begin_object_key<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()>
172        where
173          W: io::Write,
174    {
175        self.inner.begin_object_key(writer, first)
176    }
177
178    #[inline]
179    fn begin_object_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()>
180        where
181          W: io::Write,
182    {
183        self.inner.begin_object_value(writer)
184    }
185
186    #[inline]
187    fn end_object_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()>
188        where
189          W: io::Write,
190    {
191        self.inner.end_object_value(writer)
192    }
193}
194
195/// Serialize the given data structure as JSON into the IO stream.
196///
197/// # Errors
198///
199/// Serialization can fail if `T`'s implementation of `Serialize` decides to
200/// fail, or if `T` contains a map with non-string keys.
201#[inline]
202pub fn to_writer<W, T: ?Sized>(writer: W, value: &T) -> Result<()>
203where
204    W: io::Write,
205    T: Serialize,
206{
207    let mut ser = Serializer::new(writer);
208    try!(value.serialize(&mut ser));
209    Ok(())
210}
211
212/// Serialize the given data structure as pretty-printed JSON into the IO
213/// stream.
214///
215/// # Errors
216///
217/// Serialization can fail if `T`'s implementation of `Serialize` decides to
218/// fail, or if `T` contains a map with non-string keys.
219#[inline]
220pub fn to_writer_pretty<W, T: ?Sized>(writer: W, value: &T) -> Result<()>
221where
222    W: io::Write,
223    T: Serialize,
224{
225    let mut ser = Serializer::pretty(writer);
226    try!(value.serialize(&mut ser));
227    Ok(())
228}
229
230/// Serialize the given data structure as a JSON byte vector.
231///
232/// # Errors
233///
234/// Serialization can fail if `T`'s implementation of `Serialize` decides to
235/// fail, or if `T` contains a map with non-string keys.
236#[inline]
237pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>>
238where
239    T: Serialize,
240{
241    let mut writer = Vec::with_capacity(128);
242    try!(to_writer(&mut writer, value));
243    Ok(writer)
244}
245
246/// Serialize the given data structure as a pretty-printed JSON byte vector.
247///
248/// # Errors
249///
250/// Serialization can fail if `T`'s implementation of `Serialize` decides to
251/// fail, or if `T` contains a map with non-string keys.
252#[inline]
253pub fn to_vec_pretty<T: ?Sized>(value: &T) -> Result<Vec<u8>>
254where
255    T: Serialize,
256{
257    let mut writer = Vec::with_capacity(128);
258    try!(to_writer_pretty(&mut writer, value));
259    Ok(writer)
260}
261
262/// Serialize the given data structure as a String of JSON.
263///
264/// # Errors
265///
266/// Serialization can fail if `T`'s implementation of `Serialize` decides to
267/// fail, or if `T` contains a map with non-string keys.
268#[inline]
269pub fn to_string<T: ?Sized>(value: &T) -> Result<String>
270where
271    T: Serialize,
272{
273    let vec = try!(to_vec(value));
274    let string = unsafe {
275        // We do not emit invalid UTF-8.
276        String::from_utf8_unchecked(vec)
277    };
278    Ok(string)
279}
280
281/// Serialize the given data structure as a pretty-printed String of JSON.
282///
283/// # Errors
284///
285/// Serialization can fail if `T`'s implementation of `Serialize` decides to
286/// fail, or if `T` contains a map with non-string keys.
287#[inline]
288pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String>
289where
290    T: Serialize,
291{
292    let vec = try!(to_vec_pretty(value));
293    let string = unsafe {
294        // We do not emit invalid UTF-8.
295        String::from_utf8_unchecked(vec)
296    };
297    Ok(string)
298}