ubi_rs/
serde_ext.rs

1// MIT License
2//
3// Copyright (c) 2024 Ankur Srivastava
4//
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to deal
7// in the Software without restriction, including without limitation the rights
8// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9// copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11//
12// The above copyright notice and this permission notice shall be included in
13// all copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21// SOFTWARE.
22
23use serde::Serialize;
24
25/// SerdeExt trait to convert any Serializable struct to
26/// json string.
27pub trait SerdeExt {
28    /// Converts a serializable struct to pretty json
29    /// Fails in case the serde fails to convert it to pretty string.
30    ///
31    /// ```rust, no_run
32    /// use serde::Serialize;
33    /// use schema_registry_client::prelude::*;
34    ///
35    /// #[derive(Serialize)]
36    /// pub struct Test{
37    ///   pub name: String
38    /// }
39    ///
40    /// let test = Test{name:"degauss".to_string()};
41    /// println!("{}", test.pretty_string());
42    ///
43    fn pretty_string(&self) -> String;
44
45    fn pretty_print(&self);
46
47    fn boxed(self) -> Box<dyn SerdeExt>
48    where
49        Self: Sized + Serialize + 'static,
50    {
51        Box::new(self)
52    }
53}
54
55impl<T> SerdeExt for T
56where
57    T: ?Sized + Serialize,
58{
59    fn pretty_string(&self) -> String {
60        serde_json::to_string(self).unwrap()
61    }
62
63    fn pretty_print(&self) {
64        println!("{}", self.pretty_string());
65    }
66}