ferrix_lib/
traits.rs

1/* traits.rs
2 *
3 * Copyright 2025 Michail Krasnov <mskrasnov07@ya.ru>
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 *
18 * SPDX-License-Identifier: GPL-3.0-or-later
19 */
20
21//! Custom trait objects
22
23use anyhow::Result;
24use serde::Serialize;
25use std::fmt::Display;
26
27/// A trait for converting structure data to Plain Text for writing
28/// to `*.txt` or output to `stdout`
29pub trait ToPlainText {
30    /// Convert structure fields to `String`
31    fn to_plain(&self) -> String;
32}
33
34pub fn print_opt_val<T: Display>(param: &str, value: &Option<T>) -> String {
35    if let Some(value) = value {
36        format!("\t{param}: {value}\n")
37    } else {
38        format!("")
39    }
40}
41
42pub fn print_val<T: Display>(param: &str, value: &T) -> String {
43    format!("\t{param}: {value}\n")
44}
45
46/// A trate with functions for converting data from a structure or
47/// other object to the JSON format
48pub trait ToJson {
49    /// Convert object data to machine-readable JSON format (without
50    /// unnecessary indentation and newline transitions)
51    fn to_json(&self) -> Result<String>
52    where
53        Self: Serialize,
54    {
55        let s = serde_json::to_string(&self)?;
56        Ok(s)
57    }
58
59    /// Convert object data to human-readable JSON format ("pretty";
60    /// with additional newline transitions and indentation)
61    fn to_json_pretty(&self) -> Result<String>
62    where
63        Self: Serialize,
64    {
65        let s = serde_json::to_string_pretty(&self)?;
66        Ok(s)
67    }
68}