Skip to main content

aylis_data/
value.rs

1//! Valores dos campos: [`Value`] (o "Variant" tipado), [`Decimal`] para dinheiro e
2//! [`Date`]/[`Time`]/[`DateTime`].
3
4use std::cmp::Ordering;
5use std::fmt;
6
7/// Valor de um campo. `Null` é explícito.
8#[derive(Clone, Debug, Default, PartialEq)]
9pub enum Value {
10    #[default]
11    Null,
12    Bool(bool),
13    Int(i64),
14    Float(f64),
15    /// Ponto fixo exato (dinheiro).
16    Decimal(Decimal),
17    String(String),
18    Date(Date),
19    Time(Time),
20    DateTime(DateTime),
21    /// Um instante (a hora do pedido, o log de auditoria), guardado em UTC e mostrado no
22    /// fuso de quem vê, como o `ftTimeStampOffset` do FireDAC.
23    Timestamp(Timestamp),
24    Blob(Vec<u8>),
25}
26
27impl Value {
28    pub fn is_null(&self) -> bool {
29        matches!(self, Value::Null)
30    }
31
32    pub fn as_bool(&self) -> Option<bool> {
33        match self {
34            Value::Bool(b) => Some(*b),
35            _ => None,
36        }
37    }
38
39    pub fn as_i64(&self) -> Option<i64> {
40        match self {
41            Value::Int(v) => Some(*v),
42            Value::Float(v) if v.fract() == 0.0 => Some(*v as i64),
43            Value::Decimal(d) => d.to_i64(),
44            _ => None,
45        }
46    }
47
48    pub fn as_f64(&self) -> Option<f64> {
49        match self {
50            Value::Int(v) => Some(*v as f64),
51            Value::Float(v) => Some(*v),
52            Value::Decimal(d) => Some(d.to_f64()),
53            _ => None,
54        }
55    }
56
57    pub fn as_decimal(&self) -> Option<Decimal> {
58        match self {
59            Value::Decimal(d) => Some(*d),
60            Value::Int(v) => Some(Decimal::new(*v as i128, 0)),
61            Value::Float(v) => Decimal::from_f64(*v, 6),
62            _ => None,
63        }
64    }
65
66    pub fn as_str(&self) -> Option<&str> {
67        match self {
68            Value::String(s) => Some(s),
69            _ => None,
70        }
71    }
72
73    pub fn as_date(&self) -> Option<Date> {
74        match self {
75            Value::Date(d) => Some(*d),
76            Value::DateTime(dt) => Some(dt.date),
77            Value::Timestamp(ts) => Some(ts.to_local().date),
78            _ => None,
79        }
80    }
81
82    pub fn kind_name(&self) -> &'static str {
83        match self {
84            Value::Null => "nulo",
85            Value::Bool(_) => "lógico",
86            Value::Int(_) => "inteiro",
87            Value::Float(_) => "número",
88            Value::Decimal(_) => "decimal",
89            Value::String(_) => "texto",
90            Value::Date(_) => "data",
91            Value::Time(_) => "hora",
92            Value::DateTime(_) => "data e hora",
93            Value::Timestamp(_) => "instante",
94            Value::Blob(_) => "binário",
95        }
96    }
97}
98
99/// Texto neutro (ISO): `2024-05-01`, `13:45:00`, `1234.56`. A formatação para o usuário
100/// fica com o `Field` (display_format e idioma).
101impl fmt::Display for Value {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        match self {
104            Value::Null => Ok(()),
105            Value::Bool(b) => write!(f, "{b}"),
106            Value::Int(v) => write!(f, "{v}"),
107            Value::Float(v) => write!(f, "{v}"),
108            Value::Decimal(d) => write!(f, "{d}"),
109            Value::String(s) => f.write_str(s),
110            Value::Date(d) => write!(f, "{d}"),
111            Value::Time(t) => write!(f, "{t}"),
112            Value::DateTime(dt) => write!(f, "{dt}"),
113            Value::Timestamp(ts) => write!(f, "{ts}"),
114            Value::Blob(b) => write!(f, "({} bytes)", b.len()),
115        }
116    }
117}
118
119impl From<bool> for Value {
120    fn from(v: bool) -> Self {
121        Value::Bool(v)
122    }
123}
124
125impl From<i32> for Value {
126    fn from(v: i32) -> Self {
127        Value::Int(v as i64)
128    }
129}
130
131impl From<i64> for Value {
132    fn from(v: i64) -> Self {
133        Value::Int(v)
134    }
135}
136
137impl From<f64> for Value {
138    fn from(v: f64) -> Self {
139        Value::Float(v)
140    }
141}
142
143impl From<&str> for Value {
144    fn from(v: &str) -> Self {
145        Value::String(v.to_string())
146    }
147}
148
149impl From<String> for Value {
150    fn from(v: String) -> Self {
151        Value::String(v)
152    }
153}
154
155impl From<Decimal> for Value {
156    fn from(v: Decimal) -> Self {
157        Value::Decimal(v)
158    }
159}
160
161impl From<Date> for Value {
162    fn from(v: Date) -> Self {
163        Value::Date(v)
164    }
165}
166
167impl From<Time> for Value {
168    fn from(v: Time) -> Self {
169        Value::Time(v)
170    }
171}
172
173impl From<DateTime> for Value {
174    fn from(v: DateTime) -> Self {
175        Value::DateTime(v)
176    }
177}
178
179impl From<Timestamp> for Value {
180    fn from(v: Timestamp) -> Self {
181        Value::Timestamp(v)
182    }
183}
184
185impl<T: Into<Value>> From<Option<T>> for Value {
186    fn from(v: Option<T>) -> Self {
187        v.map_or(Value::Null, Into::into)
188    }
189}
190
191// ---------------------------------------------------------------------------
192
193/// Número decimal de ponto fixo: `mantissa × 10^-scale`. Exato para dinheiro.
194#[derive(Clone, Copy, Debug)]
195pub struct Decimal {
196    mantissa: i128,
197    scale: u8,
198}
199
200impl Decimal {
201    pub const ZERO: Decimal = Decimal { mantissa: 0, scale: 0 };
202
203    /// `Decimal::new(12345, 2)` = 123,45.
204    pub const fn new(mantissa: i128, scale: u8) -> Self {
205        Self { mantissa, scale }
206    }
207
208    pub fn mantissa(&self) -> i128 {
209        self.mantissa
210    }
211
212    pub fn scale(&self) -> u8 {
213        self.scale
214    }
215
216    /// Lê `"-1234.56"` (separador decimal `.`, sem separador de milhar).
217    pub fn parse(text: &str) -> Option<Decimal> {
218        Self::parse_with(text, '.')
219    }
220
221    /// Lê com o separador decimal dado (sem separador de milhar).
222    pub fn parse_with(text: &str, decimal_separator: char) -> Option<Decimal> {
223        let text = text.trim();
224        let (negative, digits) = match text.strip_prefix('-') {
225            Some(rest) => (true, rest),
226            None => (false, text.strip_prefix('+').unwrap_or(text)),
227        };
228        let (int, frac) = match digits.split_once(decimal_separator) {
229            Some((i, f)) => (i, f),
230            None => (digits, ""),
231        };
232        if (int.is_empty() && frac.is_empty())
233            || !int.chars().all(|c| c.is_ascii_digit())
234            || !frac.chars().all(|c| c.is_ascii_digit())
235            || frac.len() > 28
236        {
237            return None;
238        }
239        let mut mantissa: i128 = 0;
240        for c in int.chars().chain(frac.chars()) {
241            mantissa = mantissa.checked_mul(10)?.checked_add(c.to_digit(10)? as i128)?;
242        }
243        Some(Decimal { mantissa: if negative { -mantissa } else { mantissa }, scale: frac.len() as u8 })
244    }
245
246    /// Converte arredondando para `scale` casas.
247    pub fn from_f64(value: f64, scale: u8) -> Option<Decimal> {
248        if !value.is_finite() {
249            return None;
250        }
251        let factor = 10f64.powi(scale as i32);
252        Some(Decimal { mantissa: (value * factor).round() as i128, scale })
253    }
254
255    pub fn to_f64(&self) -> f64 {
256        self.mantissa as f64 / 10f64.powi(self.scale as i32)
257    }
258
259    pub fn to_i64(&self) -> Option<i64> {
260        let r = self.checked_rescale(0, Rounding::HalfUp)?;
261        i64::try_from(r.mantissa).ok()
262    }
263
264    /// Muda o número de casas, arredondando metade para longe do zero. Entra em pânico se o
265    /// número não couber (só com valores perto de 10³⁸); para tratar, [`checked_rescale`](Self::checked_rescale).
266    pub fn rescale(&self, scale: u8) -> Decimal {
267        self.checked_rescale(scale, Rounding::HalfUp).unwrap_or_else(|| panic!("estouro do decimal: {self} com {scale} casas"))
268    }
269
270    /// Muda o número de casas, arredondando do jeito `mode`; `None` se não couber.
271    pub fn checked_rescale(&self, scale: u8, mode: Rounding) -> Option<Decimal> {
272        if scale > MAX_SCALE {
273            return None;
274        }
275        match scale.cmp(&self.scale) {
276            Ordering::Equal => Some(*self),
277            Ordering::Greater => Some(Decimal { mantissa: self.mantissa.checked_mul(10i128.checked_pow((scale - self.scale) as u32)?)?, scale }),
278            Ordering::Less => Some(Decimal { mantissa: div_round(self.mantissa, 10i128.pow((self.scale - scale) as u32), mode)?, scale }),
279        }
280    }
281
282    /// Arredonda para `scale` casas do jeito `mode`.
283    pub fn round(&self, scale: u8, mode: Rounding) -> Option<Decimal> {
284        self.checked_rescale(scale, mode)
285    }
286
287    pub fn checked_add(&self, other: &Decimal) -> Option<Decimal> {
288        let scale = self.scale.max(other.scale);
289        let (a, b) = (self.checked_rescale(scale, Rounding::HalfUp)?, other.checked_rescale(scale, Rounding::HalfUp)?);
290        Some(Decimal { mantissa: a.mantissa.checked_add(b.mantissa)?, scale })
291    }
292
293    pub fn checked_sub(&self, other: &Decimal) -> Option<Decimal> {
294        self.checked_add(&Decimal { mantissa: other.mantissa.checked_neg()?, scale: other.scale })
295    }
296
297    /// O produto exato (as casas somam); se passar de [`MAX_SCALE`], arredonda metade para
298    /// cima até caber.
299    pub fn checked_mul(&self, other: &Decimal) -> Option<Decimal> {
300        let product = Decimal { mantissa: self.mantissa.checked_mul(other.mantissa)?, scale: self.scale.checked_add(other.scale)? };
301        if product.scale > MAX_SCALE { product.reduce(MAX_SCALE, Rounding::HalfUp) } else { Some(product) }
302    }
303
304    /// A divisão exata com `scale` casas no resultado, arredondada do jeito `mode` (sem passar
305    /// por `f64`: 0,30 / 0,10 = 3). `None` se `other` é zero ou se não couber.
306    pub fn checked_div(&self, other: &Decimal, scale: u8, mode: Rounding) -> Option<Decimal> {
307        if other.mantissa == 0 || scale > MAX_SCALE {
308            return None;
309        }
310        // resultado = (a / 10^sa) / (b / 10^sb), com `scale` casas: a · 10^(scale + sb − sa) / b.
311        let exponent = scale as i32 + other.scale as i32 - self.scale as i32;
312        let (n, d) = if exponent >= 0 {
313            (self.mantissa.checked_mul(10i128.checked_pow(exponent as u32)?)?, other.mantissa)
314        } else {
315            (self.mantissa, other.mantissa.checked_mul(10i128.checked_pow((-exponent) as u32)?)?)
316        };
317        Some(Decimal { mantissa: div_round(n, d, mode)?, scale })
318    }
319
320    /// As casas da divisão quando ninguém diz quantas: as do maior dos dois mais 4
321    /// (100,00 / 3 = 33,333333).
322    pub fn default_div_scale(&self, other: &Decimal) -> u8 {
323        (self.scale.max(other.scale) + 4).min(MAX_SCALE)
324    }
325
326    /// Corta casas até `scale` (só para menos casas).
327    fn reduce(&self, scale: u8, mode: Rounding) -> Option<Decimal> {
328        Some(Decimal { mantissa: div_round(self.mantissa, 10i128.checked_pow((self.scale - scale) as u32)?, mode)?, scale })
329    }
330
331    pub fn is_negative(&self) -> bool {
332        self.mantissa < 0
333    }
334
335    /// Partes inteira e fracionária (com `scale` dígitos), sem sinal.
336    pub(crate) fn parts(&self) -> (u128, String) {
337        let abs = self.mantissa.unsigned_abs();
338        let factor = 10u128.pow(self.scale as u32);
339        let frac = abs % factor;
340        let frac = if self.scale == 0 { String::new() } else { format!("{frac:0width$}", width = self.scale as usize) };
341        (abs / factor, frac)
342    }
343}
344
345/// O máximo de casas de um [`Decimal`] (o `i128` guarda uns 38 dígitos no total).
346pub const MAX_SCALE: u8 = 28;
347
348/// Como arredondar ao cortar casas.
349#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
350pub enum Rounding {
351    /// Metade para longe do zero: 2,345 → 2,35. O padrão.
352    #[default]
353    HalfUp,
354    /// Metade para o par, o "bancário": 2,345 → 2,34 e 2,355 → 2,36.
355    HalfEven,
356    /// Corta as casas: 2,349 → 2,34 (o `Trunc`).
357    Truncate,
358    /// Para longe do zero sempre que sobra algo: 2,341 → 2,35.
359    Up,
360}
361
362impl aylis_core::prop::PropEnum for Rounding {
363    const NAMES: &'static [&'static str] = &["half_up", "half_even", "truncate", "up"];
364
365    fn from_index(index: usize) -> Option<Self> {
366        [Rounding::HalfUp, Rounding::HalfEven, Rounding::Truncate, Rounding::Up].get(index).copied()
367    }
368
369    fn index(self) -> usize {
370        self as usize
371    }
372}
373
374impl Rounding {
375    /// Pelo nome (`"half_even"`); `None` se não for um dos quatro.
376    pub fn from_name(name: &str) -> Option<Rounding> {
377        use aylis_core::prop::PropEnum;
378        Rounding::NAMES.iter().position(|n| n.eq_ignore_ascii_case(name)).and_then(Rounding::from_index)
379    }
380}
381
382/// `n / d` arredondado do jeito `mode` (`d` diferente de zero). `None` só no caso que não
383/// cabe (`i128::MIN / −1`).
384fn div_round(n: i128, d: i128, mode: Rounding) -> Option<i128> {
385    let q = n.checked_div(d)?;
386    let r = n % d;
387    if r == 0 {
388        return Some(q);
389    }
390    let away = if (n < 0) != (d < 0) { -1 } else { 1 };
391    let (r, d) = (r.unsigned_abs(), d.unsigned_abs());
392    // Comparar o resto com a metade sem dobrar (dobrar poderia estourar).
393    let half = r.cmp(&(d - r));
394    let bump = match mode {
395        Rounding::Truncate => false,
396        Rounding::Up => true,
397        Rounding::HalfUp => half != Ordering::Less,
398        Rounding::HalfEven => half == Ordering::Greater || (half == Ordering::Equal && q % 2 != 0),
399    };
400    if bump { q.checked_add(away) } else { Some(q) }
401}
402
403/// Os operadores. Estouro entra em pânico (como os inteiros);
404/// para tratar, os `checked_*`. A divisão usa [`Decimal::default_div_scale`] e arredonda
405/// metade para cima; dividir por zero entra em pânico.
406impl std::ops::Add for Decimal {
407    type Output = Decimal;
408    fn add(self, other: Decimal) -> Decimal {
409        self.checked_add(&other).unwrap_or_else(|| panic!("estouro do decimal: {self} + {other}"))
410    }
411}
412
413impl std::ops::Sub for Decimal {
414    type Output = Decimal;
415    fn sub(self, other: Decimal) -> Decimal {
416        self.checked_sub(&other).unwrap_or_else(|| panic!("estouro do decimal: {self} - {other}"))
417    }
418}
419
420impl std::ops::Mul for Decimal {
421    type Output = Decimal;
422    fn mul(self, other: Decimal) -> Decimal {
423        self.checked_mul(&other).unwrap_or_else(|| panic!("estouro do decimal: {self} * {other}"))
424    }
425}
426
427impl std::ops::Div for Decimal {
428    type Output = Decimal;
429    fn div(self, other: Decimal) -> Decimal {
430        assert!(other.mantissa != 0, "divisão por zero: {self} / {other}");
431        self.checked_div(&other, self.default_div_scale(&other), Rounding::HalfUp).unwrap_or_else(|| panic!("estouro do decimal: {self} / {other}"))
432    }
433}
434
435impl std::ops::Neg for Decimal {
436    type Output = Decimal;
437    fn neg(self) -> Decimal {
438        Decimal { mantissa: self.mantissa.checked_neg().expect("estouro do decimal ao trocar o sinal"), scale: self.scale }
439    }
440}
441
442impl From<i64> for Decimal {
443    fn from(v: i64) -> Self {
444        Decimal { mantissa: v as i128, scale: 0 }
445    }
446}
447
448impl PartialEq for Decimal {
449    fn eq(&self, other: &Self) -> bool {
450        self.cmp(other) == Ordering::Equal
451    }
452}
453
454impl Eq for Decimal {}
455
456impl PartialOrd for Decimal {
457    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
458        Some(self.cmp(other))
459    }
460}
461
462impl Ord for Decimal {
463    fn cmp(&self, other: &Self) -> Ordering {
464        let scale = self.scale.max(other.scale);
465        match (self.checked_rescale(scale, Rounding::HalfUp), other.checked_rescale(scale, Rounding::HalfUp)) {
466            (Some(a), Some(b)) => a.mantissa.cmp(&b.mantissa),
467            // Perto de 10³⁸ as casas não cabem: a parte inteira decide (e a fração, se empatar).
468            _ => {
469                let (a, b) = (self.parts(), other.parts());
470                let signed = |neg: bool, o: Ordering| if neg { o.reverse() } else { o };
471                match (self.is_negative(), other.is_negative()) {
472                    (true, false) => Ordering::Less,
473                    (false, true) => Ordering::Greater,
474                    (neg, _) => signed(neg, a.0.cmp(&b.0).then_with(|| {
475                        let width = a.1.len().max(b.1.len());
476                        format!("{:0<width$}", a.1).cmp(&format!("{:0<width$}", b.1))
477                    })),
478                }
479            }
480        }
481    }
482}
483
484impl fmt::Display for Decimal {
485    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
486        let (int, frac) = self.parts();
487        let sign = if self.is_negative() { "-" } else { "" };
488        if frac.is_empty() { write!(f, "{sign}{int}") } else { write!(f, "{sign}{int}.{frac}") }
489    }
490}
491
492// ---------------------------------------------------------------------------
493
494pub use aylis_core::date::{Date, DateTime, Time, days_in_month, is_leap_year};
495use aylis_core::date::split_offset;
496
497/// Um instante: milissegundos desde 1970 em UTC. É o mesmo momento em qualquer fuso; para
498/// mostrar, vira o horário local de quem vê ([`to_local`](Self::to_local)). Use para o que
499/// aconteceu num momento (a hora do pedido, a última alteração); para uma data ou hora do
500/// calendário (vencimento, aniversário), o [`DateTime`].
501#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
502pub struct Timestamp {
503    millis: i64,
504}
505
506impl Timestamp {
507    pub fn from_unix_millis(millis: i64) -> Timestamp {
508        Timestamp { millis }
509    }
510
511    pub fn unix_millis(&self) -> i64 {
512        self.millis
513    }
514
515    pub fn now() -> Timestamp {
516        let since = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap_or_default();
517        Timestamp { millis: since.as_millis() as i64 }
518    }
519
520    /// O horário local desta tela neste instante.
521    pub fn to_local(&self) -> DateTime {
522        DateTime::from_unix_local(self.millis.div_euclid(1000), self.millis.rem_euclid(1000) as u16).expect("um instante válido")
523    }
524
525    /// O instante de um horário local desta tela (o que o usuário digitou).
526    pub fn from_local(local: DateTime) -> Timestamp {
527        let wall = local.to_unix();
528        // O fuso depende do instante (horário de verão): a primeira conta usa o fuso do
529        // horário de parede, e a segunda acerta com o do instante encontrado.
530        let first = wall - aylis_core::platform::local_offset(wall);
531        let utc = wall - aylis_core::platform::local_offset(first);
532        Timestamp { millis: utc * 1000 + local.time.millisecond() as i64 }
533    }
534
535    /// Lê ISO com fuso (`2026-11-02T13:00:00Z`, `...-03:00`); sem fuso, é o horário local.
536    pub fn parse_iso(text: &str) -> Option<Timestamp> {
537        let text = text.trim();
538        let (d, t) = text.split_once(['T', ' ']).unwrap_or((text, "00:00:00"));
539        let (t, offset) = split_offset(t)?;
540        let wall = DateTime::new(Date::parse_iso(d)?, Time::parse_iso(t)?);
541        Some(match offset {
542            Some(offset) => Timestamp { millis: (wall.to_unix() - offset) * 1000 + wall.time.millisecond() as i64 },
543            None => Timestamp::from_local(wall),
544        })
545    }
546}
547
548/// Em UTC, com milissegundos: `2026-11-02T13:00:00.000Z` (o que o protocolo manda).
549impl fmt::Display for Timestamp {
550    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
551        let utc = DateTime::from_unix(self.millis.div_euclid(1000), 0).ok_or(fmt::Error)?;
552        write!(f, "{}T{}.{:03}Z", utc.date, utc.time, self.millis.rem_euclid(1000))
553    }
554}