pub(crate) mod api;
pub(crate) mod data;
pub(crate) mod date;
pub(crate) mod locale;
mod number;
pub(crate) mod options;
pub(crate) mod relative;
pub use api::DateArg;
pub(crate) use data::Loc;
pub use date::Timestamp;
pub(crate) use date::{DateOptions, Zone};
pub(crate) use options::{DateFormats, Formats, NumberOptions, parse_date_formats, parse_formats};
pub use relative::RelativeOptions;
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Number(pub(crate) f64);
macro_rules! number_from {
($($t:ty),*) => {$(
impl From<$t> for Number {
#[allow(clippy::cast_precision_loss, reason = "JS holds every number as an f64")]
fn from(n: $t) -> Self {
Number(n as f64)
}
}
)*};
}
number_from!(
i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
);
pub(crate) fn write(
n: Number,
o: &NumberOptions,
loc: &Loc,
out: &mut dyn fmt::Write,
) -> fmt::Result {
number::write(n.0, o, loc, out)
}
pub(crate) fn to_string(n: Number, o: &NumberOptions, loc: &Loc) -> String {
string_of(|out| number::write(n.0, o, loc, out))
}
pub(crate) fn string_of(write: impl FnOnce(&mut dyn fmt::Write) -> fmt::Result) -> String {
let mut buf = Stack {
bytes: [0; 256],
len: 0,
spill: None,
};
let _ = write(&mut buf);
match buf.spill {
Some(s) => s,
None => {
String::from(std::str::from_utf8(buf.bytes.get(..buf.len).unwrap_or(&[])).unwrap_or(""))
}
}
}
struct Stack {
bytes: [u8; 256],
len: usize,
spill: Option<String>,
}
impl fmt::Write for Stack {
fn write_str(&mut self, s: &str) -> fmt::Result {
if let Some(spill) = &mut self.spill {
spill.push_str(s);
return Ok(());
}
let end = self.len + s.len();
match self.bytes.get_mut(self.len..end) {
Some(slot) => {
slot.copy_from_slice(s.as_bytes());
self.len = end;
}
None => {
let mut spill = String::with_capacity(end * 2);
spill.push_str(
std::str::from_utf8(self.bytes.get(..self.len).unwrap_or(&[])).unwrap_or(""),
);
spill.push_str(s);
self.spill = Some(spill);
}
}
Ok(())
}
}