glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! `Decimal`: exact numbers for `numeric`/`decimal` columns, as Rails'
//! `BigDecimal`.

use std::fmt;
use std::str::FromStr;

use bigdecimal::num_bigint::{BigInt, Sign};
use bigdecimal::{BigDecimal, One, ToPrimitive, Zero};
use serde::{Serialize, Serializer};

/// An exact decimal number of any precision, for `numeric`/`decimal`
/// columns: `field score: Option<Decimal>`. It's stored exactly on Postgres
/// (as REAL on SQLite) and written as Rails writes a `BigDecimal`: `"50.0"`,
/// `"0.25"`, as a string, so no precision is lost on the way to a client.
///
/// Arithmetic is exact, and division rounds as Ruby's `BigDecimal#/` does
/// (see [`Div`](#impl-Div-for-Decimal)), so averages match a Rails app's to
/// the last digit.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Decimal(pub BigDecimal);

impl Decimal {
    pub fn new(value: BigDecimal) -> Self {
        Self(value)
    }

    pub fn to_f64(&self) -> f64 {
        self.0.to_f64().unwrap_or(0.0)
    }

    pub fn is_zero(&self) -> bool {
        self.0.is_zero()
    }
}

/// As ActiveSupport's `BigDecimal#to_s`: plain digits (never exponent
/// notation), no trailing zeros, but always a fractional part: `50.0`,
/// `50.25`.
impl fmt::Display for Decimal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (digits, scale) = normalized(&self.0);
        let negative = digits.sign() == Sign::Minus;
        let text = digits.magnitude().to_string();
        let (int, frac) = if scale <= 0 {
            let zeros = "0".repeat(usize::try_from(-scale).unwrap_or(0));
            (format!("{text}{zeros}"), String::from("0"))
        } else {
            let scale = usize::try_from(scale).unwrap_or(0);
            let padded = format!("{text:0>width$}", width = scale + 1);
            let (int, frac) = padded.split_at(padded.len() - scale);
            (int.to_owned(), frac.to_owned())
        };
        let sign = if negative { "-" } else { "" };
        write!(f, "{sign}{int}.{frac}")
    }
}

impl FromStr for Decimal {
    type Err = bigdecimal::ParseBigDecimalError;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        BigDecimal::from_str(text.trim()).map(Decimal)
    }
}

impl From<BigDecimal> for Decimal {
    fn from(value: BigDecimal) -> Self {
        Decimal(value)
    }
}

impl From<i64> for Decimal {
    fn from(value: i64) -> Self {
        Decimal(value.into())
    }
}

impl From<i32> for Decimal {
    fn from(value: i32) -> Self {
        Decimal(value.into())
    }
}

macro_rules! exact_ops {
    ($($trait:ident $method:ident),*) => {$(
        impl std::ops::$trait for Decimal {
            type Output = Decimal;

            fn $method(self, other: Decimal) -> Decimal {
                Decimal(std::ops::$trait::$method(self.0, other.0))
            }
        }

        impl std::ops::$trait<&Decimal> for &Decimal {
            type Output = Decimal;

            fn $method(self, other: &Decimal) -> Decimal {
                Decimal(std::ops::$trait::$method(&self.0, &other.0))
            }
        }
    )*};
}

exact_ops!(Add add, Sub sub, Mul mul);

/// Division as Ruby's `BigDecimal#/` (bigdecimal 3.1) computes it, so a
/// Rails app's averages come out digit for digit: the quotient is kept to
/// the larger operand's precision doubled (at least 32 digits) plus two
/// base-10⁹ words, truncated at a word boundary, then its last digit is
/// rounded half-up from an estimate of the next word.
///
/// # Panics
///
/// On division by zero, as integer division does (Ruby raises
/// `ZeroDivisionError`).
impl std::ops::Div for Decimal {
    type Output = Decimal;

    fn div(self, other: Decimal) -> Decimal {
        &self / &other
    }
}

impl std::ops::Div<&Decimal> for &Decimal {
    type Output = Decimal;

    fn div(self, other: &Decimal) -> Decimal {
        Decimal(ruby_div(&self.0, &other.0))
    }
}

impl std::iter::Sum for Decimal {
    fn sum<I: Iterator<Item = Decimal>>(iter: I) -> Decimal {
        iter.fold(Decimal::default(), |total, d| total + d)
    }
}

impl<'a> std::iter::Sum<&'a Decimal> for Decimal {
    fn sum<I: Iterator<Item = &'a Decimal>>(iter: I) -> Decimal {
        iter.fold(Decimal::default(), |total, d| &total + d)
    }
}

impl Serialize for Decimal {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.collect_str(self)
    }
}

/// Digits and scale (value = digits × 10^-scale) without trailing zeros.
fn normalized(value: &BigDecimal) -> (BigInt, i64) {
    if value.is_zero() {
        return (BigInt::zero(), 0);
    }
    let (mut digits, mut scale) = value.as_bigint_and_exponent();
    let ten = BigInt::from(10);
    while (&digits % &ten).is_zero() {
        digits /= &ten;
        scale -= 1;
    }
    (digits, scale)
}

