use std::cmp::Ordering;
use std::fmt;
#[derive(Clone, Debug, Default, PartialEq)]
pub enum Value {
#[default]
Null,
Bool(bool),
Int(i64),
Float(f64),
Decimal(Decimal),
String(String),
Date(Date),
Time(Time),
DateTime(DateTime),
Timestamp(Timestamp),
Blob(Vec<u8>),
}
impl Value {
pub fn is_null(&self) -> bool {
matches!(self, Value::Null)
}
pub fn as_bool(&self) -> Option<bool> {
match self {
Value::Bool(b) => Some(*b),
_ => None,
}
}
pub fn as_i64(&self) -> Option<i64> {
match self {
Value::Int(v) => Some(*v),
Value::Float(v) if v.fract() == 0.0 => Some(*v as i64),
Value::Decimal(d) => d.to_i64(),
_ => None,
}
}
pub fn as_f64(&self) -> Option<f64> {
match self {
Value::Int(v) => Some(*v as f64),
Value::Float(v) => Some(*v),
Value::Decimal(d) => Some(d.to_f64()),
_ => None,
}
}
pub fn as_decimal(&self) -> Option<Decimal> {
match self {
Value::Decimal(d) => Some(*d),
Value::Int(v) => Some(Decimal::new(*v as i128, 0)),
Value::Float(v) => Decimal::from_f64(*v, 6),
_ => None,
}
}
pub fn as_str(&self) -> Option<&str> {
match self {
Value::String(s) => Some(s),
_ => None,
}
}
pub fn as_date(&self) -> Option<Date> {
match self {
Value::Date(d) => Some(*d),
Value::DateTime(dt) => Some(dt.date),
Value::Timestamp(ts) => Some(ts.to_local().date),
_ => None,
}
}
pub fn kind_name(&self) -> &'static str {
match self {
Value::Null => "nulo",
Value::Bool(_) => "lógico",
Value::Int(_) => "inteiro",
Value::Float(_) => "número",
Value::Decimal(_) => "decimal",
Value::String(_) => "texto",
Value::Date(_) => "data",
Value::Time(_) => "hora",
Value::DateTime(_) => "data e hora",
Value::Timestamp(_) => "instante",
Value::Blob(_) => "binário",
}
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Value::Null => Ok(()),
Value::Bool(b) => write!(f, "{b}"),
Value::Int(v) => write!(f, "{v}"),
Value::Float(v) => write!(f, "{v}"),
Value::Decimal(d) => write!(f, "{d}"),
Value::String(s) => f.write_str(s),
Value::Date(d) => write!(f, "{d}"),
Value::Time(t) => write!(f, "{t}"),
Value::DateTime(dt) => write!(f, "{dt}"),
Value::Timestamp(ts) => write!(f, "{ts}"),
Value::Blob(b) => write!(f, "({} bytes)", b.len()),
}
}
}
impl From<bool> for Value {
fn from(v: bool) -> Self {
Value::Bool(v)
}
}
impl From<i32> for Value {
fn from(v: i32) -> Self {
Value::Int(v as i64)
}
}
impl From<i64> for Value {
fn from(v: i64) -> Self {
Value::Int(v)
}
}
impl From<f64> for Value {
fn from(v: f64) -> Self {
Value::Float(v)
}
}
impl From<&str> for Value {
fn from(v: &str) -> Self {
Value::String(v.to_string())
}
}
impl From<String> for Value {
fn from(v: String) -> Self {
Value::String(v)
}
}
impl From<Decimal> for Value {
fn from(v: Decimal) -> Self {
Value::Decimal(v)
}
}
impl From<Date> for Value {
fn from(v: Date) -> Self {
Value::Date(v)
}
}
impl From<Time> for Value {
fn from(v: Time) -> Self {
Value::Time(v)
}
}
impl From<DateTime> for Value {
fn from(v: DateTime) -> Self {
Value::DateTime(v)
}
}
impl From<Timestamp> for Value {
fn from(v: Timestamp) -> Self {
Value::Timestamp(v)
}
}
impl<T: Into<Value>> From<Option<T>> for Value {
fn from(v: Option<T>) -> Self {
v.map_or(Value::Null, Into::into)
}
}
#[derive(Clone, Copy, Debug)]
pub struct Decimal {
mantissa: i128,
scale: u8,
}
impl Decimal {
pub const ZERO: Decimal = Decimal { mantissa: 0, scale: 0 };
pub const fn new(mantissa: i128, scale: u8) -> Self {
Self { mantissa, scale }
}
pub fn mantissa(&self) -> i128 {
self.mantissa
}
pub fn scale(&self) -> u8 {
self.scale
}
pub fn parse(text: &str) -> Option<Decimal> {
Self::parse_with(text, '.')
}
pub fn parse_with(text: &str, decimal_separator: char) -> Option<Decimal> {
let text = text.trim();
let (negative, digits) = match text.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, text.strip_prefix('+').unwrap_or(text)),
};
let (int, frac) = match digits.split_once(decimal_separator) {
Some((i, f)) => (i, f),
None => (digits, ""),
};
if (int.is_empty() && frac.is_empty())
|| !int.chars().all(|c| c.is_ascii_digit())
|| !frac.chars().all(|c| c.is_ascii_digit())
|| frac.len() > 28
{
return None;
}
let mut mantissa: i128 = 0;
for c in int.chars().chain(frac.chars()) {
mantissa = mantissa.checked_mul(10)?.checked_add(c.to_digit(10)? as i128)?;
}
Some(Decimal { mantissa: if negative { -mantissa } else { mantissa }, scale: frac.len() as u8 })
}
pub fn from_f64(value: f64, scale: u8) -> Option<Decimal> {
if !value.is_finite() {
return None;
}
let factor = 10f64.powi(scale as i32);
Some(Decimal { mantissa: (value * factor).round() as i128, scale })
}
pub fn to_f64(&self) -> f64 {
self.mantissa as f64 / 10f64.powi(self.scale as i32)
}
pub fn to_i64(&self) -> Option<i64> {
let r = self.checked_rescale(0, Rounding::HalfUp)?;
i64::try_from(r.mantissa).ok()
}
pub fn rescale(&self, scale: u8) -> Decimal {
self.checked_rescale(scale, Rounding::HalfUp).unwrap_or_else(|| panic!("estouro do decimal: {self} com {scale} casas"))
}
pub fn checked_rescale(&self, scale: u8, mode: Rounding) -> Option<Decimal> {
if scale > MAX_SCALE {
return None;
}
match scale.cmp(&self.scale) {
Ordering::Equal => Some(*self),
Ordering::Greater => Some(Decimal { mantissa: self.mantissa.checked_mul(10i128.checked_pow((scale - self.scale) as u32)?)?, scale }),
Ordering::Less => Some(Decimal { mantissa: div_round(self.mantissa, 10i128.pow((self.scale - scale) as u32), mode)?, scale }),
}
}
pub fn round(&self, scale: u8, mode: Rounding) -> Option<Decimal> {
self.checked_rescale(scale, mode)
}
pub fn checked_add(&self, other: &Decimal) -> Option<Decimal> {
let scale = self.scale.max(other.scale);
let (a, b) = (self.checked_rescale(scale, Rounding::HalfUp)?, other.checked_rescale(scale, Rounding::HalfUp)?);
Some(Decimal { mantissa: a.mantissa.checked_add(b.mantissa)?, scale })
}
pub fn checked_sub(&self, other: &Decimal) -> Option<Decimal> {
self.checked_add(&Decimal { mantissa: other.mantissa.checked_neg()?, scale: other.scale })
}
pub fn checked_mul(&self, other: &Decimal) -> Option<Decimal> {
let product = Decimal { mantissa: self.mantissa.checked_mul(other.mantissa)?, scale: self.scale.checked_add(other.scale)? };
if product.scale > MAX_SCALE { product.reduce(MAX_SCALE, Rounding::HalfUp) } else { Some(product) }
}
pub fn checked_div(&self, other: &Decimal, scale: u8, mode: Rounding) -> Option<Decimal> {
if other.mantissa == 0 || scale > MAX_SCALE {
return None;
}
let exponent = scale as i32 + other.scale as i32 - self.scale as i32;
let (n, d) = if exponent >= 0 {
(self.mantissa.checked_mul(10i128.checked_pow(exponent as u32)?)?, other.mantissa)
} else {
(self.mantissa, other.mantissa.checked_mul(10i128.checked_pow((-exponent) as u32)?)?)
};
Some(Decimal { mantissa: div_round(n, d, mode)?, scale })
}
pub fn default_div_scale(&self, other: &Decimal) -> u8 {
(self.scale.max(other.scale) + 4).min(MAX_SCALE)
}
fn reduce(&self, scale: u8, mode: Rounding) -> Option<Decimal> {
Some(Decimal { mantissa: div_round(self.mantissa, 10i128.checked_pow((self.scale - scale) as u32)?, mode)?, scale })
}
pub fn is_negative(&self) -> bool {
self.mantissa < 0
}
pub(crate) fn parts(&self) -> (u128, String) {
let abs = self.mantissa.unsigned_abs();
let factor = 10u128.pow(self.scale as u32);
let frac = abs % factor;
let frac = if self.scale == 0 { String::new() } else { format!("{frac:0width$}", width = self.scale as usize) };
(abs / factor, frac)
}
}
pub const MAX_SCALE: u8 = 28;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Rounding {
#[default]
HalfUp,
HalfEven,
Truncate,
Up,
}
impl aylis_core::prop::PropEnum for Rounding {
const NAMES: &'static [&'static str] = &["half_up", "half_even", "truncate", "up"];
fn from_index(index: usize) -> Option<Self> {
[Rounding::HalfUp, Rounding::HalfEven, Rounding::Truncate, Rounding::Up].get(index).copied()
}
fn index(self) -> usize {
self as usize
}
}
impl Rounding {
pub fn from_name(name: &str) -> Option<Rounding> {
use aylis_core::prop::PropEnum;
Rounding::NAMES.iter().position(|n| n.eq_ignore_ascii_case(name)).and_then(Rounding::from_index)
}
}
fn div_round(n: i128, d: i128, mode: Rounding) -> Option<i128> {
let q = n.checked_div(d)?;
let r = n % d;
if r == 0 {
return Some(q);
}
let away = if (n < 0) != (d < 0) { -1 } else { 1 };
let (r, d) = (r.unsigned_abs(), d.unsigned_abs());
let half = r.cmp(&(d - r));
let bump = match mode {
Rounding::Truncate => false,
Rounding::Up => true,
Rounding::HalfUp => half != Ordering::Less,
Rounding::HalfEven => half == Ordering::Greater || (half == Ordering::Equal && q % 2 != 0),
};
if bump { q.checked_add(away) } else { Some(q) }
}
impl std::ops::Add for Decimal {
type Output = Decimal;
fn add(self, other: Decimal) -> Decimal {
self.checked_add(&other).unwrap_or_else(|| panic!("estouro do decimal: {self} + {other}"))
}
}
impl std::ops::Sub for Decimal {
type Output = Decimal;
fn sub(self, other: Decimal) -> Decimal {
self.checked_sub(&other).unwrap_or_else(|| panic!("estouro do decimal: {self} - {other}"))
}
}
impl std::ops::Mul for Decimal {
type Output = Decimal;
fn mul(self, other: Decimal) -> Decimal {
self.checked_mul(&other).unwrap_or_else(|| panic!("estouro do decimal: {self} * {other}"))
}
}
impl std::ops::Div for Decimal {
type Output = Decimal;
fn div(self, other: Decimal) -> Decimal {
assert!(other.mantissa != 0, "divisão por zero: {self} / {other}");
self.checked_div(&other, self.default_div_scale(&other), Rounding::HalfUp).unwrap_or_else(|| panic!("estouro do decimal: {self} / {other}"))
}
}
impl std::ops::Neg for Decimal {
type Output = Decimal;
fn neg(self) -> Decimal {
Decimal { mantissa: self.mantissa.checked_neg().expect("estouro do decimal ao trocar o sinal"), scale: self.scale }
}
}
impl From<i64> for Decimal {
fn from(v: i64) -> Self {
Decimal { mantissa: v as i128, scale: 0 }
}
}
impl PartialEq for Decimal {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Decimal {}
impl PartialOrd for Decimal {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Decimal {
fn cmp(&self, other: &Self) -> Ordering {
let scale = self.scale.max(other.scale);
match (self.checked_rescale(scale, Rounding::HalfUp), other.checked_rescale(scale, Rounding::HalfUp)) {
(Some(a), Some(b)) => a.mantissa.cmp(&b.mantissa),
_ => {
let (a, b) = (self.parts(), other.parts());
let signed = |neg: bool, o: Ordering| if neg { o.reverse() } else { o };
match (self.is_negative(), other.is_negative()) {
(true, false) => Ordering::Less,
(false, true) => Ordering::Greater,
(neg, _) => signed(neg, a.0.cmp(&b.0).then_with(|| {
let width = a.1.len().max(b.1.len());
format!("{:0<width$}", a.1).cmp(&format!("{:0<width$}", b.1))
})),
}
}
}
}
}
impl fmt::Display for Decimal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (int, frac) = self.parts();
let sign = if self.is_negative() { "-" } else { "" };
if frac.is_empty() { write!(f, "{sign}{int}") } else { write!(f, "{sign}{int}.{frac}") }
}
}
pub use aylis_core::date::{Date, DateTime, Time, days_in_month, is_leap_year};
use aylis_core::date::split_offset;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Timestamp {
millis: i64,
}
impl Timestamp {
pub fn from_unix_millis(millis: i64) -> Timestamp {
Timestamp { millis }
}
pub fn unix_millis(&self) -> i64 {
self.millis
}
pub fn now() -> Timestamp {
let since = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap_or_default();
Timestamp { millis: since.as_millis() as i64 }
}
pub fn to_local(&self) -> DateTime {
DateTime::from_unix_local(self.millis.div_euclid(1000), self.millis.rem_euclid(1000) as u16).expect("um instante válido")
}
pub fn from_local(local: DateTime) -> Timestamp {
let wall = local.to_unix();
let first = wall - aylis_core::platform::local_offset(wall);
let utc = wall - aylis_core::platform::local_offset(first);
Timestamp { millis: utc * 1000 + local.time.millisecond() as i64 }
}
pub fn parse_iso(text: &str) -> Option<Timestamp> {
let text = text.trim();
let (d, t) = text.split_once(['T', ' ']).unwrap_or((text, "00:00:00"));
let (t, offset) = split_offset(t)?;
let wall = DateTime::new(Date::parse_iso(d)?, Time::parse_iso(t)?);
Some(match offset {
Some(offset) => Timestamp { millis: (wall.to_unix() - offset) * 1000 + wall.time.millisecond() as i64 },
None => Timestamp::from_local(wall),
})
}
}
impl fmt::Display for Timestamp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let utc = DateTime::from_unix(self.millis.div_euclid(1000), 0).ok_or(fmt::Error)?;
write!(f, "{}T{}.{:03}Z", utc.date, utc.time, self.millis.rem_euclid(1000))
}
}