use serde::{Deserialize, Serialize};
use crate::tag::{Tag, Tagged};
const TYPE_NAME: &str = "ratio";
#[derive(Serialize, Deserialize, Clone, Copy, PartialEq, PartialOrd, Debug)]
#[serde(from = "RatioTypst", into = "RatioTypst")]
pub struct Ratio {
pub ratio: f64,
}
impl Ratio {
pub const fn new(ratio: f64) -> Self {
Self { ratio }
}
pub fn to_percentage(&self) -> String {
format!("{}%", self.ratio * 100.0)
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct RatioTypst {
typwire_type: Tag<Ratio>,
ratio: f64,
}
impl Tagged for Ratio {
const TYPE_NAME: &'static str = TYPE_NAME;
}
impl From<Ratio> for RatioTypst {
fn from(value: Ratio) -> Self {
RatioTypst {
typwire_type: Tag::new(),
ratio: value.ratio,
}
}
}
impl From<RatioTypst> for Ratio {
fn from(value: RatioTypst) -> Self {
Self::new(value.ratio)
}
}
pub(crate) mod fraction {
use serde::{Deserialize, Deserializer, Serializer};
use super::Ratio;
pub(crate) fn serialize<S: Serializer>(
ratio: &Ratio,
serializer: S,
) -> Result<S::Ok, S::Error> {
serializer.serialize_f64(ratio.ratio)
}
pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Ratio, D::Error> {
f64::deserialize(deserializer).map(Ratio::new)
}
}
impl Default for Ratio {
fn default() -> Self {
Ratio::new(1.0)
}
}