/// The value with no trailing zeros but at least one decimal place.
#[cfg_attr(not(feature = "postgres"), allow(dead_code))]
fn rails_form(value: &BigDecimal) -> BigDecimal {
    let (digits, scale) = normalized(value);
    if scale >= 1 {
        BigDecimal::new(digits, scale)
    } else {
        BigDecimal::new(digits * pow10(1 - scale), 1)
    }
}

fn digit_count(n: &BigInt) -> i64 {
    i64::try_from(n.magnitude().to_string().len()).unwrap_or(i64::MAX)
}

fn pow10(exponent: i64) -> BigInt {
    BigInt::from(10).pow(u32::try_from(exponent).expect("a power of ten"))
}

/// The precision Ruby's division works from (`BigDecimal#precision` in
/// bigdecimal 3.1), counted over its base-10⁹ words: a value below 1 counts
/// the zeros after the point up to its first word, and an integer counts
/// its trailing zeros (`100` has 3) but a fraction doesn't.
fn precision(value: &BigDecimal) -> i64 {
    let (digits, scale) = normalized(value);
    if digits.is_zero() {
        return 0;
    }
    let digits = BigInt::from(digits.magnitude().clone());
    let ex = word_exponent(&digits, scale);
    // The lowest word is worth 10^(9k): the largest k with 9k ≤ -scale.
    let k = (-scale).div_euclid(9);
    let n = ex - k;
    let first = leading_word(&digits, scale);
    let last = (&digits * pow10(-scale - 9 * k) % BigInt::from(1_000_000_000))
        .to_u64()
        .unwrap_or(0);
    let nlz = 9 - i64::try_from(first.to_string().len()).unwrap_or(9);
    let mut ntz = 0;
    let mut x = last;
    while x > 0 && x.is_multiple_of(10) {
        ntz += 1;
        x /= 10;
    }
    let mut head = 9;
    let mut ex = ex;
    if ex < 0 {
        head += -ex * 9;
        ex = 0;
    } else if ex > 0 {
        head -= nlz;
    }
    if ex > n {
        head + (ex - 1) * 9
    } else {
        head + (n - 1) * 9 - if ex < n { ntz } else { 0 }
    }
}

/// The base-10⁹ word exponent: `e` with 10^(9(e-1)) ≤ |value| < 10^(9e).
fn word_exponent(digits: &BigInt, scale: i64) -> i64 {
    (digit_count(digits) - scale + 8).div_euclid(9)
}

/// The leading base-10⁹ word of a nonzero value.
fn leading_word(digits: &BigInt, scale: i64) -> u64 {
    let magnitude = BigInt::from(digits.magnitude().clone());
    // value / 10^(9(e-1)) = digits × 10^(-scale - 9(e-1))
    let shift = -scale - 9 * (word_exponent(digits, scale) - 1);
    let word = if shift >= 0 {
        magnitude * pow10(shift)
    } else {
        magnitude / pow10(-shift)
    };
    word.to_u64().unwrap_or(0)
}

fn ruby_div(a: &BigDecimal, b: &BigDecimal) -> BigDecimal {
    assert!(!b.is_zero(), "division by zero");
    if a.is_zero() {
        return BigDecimal::zero();
    }
    if b.is_one() {
        return a.clone();
    }
    let (na, sa) = normalized(a);
    let (nb, sb) = normalized(b);
    let negative = (na.sign() == Sign::Minus) != (nb.sign() == Sign::Minus);
    let na = BigInt::from(na.magnitude().clone());
    let nb = BigInt::from(nb.magnitude().clone());

    // The digits Ruby allocates for the quotient, as base-10⁹ words.
    let mx = (precision(a).max(precision(b)) * 2).max(32);
    let word_c = (mx + 18 + 8) / 9;
    // The quotient's lowest word is worth 10^(9 × lowest).
    let lowest = word_exponent(&na, sa) - word_exponent(&nb, sb) + 2 - word_c;

    // q = floor(|a| / (|b| × 10^(9 × lowest))), exactly.
    let t = sb - sa - 9 * lowest;
    let (numerator, denominator) = if t >= 0 {
        (&na * pow10(t), nb.clone())
    } else {
        (na.clone(), &nb * pow10(-t))
    };
    let mut q = &numerator / &denominator;
    let remainder = &numerator - &q * &denominator;

    // Ruby rounds from the remainder's leading word over the divisor's,
    // ignoring their exponents and truncating to 32 bits, as it does.
    if !remainder.is_zero() {
        // The remainder in |a|'s units: remainder / 10^(max(t,0) + sa).
        let r_scale = sa + t.max(0);
        let r0 = leading_word(&remainder, r_scale);
        let b0 = leading_word(&nb, sb);
        #[allow(clippy::cast_possible_truncation)]
        let v = ((1_000_000_000u64 * r0) / b0.max(1)) as u32;
        if v != 0 && v / 100_000_000 >= 5 {
            q += 1;
        }
    }
    if negative {
        q = -q;
    }
    BigDecimal::new(q, -9 * lowest)
}

