tobogganSe connecter

packages

The Louise packages, each released on its own

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

231 lignes · 6313 octetsBrut · Historique
1/// PostgreSQL's `NUMERIC` (OID 1700) as `std/dec`'s `Dec` (ADR 0070).
2///
3/// The binary form is `be16 ndigits`, `be16 weight`, `be16 sign`,
4/// `be16 dscale`, then `ndigits` base-10000 digits (be16 each), the
5/// value `Σ digit[i] · 10000^(weight - i)`. A `Dec` always encodes
6/// exactly (18 places fit NUMERIC's 16383); decoding rounds half-even
7/// past 18 places (the one rule of `std/dec`) and is an `Error` on NaN,
8/// an infinity, or an integral part out of `Dec`'s range — never a
9/// silent truncation.
10
11import std/bytes
12import std/dec.{type Dec}
13import std/list
14import std/result
15
16import binary
17
18/// The numeric at the start of `b` (the whole buffer: a column's value).
19pub fn to_dec :: b: Bytes -> Result<Dec, String>
20{
21 if bytes.length b < 8
22 {
23 Error("numeric: short header")
24 }
25 else
26 {
27 let ndigits = binary.u16_at b 0
28 let weight = binary.i16_at b 2
29 let sign = binary.u16_at b 4
30 if bytes.length b < 8 + ndigits * 2
31 {
32 Error("numeric: short digits")
33 }
34 else
35 {
36 match sign
37 { 0 -> decode b ndigits weight False
38 , 16384 -> decode b ndigits weight True // 0x4000: negative
39 , 49152 -> Error("numeric: NaN is not a Dec") // 0xC000
40 , 53248 -> Error("numeric: +Infinity is not a Dec") // 0xD000
41 , 61440 -> Error("numeric: -Infinity is not a Dec") // 0xF000
42 , _ -> Error("numeric: unknown sign {sign}")
43 }
44 }
45 }
46}
47
48fn decode ::
49 b: Bytes
50 ndigits: Int
51 weight: Int
52 negative: Bool
53 -> Result<Dec, String>
54{
55 // The exact value as `n · 10000^e`, with `n` an integer.
56 let n = digits b ndigits 0 0
57 let e = weight - ndigits + 1
58 let scaled = if e >= 0
59 {
60 n * pow10k e * 1000000000000000000
61 }
62 else
63 {
64 div_round_half_even (n * 1000000000000000000) (pow10k (0 - e))
65 }
66 let signed = if negative { 0 - scaled } else { scaled }
67 dec.from_scaled signed |> result.map_error fn msg { "numeric: {msg}" }
68}
69
70/// The base-10000 digits as one integer (`d[0]·10000^(n-1) + … + d[n-1]`).
71fn digits :: b: Bytes ndigits: Int at: Int acc: Int -> Int
72{
73 if at >= ndigits
74 {
75 acc
76 }
77 else
78 {
79 digits b ndigits (at + 1) (acc * 10000 + binary.u16_at b (8 + at * 2))
80 }
81}
82
83/// `10000^k` (`k >= 0`).
84fn pow10k :: k: Int -> Int
85{
86 if k <= 0
87 {
88 1
89 }
90 else
91 {
92 pow10k (k - 1) * 10000
93 }
94}
95
96/// `n / d` with the remainder rounded to the nearest quotient, ties to
97/// even (the rule of `std/dec`; `d` must be positive).
98pub fn div_round_half_even :: n: Int d: Int -> Int
99{
100 let q = n / d
101 let r = n % d // the sign of n
102 let twice = (if r < 0 { 0 - r } else { r }) * 2
103 let step = if n < 0 { -1 } else { 1 }
104 if twice > d
105 {
106 q + step
107 }
108 else if twice == d
109 {
110 if q % 2 == 0
111 {
112 q
113 }
114 else
115 {
116 q + step
117 }
118 }
119 else
120 {
121 q
122 }
123}
124
125/// `d` in the binary form. Always exact; zero is `ndigits = 0`.
126pub fn from_dec :: d: Dec -> Bytes
127{
128 let s = dec.scaled d
129 let negative = s < 0
130 let mag = if negative { 0 - s } else { s }
131 if mag == 0
132 {
133 bytes.from_list [0, 0, 0, 0, 0, 0, 0, 0]
134 }
135 else
136 {
137 // 18 fractional digits are 4.5 base-10000 groups; two more decimal
138 // digits (the value unchanged) align the fraction to 5 whole groups.
139 let groups = groups_of (mag * 100) []
140 let weight = list.length groups - 6
141 // Trailing zero groups only pad the fraction: strip them (4 fewer
142 // `dscale` digits each). The weight is the first group's exponent,
143 // untouched by the strip.
144 let kept = strip_trailing_zeros groups
145 let ndigits = list.length kept
146 let dscale = 20 - 4 * (list.length groups - ndigits)
147 let sign = if negative { 16384 } else { 0 }
148 let be = fn n { bytes.to_list (binary.be16 n) }
149 bytes.from_list
150 ( be ndigits <> be weight <> be sign <> be dscale
151 <> list.fold kept [] fn acc g { acc <> be g }
152 )
153 }
154}
155
156/// `n`'s base-10000 digits, most significant first (`[]` for 0).
157fn groups_of :: n: Int acc: List<Int> -> List<Int>
158{
159 if n == 0
160 {
161 acc
162 }
163 else
164 {
165 groups_of (n / 10000) [n % 10000, ..acc]
166 }
167}
168
169fn strip_trailing_zeros :: groups: List<Int> -> List<Int>
170{
171 let reversed = list.reverse groups
172 list.reverse (drop_zeros reversed)
173}
174
175fn drop_zeros :: groups: List<Int> -> List<Int>
176{
177 match groups { [0, ..rest] -> drop_zeros rest, _ -> groups }
178}
179
180// ---- tests --------------------------------------------------------------------
181
182import std/test.{assert_equal}
183
184fn d :: s: String -> Dec
185{
186 result.expect (dec.parse s) "a decimal"
187}
188
189@test
190fn numeric_binary_vectors ::
191{
192 // 1.5: ndigits 2, weight 0, sign 0, dscale 4, digits 1 and 5000.
193 let encoded = from_dec (d "1.5")
194 assert_equal (bytes.to_list encoded) [0, 2, 0, 0, 0, 0, 0, 4, 0, 1, 19, 136]
195 assert_equal (to_dec encoded) (Ok(d "1.5"))
196 // 0 is ndigits 0; -42 is one digit with the negative sign.
197 assert_equal (bytes.to_list (from_dec (d "0"))) [0, 0, 0, 0, 0, 0, 0, 0]
198 assert_equal
199 (bytes.to_list (from_dec (d "-42")))
200 [0, 1, 0, 0, 64, 0, 0, 0, 0, 42]
201 // The full precision: 18 places, then stripped trailing zero groups.
202 let pi = d "3.141592653589793238"
203 assert_equal (to_dec (from_dec pi)) (Ok(pi))
204 // Past 18 places the decode rounds half-even, as dec.parse does: 1/3
205 // as NUMERIC is five groups of 3333 (dscale 20).
206 let third =
207 bytes.from_list
208 [0, 5, 255, 255, 0, 0, 0, 20, 13, 5, 13, 5, 13, 5, 13, 5, 13, 5]
209 assert_equal (to_dec third) (Ok(d "0.333333333333333333"))
210 // NaN and out-of-range are errors, never silent.
211 assert_equal
212 (to_dec (bytes.from_list [0, 0, 0, 0, 192, 0, 0, 0]))
213 (Error("numeric: NaN is not a Dec"))
214 // 10^24: ndigits 6, weight 6, digits 1 then zeros.
215 let huge =
216 bytes.from_list [0, 6, 0, 6, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
217 match to_dec huge
218 { Error(_) -> (), Ok(v) -> panic "1e24 should not fit a Dec, got {v}" }
219}
220
221@test
222fn div_round_half_even_matches_the_dec_rule ::
223{
224 assert_equal (div_round_half_even 5 10) 0 // 0.5, tie, 0 even
225 assert_equal (div_round_half_even 15 10) 2 // 1.5, tie, 1 odd -> 2
226 assert_equal (div_round_half_even 25 10) 2 // 2.5, tie, 2 even -> 2
227 assert_equal (div_round_half_even (-15) 10) (-2)
228 assert_equal (div_round_half_even (-25) 10) (-2)
229 assert_equal (div_round_half_even 14 10) 1
230 assert_equal (div_round_half_even 16 10) 2
231}