substrate_serializer/lib.rs
1// Copyright 2017-2019 Parity Technologies (UK) Ltd.
2// This file is part of Substrate.
3
4// Substrate is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Substrate is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
16
17//! Substrate customizable serde serializer.
18//!
19//! The idea is that we can later change the implementation
20//! to something more compact, but for now we're using JSON.
21
22#![warn(missing_docs)]
23
24pub use serde_json::{from_str, from_slice, from_reader, Result, Error};
25
26const PROOF: &str = "Serializers are infallible; qed";
27
28/// Serialize the given data structure as a pretty-printed String of JSON.
29pub fn to_string_pretty<T: serde::Serialize + ?Sized>(value: &T) -> String {
30 serde_json::to_string_pretty(value).expect(PROOF)
31}
32
33/// Serialize the given data structure as a JSON byte vector.
34pub fn encode<T: serde::Serialize + ?Sized>(value: &T) -> Vec<u8> {
35 serde_json::to_vec(value).expect(PROOF)
36}
37
38/// Serialize the given data structure as JSON into the IO stream.
39pub fn to_writer<W: ::std::io::Write, T: serde::Serialize + ?Sized>(writer: W, value: &T) -> Result<()> {
40 serde_json::to_writer(writer, value)
41}