/// PostgreSQL's `NUMERIC` (OID 1700) as `std/dec`'s `Dec` (ADR 0070). /// /// The binary form is `be16 ndigits`, `be16 weight`, `be16 sign`, /// `be16 dscale`, then `ndigits` base-10000 digits (be16 each), the /// value `Σ digit[i] · 10000^(weight - i)`. A `Dec` always encodes /// exactly (18 places fit NUMERIC's 16383); decoding rounds half-even /// past 18 places (the one rule of `std/dec`) and is an `Error` on NaN, /// an infinity, or an integral part out of `Dec`'s range — never a /// silent truncation. import std/bytes import std/dec.{type Dec} import std/list import std/result import binary /// The numeric at the start of `b` (the whole buffer: a column's value). pub fn to_dec :: b: Bytes -> Result { if bytes.length b < 8 { Error("numeric: short header") } else { let ndigits = binary.u16_at b 0 let weight = binary.i16_at b 2 let sign = binary.u16_at b 4 if bytes.length b < 8 + ndigits * 2 { Error("numeric: short digits") } else { match sign { 0 -> decode b ndigits weight False , 16384 -> decode b ndigits weight True // 0x4000: negative , 49152 -> Error("numeric: NaN is not a Dec") // 0xC000 , 53248 -> Error("numeric: +Infinity is not a Dec") // 0xD000 , 61440 -> Error("numeric: -Infinity is not a Dec") // 0xF000 , _ -> Error("numeric: unknown sign {sign}") } } } } fn decode :: b: Bytes ndigits: Int weight: Int negative: Bool -> Result { // The exact value as `n · 10000^e`, with `n` an integer. let n = digits b ndigits 0 0 let e = weight - ndigits + 1 let scaled = if e >= 0 { n * pow10k e * 1000000000000000000 } else { div_round_half_even (n * 1000000000000000000) (pow10k (0 - e)) } let signed = if negative { 0 - scaled } else { scaled } dec.from_scaled signed |> result.map_error fn msg { "numeric: {msg}" } } /// The base-10000 digits as one integer (`d[0]·10000^(n-1) + … + d[n-1]`). fn digits :: b: Bytes ndigits: Int at: Int acc: Int -> Int { if at >= ndigits { acc } else { digits b ndigits (at + 1) (acc * 10000 + binary.u16_at b (8 + at * 2)) } } /// `10000^k` (`k >= 0`). fn pow10k :: k: Int -> Int { if k <= 0 { 1 } else { pow10k (k - 1) * 10000 } } /// `n / d` with the remainder rounded to the nearest quotient, ties to /// even (the rule of `std/dec`; `d` must be positive). pub fn div_round_half_even :: n: Int d: Int -> Int { let q = n / d let r = n % d // the sign of n let twice = (if r < 0 { 0 - r } else { r }) * 2 let step = if n < 0 { -1 } else { 1 } if twice > d { q + step } else if twice == d { if q % 2 == 0 { q } else { q + step } } else { q } } /// `d` in the binary form. Always exact; zero is `ndigits = 0`. pub fn from_dec :: d: Dec -> Bytes { let s = dec.scaled d let negative = s < 0 let mag = if negative { 0 - s } else { s } if mag == 0 { bytes.from_list [0, 0, 0, 0, 0, 0, 0, 0] } else { // 18 fractional digits are 4.5 base-10000 groups; two more decimal // digits (the value unchanged) align the fraction to 5 whole groups. let groups = groups_of (mag * 100) [] let weight = list.length groups - 6 // Trailing zero groups only pad the fraction: strip them (4 fewer // `dscale` digits each). The weight is the first group's exponent, // untouched by the strip. let kept = strip_trailing_zeros groups let ndigits = list.length kept let dscale = 20 - 4 * (list.length groups - ndigits) let sign = if negative { 16384 } else { 0 } let be = fn n { bytes.to_list (binary.be16 n) } bytes.from_list ( be ndigits <> be weight <> be sign <> be dscale <> list.fold kept [] fn acc g { acc <> be g } ) } } /// `n`'s base-10000 digits, most significant first (`[]` for 0). fn groups_of :: n: Int acc: List -> List { if n == 0 { acc } else { groups_of (n / 10000) [n % 10000, ..acc] } } fn strip_trailing_zeros :: groups: List -> List { let reversed = list.reverse groups list.reverse (drop_zeros reversed) } fn drop_zeros :: groups: List -> List { match groups { [0, ..rest] -> drop_zeros rest, _ -> groups } } // ---- tests -------------------------------------------------------------------- import std/test.{assert_equal} fn d :: s: String -> Dec { result.expect (dec.parse s) "a decimal" } @test fn numeric_binary_vectors :: { // 1.5: ndigits 2, weight 0, sign 0, dscale 4, digits 1 and 5000. let encoded = from_dec (d "1.5") assert_equal (bytes.to_list encoded) [0, 2, 0, 0, 0, 0, 0, 4, 0, 1, 19, 136] assert_equal (to_dec encoded) (Ok(d "1.5")) // 0 is ndigits 0; -42 is one digit with the negative sign. assert_equal (bytes.to_list (from_dec (d "0"))) [0, 0, 0, 0, 0, 0, 0, 0] assert_equal (bytes.to_list (from_dec (d "-42"))) [0, 1, 0, 0, 64, 0, 0, 0, 0, 42] // The full precision: 18 places, then stripped trailing zero groups. let pi = d "3.141592653589793238" assert_equal (to_dec (from_dec pi)) (Ok(pi)) // Past 18 places the decode rounds half-even, as dec.parse does: 1/3 // as NUMERIC is five groups of 3333 (dscale 20). let third = bytes.from_list [0, 5, 255, 255, 0, 0, 0, 20, 13, 5, 13, 5, 13, 5, 13, 5, 13, 5] assert_equal (to_dec third) (Ok(d "0.333333333333333333")) // NaN and out-of-range are errors, never silent. assert_equal (to_dec (bytes.from_list [0, 0, 0, 0, 192, 0, 0, 0])) (Error("numeric: NaN is not a Dec")) // 10^24: ndigits 6, weight 6, digits 1 then zeros. let huge = bytes.from_list [0, 6, 0, 6, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] match to_dec huge { Error(_) -> (), Ok(v) -> panic "1e24 should not fit a Dec, got {v}" } } @test fn div_round_half_even_matches_the_dec_rule :: { assert_equal (div_round_half_even 5 10) 0 // 0.5, tie, 0 even assert_equal (div_round_half_even 15 10) 2 // 1.5, tie, 1 odd -> 2 assert_equal (div_round_half_even 25 10) 2 // 2.5, tie, 2 even -> 2 assert_equal (div_round_half_even (-15) 10) (-2) assert_equal (div_round_half_even (-25) 10) (-2) assert_equal (div_round_half_even 14 10) 1 assert_equal (div_round_half_even 16 10) 2 }