tiny-serde 0.1.2

A tiny library to serialize and deserialize to/from JSON
Documentation
pub mod deserialize;
pub mod error;
pub mod serialize;
pub use deserialize::{from_str, Deserialize};
pub use serialize::Serialize;
pub use tiny_serde_derive::Serialize;

use std::collections::HashMap;

#[derive(Clone, Debug)]
pub enum Number {
    Integer(u128),
    SignedInteger(i128),
    Decimal(f64),
}

impl ToString for Number {
    fn to_string(&self) -> String {
        match self {
            Self::Integer(int) => int.to_string(),
            Self::SignedInteger(int) => int.to_string(),
            Self::Decimal(dec) => dec.to_string(),
        }
    }
}

#[derive(Clone, Debug)]
pub enum Value {
    Null,
    Boolean(bool),
    Number(Number),
    String(String),
    Array(Vec<Value>),
    Object(HashMap<String, Value>),
}

impl ToString for Value {
    fn to_string(&self) -> String {
        match self {
            Self::Null => "null".to_string(),
            Self::Boolean(b) => match b {
                true => "true",
                false => "false",
            }
            .to_string(),
            Self::Number(nb) => nb.to_string(),
            Self::String(value) => {
                let value = value
                    .replace('"', r#"\""#)
                    .replace('\\', r#"\\"#)
                    .replace('\n', r#"\n"#)
                    .replace('\r', r#"\r"#);
                format!("\"{value}\"")
            }
            Self::Array(array) => array_to_json(array),
            Self::Object(object) => object_to_json(object),
        }
    }
}

fn array_to_json(array: &[Value]) -> String {
    let mut final_value = "[".to_string();
    let last_index = array.len() - 1;
    for (i, value) in array.iter().enumerate() {
        final_value += &value.to_string();
        if i < last_index {
            final_value.push(',');
        }
    }
    final_value += "]";
    final_value
}

fn object_to_json(object: &HashMap<String, Value>) -> String {
    let mut final_value = "{".to_string();
    let last_index = object.len() - 1;
    let mut i = 0;
    for (key, value) in object.iter() {
        if i < last_index {
            final_value += &format!("\"{key}\":{},", value.to_string());
        } else {
            final_value += &format!("\"{key}\":{}", value.to_string());
        }
        i += 1;
    }
    final_value += "}";
    final_value
}