#[cfg(feature = "postgres")]
mod postgres {
    use bigdecimal::BigDecimal;
    use sqlx::encode::IsNull;
    use sqlx::error::BoxDynError;
    use sqlx::postgres::{PgArgumentBuffer, PgTypeInfo, PgValueRef, Postgres};
    use sqlx::{Decode, Encode, Type};

    use super::Decimal;

    impl Type<Postgres> for Decimal {
        fn type_info() -> PgTypeInfo {
            <BigDecimal as Type<Postgres>>::type_info()
        }
    }

    impl<'r> Decode<'r, Postgres> for Decimal {
        fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
            <BigDecimal as Decode<Postgres>>::decode(value).map(Decimal)
        }
    }

    /// Written as Rails writes a `BigDecimal` (its `to_s`): no trailing
    /// zeros but at least one decimal place, so `100` is stored as `100.0`.
    impl Encode<'_, Postgres> for Decimal {
        fn encode_by_ref(&self, buf: &mut PgArgumentBuffer) -> Result<IsNull, BoxDynError> {
            <BigDecimal as Encode<Postgres>>::encode_by_ref(&super::rails_form(&self.0), buf)
        }
    }
}

#[cfg(feature = "sqlite")]
mod sqlite {
    use std::str::FromStr;

    use bigdecimal::BigDecimal;
    use sqlx::encode::IsNull;
    use sqlx::error::BoxDynError;
    use sqlx::sqlite::{Sqlite, SqliteArgumentsBuffer, SqliteTypeInfo, SqliteValueRef};
    use sqlx::{Decode, Encode, Type};

    use super::Decimal;

    impl Type<Sqlite> for Decimal {
        fn type_info() -> SqliteTypeInfo {
            <f64 as Type<Sqlite>>::type_info()
        }

        // NUMERIC columns hold integers, reals or text.
        fn compatible(_: &SqliteTypeInfo) -> bool {
            true
        }
    }

    impl<'r> Decode<'r, Sqlite> for Decimal {
        fn decode(value: SqliteValueRef<'r>) -> Result<Self, BoxDynError> {
            let float = <f64 as Decode<Sqlite>>::decode(value)?;
            // Through its shortest text, so 0.1 reads as 0.1.
            BigDecimal::from_str(&float.to_string())
                .map(Decimal)
                .map_err(|_| format!("{float} is not a decimal").into())
        }
    }

    impl Encode<'_, Sqlite> for Decimal {
        fn encode_by_ref(&self, buf: &mut SqliteArgumentsBuffer) -> Result<IsNull, BoxDynError> {
            <f64 as Encode<Sqlite>>::encode_by_ref(&self.to_f64(), buf)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn d(text: &str) -> Decimal {
        Decimal::from_str(text).unwrap()
    }

    #[test]
    fn writes_as_rails_does() {
        let s = |text: &str| d(text).to_string();
        assert_eq!(s("50"), "50.0");
        assert_eq!(s("50.00"), "50.0");
        assert_eq!(s("50.250"), "50.25");
        assert_eq!(s("-0.5"), "-0.5");
        assert_eq!(s("1e20"), "100000000000000000000.0");
        assert_eq!(s("0.000123"), "0.000123");
        assert_eq!(
            serde_json::to_string(&Decimal::from(3)).unwrap(),
            r#""3.0""#
        );
    }

    #[test]
    fn divides_as_ruby_does() {
        // Each from Ruby 3.2's bigdecimal 3.1.3: (BigDecimal(a) / BigDecimal(b)).to_s("F").
        let cases = [
            ("1", "3", "0.333333333333333333333333333333333333"),
            ("2", "3", "0.666666666666666666666666666666666667"),
            ("200", "3", "66.666666666666666666666666666666666667"),
            (
                "12345.6789",
                "7",
                "1763.668414285714285714285714285714285714",
            ),
            (
                "1.23456789012345678901234567890",
                "3",
                "0.4115226300411522630041152263",
            ),
            ("100", "8", "12.5"),
            ("1", "7", "0.142857142857142857142857142857142857"),
            (
                "0.001",
                "3",
                "0.000333333333333333333333333333333333333333333",
            ),
            ("9", "7", "1.285714285714285714285714285714285714"),
            ("1", "300", "0.003333333333333333333333333333333333"),
            ("50.5", "3", "16.833333333333333333333333333333333333"),
            ("-2", "3", "-0.666666666666666666666666666666666667"),
            ("7", "1", "7.0"),
            // Small operands: Ruby counts their leading zero words.
            (
                "0.00000000000264238891865",
                "3",
                "0.000000000000880796306216666666666666666666666666666666666666666666666667",
            ),
            (
                "-0.000004",
                "0.0000000000570914868260565052558237894069",
                "-70062.985260604624091141219373855968543852591860891222131187381483034565983886",
            ),
        ];
        for (a, b, expected) in cases {
            assert_eq!((d(a) / d(b)).to_string(), expected, "{a} / {b}");
        }
    }
}