sp_serializer/lib.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Substrate customizable serde serializer.
19//!
20//! The idea is that we can later change the implementation
21//! to something more compact, but for now we're using JSON.
22
23#![warn(missing_docs)]
24
25pub use serde_json::{from_reader, from_slice, from_str, Error, Result};
26
27const PROOF: &str = "Serializers are infallible; qed";
28
29/// Serialize the given data structure as a pretty-printed String of JSON.
30pub fn to_string_pretty<T: serde::Serialize + ?Sized>(value: &T) -> String {
31 serde_json::to_string_pretty(value).expect(PROOF)
32}
33
34/// Serialize the given data structure as a JSON byte vector.
35pub fn encode<T: serde::Serialize + ?Sized>(value: &T) -> Vec<u8> {
36 serde_json::to_vec(value).expect(PROOF)
37}
38
39/// Serialize the given data structure as JSON into the IO stream.
40pub fn to_writer<W: ::std::io::Write, T: serde::Serialize + ?Sized>(
41 writer: W,
42 value: &T,
43) -> Result<()> {
44 serde_json::to_writer(writer, value)
45}