use crate::num::float::NiceFloat;
use crate::strings::latex::ToLatex;
use alloc::string::ToString;
use core::fmt::{Display, Formatter, Result, Write};
macro_rules! impl_to_latex {
($t:ident) => {
impl ToLatex for $t {
#[inline]
fn fmt_latex(&self, f: &mut Formatter) -> Result {
Display::fmt(self, f)
}
}
};
}
apply_to_primitive_ints!(impl_to_latex);
macro_rules! impl_to_latex_primitive_float {
($t:ident) => {
impl ToLatex for $t {
fn fmt_latex(&self, f: &mut Formatter) -> Result {
if self.is_nan() {
return f.write_str("\\text{NaN}");
} else if self.is_infinite() {
return f.write_str(if self.is_sign_positive() {
"\\infty"
} else {
"-\\infty"
});
}
let s = NiceFloat(*self).to_string();
let Some(e_index) = s.find('e') else {
return f.write_str(&s);
};
let (mantissa, exponent) = s.split_at(e_index);
let exponent = &exponent[1..];
f.write_str(mantissa)?;
f.write_str(" \\times 10^")?;
if exponent.len() == 1 {
f.write_str(exponent)
} else {
f.write_char('{')?;
f.write_str(exponent)?;
f.write_char('}')
}
}
}
};
}
apply_to_primitive_floats!(impl_to_latex_primitive_float);