Debian Codegraph @

src/backend/utils/adt/numeric.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * numeric.c
4 * An exact numeric data type for the Postgres database system
5 *
6 * Original coding 1998, Jan Wieck. Heavily revised 2003, Tom Lane.
7 *
8 * Many of the algorithmic ideas are borrowed from David M. Smith's "FM"
9 * multiple-precision math library, most recently published as Algorithm
10 * 786: Multiple-Precision Complex Arithmetic and Functions, ACM
11 * Transactions on Mathematical Software, Vol. 24, No. 4, December 1998,
12 * pages 359-367.
13 *
14 * Copyright (c) 1998-2025, PostgreSQL Global Development Group
15 *
16 * IDENTIFICATION
17 * src/backend/utils/adt/numeric.c
18 *
19 *-------------------------------------------------------------------------
20 */
21
22 #include "postgres.h"
23
24 #include <ctype.h>
25 #include <float.h>
26 #include <limits.h>
27 #include <math.h>
28
29 #include "common/hashfn.h"
30 #include "common/int.h"
31 #include "funcapi.h"
32 #include "lib/hyperloglog.h"
33 #include "libpq/pqformat.h"
34 #include "miscadmin.h"
35 #include "nodes/nodeFuncs.h"
36 #include "nodes/supportnodes.h"
37 #include "optimizer/optimizer.h"
38 #include "utils/array.h"
39 #include "utils/builtins.h"
40 #include "utils/float.h"
41 #include "utils/guc.h"
42 #include "utils/numeric.h"
43 #include "utils/pg_lsn.h"
44 #include "utils/sortsupport.h"
45
46 /* ----------
47 * Uncomment the following to enable compilation of dump_numeric()
48 * and dump_var() and to get a dump of any result produced by make_result().
49 * ----------
50 #define NUMERIC_DEBUG
51 */
52
53
54 /* ----------
55 * Local data types
56 *
57 * Numeric values are represented in a base-NBASE floating point format.
58 * Each "digit" ranges from 0 to NBASE-1. The type NumericDigit is signed
59 * and wide enough to store a digit. We assume that NBASE*NBASE can fit in
60 * an int. Although the purely calculational routines could handle any even
61 * NBASE that's less than sqrt(INT_MAX), in practice we are only interested
62 * in NBASE a power of ten, so that I/O conversions and decimal rounding
63 * are easy. Also, it's actually more efficient if NBASE is rather less than
64 * sqrt(INT_MAX), so that there is "headroom" for mul_var and div_var to
65 * postpone processing carries.
66 *
67 * Values of NBASE other than 10000 are considered of historical interest only
68 * and are no longer supported in any sense; no mechanism exists for the client
69 * to discover the base, so every client supporting binary mode expects the
70 * base-10000 format. If you plan to change this, also note the numeric
71 * abbreviation code, which assumes NBASE=10000.
72 * ----------
73 */
74
75 #if 0
76 #define NBASE 10
77 #define HALF_NBASE 5
78 #define DEC_DIGITS 1 /* decimal digits per NBASE digit */
79 #define MUL_GUARD_DIGITS 4 /* these are measured in NBASE digits */
80 #define DIV_GUARD_DIGITS 8
81
82 typedef signed char NumericDigit;
83 #endif
84
85 #if 0
86 #define NBASE 100
87 #define HALF_NBASE 50
88 #define DEC_DIGITS 2 /* decimal digits per NBASE digit */
89 #define MUL_GUARD_DIGITS 3 /* these are measured in NBASE digits */
90 #define DIV_GUARD_DIGITS 6
91
92 typedef signed char NumericDigit;
93 #endif
94
95 #if 1
96 #define NBASE 10000
97 #define HALF_NBASE 5000
98 #define DEC_DIGITS 4 /* decimal digits per NBASE digit */
99 #define MUL_GUARD_DIGITS 2 /* these are measured in NBASE digits */
100 #define DIV_GUARD_DIGITS 4
101
102 typedef int16 NumericDigit;
103 #endif
104
105 #define NBASE_SQR (NBASE * NBASE)
106
107 /*
108 * The Numeric type as stored on disk.
109 *
110 * If the high bits of the first word of a NumericChoice (n_header, or
111 * n_short.n_header, or n_long.n_sign_dscale) are NUMERIC_SHORT, then the
112 * numeric follows the NumericShort format; if they are NUMERIC_POS or
113 * NUMERIC_NEG, it follows the NumericLong format. If they are NUMERIC_SPECIAL,
114 * the value is a NaN or Infinity. We currently always store SPECIAL values
115 * using just two bytes (i.e. only n_header), but previous releases used only
116 * the NumericLong format, so we might find 4-byte NaNs (though not infinities)
117 * on disk if a database has been migrated using pg_upgrade. In either case,
118 * the low-order bits of a special value's header are reserved and currently
119 * should always be set to zero.
120 *
121 * In the NumericShort format, the remaining 14 bits of the header word
122 * (n_short.n_header) are allocated as follows: 1 for sign (positive or
123 * negative), 6 for dynamic scale, and 7 for weight. In practice, most
124 * commonly-encountered values can be represented this way.
125 *
126 * In the NumericLong format, the remaining 14 bits of the header word
127 * (n_long.n_sign_dscale) represent the display scale; and the weight is
128 * stored separately in n_weight.
129 *
130 * NOTE: by convention, values in the packed form have been stripped of
131 * all leading and trailing zero digits (where a "digit" is of base NBASE).
132 * In particular, if the value is zero, there will be no digits at all!
133 * The weight is arbitrary in that case, but we normally set it to zero.
134 */
135
136 struct NumericShort
137 {
138 uint16 n_header; /* Sign + display scale + weight */
139 NumericDigit n_data[FLEXIBLE_ARRAY_MEMBER]; /* Digits */
140 };
141
142 struct NumericLong
143 {
144 uint16 n_sign_dscale; /* Sign + display scale */
145 int16 n_weight; /* Weight of 1st digit */
146 NumericDigit n_data[FLEXIBLE_ARRAY_MEMBER]; /* Digits */
147 };
148
149 union NumericChoice
150 {
151 uint16 n_header; /* Header word */
152 struct NumericLong n_long; /* Long form (4-byte header) */
153 struct NumericShort n_short; /* Short form (2-byte header) */
154 };
155
156 struct NumericData
157 {
158 int32 vl_len_; /* varlena header (do not touch directly!) */
159 union NumericChoice choice; /* choice of format */
160 };
161
162
163 /*
164 * Interpretation of high bits.
165 */
166
167 #define NUMERIC_SIGN_MASK 0xC000
168 #define NUMERIC_POS 0x0000
169 #define NUMERIC_NEG 0x4000
170 #define NUMERIC_SHORT 0x8000
171 #define NUMERIC_SPECIAL 0xC000
172
173 #define NUMERIC_FLAGBITS(n) ((n)->choice.n_header & NUMERIC_SIGN_MASK)
174 #define NUMERIC_IS_SHORT(n) (NUMERIC_FLAGBITS(n) == NUMERIC_SHORT)
175 #define NUMERIC_IS_SPECIAL(n) (NUMERIC_FLAGBITS(n) == NUMERIC_SPECIAL)
176
177 #define NUMERIC_HDRSZ (VARHDRSZ + sizeof(uint16) + sizeof(int16))
178 #define NUMERIC_HDRSZ_SHORT (VARHDRSZ + sizeof(uint16))
179
180 /*
181 * If the flag bits are NUMERIC_SHORT or NUMERIC_SPECIAL, we want the short
182 * header; otherwise, we want the long one. Instead of testing against each
183 * value, we can just look at the high bit, for a slight efficiency gain.
184 */
185 #define NUMERIC_HEADER_IS_SHORT(n) (((n)->choice.n_header & 0x8000) != 0)
186 #define NUMERIC_HEADER_SIZE(n) \
187 (VARHDRSZ + sizeof(uint16) + \
188 (NUMERIC_HEADER_IS_SHORT(n) ? 0 : sizeof(int16)))
189
190 /*
191 * Definitions for special values (NaN, positive infinity, negative infinity).
192 *
193 * The two bits after the NUMERIC_SPECIAL bits are 00 for NaN, 01 for positive
194 * infinity, 11 for negative infinity. (This makes the sign bit match where
195 * it is in a short-format value, though we make no use of that at present.)
196 * We could mask off the remaining bits before testing the active bits, but
197 * currently those bits must be zeroes, so masking would just add cycles.
198 */
199 #define NUMERIC_EXT_SIGN_MASK 0xF000 /* high bits plus NaN/Inf flag bits */
200 #define NUMERIC_NAN 0xC000
201 #define NUMERIC_PINF 0xD000
202 #define NUMERIC_NINF 0xF000
203 #define NUMERIC_INF_SIGN_MASK 0x2000
204
205 #define NUMERIC_EXT_FLAGBITS(n) ((n)->choice.n_header & NUMERIC_EXT_SIGN_MASK)
206 #define NUMERIC_IS_NAN(n) ((n)->choice.n_header == NUMERIC_NAN)
207 #define NUMERIC_IS_PINF(n) ((n)->choice.n_header == NUMERIC_PINF)
208 #define NUMERIC_IS_NINF(n) ((n)->choice.n_header == NUMERIC_NINF)
209 #define NUMERIC_IS_INF(n) \
210 (((n)->choice.n_header & ~NUMERIC_INF_SIGN_MASK) == NUMERIC_PINF)
211
212 /*
213 * Short format definitions.
214 */
215
216 #define NUMERIC_SHORT_SIGN_MASK 0x2000
217 #define NUMERIC_SHORT_DSCALE_MASK 0x1F80
218 #define NUMERIC_SHORT_DSCALE_SHIFT 7
219 #define NUMERIC_SHORT_DSCALE_MAX \
220 (NUMERIC_SHORT_DSCALE_MASK >> NUMERIC_SHORT_DSCALE_SHIFT)
221 #define NUMERIC_SHORT_WEIGHT_SIGN_MASK 0x0040
222 #define NUMERIC_SHORT_WEIGHT_MASK 0x003F
223 #define NUMERIC_SHORT_WEIGHT_MAX NUMERIC_SHORT_WEIGHT_MASK
224 #define NUMERIC_SHORT_WEIGHT_MIN (-(NUMERIC_SHORT_WEIGHT_MASK+1))
225
226 /*
227 * Extract sign, display scale, weight. These macros extract field values
228 * suitable for the NumericVar format from the Numeric (on-disk) format.
229 *
230 * Note that we don't trouble to ensure that dscale and weight read as zero
231 * for an infinity; however, that doesn't matter since we never convert
232 * "special" numerics to NumericVar form. Only the constants defined below
233 * (const_nan, etc) ever represent a non-finite value as a NumericVar.
234 */
235
236 #define NUMERIC_DSCALE_MASK 0x3FFF
237 #define NUMERIC_DSCALE_MAX NUMERIC_DSCALE_MASK
238
239 #define NUMERIC_SIGN(n) \
240 (NUMERIC_IS_SHORT(n) ? \
241 (((n)->choice.n_short.n_header & NUMERIC_SHORT_SIGN_MASK) ? \
242 NUMERIC_NEG : NUMERIC_POS) : \
243 (NUMERIC_IS_SPECIAL(n) ? \
244 NUMERIC_EXT_FLAGBITS(n) : NUMERIC_FLAGBITS(n)))
245 #define NUMERIC_DSCALE(n) (NUMERIC_HEADER_IS_SHORT((n)) ? \
246 ((n)->choice.n_short.n_header & NUMERIC_SHORT_DSCALE_MASK) \
247 >> NUMERIC_SHORT_DSCALE_SHIFT \
248 : ((n)->choice.n_long.n_sign_dscale & NUMERIC_DSCALE_MASK))
249 #define NUMERIC_WEIGHT(n) (NUMERIC_HEADER_IS_SHORT((n)) ? \
250 (((n)->choice.n_short.n_header & NUMERIC_SHORT_WEIGHT_SIGN_MASK ? \
251 ~NUMERIC_SHORT_WEIGHT_MASK : 0) \
252 | ((n)->choice.n_short.n_header & NUMERIC_SHORT_WEIGHT_MASK)) \
253 : ((n)->choice.n_long.n_weight))
254
255 /*
256 * Maximum weight of a stored Numeric value (based on the use of int16 for the
257 * weight in NumericLong). Note that intermediate values held in NumericVar
258 * and NumericSumAccum variables may have much larger weights.
259 */
260 #define NUMERIC_WEIGHT_MAX PG_INT16_MAX
261
262 /* ----------
263 * NumericVar is the format we use for arithmetic. The digit-array part
264 * is the same as the NumericData storage format, but the header is more
265 * complex.
266 *
267 * The value represented by a NumericVar is determined by the sign, weight,
268 * ndigits, and digits[] array. If it is a "special" value (NaN or Inf)
269 * then only the sign field matters; ndigits should be zero, and the weight
270 * and dscale fields are ignored.
271 *
272 * Note: the first digit of a NumericVar's value is assumed to be multiplied
273 * by NBASE ** weight. Another way to say it is that there are weight+1
274 * digits before the decimal point. It is possible to have weight < 0.
275 *
276 * buf points at the physical start of the palloc'd digit buffer for the
277 * NumericVar. digits points at the first digit in actual use (the one
278 * with the specified weight). We normally leave an unused digit or two
279 * (preset to zeroes) between buf and digits, so that there is room to store
280 * a carry out of the top digit without reallocating space. We just need to
281 * decrement digits (and increment weight) to make room for the carry digit.
282 * (There is no such extra space in a numeric value stored in the database,
283 * only in a NumericVar in memory.)
284 *
285 * If buf is NULL then the digit buffer isn't actually palloc'd and should
286 * not be freed --- see the constants below for an example.
287 *
288 * dscale, or display scale, is the nominal precision expressed as number
289 * of digits after the decimal point (it must always be >= 0 at present).
290 * dscale may be more than the number of physically stored fractional digits,
291 * implying that we have suppressed storage of significant trailing zeroes.
292 * It should never be less than the number of stored digits, since that would
293 * imply hiding digits that are present. NOTE that dscale is always expressed
294 * in *decimal* digits, and so it may correspond to a fractional number of
295 * base-NBASE digits --- divide by DEC_DIGITS to convert to NBASE digits.
296 *
297 * rscale, or result scale, is the target precision for a computation.
298 * Like dscale it is expressed as number of *decimal* digits after the decimal
299 * point, and is always >= 0 at present.
300 * Note that rscale is not stored in variables --- it's figured on-the-fly
301 * from the dscales of the inputs.
302 *
303 * While we consistently use "weight" to refer to the base-NBASE weight of
304 * a numeric value, it is convenient in some scale-related calculations to
305 * make use of the base-10 weight (ie, the approximate log10 of the value).
306 * To avoid confusion, such a decimal-units weight is called a "dweight".
307 *
308 * NB: All the variable-level functions are written in a style that makes it
309 * possible to give one and the same variable as argument and destination.
310 * This is feasible because the digit buffer is separate from the variable.
311 * ----------
312 */
313 typedef struct NumericVar
314 {
315 int ndigits; /* # of digits in digits[] - can be 0! */
316 int weight; /* weight of first digit */
317 int sign; /* NUMERIC_POS, _NEG, _NAN, _PINF, or _NINF */
318 int dscale; /* display scale */
319 NumericDigit *buf; /* start of palloc'd space for digits[] */
320 NumericDigit *digits; /* base-NBASE digits */
321 } NumericVar;
322
323
324 /* ----------
325 * Data for generate_series
326 * ----------
327 */
328 typedef struct
329 {
330 NumericVar current;
331 NumericVar stop;
332 NumericVar step;
333 } generate_series_numeric_fctx;
334
335
336 /* ----------
337 * Sort support.
338 * ----------
339 */
340 typedef struct
341 {
342 void *buf; /* buffer for short varlenas */
343 int64 input_count; /* number of non-null values seen */
344 bool estimating; /* true if estimating cardinality */
345
346 hyperLogLogState abbr_card; /* cardinality estimator */
347 } NumericSortSupport;
348
349
350 /* ----------
351 * Fast sum accumulator.
352 *
353 * NumericSumAccum is used to implement SUM(), and other standard aggregates
354 * that track the sum of input values. It uses 32-bit integers to store the
355 * digits, instead of the normal 16-bit integers (with NBASE=10000). This
356 * way, we can safely accumulate up to NBASE - 1 values without propagating
357 * carry, before risking overflow of any of the digits. 'num_uncarried'
358 * tracks how many values have been accumulated without propagating carry.
359 *
360 * Positive and negative values are accumulated separately, in 'pos_digits'
361 * and 'neg_digits'. This is simpler and faster than deciding whether to add
362 * or subtract from the current value, for each new value (see sub_var() for
363 * the logic we avoid by doing this). Both buffers are of same size, and
364 * have the same weight and scale. In accum_sum_final(), the positive and
365 * negative sums are added together to produce the final result.
366 *
367 * When a new value has a larger ndigits or weight than the accumulator
368 * currently does, the accumulator is enlarged to accommodate the new value.
369 * We normally have one zero digit reserved for carry propagation, and that
370 * is indicated by the 'have_carry_space' flag. When accum_sum_carry() uses
371 * up the reserved digit, it clears the 'have_carry_space' flag. The next
372 * call to accum_sum_add() will enlarge the buffer, to make room for the
373 * extra digit, and set the flag again.
374 *
375 * To initialize a new accumulator, simply reset all fields to zeros.
376 *
377 * The accumulator does not handle NaNs.
378 * ----------
379 */
380 typedef struct NumericSumAccum
381 {
382 int ndigits;
383 int weight;
384 int dscale;
385 int num_uncarried;
386 bool have_carry_space;
387 int32 *pos_digits;
388 int32 *neg_digits;
389 } NumericSumAccum;
390
391
392 /*
393 * We define our own macros for packing and unpacking abbreviated-key
394 * representations for numeric values in order to avoid depending on
395 * USE_FLOAT8_BYVAL. The type of abbreviation we use is based only on
396 * the size of a datum, not the argument-passing convention for float8.
397 *
398 * The range of abbreviations for finite values is from +PG_INT64/32_MAX
399 * to -PG_INT64/32_MAX. NaN has the abbreviation PG_INT64/32_MIN, and we
400 * define the sort ordering to make that work out properly (see further
401 * comments below). PINF and NINF share the abbreviations of the largest
402 * and smallest finite abbreviation classes.
403 */
404 #define NUMERIC_ABBREV_BITS (SIZEOF_DATUM * BITS_PER_BYTE)
405 #if SIZEOF_DATUM == 8
406 #define NumericAbbrevGetDatum(X) ((Datum) (X))
407 #define DatumGetNumericAbbrev(X) ((int64) (X))
408 #define NUMERIC_ABBREV_NAN NumericAbbrevGetDatum(PG_INT64_MIN)
409 #define NUMERIC_ABBREV_PINF NumericAbbrevGetDatum(-PG_INT64_MAX)
410 #define NUMERIC_ABBREV_NINF NumericAbbrevGetDatum(PG_INT64_MAX)
411 #else
412 #define NumericAbbrevGetDatum(X) ((Datum) (X))
413 #define DatumGetNumericAbbrev(X) ((int32) (X))
414 #define NUMERIC_ABBREV_NAN NumericAbbrevGetDatum(PG_INT32_MIN)
415 #define NUMERIC_ABBREV_PINF NumericAbbrevGetDatum(-PG_INT32_MAX)
416 #define NUMERIC_ABBREV_NINF NumericAbbrevGetDatum(PG_INT32_MAX)
417 #endif
418
419
420 /* ----------
421 * Some preinitialized constants
422 * ----------
423 */
424 static const NumericDigit const_zero_data[1] = {0};
425 static const NumericVar const_zero =
426 {0, 0, NUMERIC_POS, 0, NULL, (NumericDigit *) const_zero_data};
427
428 static const NumericDigit const_one_data[1] = {1};
429 static const NumericVar const_one =
430 {1, 0, NUMERIC_POS, 0, NULL, (NumericDigit *) const_one_data};
431
432 static const NumericVar const_minus_one =
433 {1, 0, NUMERIC_NEG, 0, NULL, (NumericDigit *) const_one_data};
434
435 static const NumericDigit const_two_data[1] = {2};
436 static const NumericVar const_two =
437 {1, 0, NUMERIC_POS, 0, NULL, (NumericDigit *) const_two_data};
438
439 #if DEC_DIGITS == 4
440 static const NumericDigit const_zero_point_nine_data[1] = {9000};
441 #elif DEC_DIGITS == 2
442 static const NumericDigit const_zero_point_nine_data[1] = {90};
443 #elif DEC_DIGITS == 1
444 static const NumericDigit const_zero_point_nine_data[1] = {9};
445 #endif
446 static const NumericVar const_zero_point_nine =
447 {1, -1, NUMERIC_POS, 1, NULL, (NumericDigit *) const_zero_point_nine_data};
448
449 #if DEC_DIGITS == 4
450 static const NumericDigit const_one_point_one_data[2] = {1, 1000};
451 #elif DEC_DIGITS == 2
452 static const NumericDigit const_one_point_one_data[2] = {1, 10};
453 #elif DEC_DIGITS == 1
454 static const NumericDigit const_one_point_one_data[2] = {1, 1};
455 #endif
456 static const NumericVar const_one_point_one =
457 {2, 0, NUMERIC_POS, 1, NULL, (NumericDigit *) const_one_point_one_data};
458
459 static const NumericVar const_nan =
460 {0, 0, NUMERIC_NAN, 0, NULL, NULL};
461
462 static const NumericVar const_pinf =
463 {0, 0, NUMERIC_PINF, 0, NULL, NULL};
464
465 static const NumericVar const_ninf =
466 {0, 0, NUMERIC_NINF, 0, NULL, NULL};
467
468 #if DEC_DIGITS == 4
469 static const int round_powers[4] = {0, 1000, 100, 10};
470 #endif
471
472
473 /* ----------
474 * Local functions
475 * ----------
476 */
477
478 #ifdef NUMERIC_DEBUG
479 static void dump_numeric(const char *str, Numeric num);
480 static void dump_var(const char *str, NumericVar *var);
481 #else
482 #define dump_numeric(s,n)
483 #define dump_var(s,v)
484 #endif
485
486 #define digitbuf_alloc(ndigits) \
487 ((NumericDigit *) palloc((ndigits) * sizeof(NumericDigit)))
488 #define digitbuf_free(buf) \
489 do { \
490 if ((buf) != NULL) \
491 pfree(buf); \
492 } while (0)
493
494 #define init_var(v) memset(v, 0, sizeof(NumericVar))
495
496 #define NUMERIC_DIGITS(num) (NUMERIC_HEADER_IS_SHORT(num) ? \
497 (num)->choice.n_short.n_data : (num)->choice.n_long.n_data)
498 #define NUMERIC_NDIGITS(num) \
499 ((VARSIZE(num) - NUMERIC_HEADER_SIZE(num)) / sizeof(NumericDigit))
500 #define NUMERIC_CAN_BE_SHORT(scale,weight) \
501 ((scale) <= NUMERIC_SHORT_DSCALE_MAX && \
502 (weight) <= NUMERIC_SHORT_WEIGHT_MAX && \
503 (weight) >= NUMERIC_SHORT_WEIGHT_MIN)
504
505 static void alloc_var(NumericVar *var, int ndigits);
506 static void free_var(NumericVar *var);
507 static void zero_var(NumericVar *var);
508
509 static bool set_var_from_str(const char *str, const char *cp,
510 NumericVar *dest, const char **endptr,
511 Node *escontext);
512 static bool set_var_from_non_decimal_integer_str(const char *str,
513 const char *cp, int sign,
514 int base, NumericVar *dest,
515 const char **endptr,
516 Node *escontext);
517 static void set_var_from_num(Numeric num, NumericVar *dest);
518 static void init_var_from_num(Numeric num, NumericVar *dest);
519 static void set_var_from_var(const NumericVar *value, NumericVar *dest);
520 static char *get_str_from_var(const NumericVar *var);
521 static char *get_str_from_var_sci(const NumericVar *var, int rscale);
522
523 static void numericvar_serialize(StringInfo buf, const NumericVar *var);
524 static void numericvar_deserialize(StringInfo buf, NumericVar *var);
525
526 static Numeric duplicate_numeric(Numeric num);
527 static Numeric make_result(const NumericVar *var);
528 static Numeric make_result_opt_error(const NumericVar *var, bool *have_error);
529
530 static bool apply_typmod(NumericVar *var, int32 typmod, Node *escontext);
531 static bool apply_typmod_special(Numeric num, int32 typmod, Node *escontext);
532
533 static bool numericvar_to_int32(const NumericVar *var, int32 *result);
534 static bool numericvar_to_int64(const NumericVar *var, int64 *result);
535 static void int64_to_numericvar(int64 val, NumericVar *var);
536 static bool numericvar_to_uint64(const NumericVar *var, uint64 *result);
537 #ifdef HAVE_INT128
538 static bool numericvar_to_int128(const NumericVar *var, int128 *result);
539 static void int128_to_numericvar(int128 val, NumericVar *var);
540 #endif
541 static double numericvar_to_double_no_overflow(const NumericVar *var);
542
543 static Datum numeric_abbrev_convert(Datum original_datum, SortSupport ssup);
544 static bool numeric_abbrev_abort(int memtupcount, SortSupport ssup);
545 static int numeric_fast_cmp(Datum x, Datum y, SortSupport ssup);
546 static int numeric_cmp_abbrev(Datum x, Datum y, SortSupport ssup);
547
548 static Datum numeric_abbrev_convert_var(const NumericVar *var,
549 NumericSortSupport *nss);
550
551 static int cmp_numerics(Numeric num1, Numeric num2);
552 static int cmp_var(const NumericVar *var1, const NumericVar *var2);
553 static int cmp_var_common(const NumericDigit *var1digits, int var1ndigits,
554 int var1weight, int var1sign,
555 const NumericDigit *var2digits, int var2ndigits,
556 int var2weight, int var2sign);
557 static void add_var(const NumericVar *var1, const NumericVar *var2,
558 NumericVar *result);
559 static void sub_var(const NumericVar *var1, const NumericVar *var2,
560 NumericVar *result);
561 static void mul_var(const NumericVar *var1, const NumericVar *var2,
562 NumericVar *result,
563 int rscale);
564 static void mul_var_short(const NumericVar *var1, const NumericVar *var2,
565 NumericVar *result);
566 static void div_var(const NumericVar *var1, const NumericVar *var2,
567 NumericVar *result, int rscale, bool round, bool exact);
568 static void div_var_int(const NumericVar *var, int ival, int ival_weight,
569 NumericVar *result, int rscale, bool round);
570 #ifdef HAVE_INT128
571 static void div_var_int64(const NumericVar *var, int64 ival, int ival_weight,
572 NumericVar *result, int rscale, bool round);
573 #endif
574 static int select_div_scale(const NumericVar *var1, const NumericVar *var2);
575 static void mod_var(const NumericVar *var1, const NumericVar *var2,
576 NumericVar *result);
577 static void div_mod_var(const NumericVar *var1, const NumericVar *var2,
578 NumericVar *quot, NumericVar *rem);
579 static void ceil_var(const NumericVar *var, NumericVar *result);
580 static void floor_var(const NumericVar *var, NumericVar *result);
581
582 static void gcd_var(const NumericVar *var1, const NumericVar *var2,
583 NumericVar *result);
584 static void sqrt_var(const NumericVar *arg, NumericVar *result, int rscale);
585 static void exp_var(const NumericVar *arg, NumericVar *result, int rscale);
586 static int estimate_ln_dweight(const NumericVar *var);
587 static void ln_var(const NumericVar *arg, NumericVar *result, int rscale);
588 static void log_var(const NumericVar *base, const NumericVar *num,
589 NumericVar *result);
590 static void power_var(const NumericVar *base, const NumericVar *exp,
591 NumericVar *result);
592 static void power_var_int(const NumericVar *base, int exp, int exp_dscale,
593 NumericVar *result);
594 static void power_ten_int(int exp, NumericVar *result);
595 static void random_var(pg_prng_state *state, const NumericVar *rmin,
596 const NumericVar *rmax, NumericVar *result);
597
598 static int cmp_abs(const NumericVar *var1, const NumericVar *var2);
599 static int cmp_abs_common(const NumericDigit *var1digits, int var1ndigits,
600 int var1weight,
601 const NumericDigit *var2digits, int var2ndigits,
602 int var2weight);
603 static void add_abs(const NumericVar *var1, const NumericVar *var2,
604 NumericVar *result);
605 static void sub_abs(const NumericVar *var1, const NumericVar *var2,
606 NumericVar *result);
607 static void round_var(NumericVar *var, int rscale);
608 static void trunc_var(NumericVar *var, int rscale);
609 static void strip_var(NumericVar *var);
610 static void compute_bucket(Numeric operand, Numeric bound1, Numeric bound2,
611 const NumericVar *count_var,
612 NumericVar *result_var);
613
614 static void accum_sum_add(NumericSumAccum *accum, const NumericVar *val);
615 static void accum_sum_rescale(NumericSumAccum *accum, const NumericVar *val);
616 static void accum_sum_carry(NumericSumAccum *accum);
617 static void accum_sum_reset(NumericSumAccum *accum);
618 static void accum_sum_final(NumericSumAccum *accum, NumericVar *result);
619 static void accum_sum_copy(NumericSumAccum *dst, NumericSumAccum *src);
620 static void accum_sum_combine(NumericSumAccum *accum, NumericSumAccum *accum2);
621
622
623 /* ----------------------------------------------------------------------
624 *
625 * Input-, output- and rounding-functions
626 *
627 * ----------------------------------------------------------------------
628 */
629
630
631 /*
632 * numeric_in() -
633 *
634 * Input function for numeric data type
635 */
636 Datum
637 numeric_in(PG_FUNCTION_ARGS)
638 {
639 char *str = PG_GETARG_CSTRING(0);
640 #ifdef NOT_USED
641 Oid typelem = PG_GETARG_OID(1);
642 #endif
643 int32 typmod = PG_GETARG_INT32(2);
644 Node *escontext = fcinfo->context;
645 Numeric res;
646 const char *cp;
647 const char *numstart;
648 int sign;
649
650 /* Skip leading spaces */
651 cp = str;
652 while (*cp)
653 {
654 if (!isspace((unsigned char) *cp))
655 break;
656 cp++;
657 }
658
659 /*
660 * Process the number's sign. This duplicates logic in set_var_from_str(),
661 * but it's worth doing here, since it simplifies the handling of
662 * infinities and non-decimal integers.
663 */
664 numstart = cp;
665 sign = NUMERIC_POS;
666
667 if (*cp == '+')
668 cp++;
669 else if (*cp == '-')
670 {
671 sign = NUMERIC_NEG;
672 cp++;
673 }
674
675 /*
676 * Check for NaN and infinities. We recognize the same strings allowed by
677 * float8in().
678 *
679 * Since all other legal inputs have a digit or a decimal point after the
680 * sign, we need only check for NaN/infinity if that's not the case.
681 */
682 if (!isdigit((unsigned char) *cp) && *cp != '.')
683 {
684 /*
685 * The number must be NaN or infinity; anything else can only be a
686 * syntax error. Note that NaN mustn't have a sign.
687 */
688 if (pg_strncasecmp(numstart, "NaN", 3) == 0)
689 {
690 res = make_result(&const_nan);
691 cp = numstart + 3;
692 }
693 else if (pg_strncasecmp(cp, "Infinity", 8) == 0)
694 {
695 res = make_result(sign == NUMERIC_POS ? &const_pinf : &const_ninf);
696 cp += 8;
697 }
698 else if (pg_strncasecmp(cp, "inf", 3) == 0)
699 {
700 res = make_result(sign == NUMERIC_POS ? &const_pinf : &const_ninf);
701 cp += 3;
702 }
703 else
704 goto invalid_syntax;
705
706 /*
707 * Check for trailing junk; there should be nothing left but spaces.
708 *
709 * We intentionally do this check before applying the typmod because
710 * we would like to throw any trailing-junk syntax error before any
711 * semantic error resulting from apply_typmod_special().
712 */
713 while (*cp)
714 {
715 if (!isspace((unsigned char) *cp))
716 goto invalid_syntax;
717 cp++;
718 }
719
720 if (!apply_typmod_special(res, typmod, escontext))
721 PG_RETURN_NULL();
722 }
723 else
724 {
725 /*
726 * We have a normal numeric value, which may be a non-decimal integer
727 * or a regular decimal number.
728 */
729 NumericVar value;
730 int base;
731 bool have_error;
732
733 init_var(&value);
734
735 /*
736 * Determine the number's base by looking for a non-decimal prefix
737 * indicator ("0x", "0o", or "0b").
738 */
739 if (cp[0] == '0')
740 {
741 switch (cp[1])
742 {
743 case 'x':
744 case 'X':
745 base = 16;
746 break;
747 case 'o':
748 case 'O':
749 base = 8;
750 break;
751 case 'b':
752 case 'B':
753 base = 2;
754 break;
755 default:
756 base = 10;
757 }
758 }
759 else
760 base = 10;
761
762 /* Parse the rest of the number and apply the sign */
763 if (base == 10)
764 {
765 if (!set_var_from_str(str, cp, &value, &cp, escontext))
766 PG_RETURN_NULL();
767 value.sign = sign;
768 }
769 else
770 {
771 if (!set_var_from_non_decimal_integer_str(str, cp + 2, sign, base,
772 &value, &cp, escontext))
773 PG_RETURN_NULL();
774 }
775
776 /*
777 * Should be nothing left but spaces. As above, throw any typmod error
778 * after finishing syntax check.
779 */
780 while (*cp)
781 {
782 if (!isspace((unsigned char) *cp))
783 goto invalid_syntax;
784 cp++;
785 }
786
787 if (!apply_typmod(&value, typmod, escontext))
788 PG_RETURN_NULL();
789
790 res = make_result_opt_error(&value, &have_error);
791
792 if (have_error)
793 ereturn(escontext, (Datum) 0,
794 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
795 errmsg("value overflows numeric format")));
796
797 free_var(&value);
798 }
799
800 PG_RETURN_NUMERIC(res);
801
802 invalid_syntax:
803 ereturn(escontext, (Datum) 0,
804 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
805 errmsg("invalid input syntax for type %s: \"%s\"",
806 "numeric", str)));
807 }
808
809
810 /*
811 * numeric_out() -
812 *
813 * Output function for numeric data type
814 */
815 Datum
816 numeric_out(PG_FUNCTION_ARGS)
817 {
818 Numeric num = PG_GETARG_NUMERIC(0);
819 NumericVar x;
820 char *str;
821
822 /*
823 * Handle NaN and infinities
824 */
825 if (NUMERIC_IS_SPECIAL(num))
826 {
827 if (NUMERIC_IS_PINF(num))
828 PG_RETURN_CSTRING(pstrdup("Infinity"));
829 else if (NUMERIC_IS_NINF(num))
830 PG_RETURN_CSTRING(pstrdup("-Infinity"));
831 else
832 PG_RETURN_CSTRING(pstrdup("NaN"));
833 }
834
835 /*
836 * Get the number in the variable format.
837 */
838 init_var_from_num(num, &x);
839
840 str = get_str_from_var(&x);
841
842 PG_RETURN_CSTRING(str);
843 }
844
845 /*
846 * numeric_is_nan() -
847 *
848 * Is Numeric value a NaN?
849 */
850 bool
851 numeric_is_nan(Numeric num)
852 {
853 return NUMERIC_IS_NAN(num);
854 }
855
856 /*
857 * numeric_is_inf() -
858 *
859 * Is Numeric value an infinity?
860 */
861 bool
862 numeric_is_inf(Numeric num)
863 {
864 return NUMERIC_IS_INF(num);
865 }
866
867 /*
868 * numeric_is_integral() -
869 *
870 * Is Numeric value integral?
871 */
872 static bool
873 numeric_is_integral(Numeric num)
874 {
875 NumericVar arg;
876
877 /* Reject NaN, but infinities are considered integral */
878 if (NUMERIC_IS_SPECIAL(num))
879 {
880 if (NUMERIC_IS_NAN(num))
881 return false;
882 return true;
883 }
884
885 /* Integral if there are no digits to the right of the decimal point */
886 init_var_from_num(num, &arg);
887
888 return (arg.ndigits == 0 || arg.ndigits <= arg.weight + 1);
889 }
890
891 /*
892 * make_numeric_typmod() -
893 *
894 * Pack numeric precision and scale values into a typmod. The upper 16 bits
895 * are used for the precision (though actually not all these bits are needed,
896 * since the maximum allowed precision is 1000). The lower 16 bits are for
897 * the scale, but since the scale is constrained to the range [-1000, 1000],
898 * we use just the lower 11 of those 16 bits, and leave the remaining 5 bits
899 * unset, for possible future use.
900 *
901 * For purely historical reasons VARHDRSZ is then added to the result, thus
902 * the unused space in the upper 16 bits is not all as freely available as it
903 * might seem. (We can't let the result overflow to a negative int32, as
904 * other parts of the system would interpret that as not-a-valid-typmod.)
905 */
906 static inline int32
907 make_numeric_typmod(int precision, int scale)
908 {
909 return ((precision << 16) | (scale & 0x7ff)) + VARHDRSZ;
910 }
911
912 /*
913 * Because of the offset, valid numeric typmods are at least VARHDRSZ
914 */
915 static inline bool
916 is_valid_numeric_typmod(int32 typmod)
917 {
918 return typmod >= (int32) VARHDRSZ;
919 }
920
921 /*
922 * numeric_typmod_precision() -
923 *
924 * Extract the precision from a numeric typmod --- see make_numeric_typmod().
925 */
926 static inline int
927 numeric_typmod_precision(int32 typmod)
928 {
929 return ((typmod - VARHDRSZ) >> 16) & 0xffff;
930 }
931
932 /*
933 * numeric_typmod_scale() -
934 *
935 * Extract the scale from a numeric typmod --- see make_numeric_typmod().
936 *
937 * Note that the scale may be negative, so we must do sign extension when
938 * unpacking it. We do this using the bit hack (x^1024)-1024, which sign
939 * extends an 11-bit two's complement number x.
940 */
941 static inline int
942 numeric_typmod_scale(int32 typmod)
943 {
944 return (((typmod - VARHDRSZ) & 0x7ff) ^ 1024) - 1024;
945 }
946
947 /*
948 * numeric_maximum_size() -
949 *
950 * Maximum size of a numeric with given typmod, or -1 if unlimited/unknown.
951 */
952 int32
953 numeric_maximum_size(int32 typmod)
954 {
955 int precision;
956 int numeric_digits;
957
958 if (!is_valid_numeric_typmod(typmod))
959 return -1;
960
961 /* precision (ie, max # of digits) is in upper bits of typmod */
962 precision = numeric_typmod_precision(typmod);
963
964 /*
965 * This formula computes the maximum number of NumericDigits we could need
966 * in order to store the specified number of decimal digits. Because the
967 * weight is stored as a number of NumericDigits rather than a number of
968 * decimal digits, it's possible that the first NumericDigit will contain
969 * only a single decimal digit. Thus, the first two decimal digits can
970 * require two NumericDigits to store, but it isn't until we reach
971 * DEC_DIGITS + 2 decimal digits that we potentially need a third
972 * NumericDigit.
973 */
974 numeric_digits = (precision + 2 * (DEC_DIGITS - 1)) / DEC_DIGITS;
975
976 /*
977 * In most cases, the size of a numeric will be smaller than the value
978 * computed below, because the varlena header will typically get toasted
979 * down to a single byte before being stored on disk, and it may also be
980 * possible to use a short numeric header. But our job here is to compute
981 * the worst case.
982 */
983 return NUMERIC_HDRSZ + (numeric_digits * sizeof(NumericDigit));
984 }
985
986 /*
987 * numeric_out_sci() -
988 *
989 * Output function for numeric data type in scientific notation.
990 */
991 char *
992 numeric_out_sci(Numeric num, int scale)
993 {
994 NumericVar x;
995 char *str;
996
997 /*
998 * Handle NaN and infinities
999 */
1000 if (NUMERIC_IS_SPECIAL(num))
1001 {
1002 if (NUMERIC_IS_PINF(num))
1003 return pstrdup("Infinity");
1004 else if (NUMERIC_IS_NINF(num))
1005 return pstrdup("-Infinity");
1006 else
1007 return pstrdup("NaN");
1008 }
1009
1010 init_var_from_num(num, &x);
1011
1012 str = get_str_from_var_sci(&x, scale);
1013
1014 return str;
1015 }
1016
1017 /*
1018 * numeric_normalize() -
1019 *
1020 * Output function for numeric data type, suppressing insignificant trailing
1021 * zeroes and then any trailing decimal point. The intent of this is to
1022 * produce strings that are equal if and only if the input numeric values
1023 * compare equal.
1024 */
1025 char *
1026 numeric_normalize(Numeric num)
1027 {
1028 NumericVar x;
1029 char *str;
1030 int last;
1031
1032 /*
1033 * Handle NaN and infinities
1034 */
1035 if (NUMERIC_IS_SPECIAL(num))
1036 {
1037 if (NUMERIC_IS_PINF(num))
1038 return pstrdup("Infinity");
1039 else if (NUMERIC_IS_NINF(num))
1040 return pstrdup("-Infinity");
1041 else
1042 return pstrdup("NaN");
1043 }
1044
1045 init_var_from_num(num, &x);
1046
1047 str = get_str_from_var(&x);
1048
1049 /* If there's no decimal point, there's certainly nothing to remove. */
1050 if (strchr(str, '.') != NULL)
1051 {
1052 /*
1053 * Back up over trailing fractional zeroes. Since there is a decimal
1054 * point, this loop will terminate safely.
1055 */
1056 last = strlen(str) - 1;
1057 while (str[last] == '0')
1058 last--;
1059
1060 /* We want to get rid of the decimal point too, if it's now last. */
1061 if (str[last] == '.')
1062 last--;
1063
1064 /* Delete whatever we backed up over. */
1065 str[last + 1] = '\0';
1066 }
1067
1068 return str;
1069 }
1070
1071 /*
1072 * numeric_recv - converts external binary format to numeric
1073 *
1074 * External format is a sequence of int16's:
1075 * ndigits, weight, sign, dscale, NumericDigits.
1076 */
1077 Datum
1078 numeric_recv(PG_FUNCTION_ARGS)
1079 {
1080 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
1081
1082 #ifdef NOT_USED
1083 Oid typelem = PG_GETARG_OID(1);
1084 #endif
1085 int32 typmod = PG_GETARG_INT32(2);
1086 NumericVar value;
1087 Numeric res;
1088 int len,
1089 i;
1090
1091 init_var(&value);
1092
1093 len = (uint16) pq_getmsgint(buf, sizeof(uint16));
1094
1095 alloc_var(&value, len);
1096
1097 value.weight = (int16) pq_getmsgint(buf, sizeof(int16));
1098 /* we allow any int16 for weight --- OK? */
1099
1100 value.sign = (uint16) pq_getmsgint(buf, sizeof(uint16));
1101 if (!(value.sign == NUMERIC_POS ||
1102 value.sign == NUMERIC_NEG ||
1103 value.sign == NUMERIC_NAN ||
1104 value.sign == NUMERIC_PINF ||
1105 value.sign == NUMERIC_NINF))
1106 ereport(ERROR,
1107 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1108 errmsg("invalid sign in external \"numeric\" value")));
1109
1110 value.dscale = (uint16) pq_getmsgint(buf, sizeof(uint16));
1111 if ((value.dscale & NUMERIC_DSCALE_MASK) != value.dscale)
1112 ereport(ERROR,
1113 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1114 errmsg("invalid scale in external \"numeric\" value")));
1115
1116 for (i = 0; i < len; i++)
1117 {
1118 NumericDigit d = pq_getmsgint(buf, sizeof(NumericDigit));
1119
1120 if (d < 0 || d >= NBASE)
1121 ereport(ERROR,
1122 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1123 errmsg("invalid digit in external \"numeric\" value")));
1124 value.digits[i] = d;
1125 }
1126
1127 /*
1128 * If the given dscale would hide any digits, truncate those digits away.
1129 * We could alternatively throw an error, but that would take a bunch of
1130 * extra code (about as much as trunc_var involves), and it might cause
1131 * client compatibility issues. Be careful not to apply trunc_var to
1132 * special values, as it could do the wrong thing; we don't need it
1133 * anyway, since make_result will ignore all but the sign field.
1134 *
1135 * After doing that, be sure to check the typmod restriction.
1136 */
1137 if (value.sign == NUMERIC_POS ||
1138 value.sign == NUMERIC_NEG)
1139 {
1140 trunc_var(&value, value.dscale);
1141
1142 (void) apply_typmod(&value, typmod, NULL);
1143
1144 res = make_result(&value);
1145 }
1146 else
1147 {
1148 /* apply_typmod_special wants us to make the Numeric first */
1149 res = make_result(&value);
1150
1151 (void) apply_typmod_special(res, typmod, NULL);
1152 }
1153
1154 free_var(&value);
1155
1156 PG_RETURN_NUMERIC(res);
1157 }
1158
1159 /*
1160 * numeric_send - converts numeric to binary format
1161 */
1162 Datum
1163 numeric_send(PG_FUNCTION_ARGS)
1164 {
1165 Numeric num = PG_GETARG_NUMERIC(0);
1166 NumericVar x;
1167 StringInfoData buf;
1168 int i;
1169
1170 init_var_from_num(num, &x);
1171
1172 pq_begintypsend(&buf);
1173
1174 pq_sendint16(&buf, x.ndigits);
1175 pq_sendint16(&buf, x.weight);
1176 pq_sendint16(&buf, x.sign);
1177 pq_sendint16(&buf, x.dscale);
1178 for (i = 0; i < x.ndigits; i++)
1179 pq_sendint16(&buf, x.digits[i]);
1180
1181 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
1182 }
1183
1184
1185 /*
1186 * numeric_support()
1187 *
1188 * Planner support function for the numeric() length coercion function.
1189 *
1190 * Flatten calls that solely represent increases in allowable precision.
1191 * Scale changes mutate every datum, so they are unoptimizable. Some values,
1192 * e.g. 1E-1001, can only fit into an unconstrained numeric, so a change from
1193 * an unconstrained numeric to any constrained numeric is also unoptimizable.
1194 */
1195 Datum
1196 numeric_support(PG_FUNCTION_ARGS)
1197 {
1198 Node *rawreq = (Node *) PG_GETARG_POINTER(0);
1199 Node *ret = NULL;
1200
1201 if (IsA(rawreq, SupportRequestSimplify))
1202 {
1203 SupportRequestSimplify *req = (SupportRequestSimplify *) rawreq;
1204 FuncExpr *expr = req->fcall;
1205 Node *typmod;
1206
1207 Assert(list_length(expr->args) >= 2);
1208
1209 typmod = (Node *) lsecond(expr->args);
1210
1211 if (IsA(typmod, Const) && !((Const *) typmod)->constisnull)
1212 {
1213 Node *source = (Node *) linitial(expr->args);
1214 int32 old_typmod = exprTypmod(source);
1215 int32 new_typmod = DatumGetInt32(((Const *) typmod)->constvalue);
1216 int32 old_scale = numeric_typmod_scale(old_typmod);
1217 int32 new_scale = numeric_typmod_scale(new_typmod);
1218 int32 old_precision = numeric_typmod_precision(old_typmod);
1219 int32 new_precision = numeric_typmod_precision(new_typmod);
1220
1221 /*
1222 * If new_typmod is invalid, the destination is unconstrained;
1223 * that's always OK. If old_typmod is valid, the source is
1224 * constrained, and we're OK if the scale is unchanged and the
1225 * precision is not decreasing. See further notes in function
1226 * header comment.
1227 */
1228 if (!is_valid_numeric_typmod(new_typmod) ||
1229 (is_valid_numeric_typmod(old_typmod) &&
1230 new_scale == old_scale && new_precision >= old_precision))
1231 ret = relabel_to_typmod(source, new_typmod);
1232 }
1233 }
1234
1235 PG_RETURN_POINTER(ret);
1236 }
1237
1238 /*
1239 * numeric() -
1240 *
1241 * This is a special function called by the Postgres database system
1242 * before a value is stored in a tuple's attribute. The precision and
1243 * scale of the attribute have to be applied on the value.
1244 */
1245 Datum
1246 numeric (PG_FUNCTION_ARGS)
1247 {
1248 Numeric num = PG_GETARG_NUMERIC(0);
1249 int32 typmod = PG_GETARG_INT32(1);
1250 Numeric new;
1251 int precision;
1252 int scale;
1253 int ddigits;
1254 int maxdigits;
1255 int dscale;
1256 NumericVar var;
1257
1258 /*
1259 * Handle NaN and infinities: if apply_typmod_special doesn't complain,
1260 * just return a copy of the input.
1261 */
1262 if (NUMERIC_IS_SPECIAL(num))
1263 {
1264 (void) apply_typmod_special(num, typmod, NULL);
1265 PG_RETURN_NUMERIC(duplicate_numeric(num));
1266 }
1267
1268 /*
1269 * If the value isn't a valid type modifier, simply return a copy of the
1270 * input value
1271 */
1272 if (!is_valid_numeric_typmod(typmod))
1273 PG_RETURN_NUMERIC(duplicate_numeric(num));
1274
1275 /*
1276 * Get the precision and scale out of the typmod value
1277 */
1278 precision = numeric_typmod_precision(typmod);
1279 scale = numeric_typmod_scale(typmod);
1280 maxdigits = precision - scale;
1281
1282 /* The target display scale is non-negative */
1283 dscale = Max(scale, 0);
1284
1285 /*
1286 * If the number is certainly in bounds and due to the target scale no
1287 * rounding could be necessary, just make a copy of the input and modify
1288 * its scale fields, unless the larger scale forces us to abandon the
1289 * short representation. (Note we assume the existing dscale is
1290 * honest...)
1291 */
1292 ddigits = (NUMERIC_WEIGHT(num) + 1) * DEC_DIGITS;
1293 if (ddigits <= maxdigits && scale >= NUMERIC_DSCALE(num)
1294 && (NUMERIC_CAN_BE_SHORT(dscale, NUMERIC_WEIGHT(num))
1295 || !NUMERIC_IS_SHORT(num)))
1296 {
1297 new = duplicate_numeric(num);
1298 if (NUMERIC_IS_SHORT(num))
1299 new->choice.n_short.n_header =
1300 (num->choice.n_short.n_header & ~NUMERIC_SHORT_DSCALE_MASK)
1301 | (dscale << NUMERIC_SHORT_DSCALE_SHIFT);
1302 else
1303 new->choice.n_long.n_sign_dscale = NUMERIC_SIGN(new) |
1304 ((uint16) dscale & NUMERIC_DSCALE_MASK);
1305 PG_RETURN_NUMERIC(new);
1306 }
1307
1308 /*
1309 * We really need to fiddle with things - unpack the number into a
1310 * variable and let apply_typmod() do it.
1311 */
1312 init_var(&var);
1313
1314 set_var_from_num(num, &var);
1315 (void) apply_typmod(&var, typmod, NULL);
1316 new = make_result(&var);
1317
1318 free_var(&var);
1319
1320 PG_RETURN_NUMERIC(new);
1321 }
1322
1323 /*
1324 * make_numeric_typmod_safe() -
1325 *
1326 * Validate a numeric precision/scale and pack them into a typmod value,
1327 * with soft error handling.
1328 */
1329 int32
1330 make_numeric_typmod_safe(int32 precision, int32 scale, Node *escontext)
1331 {
1332 if (precision < 1 || precision > NUMERIC_MAX_PRECISION)
1333 ereturn(escontext, -1,
1334 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1335 errmsg("NUMERIC precision %d must be between 1 and %d",
1336 precision, NUMERIC_MAX_PRECISION)));
1337 if (scale < NUMERIC_MIN_SCALE || scale > NUMERIC_MAX_SCALE)
1338 ereturn(escontext, -1,
1339 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1340 errmsg("NUMERIC scale %d must be between %d and %d",
1341 scale, NUMERIC_MIN_SCALE, NUMERIC_MAX_SCALE)));
1342
1343 return make_numeric_typmod(precision, scale);
1344 }
1345
1346 Datum
1347 numerictypmodin(PG_FUNCTION_ARGS)
1348 {
1349 ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
1350 int32 *tl;
1351 int n;
1352 int32 typmod;
1353
1354 tl = ArrayGetIntegerTypmods(ta, &n);
1355
1356 if (n == 2)
1357 typmod = make_numeric_typmod_safe(tl[0], tl[1], NULL);
1358 else if (n == 1)
1359 {
1360 /* scale defaults to zero */
1361 typmod = make_numeric_typmod_safe(tl[0], 0, NULL);
1362 }
1363 else
1364 {
1365 ereport(ERROR,
1366 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1367 errmsg("invalid NUMERIC type modifier")));
1368 typmod = 0; /* keep compiler quiet */
1369 }
1370
1371 PG_RETURN_INT32(typmod);
1372 }
1373
1374 Datum
1375 numerictypmodout(PG_FUNCTION_ARGS)
1376 {
1377 int32 typmod = PG_GETARG_INT32(0);
1378 char *res = (char *) palloc(64);
1379
1380 if (is_valid_numeric_typmod(typmod))
1381 snprintf(res, 64, "(%d,%d)",
1382 numeric_typmod_precision(typmod),
1383 numeric_typmod_scale(typmod));
1384 else
1385 *res = '\0';
1386
1387 PG_RETURN_CSTRING(res);
1388 }
1389
1390
1391 /* ----------------------------------------------------------------------
1392 *
1393 * Sign manipulation, rounding and the like
1394 *
1395 * ----------------------------------------------------------------------
1396 */
1397
1398 Datum
1399 numeric_abs(PG_FUNCTION_ARGS)
1400 {
1401 Numeric num = PG_GETARG_NUMERIC(0);
1402 Numeric res;
1403
1404 /*
1405 * Do it the easy way directly on the packed format
1406 */
1407 res = duplicate_numeric(num);
1408
1409 if (NUMERIC_IS_SHORT(num))
1410 res->choice.n_short.n_header =
1411 num->choice.n_short.n_header & ~NUMERIC_SHORT_SIGN_MASK;
1412 else if (NUMERIC_IS_SPECIAL(num))
1413 {
1414 /* This changes -Inf to Inf, and doesn't affect NaN */
1415 res->choice.n_short.n_header =
1416 num->choice.n_short.n_header & ~NUMERIC_INF_SIGN_MASK;
1417 }
1418 else
1419 res->choice.n_long.n_sign_dscale = NUMERIC_POS | NUMERIC_DSCALE(num);
1420
1421 PG_RETURN_NUMERIC(res);
1422 }
1423
1424
1425 Datum
1426 numeric_uminus(PG_FUNCTION_ARGS)
1427 {
1428 Numeric num = PG_GETARG_NUMERIC(0);
1429 Numeric res;
1430
1431 /*
1432 * Do it the easy way directly on the packed format
1433 */
1434 res = duplicate_numeric(num);
1435
1436 if (NUMERIC_IS_SPECIAL(num))
1437 {
1438 /* Flip the sign, if it's Inf or -Inf */
1439 if (!NUMERIC_IS_NAN(num))
1440 res->choice.n_short.n_header =
1441 num->choice.n_short.n_header ^ NUMERIC_INF_SIGN_MASK;
1442 }
1443
1444 /*
1445 * The packed format is known to be totally zero digit trimmed always. So
1446 * once we've eliminated specials, we can identify a zero by the fact that
1447 * there are no digits at all. Do nothing to a zero.
1448 */
1449 else if (NUMERIC_NDIGITS(num) != 0)
1450 {
1451 /* Else, flip the sign */
1452 if (NUMERIC_IS_SHORT(num))
1453 res->choice.n_short.n_header =
1454 num->choice.n_short.n_header ^ NUMERIC_SHORT_SIGN_MASK;
1455 else if (NUMERIC_SIGN(num) == NUMERIC_POS)
1456 res->choice.n_long.n_sign_dscale =
1457 NUMERIC_NEG | NUMERIC_DSCALE(num);
1458 else
1459 res->choice.n_long.n_sign_dscale =
1460 NUMERIC_POS | NUMERIC_DSCALE(num);
1461 }
1462
1463 PG_RETURN_NUMERIC(res);
1464 }
1465
1466
1467 Datum
1468 numeric_uplus(PG_FUNCTION_ARGS)
1469 {
1470 Numeric num = PG_GETARG_NUMERIC(0);
1471
1472 PG_RETURN_NUMERIC(duplicate_numeric(num));
1473 }
1474
1475
1476 /*
1477 * numeric_sign_internal() -
1478 *
1479 * Returns -1 if the argument is less than 0, 0 if the argument is equal
1480 * to 0, and 1 if the argument is greater than zero. Caller must have
1481 * taken care of the NaN case, but we can handle infinities here.
1482 */
1483 static int
1484 numeric_sign_internal(Numeric num)
1485 {
1486 if (NUMERIC_IS_SPECIAL(num))
1487 {
1488 Assert(!NUMERIC_IS_NAN(num));
1489 /* Must be Inf or -Inf */
1490 if (NUMERIC_IS_PINF(num))
1491 return 1;
1492 else
1493 return -1;
1494 }
1495
1496 /*
1497 * The packed format is known to be totally zero digit trimmed always. So
1498 * once we've eliminated specials, we can identify a zero by the fact that
1499 * there are no digits at all.
1500 */
1501 else if (NUMERIC_NDIGITS(num) == 0)
1502 return 0;
1503 else if (NUMERIC_SIGN(num) == NUMERIC_NEG)
1504 return -1;
1505 else
1506 return 1;
1507 }
1508
1509 /*
1510 * numeric_sign() -
1511 *
1512 * returns -1 if the argument is less than 0, 0 if the argument is equal
1513 * to 0, and 1 if the argument is greater than zero.
1514 */
1515 Datum
1516 numeric_sign(PG_FUNCTION_ARGS)
1517 {
1518 Numeric num = PG_GETARG_NUMERIC(0);
1519
1520 /*
1521 * Handle NaN (infinities can be handled normally)
1522 */
1523 if (NUMERIC_IS_NAN(num))
1524 PG_RETURN_NUMERIC(make_result(&const_nan));
1525
1526 switch (numeric_sign_internal(num))
1527 {
1528 case 0:
1529 PG_RETURN_NUMERIC(make_result(&const_zero));
1530 case 1:
1531 PG_RETURN_NUMERIC(make_result(&const_one));
1532 case -1:
1533 PG_RETURN_NUMERIC(make_result(&const_minus_one));
1534 }
1535
1536 Assert(false);
1537 return (Datum) 0;
1538 }
1539
1540
1541 /*
1542 * numeric_round() -
1543 *
1544 * Round a value to have 'scale' digits after the decimal point.
1545 * We allow negative 'scale', implying rounding before the decimal
1546 * point --- Oracle interprets rounding that way.
1547 */
1548 Datum
1549 numeric_round(PG_FUNCTION_ARGS)
1550 {
1551 Numeric num = PG_GETARG_NUMERIC(0);
1552 int32 scale = PG_GETARG_INT32(1);
1553 Numeric res;
1554 NumericVar arg;
1555
1556 /*
1557 * Handle NaN and infinities
1558 */
1559 if (NUMERIC_IS_SPECIAL(num))
1560 PG_RETURN_NUMERIC(duplicate_numeric(num));
1561
1562 /*
1563 * Limit the scale value to avoid possible overflow in calculations.
1564 *
1565 * These limits are based on the maximum number of digits a Numeric value
1566 * can have before and after the decimal point, but we must allow for one
1567 * extra digit before the decimal point, in case the most significant
1568 * digit rounds up; we must check if that causes Numeric overflow.
1569 */
1570 scale = Max(scale, -(NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS - 1);
1571 scale = Min(scale, NUMERIC_DSCALE_MAX);
1572
1573 /*
1574 * Unpack the argument and round it at the proper digit position
1575 */
1576 init_var(&arg);
1577 set_var_from_num(num, &arg);
1578
1579 round_var(&arg, scale);
1580
1581 /* We don't allow negative output dscale */
1582 if (scale < 0)
1583 arg.dscale = 0;
1584
1585 /*
1586 * Return the rounded result
1587 */
1588 res = make_result(&arg);
1589
1590 free_var(&arg);
1591 PG_RETURN_NUMERIC(res);
1592 }
1593
1594
1595 /*
1596 * numeric_trunc() -
1597 *
1598 * Truncate a value to have 'scale' digits after the decimal point.
1599 * We allow negative 'scale', implying a truncation before the decimal
1600 * point --- Oracle interprets truncation that way.
1601 */
1602 Datum
1603 numeric_trunc(PG_FUNCTION_ARGS)
1604 {
1605 Numeric num = PG_GETARG_NUMERIC(0);
1606 int32 scale = PG_GETARG_INT32(1);
1607 Numeric res;
1608 NumericVar arg;
1609
1610 /*
1611 * Handle NaN and infinities
1612 */
1613 if (NUMERIC_IS_SPECIAL(num))
1614 PG_RETURN_NUMERIC(duplicate_numeric(num));
1615
1616 /*
1617 * Limit the scale value to avoid possible overflow in calculations.
1618 *
1619 * These limits are based on the maximum number of digits a Numeric value
1620 * can have before and after the decimal point.
1621 */
1622 scale = Max(scale, -(NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS);
1623 scale = Min(scale, NUMERIC_DSCALE_MAX);
1624
1625 /*
1626 * Unpack the argument and truncate it at the proper digit position
1627 */
1628 init_var(&arg);
1629 set_var_from_num(num, &arg);
1630
1631 trunc_var(&arg, scale);
1632
1633 /* We don't allow negative output dscale */
1634 if (scale < 0)
1635 arg.dscale = 0;
1636
1637 /*
1638 * Return the truncated result
1639 */
1640 res = make_result(&arg);
1641
1642 free_var(&arg);
1643 PG_RETURN_NUMERIC(res);
1644 }
1645
1646
1647 /*
1648 * numeric_ceil() -
1649 *
1650 * Return the smallest integer greater than or equal to the argument
1651 */
1652 Datum
1653 numeric_ceil(PG_FUNCTION_ARGS)
1654 {
1655 Numeric num = PG_GETARG_NUMERIC(0);
1656 Numeric res;
1657 NumericVar result;
1658
1659 /*
1660 * Handle NaN and infinities
1661 */
1662 if (NUMERIC_IS_SPECIAL(num))
1663 PG_RETURN_NUMERIC(duplicate_numeric(num));
1664
1665 init_var_from_num(num, &result);
1666 ceil_var(&result, &result);
1667
1668 res = make_result(&result);
1669 free_var(&result);
1670
1671 PG_RETURN_NUMERIC(res);
1672 }
1673
1674
1675 /*
1676 * numeric_floor() -
1677 *
1678 * Return the largest integer equal to or less than the argument
1679 */
1680 Datum
1681 numeric_floor(PG_FUNCTION_ARGS)
1682 {
1683 Numeric num = PG_GETARG_NUMERIC(0);
1684 Numeric res;
1685 NumericVar result;
1686
1687 /*
1688 * Handle NaN and infinities
1689 */
1690 if (NUMERIC_IS_SPECIAL(num))
1691 PG_RETURN_NUMERIC(duplicate_numeric(num));
1692
1693 init_var_from_num(num, &result);
1694 floor_var(&result, &result);
1695
1696 res = make_result(&result);
1697 free_var(&result);
1698
1699 PG_RETURN_NUMERIC(res);
1700 }
1701
1702
1703 /*
1704 * generate_series_numeric() -
1705 *
1706 * Generate series of numeric.
1707 */
1708 Datum
1709 generate_series_numeric(PG_FUNCTION_ARGS)
1710 {
1711 return generate_series_step_numeric(fcinfo);
1712 }
1713
1714 Datum
1715 generate_series_step_numeric(PG_FUNCTION_ARGS)
1716 {
1717 generate_series_numeric_fctx *fctx;
1718 FuncCallContext *funcctx;
1719 MemoryContext oldcontext;
1720
1721 if (SRF_IS_FIRSTCALL())
1722 {
1723 Numeric start_num = PG_GETARG_NUMERIC(0);
1724 Numeric stop_num = PG_GETARG_NUMERIC(1);
1725 NumericVar steploc = const_one;
1726
1727 /* Reject NaN and infinities in start and stop values */
1728 if (NUMERIC_IS_SPECIAL(start_num))
1729 {
1730 if (NUMERIC_IS_NAN(start_num))
1731 ereport(ERROR,
1732 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1733 errmsg("start value cannot be NaN")));
1734 else
1735 ereport(ERROR,
1736 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1737 errmsg("start value cannot be infinity")));
1738 }
1739 if (NUMERIC_IS_SPECIAL(stop_num))
1740 {
1741 if (NUMERIC_IS_NAN(stop_num))
1742 ereport(ERROR,
1743 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1744 errmsg("stop value cannot be NaN")));
1745 else
1746 ereport(ERROR,
1747 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1748 errmsg("stop value cannot be infinity")));
1749 }
1750
1751 /* see if we were given an explicit step size */
1752 if (PG_NARGS() == 3)
1753 {
1754 Numeric step_num = PG_GETARG_NUMERIC(2);
1755
1756 if (NUMERIC_IS_SPECIAL(step_num))
1757 {
1758 if (NUMERIC_IS_NAN(step_num))
1759 ereport(ERROR,
1760 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1761 errmsg("step size cannot be NaN")));
1762 else
1763 ereport(ERROR,
1764 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1765 errmsg("step size cannot be infinity")));
1766 }
1767
1768 init_var_from_num(step_num, &steploc);
1769
1770 if (cmp_var(&steploc, &const_zero) == 0)
1771 ereport(ERROR,
1772 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1773 errmsg("step size cannot equal zero")));
1774 }
1775
1776 /* create a function context for cross-call persistence */
1777 funcctx = SRF_FIRSTCALL_INIT();
1778
1779 /*
1780 * Switch to memory context appropriate for multiple function calls.
1781 */
1782 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1783
1784 /* allocate memory for user context */
1785 fctx = (generate_series_numeric_fctx *)
1786 palloc(sizeof(generate_series_numeric_fctx));
1787
1788 /*
1789 * Use fctx to keep state from call to call. Seed current with the
1790 * original start value. We must copy the start_num and stop_num
1791 * values rather than pointing to them, since we may have detoasted
1792 * them in the per-call context.
1793 */
1794 init_var(&fctx->current);
1795 init_var(&fctx->stop);
1796 init_var(&fctx->step);
1797
1798 set_var_from_num(start_num, &fctx->current);
1799 set_var_from_num(stop_num, &fctx->stop);
1800 set_var_from_var(&steploc, &fctx->step);
1801
1802 funcctx->user_fctx = fctx;
1803 MemoryContextSwitchTo(oldcontext);
1804 }
1805
1806 /* stuff done on every call of the function */
1807 funcctx = SRF_PERCALL_SETUP();
1808
1809 /*
1810 * Get the saved state and use current state as the result of this
1811 * iteration.
1812 */
1813 fctx = funcctx->user_fctx;
1814
1815 if ((fctx->step.sign == NUMERIC_POS &&
1816 cmp_var(&fctx->current, &fctx->stop) <= 0) ||
1817 (fctx->step.sign == NUMERIC_NEG &&
1818 cmp_var(&fctx->current, &fctx->stop) >= 0))
1819 {
1820 Numeric result = make_result(&fctx->current);
1821
1822 /* switch to memory context appropriate for iteration calculation */
1823 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1824
1825 /* increment current in preparation for next iteration */
1826 add_var(&fctx->current, &fctx->step, &fctx->current);
1827 MemoryContextSwitchTo(oldcontext);
1828
1829 /* do when there is more left to send */
1830 SRF_RETURN_NEXT(funcctx, NumericGetDatum(result));
1831 }
1832 else
1833 /* do when there is no more left */
1834 SRF_RETURN_DONE(funcctx);
1835 }
1836
1837 /*
1838 * Planner support function for generate_series(numeric, numeric [, numeric])
1839 */
1840 Datum
1841 generate_series_numeric_support(PG_FUNCTION_ARGS)
1842 {
1843 Node *rawreq = (Node *) PG_GETARG_POINTER(0);
1844 Node *ret = NULL;
1845
1846 if (IsA(rawreq, SupportRequestRows))
1847 {
1848 /* Try to estimate the number of rows returned */
1849 SupportRequestRows *req = (SupportRequestRows *) rawreq;
1850
1851 if (is_funcclause(req->node)) /* be paranoid */
1852 {
1853 List *args = ((FuncExpr *) req->node)->args;
1854 Node *arg1,
1855 *arg2,
1856 *arg3;
1857
1858 /* We can use estimated argument values here */
1859 arg1 = estimate_expression_value(req->root, linitial(args));
1860 arg2 = estimate_expression_value(req->root, lsecond(args));
1861 if (list_length(args) >= 3)
1862 arg3 = estimate_expression_value(req->root, lthird(args));
1863 else
1864 arg3 = NULL;
1865
1866 /*
1867 * If any argument is constant NULL, we can safely assume that
1868 * zero rows are returned. Otherwise, if they're all non-NULL
1869 * constants, we can calculate the number of rows that will be
1870 * returned.
1871 */
1872 if ((IsA(arg1, Const) &&
1873 ((Const *) arg1)->constisnull) ||
1874 (IsA(arg2, Const) &&
1875 ((Const *) arg2)->constisnull) ||
1876 (arg3 != NULL && IsA(arg3, Const) &&
1877 ((Const *) arg3)->constisnull))
1878 {
1879 req->rows = 0;
1880 ret = (Node *) req;
1881 }
1882 else if (IsA(arg1, Const) &&
1883 IsA(arg2, Const) &&
1884 (arg3 == NULL || IsA(arg3, Const)))
1885 {
1886 Numeric start_num;
1887 Numeric stop_num;
1888 NumericVar step = const_one;
1889
1890 /*
1891 * If any argument is NaN or infinity, generate_series() will
1892 * error out, so we needn't produce an estimate.
1893 */
1894 start_num = DatumGetNumeric(((Const *) arg1)->constvalue);
1895 stop_num = DatumGetNumeric(((Const *) arg2)->constvalue);
1896
1897 if (NUMERIC_IS_SPECIAL(start_num) ||
1898 NUMERIC_IS_SPECIAL(stop_num))
1899 PG_RETURN_POINTER(NULL);
1900
1901 if (arg3)
1902 {
1903 Numeric step_num;
1904
1905 step_num = DatumGetNumeric(((Const *) arg3)->constvalue);
1906
1907 if (NUMERIC_IS_SPECIAL(step_num))
1908 PG_RETURN_POINTER(NULL);
1909
1910 init_var_from_num(step_num, &step);
1911 }
1912
1913 /*
1914 * The number of rows that will be returned is given by
1915 * floor((stop - start) / step) + 1, if the sign of step
1916 * matches the sign of stop - start. Otherwise, no rows will
1917 * be returned.
1918 */
1919 if (cmp_var(&step, &const_zero) != 0)
1920 {
1921 NumericVar start;
1922 NumericVar stop;
1923 NumericVar res;
1924
1925 init_var_from_num(start_num, &start);
1926 init_var_from_num(stop_num, &stop);
1927
1928 init_var(&res);
1929 sub_var(&stop, &start, &res);
1930
1931 if (step.sign != res.sign)
1932 {
1933 /* no rows will be returned */
1934 req->rows = 0;
1935 ret = (Node *) req;
1936 }
1937 else
1938 {
1939 if (arg3)
1940 div_var(&res, &step, &res, 0, false, false);
1941 else
1942 trunc_var(&res, 0); /* step = 1 */
1943
1944 req->rows = numericvar_to_double_no_overflow(&res) + 1;
1945 ret = (Node *) req;
1946 }
1947
1948 free_var(&res);
1949 }
1950 }
1951 }
1952 }
1953
1954 PG_RETURN_POINTER(ret);
1955 }
1956
1957
1958 /*
1959 * Implements the numeric version of the width_bucket() function
1960 * defined by SQL2003. See also width_bucket_float8().
1961 *
1962 * 'bound1' and 'bound2' are the lower and upper bounds of the
1963 * histogram's range, respectively. 'count' is the number of buckets
1964 * in the histogram. width_bucket() returns an integer indicating the
1965 * bucket number that 'operand' belongs to in an equiwidth histogram
1966 * with the specified characteristics. An operand smaller than the
1967 * lower bound is assigned to bucket 0. An operand greater than or equal
1968 * to the upper bound is assigned to an additional bucket (with number
1969 * count+1). We don't allow "NaN" for any of the numeric inputs, and we
1970 * don't allow either of the histogram bounds to be +/- infinity.
1971 */
1972 Datum
1973 width_bucket_numeric(PG_FUNCTION_ARGS)
1974 {
1975 Numeric operand = PG_GETARG_NUMERIC(0);
1976 Numeric bound1 = PG_GETARG_NUMERIC(1);
1977 Numeric bound2 = PG_GETARG_NUMERIC(2);
1978 int32 count = PG_GETARG_INT32(3);
1979 NumericVar count_var;
1980 NumericVar result_var;
1981 int32 result;
1982
1983 if (count <= 0)
1984 ereport(ERROR,
1985 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
1986 errmsg("count must be greater than zero")));
1987
1988 if (NUMERIC_IS_SPECIAL(operand) ||
1989 NUMERIC_IS_SPECIAL(bound1) ||
1990 NUMERIC_IS_SPECIAL(bound2))
1991 {
1992 if (NUMERIC_IS_NAN(operand) ||
1993 NUMERIC_IS_NAN(bound1) ||
1994 NUMERIC_IS_NAN(bound2))
1995 ereport(ERROR,
1996 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
1997 errmsg("operand, lower bound, and upper bound cannot be NaN")));
1998 /* We allow "operand" to be infinite; cmp_numerics will cope */
1999 if (NUMERIC_IS_INF(bound1) || NUMERIC_IS_INF(bound2))
2000 ereport(ERROR,
2001 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
2002 errmsg("lower and upper bounds must be finite")));
2003 }
2004
2005 init_var(&result_var);
2006 init_var(&count_var);
2007
2008 /* Convert 'count' to a numeric, for ease of use later */
2009 int64_to_numericvar((int64) count, &count_var);
2010
2011 switch (cmp_numerics(bound1, bound2))
2012 {
2013 case 0:
2014 ereport(ERROR,
2015 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
2016 errmsg("lower bound cannot equal upper bound")));
2017 break;
2018
2019 /* bound1 < bound2 */
2020 case -1:
2021 if (cmp_numerics(operand, bound1) < 0)
2022 set_var_from_var(&const_zero, &result_var);
2023 else if (cmp_numerics(operand, bound2) >= 0)
2024 add_var(&count_var, &const_one, &result_var);
2025 else
2026 compute_bucket(operand, bound1, bound2, &count_var,
2027 &result_var);
2028 break;
2029
2030 /* bound1 > bound2 */
2031 case 1:
2032 if (cmp_numerics(operand, bound1) > 0)
2033 set_var_from_var(&const_zero, &result_var);
2034 else if (cmp_numerics(operand, bound2) <= 0)
2035 add_var(&count_var, &const_one, &result_var);
2036 else
2037 compute_bucket(operand, bound1, bound2, &count_var,
2038 &result_var);
2039 break;
2040 }
2041
2042 /* if result exceeds the range of a legal int4, we ereport here */
2043 if (!numericvar_to_int32(&result_var, &result))
2044 ereport(ERROR,
2045 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
2046 errmsg("integer out of range")));
2047
2048 free_var(&count_var);
2049 free_var(&result_var);
2050
2051 PG_RETURN_INT32(result);
2052 }
2053
2054 /*
2055 * 'operand' is inside the bucket range, so determine the correct
2056 * bucket for it to go in. The calculations performed by this function
2057 * are derived directly from the SQL2003 spec. Note however that we
2058 * multiply by count before dividing, to avoid unnecessary roundoff error.
2059 */
2060 static void
2061 compute_bucket(Numeric operand, Numeric bound1, Numeric bound2,
2062 const NumericVar *count_var, NumericVar *result_var)
2063 {
2064 NumericVar bound1_var;
2065 NumericVar bound2_var;
2066 NumericVar operand_var;
2067
2068 init_var_from_num(bound1, &bound1_var);
2069 init_var_from_num(bound2, &bound2_var);
2070 init_var_from_num(operand, &operand_var);
2071
2072 /*
2073 * Per spec, bound1 is inclusive and bound2 is exclusive, and so we have
2074 * bound1 <= operand < bound2 or bound1 >= operand > bound2. Either way,
2075 * the result is ((operand - bound1) * count) / (bound2 - bound1) + 1,
2076 * where the quotient is computed using floor division (i.e., division to
2077 * zero decimal places with truncation), which guarantees that the result
2078 * is in the range [1, count]. Reversing the bounds doesn't affect the
2079 * computation, because the signs cancel out when dividing.
2080 */
2081 sub_var(&operand_var, &bound1_var, &operand_var);
2082 sub_var(&bound2_var, &bound1_var, &bound2_var);
2083
2084 mul_var(&operand_var, count_var, &operand_var,
2085 operand_var.dscale + count_var->dscale);
2086 div_var(&operand_var, &bound2_var, result_var, 0, false, true);
2087 add_var(result_var, &const_one, result_var);
2088
2089 free_var(&bound1_var);
2090 free_var(&bound2_var);
2091 free_var(&operand_var);
2092 }
2093
2094 /* ----------------------------------------------------------------------
2095 *
2096 * Comparison functions
2097 *
2098 * Note: btree indexes need these routines not to leak memory; therefore,
2099 * be careful to free working copies of toasted datums. Most places don't
2100 * need to be so careful.
2101 *
2102 * Sort support:
2103 *
2104 * We implement the sortsupport strategy routine in order to get the benefit of
2105 * abbreviation. The ordinary numeric comparison can be quite slow as a result
2106 * of palloc/pfree cycles (due to detoasting packed values for alignment);
2107 * while this could be worked on itself, the abbreviation strategy gives more
2108 * speedup in many common cases.
2109 *
2110 * Two different representations are used for the abbreviated form, one in
2111 * int32 and one in int64, whichever fits into a by-value Datum. In both cases
2112 * the representation is negated relative to the original value, because we use
2113 * the largest negative value for NaN, which sorts higher than other values. We
2114 * convert the absolute value of the numeric to a 31-bit or 63-bit positive
2115 * value, and then negate it if the original number was positive.
2116 *
2117 * We abort the abbreviation process if the abbreviation cardinality is below
2118 * 0.01% of the row count (1 per 10k non-null rows). The actual break-even
2119 * point is somewhat below that, perhaps 1 per 30k (at 1 per 100k there's a
2120 * very small penalty), but we don't want to build up too many abbreviated
2121 * values before first testing for abort, so we take the slightly pessimistic
2122 * number. We make no attempt to estimate the cardinality of the real values,
2123 * since it plays no part in the cost model here (if the abbreviation is equal,
2124 * the cost of comparing equal and unequal underlying values is comparable).
2125 * We discontinue even checking for abort (saving us the hashing overhead) if
2126 * the estimated cardinality gets to 100k; that would be enough to support many
2127 * billions of rows while doing no worse than breaking even.
2128 *
2129 * ----------------------------------------------------------------------
2130 */
2131
2132 /*
2133 * Sort support strategy routine.
2134 */
2135 Datum
2136 numeric_sortsupport(PG_FUNCTION_ARGS)
2137 {
2138 SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
2139
2140 ssup->comparator = numeric_fast_cmp;
2141
2142 if (ssup->abbreviate)
2143 {
2144 NumericSortSupport *nss;
2145 MemoryContext oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
2146
2147 nss = palloc(sizeof(NumericSortSupport));
2148
2149 /*
2150 * palloc a buffer for handling unaligned packed values in addition to
2151 * the support struct
2152 */
2153 nss->buf = palloc(VARATT_SHORT_MAX + VARHDRSZ + 1);
2154
2155 nss->input_count = 0;
2156 nss->estimating = true;
2157 initHyperLogLog(&nss->abbr_card, 10);
2158
2159 ssup->ssup_extra = nss;
2160
2161 ssup->abbrev_full_comparator = ssup->comparator;
2162 ssup->comparator = numeric_cmp_abbrev;
2163 ssup->abbrev_converter = numeric_abbrev_convert;
2164 ssup->abbrev_abort = numeric_abbrev_abort;
2165
2166 MemoryContextSwitchTo(oldcontext);
2167 }
2168
2169 PG_RETURN_VOID();
2170 }
2171
2172 /*
2173 * Abbreviate a numeric datum, handling NaNs and detoasting
2174 * (must not leak memory!)
2175 */
2176 static Datum
2177 numeric_abbrev_convert(Datum original_datum, SortSupport ssup)
2178 {
2179 NumericSortSupport *nss = ssup->ssup_extra;
2180 void *original_varatt = PG_DETOAST_DATUM_PACKED(original_datum);
2181 Numeric value;
2182 Datum result;
2183
2184 nss->input_count += 1;
2185
2186 /*
2187 * This is to handle packed datums without needing a palloc/pfree cycle;
2188 * we keep and reuse a buffer large enough to handle any short datum.
2189 */
2190 if (VARATT_IS_SHORT(original_varatt))
2191 {
2192 void *buf = nss->buf;
2193 Size sz = VARSIZE_SHORT(original_varatt) - VARHDRSZ_SHORT;
2194
2195 Assert(sz <= VARATT_SHORT_MAX - VARHDRSZ_SHORT);
2196
2197 SET_VARSIZE(buf, VARHDRSZ + sz);
2198 memcpy(VARDATA(buf), VARDATA_SHORT(original_varatt), sz);
2199
2200 value = (Numeric) buf;
2201 }
2202 else
2203 value = (Numeric) original_varatt;
2204
2205 if (NUMERIC_IS_SPECIAL(value))
2206 {
2207 if (NUMERIC_IS_PINF(value))
2208 result = NUMERIC_ABBREV_PINF;
2209 else if (NUMERIC_IS_NINF(value))
2210 result = NUMERIC_ABBREV_NINF;
2211 else
2212 result = NUMERIC_ABBREV_NAN;
2213 }
2214 else
2215 {
2216 NumericVar var;
2217
2218 init_var_from_num(value, &var);
2219
2220 result = numeric_abbrev_convert_var(&var, nss);
2221 }
2222
2223 /* should happen only for external/compressed toasts */
2224 if ((Pointer) original_varatt != DatumGetPointer(original_datum))
2225 pfree(original_varatt);
2226
2227 return result;
2228 }
2229
2230 /*
2231 * Consider whether to abort abbreviation.
2232 *
2233 * We pay no attention to the cardinality of the non-abbreviated data. There is
2234 * no reason to do so: unlike text, we have no fast check for equal values, so
2235 * we pay the full overhead whenever the abbreviations are equal regardless of
2236 * whether the underlying values are also equal.
2237 */
2238 static bool
2239 numeric_abbrev_abort(int memtupcount, SortSupport ssup)
2240 {
2241 NumericSortSupport *nss = ssup->ssup_extra;
2242 double abbr_card;
2243
2244 if (memtupcount < 10000 || nss->input_count < 10000 || !nss->estimating)
2245 return false;
2246
2247 abbr_card = estimateHyperLogLog(&nss->abbr_card);
2248
2249 /*
2250 * If we have >100k distinct values, then even if we were sorting many
2251 * billion rows we'd likely still break even, and the penalty of undoing
2252 * that many rows of abbrevs would probably not be worth it. Stop even
2253 * counting at that point.
2254 */
2255 if (abbr_card > 100000.0)
2256 {
2257 if (trace_sort)
2258 elog(LOG,
2259 "numeric_abbrev: estimation ends at cardinality %f"
2260 " after " INT64_FORMAT " values (%d rows)",
2261 abbr_card, nss->input_count, memtupcount);
2262 nss->estimating = false;
2263 return false;
2264 }
2265
2266 /*
2267 * Target minimum cardinality is 1 per ~10k of non-null inputs. (The
2268 * break even point is somewhere between one per 100k rows, where
2269 * abbreviation has a very slight penalty, and 1 per 10k where it wins by
2270 * a measurable percentage.) We use the relatively pessimistic 10k
2271 * threshold, and add a 0.5 row fudge factor, because it allows us to
2272 * abort earlier on genuinely pathological data where we've had exactly
2273 * one abbreviated value in the first 10k (non-null) rows.
2274 */
2275 if (abbr_card < nss->input_count / 10000.0 + 0.5)
2276 {
2277 if (trace_sort)
2278 elog(LOG,
2279 "numeric_abbrev: aborting abbreviation at cardinality %f"
2280 " below threshold %f after " INT64_FORMAT " values (%d rows)",
2281 abbr_card, nss->input_count / 10000.0 + 0.5,
2282 nss->input_count, memtupcount);
2283 return true;
2284 }
2285
2286 if (trace_sort)
2287 elog(LOG,
2288 "numeric_abbrev: cardinality %f"
2289 " after " INT64_FORMAT " values (%d rows)",
2290 abbr_card, nss->input_count, memtupcount);
2291
2292 return false;
2293 }
2294
2295 /*
2296 * Non-fmgr interface to the comparison routine to allow sortsupport to elide
2297 * the fmgr call. The saving here is small given how slow numeric comparisons
2298 * are, but it is a required part of the sort support API when abbreviations
2299 * are performed.
2300 *
2301 * Two palloc/pfree cycles could be saved here by using persistent buffers for
2302 * aligning short-varlena inputs, but this has not so far been considered to
2303 * be worth the effort.
2304 */
2305 static int
2306 numeric_fast_cmp(Datum x, Datum y, SortSupport ssup)
2307 {
2308 Numeric nx = DatumGetNumeric(x);
2309 Numeric ny = DatumGetNumeric(y);
2310 int result;
2311
2312 result = cmp_numerics(nx, ny);
2313
2314 if ((Pointer) nx != DatumGetPointer(x))
2315 pfree(nx);
2316 if ((Pointer) ny != DatumGetPointer(y))
2317 pfree(ny);
2318
2319 return result;
2320 }
2321
2322 /*
2323 * Compare abbreviations of values. (Abbreviations may be equal where the true
2324 * values differ, but if the abbreviations differ, they must reflect the
2325 * ordering of the true values.)
2326 */
2327 static int
2328 numeric_cmp_abbrev(Datum x, Datum y, SortSupport ssup)
2329 {
2330 /*
2331 * NOTE WELL: this is intentionally backwards, because the abbreviation is
2332 * negated relative to the original value, to handle NaN/infinity cases.
2333 */
2334 if (DatumGetNumericAbbrev(x) < DatumGetNumericAbbrev(y))
2335 return 1;
2336 if (DatumGetNumericAbbrev(x) > DatumGetNumericAbbrev(y))
2337 return -1;
2338 return 0;
2339 }
2340
2341 /*
2342 * Abbreviate a NumericVar according to the available bit size.
2343 *
2344 * The 31-bit value is constructed as:
2345 *
2346 * 0 + 7bits digit weight + 24 bits digit value
2347 *
2348 * where the digit weight is in single decimal digits, not digit words, and
2349 * stored in excess-44 representation[1]. The 24-bit digit value is the 7 most
2350 * significant decimal digits of the value converted to binary. Values whose
2351 * weights would fall outside the representable range are rounded off to zero
2352 * (which is also used to represent actual zeros) or to 0x7FFFFFFF (which
2353 * otherwise cannot occur). Abbreviation therefore fails to gain any advantage
2354 * where values are outside the range 10^-44 to 10^83, which is not considered
2355 * to be a serious limitation, or when values are of the same magnitude and
2356 * equal in the first 7 decimal digits, which is considered to be an
2357 * unavoidable limitation given the available bits. (Stealing three more bits
2358 * to compare another digit would narrow the range of representable weights by
2359 * a factor of 8, which starts to look like a real limiting factor.)
2360 *
2361 * (The value 44 for the excess is essentially arbitrary)
2362 *
2363 * The 63-bit value is constructed as:
2364 *
2365 * 0 + 7bits weight + 4 x 14-bit packed digit words
2366 *
2367 * The weight in this case is again stored in excess-44, but this time it is
2368 * the original weight in digit words (i.e. powers of 10000). The first four
2369 * digit words of the value (if present; trailing zeros are assumed as needed)
2370 * are packed into 14 bits each to form the rest of the value. Again,
2371 * out-of-range values are rounded off to 0 or 0x7FFFFFFFFFFFFFFF. The
2372 * representable range in this case is 10^-176 to 10^332, which is considered
2373 * to be good enough for all practical purposes, and comparison of 4 words
2374 * means that at least 13 decimal digits are compared, which is considered to
2375 * be a reasonable compromise between effectiveness and efficiency in computing
2376 * the abbreviation.
2377 *
2378 * (The value 44 for the excess is even more arbitrary here, it was chosen just
2379 * to match the value used in the 31-bit case)
2380 *
2381 * [1] - Excess-k representation means that the value is offset by adding 'k'
2382 * and then treated as unsigned, so the smallest representable value is stored
2383 * with all bits zero. This allows simple comparisons to work on the composite
2384 * value.
2385 */
2386
2387 #if NUMERIC_ABBREV_BITS == 64
2388
2389 static Datum
2390 numeric_abbrev_convert_var(const NumericVar *var, NumericSortSupport *nss)
2391 {
2392 int ndigits = var->ndigits;
2393 int weight = var->weight;
2394 int64 result;
2395
2396 if (ndigits == 0 || weight < -44)
2397 {
2398 result = 0;
2399 }
2400 else if (weight > 83)
2401 {
2402 result = PG_INT64_MAX;
2403 }
2404 else
2405 {
2406 result = ((int64) (weight + 44) << 56);
2407
2408 switch (ndigits)
2409 {
2410 default:
2411 result |= ((int64) var->digits[3]);
2412 /* FALLTHROUGH */
2413 case 3:
2414 result |= ((int64) var->digits[2]) << 14;
2415 /* FALLTHROUGH */
2416 case 2:
2417 result |= ((int64) var->digits[1]) << 28;
2418 /* FALLTHROUGH */
2419 case 1:
2420 result |= ((int64) var->digits[0]) << 42;
2421 break;
2422 }
2423 }
2424
2425 /* the abbrev is negated relative to the original */
2426 if (var->sign == NUMERIC_POS)
2427 result = -result;
2428
2429 if (nss->estimating)
2430 {
2431 uint32 tmp = ((uint32) result
2432 ^ (uint32) ((uint64) result >> 32));
2433
2434 addHyperLogLog(&nss->abbr_card, DatumGetUInt32(hash_uint32(tmp)));
2435 }
2436
2437 return NumericAbbrevGetDatum(result);
2438 }
2439
2440 #endif /* NUMERIC_ABBREV_BITS == 64 */
2441
2442 #if NUMERIC_ABBREV_BITS == 32
2443
2444 static Datum
2445 numeric_abbrev_convert_var(const NumericVar *var, NumericSortSupport *nss)
2446 {
2447 int ndigits = var->ndigits;
2448 int weight = var->weight;
2449 int32 result;
2450
2451 if (ndigits == 0 || weight < -11)
2452 {
2453 result = 0;
2454 }
2455 else if (weight > 20)
2456 {
2457 result = PG_INT32_MAX;
2458 }
2459 else
2460 {
2461 NumericDigit nxt1 = (ndigits > 1) ? var->digits[1] : 0;
2462
2463 weight = (weight + 11) * 4;
2464
2465 result = var->digits[0];
2466
2467 /*
2468 * "result" now has 1 to 4 nonzero decimal digits. We pack in more
2469 * digits to make 7 in total (largest we can fit in 24 bits)
2470 */
2471
2472 if (result > 999)
2473 {
2474 /* already have 4 digits, add 3 more */
2475 result = (result * 1000) + (nxt1 / 10);
2476 weight += 3;
2477 }
2478 else if (result > 99)
2479 {
2480 /* already have 3 digits, add 4 more */
2481 result = (result * 10000) + nxt1;
2482 weight += 2;
2483 }
2484 else if (result > 9)
2485 {
2486 NumericDigit nxt2 = (ndigits > 2) ? var->digits[2] : 0;
2487
2488 /* already have 2 digits, add 5 more */
2489 result = (result * 100000) + (nxt1 * 10) + (nxt2 / 1000);
2490 weight += 1;
2491 }
2492 else
2493 {
2494 NumericDigit nxt2 = (ndigits > 2) ? var->digits[2] : 0;
2495
2496 /* already have 1 digit, add 6 more */
2497 result = (result * 1000000) + (nxt1 * 100) + (nxt2 / 100);
2498 }
2499
2500 result = result | (weight << 24);
2501 }
2502
2503 /* the abbrev is negated relative to the original */
2504 if (var->sign == NUMERIC_POS)
2505 result = -result;
2506
2507 if (nss->estimating)
2508 {
2509 uint32 tmp = (uint32) result;
2510
2511 addHyperLogLog(&nss->abbr_card, DatumGetUInt32(hash_uint32(tmp)));
2512 }
2513
2514 return NumericAbbrevGetDatum(result);
2515 }
2516
2517 #endif /* NUMERIC_ABBREV_BITS == 32 */
2518
2519 /*
2520 * Ordinary (non-sortsupport) comparisons follow.
2521 */
2522
2523 Datum
2524 numeric_cmp(PG_FUNCTION_ARGS)
2525 {
2526 Numeric num1 = PG_GETARG_NUMERIC(0);
2527 Numeric num2 = PG_GETARG_NUMERIC(1);
2528 int result;
2529
2530 result = cmp_numerics(num1, num2);
2531
2532 PG_FREE_IF_COPY(num1, 0);
2533 PG_FREE_IF_COPY(num2, 1);
2534
2535 PG_RETURN_INT32(result);
2536 }
2537
2538
2539 Datum
2540 numeric_eq(PG_FUNCTION_ARGS)
2541 {
2542 Numeric num1 = PG_GETARG_NUMERIC(0);
2543 Numeric num2 = PG_GETARG_NUMERIC(1);
2544 bool result;
2545
2546 result = cmp_numerics(num1, num2) == 0;
2547
2548 PG_FREE_IF_COPY(num1, 0);
2549 PG_FREE_IF_COPY(num2, 1);
2550
2551 PG_RETURN_BOOL(result);
2552 }
2553
2554 Datum
2555 numeric_ne(PG_FUNCTION_ARGS)
2556 {
2557 Numeric num1 = PG_GETARG_NUMERIC(0);
2558 Numeric num2 = PG_GETARG_NUMERIC(1);
2559 bool result;
2560
2561 result = cmp_numerics(num1, num2) != 0;
2562
2563 PG_FREE_IF_COPY(num1, 0);
2564 PG_FREE_IF_COPY(num2, 1);
2565
2566 PG_RETURN_BOOL(result);
2567 }
2568
2569 Datum
2570 numeric_gt(PG_FUNCTION_ARGS)
2571 {
2572 Numeric num1 = PG_GETARG_NUMERIC(0);
2573 Numeric num2 = PG_GETARG_NUMERIC(1);
2574 bool result;
2575
2576 result = cmp_numerics(num1, num2) > 0;
2577
2578 PG_FREE_IF_COPY(num1, 0);
2579 PG_FREE_IF_COPY(num2, 1);
2580
2581 PG_RETURN_BOOL(result);
2582 }
2583
2584 Datum
2585 numeric_ge(PG_FUNCTION_ARGS)
2586 {
2587 Numeric num1 = PG_GETARG_NUMERIC(0);
2588 Numeric num2 = PG_GETARG_NUMERIC(1);
2589 bool result;
2590
2591 result = cmp_numerics(num1, num2) >= 0;
2592
2593 PG_FREE_IF_COPY(num1, 0);
2594 PG_FREE_IF_COPY(num2, 1);
2595
2596 PG_RETURN_BOOL(result);
2597 }
2598
2599 Datum
2600 numeric_lt(PG_FUNCTION_ARGS)
2601 {
2602 Numeric num1 = PG_GETARG_NUMERIC(0);
2603 Numeric num2 = PG_GETARG_NUMERIC(1);
2604 bool result;
2605
2606 result = cmp_numerics(num1, num2) < 0;
2607
2608 PG_FREE_IF_COPY(num1, 0);
2609 PG_FREE_IF_COPY(num2, 1);
2610
2611 PG_RETURN_BOOL(result);
2612 }
2613
2614 Datum
2615 numeric_le(PG_FUNCTION_ARGS)
2616 {
2617 Numeric num1 = PG_GETARG_NUMERIC(0);
2618 Numeric num2 = PG_GETARG_NUMERIC(1);
2619 bool result;
2620
2621 result = cmp_numerics(num1, num2) <= 0;
2622
2623 PG_FREE_IF_COPY(num1, 0);
2624 PG_FREE_IF_COPY(num2, 1);
2625
2626 PG_RETURN_BOOL(result);
2627 }
2628
2629 static int
2630 cmp_numerics(Numeric num1, Numeric num2)
2631 {
2632 int result;
2633
2634 /*
2635 * We consider all NANs to be equal and larger than any non-NAN (including
2636 * Infinity). This is somewhat arbitrary; the important thing is to have
2637 * a consistent sort order.
2638 */
2639 if (NUMERIC_IS_SPECIAL(num1))
2640 {
2641 if (NUMERIC_IS_NAN(num1))
2642 {
2643 if (NUMERIC_IS_NAN(num2))
2644 result = 0; /* NAN = NAN */
2645 else
2646 result = 1; /* NAN > non-NAN */
2647 }
2648 else if (NUMERIC_IS_PINF(num1))
2649 {
2650 if (NUMERIC_IS_NAN(num2))
2651 result = -1; /* PINF < NAN */
2652 else if (NUMERIC_IS_PINF(num2))
2653 result = 0; /* PINF = PINF */
2654 else
2655 result = 1; /* PINF > anything else */
2656 }
2657 else /* num1 must be NINF */
2658 {
2659 if (NUMERIC_IS_NINF(num2))
2660 result = 0; /* NINF = NINF */
2661 else
2662 result = -1; /* NINF < anything else */
2663 }
2664 }
2665 else if (NUMERIC_IS_SPECIAL(num2))
2666 {
2667 if (NUMERIC_IS_NINF(num2))
2668 result = 1; /* normal > NINF */
2669 else
2670 result = -1; /* normal < NAN or PINF */
2671 }
2672 else
2673 {
2674 result = cmp_var_common(NUMERIC_DIGITS(num1), NUMERIC_NDIGITS(num1),
2675 NUMERIC_WEIGHT(num1), NUMERIC_SIGN(num1),
2676 NUMERIC_DIGITS(num2), NUMERIC_NDIGITS(num2),
2677 NUMERIC_WEIGHT(num2), NUMERIC_SIGN(num2));
2678 }
2679
2680 return result;
2681 }
2682
2683 /*
2684 * in_range support function for numeric.
2685 */
2686 Datum
2687 in_range_numeric_numeric(PG_FUNCTION_ARGS)
2688 {
2689 Numeric val = PG_GETARG_NUMERIC(0);
2690 Numeric base = PG_GETARG_NUMERIC(1);
2691 Numeric offset = PG_GETARG_NUMERIC(2);
2692 bool sub = PG_GETARG_BOOL(3);
2693 bool less = PG_GETARG_BOOL(4);
2694 bool result;
2695
2696 /*
2697 * Reject negative (including -Inf) or NaN offset. Negative is per spec,
2698 * and NaN is because appropriate semantics for that seem non-obvious.
2699 */
2700 if (NUMERIC_IS_NAN(offset) ||
2701 NUMERIC_IS_NINF(offset) ||
2702 NUMERIC_SIGN(offset) == NUMERIC_NEG)
2703 ereport(ERROR,
2704 (errcode(ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE),
2705 errmsg("invalid preceding or following size in window function")));
2706
2707 /*
2708 * Deal with cases where val and/or base is NaN, following the rule that
2709 * NaN sorts after non-NaN (cf cmp_numerics). The offset cannot affect
2710 * the conclusion.
2711 */
2712 if (NUMERIC_IS_NAN(val))
2713 {
2714 if (NUMERIC_IS_NAN(base))
2715 result = true; /* NAN = NAN */
2716 else
2717 result = !less; /* NAN > non-NAN */
2718 }
2719 else if (NUMERIC_IS_NAN(base))
2720 {
2721 result = less; /* non-NAN < NAN */
2722 }
2723
2724 /*
2725 * Deal with infinite offset (necessarily +Inf, at this point).
2726 */
2727 else if (NUMERIC_IS_SPECIAL(offset))
2728 {
2729 Assert(NUMERIC_IS_PINF(offset));
2730 if (sub ? NUMERIC_IS_PINF(base) : NUMERIC_IS_NINF(base))
2731 {
2732 /*
2733 * base +/- offset would produce NaN, so return true for any val
2734 * (see in_range_float8_float8() for reasoning).
2735 */
2736 result = true;
2737 }
2738 else if (sub)
2739 {
2740 /* base - offset must be -inf */
2741 if (less)
2742 result = NUMERIC_IS_NINF(val); /* only -inf is <= sum */
2743 else
2744 result = true; /* any val is >= sum */
2745 }
2746 else
2747 {
2748 /* base + offset must be +inf */
2749 if (less)
2750 result = true; /* any val is <= sum */
2751 else
2752 result = NUMERIC_IS_PINF(val); /* only +inf is >= sum */
2753 }
2754 }
2755
2756 /*
2757 * Deal with cases where val and/or base is infinite. The offset, being
2758 * now known finite, cannot affect the conclusion.
2759 */
2760 else if (NUMERIC_IS_SPECIAL(val))
2761 {
2762 if (NUMERIC_IS_PINF(val))
2763 {
2764 if (NUMERIC_IS_PINF(base))
2765 result = true; /* PINF = PINF */
2766 else
2767 result = !less; /* PINF > any other non-NAN */
2768 }
2769 else /* val must be NINF */
2770 {
2771 if (NUMERIC_IS_NINF(base))
2772 result = true; /* NINF = NINF */
2773 else
2774 result = less; /* NINF < anything else */
2775 }
2776 }
2777 else if (NUMERIC_IS_SPECIAL(base))
2778 {
2779 if (NUMERIC_IS_NINF(base))
2780 result = !less; /* normal > NINF */
2781 else
2782 result = less; /* normal < PINF */
2783 }
2784 else
2785 {
2786 /*
2787 * Otherwise go ahead and compute base +/- offset. While it's
2788 * possible for this to overflow the numeric format, it's unlikely
2789 * enough that we don't take measures to prevent it.
2790 */
2791 NumericVar valv;
2792 NumericVar basev;
2793 NumericVar offsetv;
2794 NumericVar sum;
2795
2796 init_var_from_num(val, &valv);
2797 init_var_from_num(base, &basev);
2798 init_var_from_num(offset, &offsetv);
2799 init_var(&sum);
2800
2801 if (sub)
2802 sub_var(&basev, &offsetv, &sum);
2803 else
2804 add_var(&basev, &offsetv, &sum);
2805
2806 if (less)
2807 result = (cmp_var(&valv, &sum) <= 0);
2808 else
2809 result = (cmp_var(&valv, &sum) >= 0);
2810
2811 free_var(&sum);
2812 }
2813
2814 PG_FREE_IF_COPY(val, 0);
2815 PG_FREE_IF_COPY(base, 1);
2816 PG_FREE_IF_COPY(offset, 2);
2817
2818 PG_RETURN_BOOL(result);
2819 }
2820
2821 Datum
2822 hash_numeric(PG_FUNCTION_ARGS)
2823 {
2824 Numeric key = PG_GETARG_NUMERIC(0);
2825 Datum digit_hash;
2826 Datum result;
2827 int weight;
2828 int start_offset;
2829 int end_offset;
2830 int i;
2831 int hash_len;
2832 NumericDigit *digits;
2833
2834 /* If it's NaN or infinity, don't try to hash the rest of the fields */
2835 if (NUMERIC_IS_SPECIAL(key))
2836 PG_RETURN_UINT32(0);
2837
2838 weight = NUMERIC_WEIGHT(key);
2839 start_offset = 0;
2840 end_offset = 0;
2841
2842 /*
2843 * Omit any leading or trailing zeros from the input to the hash. The
2844 * numeric implementation *should* guarantee that leading and trailing
2845 * zeros are suppressed, but we're paranoid. Note that we measure the
2846 * starting and ending offsets in units of NumericDigits, not bytes.
2847 */
2848 digits = NUMERIC_DIGITS(key);
2849 for (i = 0; i < NUMERIC_NDIGITS(key); i++)
2850 {
2851 if (digits[i] != (NumericDigit) 0)
2852 break;
2853
2854 start_offset++;
2855
2856 /*
2857 * The weight is effectively the # of digits before the decimal point,
2858 * so decrement it for each leading zero we skip.
2859 */
2860 weight--;
2861 }
2862
2863 /*
2864 * If there are no non-zero digits, then the value of the number is zero,
2865 * regardless of any other fields.
2866 */
2867 if (NUMERIC_NDIGITS(key) == start_offset)
2868 PG_RETURN_UINT32(-1);
2869
2870 for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--)
2871 {
2872 if (digits[i] != (NumericDigit) 0)
2873 break;
2874
2875 end_offset++;
2876 }
2877
2878 /* If we get here, there should be at least one non-zero digit */
2879 Assert(start_offset + end_offset < NUMERIC_NDIGITS(key));
2880
2881 /*
2882 * Note that we don't hash on the Numeric's scale, since two numerics can
2883 * compare equal but have different scales. We also don't hash on the
2884 * sign, although we could: since a sign difference implies inequality,
2885 * this shouldn't affect correctness.
2886 */
2887 hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset;
2888 digit_hash = hash_any((unsigned char *) (NUMERIC_DIGITS(key) + start_offset),
2889 hash_len * sizeof(NumericDigit));
2890
2891 /* Mix in the weight, via XOR */
2892 result = digit_hash ^ weight;
2893
2894 PG_RETURN_DATUM(result);
2895 }
2896
2897 /*
2898 * Returns 64-bit value by hashing a value to a 64-bit value, with a seed.
2899 * Otherwise, similar to hash_numeric.
2900 */
2901 Datum
2902 hash_numeric_extended(PG_FUNCTION_ARGS)
2903 {
2904 Numeric key = PG_GETARG_NUMERIC(0);
2905 uint64 seed = PG_GETARG_INT64(1);
2906 Datum digit_hash;
2907 Datum result;
2908 int weight;
2909 int start_offset;
2910 int end_offset;
2911 int i;
2912 int hash_len;
2913 NumericDigit *digits;
2914
2915 /* If it's NaN or infinity, don't try to hash the rest of the fields */
2916 if (NUMERIC_IS_SPECIAL(key))
2917 PG_RETURN_UINT64(seed);
2918
2919 weight = NUMERIC_WEIGHT(key);
2920 start_offset = 0;
2921 end_offset = 0;
2922
2923 digits = NUMERIC_DIGITS(key);
2924 for (i = 0; i < NUMERIC_NDIGITS(key); i++)
2925 {
2926 if (digits[i] != (NumericDigit) 0)
2927 break;
2928
2929 start_offset++;
2930
2931 weight--;
2932 }
2933
2934 if (NUMERIC_NDIGITS(key) == start_offset)
2935 PG_RETURN_UINT64(seed - 1);
2936
2937 for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--)
2938 {
2939 if (digits[i] != (NumericDigit) 0)
2940 break;
2941
2942 end_offset++;
2943 }
2944
2945 Assert(start_offset + end_offset < NUMERIC_NDIGITS(key));
2946
2947 hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset;
2948 digit_hash = hash_any_extended((unsigned char *) (NUMERIC_DIGITS(key)
2949 + start_offset),
2950 hash_len * sizeof(NumericDigit),
2951 seed);
2952
2953 result = UInt64GetDatum(DatumGetUInt64(digit_hash) ^ weight);
2954
2955 PG_RETURN_DATUM(result);
2956 }
2957
2958
2959 /* ----------------------------------------------------------------------
2960 *
2961 * Basic arithmetic functions
2962 *
2963 * ----------------------------------------------------------------------
2964 */
2965
2966
2967 /*
2968 * numeric_add() -
2969 *
2970 * Add two numerics
2971 */
2972 Datum
2973 numeric_add(PG_FUNCTION_ARGS)
2974 {
2975 Numeric num1 = PG_GETARG_NUMERIC(0);
2976 Numeric num2 = PG_GETARG_NUMERIC(1);
2977 Numeric res;
2978
2979 res = numeric_add_opt_error(num1, num2, NULL);
2980
2981 PG_RETURN_NUMERIC(res);
2982 }
2983
2984 /*
2985 * numeric_add_opt_error() -
2986 *
2987 * Internal version of numeric_add(). If "*have_error" flag is provided,
2988 * on error it's set to true, NULL returned. This is helpful when caller
2989 * need to handle errors by itself.
2990 */
2991 Numeric
2992 numeric_add_opt_error(Numeric num1, Numeric num2, bool *have_error)
2993 {
2994 NumericVar arg1;
2995 NumericVar arg2;
2996 NumericVar result;
2997 Numeric res;
2998
2999 /*
3000 * Handle NaN and infinities
3001 */
3002 if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3003 {
3004 if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3005 return make_result(&const_nan);
3006 if (NUMERIC_IS_PINF(num1))
3007 {
3008 if (NUMERIC_IS_NINF(num2))
3009 return make_result(&const_nan); /* Inf + -Inf */
3010 else
3011 return make_result(&const_pinf);
3012 }
3013 if (NUMERIC_IS_NINF(num1))
3014 {
3015 if (NUMERIC_IS_PINF(num2))
3016 return make_result(&const_nan); /* -Inf + Inf */
3017 else
3018 return make_result(&const_ninf);
3019 }
3020 /* by here, num1 must be finite, so num2 is not */
3021 if (NUMERIC_IS_PINF(num2))
3022 return make_result(&const_pinf);
3023 Assert(NUMERIC_IS_NINF(num2));
3024 return make_result(&const_ninf);
3025 }
3026
3027 /*
3028 * Unpack the values, let add_var() compute the result and return it.
3029 */
3030 init_var_from_num(num1, &arg1);
3031 init_var_from_num(num2, &arg2);
3032
3033 init_var(&result);
3034 add_var(&arg1, &arg2, &result);
3035
3036 res = make_result_opt_error(&result, have_error);
3037
3038 free_var(&result);
3039
3040 return res;
3041 }
3042
3043
3044 /*
3045 * numeric_sub() -
3046 *
3047 * Subtract one numeric from another
3048 */
3049 Datum
3050 numeric_sub(PG_FUNCTION_ARGS)
3051 {
3052 Numeric num1 = PG_GETARG_NUMERIC(0);
3053 Numeric num2 = PG_GETARG_NUMERIC(1);
3054 Numeric res;
3055
3056 res = numeric_sub_opt_error(num1, num2, NULL);
3057
3058 PG_RETURN_NUMERIC(res);
3059 }
3060
3061
3062 /*
3063 * numeric_sub_opt_error() -
3064 *
3065 * Internal version of numeric_sub(). If "*have_error" flag is provided,
3066 * on error it's set to true, NULL returned. This is helpful when caller
3067 * need to handle errors by itself.
3068 */
3069 Numeric
3070 numeric_sub_opt_error(Numeric num1, Numeric num2, bool *have_error)
3071 {
3072 NumericVar arg1;
3073 NumericVar arg2;
3074 NumericVar result;
3075 Numeric res;
3076
3077 /*
3078 * Handle NaN and infinities
3079 */
3080 if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3081 {
3082 if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3083 return make_result(&const_nan);
3084 if (NUMERIC_IS_PINF(num1))
3085 {
3086 if (NUMERIC_IS_PINF(num2))
3087 return make_result(&const_nan); /* Inf - Inf */
3088 else
3089 return make_result(&const_pinf);
3090 }
3091 if (NUMERIC_IS_NINF(num1))
3092 {
3093 if (NUMERIC_IS_NINF(num2))
3094 return make_result(&const_nan); /* -Inf - -Inf */
3095 else
3096 return make_result(&const_ninf);
3097 }
3098 /* by here, num1 must be finite, so num2 is not */
3099 if (NUMERIC_IS_PINF(num2))
3100 return make_result(&const_ninf);
3101 Assert(NUMERIC_IS_NINF(num2));
3102 return make_result(&const_pinf);
3103 }
3104
3105 /*
3106 * Unpack the values, let sub_var() compute the result and return it.
3107 */
3108 init_var_from_num(num1, &arg1);
3109 init_var_from_num(num2, &arg2);
3110
3111 init_var(&result);
3112 sub_var(&arg1, &arg2, &result);
3113
3114 res = make_result_opt_error(&result, have_error);
3115
3116 free_var(&result);
3117
3118 return res;
3119 }
3120
3121
3122 /*
3123 * numeric_mul() -
3124 *
3125 * Calculate the product of two numerics
3126 */
3127 Datum
3128 numeric_mul(PG_FUNCTION_ARGS)
3129 {
3130 Numeric num1 = PG_GETARG_NUMERIC(0);
3131 Numeric num2 = PG_GETARG_NUMERIC(1);
3132 Numeric res;
3133
3134 res = numeric_mul_opt_error(num1, num2, NULL);
3135
3136 PG_RETURN_NUMERIC(res);
3137 }
3138
3139
3140 /*
3141 * numeric_mul_opt_error() -
3142 *
3143 * Internal version of numeric_mul(). If "*have_error" flag is provided,
3144 * on error it's set to true, NULL returned. This is helpful when caller
3145 * need to handle errors by itself.
3146 */
3147 Numeric
3148 numeric_mul_opt_error(Numeric num1, Numeric num2, bool *have_error)
3149 {
3150 NumericVar arg1;
3151 NumericVar arg2;
3152 NumericVar result;
3153 Numeric res;
3154
3155 /*
3156 * Handle NaN and infinities
3157 */
3158 if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3159 {
3160 if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3161 return make_result(&const_nan);
3162 if (NUMERIC_IS_PINF(num1))
3163 {
3164 switch (numeric_sign_internal(num2))
3165 {
3166 case 0:
3167 return make_result(&const_nan); /* Inf * 0 */
3168 case 1:
3169 return make_result(&const_pinf);
3170 case -1:
3171 return make_result(&const_ninf);
3172 }
3173 Assert(false);
3174 }
3175 if (NUMERIC_IS_NINF(num1))
3176 {
3177 switch (numeric_sign_internal(num2))
3178 {
3179 case 0:
3180 return make_result(&const_nan); /* -Inf * 0 */
3181 case 1:
3182 return make_result(&const_ninf);
3183 case -1:
3184 return make_result(&const_pinf);
3185 }
3186 Assert(false);
3187 }
3188 /* by here, num1 must be finite, so num2 is not */
3189 if (NUMERIC_IS_PINF(num2))
3190 {
3191 switch (numeric_sign_internal(num1))
3192 {
3193 case 0:
3194 return make_result(&const_nan); /* 0 * Inf */
3195 case 1:
3196 return make_result(&const_pinf);
3197 case -1:
3198 return make_result(&const_ninf);
3199 }
3200 Assert(false);
3201 }
3202 Assert(NUMERIC_IS_NINF(num2));
3203 switch (numeric_sign_internal(num1))
3204 {
3205 case 0:
3206 return make_result(&const_nan); /* 0 * -Inf */
3207 case 1:
3208 return make_result(&const_ninf);
3209 case -1:
3210 return make_result(&const_pinf);
3211 }
3212 Assert(false);
3213 }
3214
3215 /*
3216 * Unpack the values, let mul_var() compute the result and return it.
3217 * Unlike add_var() and sub_var(), mul_var() will round its result. In the
3218 * case of numeric_mul(), which is invoked for the * operator on numerics,
3219 * we request exact representation for the product (rscale = sum(dscale of
3220 * arg1, dscale of arg2)). If the exact result has more digits after the
3221 * decimal point than can be stored in a numeric, we round it. Rounding
3222 * after computing the exact result ensures that the final result is
3223 * correctly rounded (rounding in mul_var() using a truncated product
3224 * would not guarantee this).
3225 */
3226 init_var_from_num(num1, &arg1);
3227 init_var_from_num(num2, &arg2);
3228
3229 init_var(&result);
3230 mul_var(&arg1, &arg2, &result, arg1.dscale + arg2.dscale);
3231
3232 if (result.dscale > NUMERIC_DSCALE_MAX)
3233 round_var(&result, NUMERIC_DSCALE_MAX);
3234
3235 res = make_result_opt_error(&result, have_error);
3236
3237 free_var(&result);
3238
3239 return res;
3240 }
3241
3242
3243 /*
3244 * numeric_div() -
3245 *
3246 * Divide one numeric into another
3247 */
3248 Datum
3249 numeric_div(PG_FUNCTION_ARGS)
3250 {
3251 Numeric num1 = PG_GETARG_NUMERIC(0);
3252 Numeric num2 = PG_GETARG_NUMERIC(1);
3253 Numeric res;
3254
3255 res = numeric_div_opt_error(num1, num2, NULL);
3256
3257 PG_RETURN_NUMERIC(res);
3258 }
3259
3260
3261 /*
3262 * numeric_div_opt_error() -
3263 *
3264 * Internal version of numeric_div(). If "*have_error" flag is provided,
3265 * on error it's set to true, NULL returned. This is helpful when caller
3266 * need to handle errors by itself.
3267 */
3268 Numeric
3269 numeric_div_opt_error(Numeric num1, Numeric num2, bool *have_error)
3270 {
3271 NumericVar arg1;
3272 NumericVar arg2;
3273 NumericVar result;
3274 Numeric res;
3275 int rscale;
3276
3277 if (have_error)
3278 *have_error = false;
3279
3280 /*
3281 * Handle NaN and infinities
3282 */
3283 if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3284 {
3285 if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3286 return make_result(&const_nan);
3287 if (NUMERIC_IS_PINF(num1))
3288 {
3289 if (NUMERIC_IS_SPECIAL(num2))
3290 return make_result(&const_nan); /* Inf / [-]Inf */
3291 switch (numeric_sign_internal(num2))
3292 {
3293 case 0:
3294 if (have_error)
3295 {
3296 *have_error = true;
3297 return NULL;
3298 }
3299 ereport(ERROR,
3300 (errcode(ERRCODE_DIVISION_BY_ZERO),
3301 errmsg("division by zero")));
3302 break;
3303 case 1:
3304 return make_result(&const_pinf);
3305 case -1:
3306 return make_result(&const_ninf);
3307 }
3308 Assert(false);
3309 }
3310 if (NUMERIC_IS_NINF(num1))
3311 {
3312 if (NUMERIC_IS_SPECIAL(num2))
3313 return make_result(&const_nan); /* -Inf / [-]Inf */
3314 switch (numeric_sign_internal(num2))
3315 {
3316 case 0:
3317 if (have_error)
3318 {
3319 *have_error = true;
3320 return NULL;
3321 }
3322 ereport(ERROR,
3323 (errcode(ERRCODE_DIVISION_BY_ZERO),
3324 errmsg("division by zero")));
3325 break;
3326 case 1:
3327 return make_result(&const_ninf);
3328 case -1:
3329 return make_result(&const_pinf);
3330 }
3331 Assert(false);
3332 }
3333 /* by here, num1 must be finite, so num2 is not */
3334
3335 /*
3336 * POSIX would have us return zero or minus zero if num1 is zero, and
3337 * otherwise throw an underflow error. But the numeric type doesn't
3338 * really do underflow, so let's just return zero.
3339 */
3340 return make_result(&const_zero);
3341 }
3342
3343 /*
3344 * Unpack the arguments
3345 */
3346 init_var_from_num(num1, &arg1);
3347 init_var_from_num(num2, &arg2);
3348
3349 init_var(&result);
3350
3351 /*
3352 * Select scale for division result
3353 */
3354 rscale = select_div_scale(&arg1, &arg2);
3355
3356 /*
3357 * If "have_error" is provided, check for division by zero here
3358 */
3359 if (have_error && (arg2.ndigits == 0 || arg2.digits[0] == 0))
3360 {
3361 *have_error = true;
3362 return NULL;
3363 }
3364
3365 /*
3366 * Do the divide and return the result
3367 */
3368 div_var(&arg1, &arg2, &result, rscale, true, true);
3369
3370 res = make_result_opt_error(&result, have_error);
3371
3372 free_var(&result);
3373
3374 return res;
3375 }
3376
3377
3378 /*
3379 * numeric_div_trunc() -
3380 *
3381 * Divide one numeric into another, truncating the result to an integer
3382 */
3383 Datum
3384 numeric_div_trunc(PG_FUNCTION_ARGS)
3385 {
3386 Numeric num1 = PG_GETARG_NUMERIC(0);
3387 Numeric num2 = PG_GETARG_NUMERIC(1);
3388 NumericVar arg1;
3389 NumericVar arg2;
3390 NumericVar result;
3391 Numeric res;
3392
3393 /*
3394 * Handle NaN and infinities
3395 */
3396 if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3397 {
3398 if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3399 PG_RETURN_NUMERIC(make_result(&const_nan));
3400 if (NUMERIC_IS_PINF(num1))
3401 {
3402 if (NUMERIC_IS_SPECIAL(num2))
3403 PG_RETURN_NUMERIC(make_result(&const_nan)); /* Inf / [-]Inf */
3404 switch (numeric_sign_internal(num2))
3405 {
3406 case 0:
3407 ereport(ERROR,
3408 (errcode(ERRCODE_DIVISION_BY_ZERO),
3409 errmsg("division by zero")));
3410 break;
3411 case 1:
3412 PG_RETURN_NUMERIC(make_result(&const_pinf));
3413 case -1:
3414 PG_RETURN_NUMERIC(make_result(&const_ninf));
3415 }
3416 Assert(false);
3417 }
3418 if (NUMERIC_IS_NINF(num1))
3419 {
3420 if (NUMERIC_IS_SPECIAL(num2))
3421 PG_RETURN_NUMERIC(make_result(&const_nan)); /* -Inf / [-]Inf */
3422 switch (numeric_sign_internal(num2))
3423 {
3424 case 0:
3425 ereport(ERROR,
3426 (errcode(ERRCODE_DIVISION_BY_ZERO),
3427 errmsg("division by zero")));
3428 break;
3429 case 1:
3430 PG_RETURN_NUMERIC(make_result(&const_ninf));
3431 case -1:
3432 PG_RETURN_NUMERIC(make_result(&const_pinf));
3433 }
3434 Assert(false);
3435 }
3436 /* by here, num1 must be finite, so num2 is not */
3437
3438 /*
3439 * POSIX would have us return zero or minus zero if num1 is zero, and
3440 * otherwise throw an underflow error. But the numeric type doesn't
3441 * really do underflow, so let's just return zero.
3442 */
3443 PG_RETURN_NUMERIC(make_result(&const_zero));
3444 }
3445
3446 /*
3447 * Unpack the arguments
3448 */
3449 init_var_from_num(num1, &arg1);
3450 init_var_from_num(num2, &arg2);
3451
3452 init_var(&result);
3453
3454 /*
3455 * Do the divide and return the result
3456 */
3457 div_var(&arg1, &arg2, &result, 0, false, true);
3458
3459 res = make_result(&result);
3460
3461 free_var(&result);
3462
3463 PG_RETURN_NUMERIC(res);
3464 }
3465
3466
3467 /*
3468 * numeric_mod() -
3469 *
3470 * Calculate the modulo of two numerics
3471 */
3472 Datum
3473 numeric_mod(PG_FUNCTION_ARGS)
3474 {
3475 Numeric num1 = PG_GETARG_NUMERIC(0);
3476 Numeric num2 = PG_GETARG_NUMERIC(1);
3477 Numeric res;
3478
3479 res = numeric_mod_opt_error(num1, num2, NULL);
3480
3481 PG_RETURN_NUMERIC(res);
3482 }
3483
3484
3485 /*
3486 * numeric_mod_opt_error() -
3487 *
3488 * Internal version of numeric_mod(). If "*have_error" flag is provided,
3489 * on error it's set to true, NULL returned. This is helpful when caller
3490 * need to handle errors by itself.
3491 */
3492 Numeric
3493 numeric_mod_opt_error(Numeric num1, Numeric num2, bool *have_error)
3494 {
3495 Numeric res;
3496 NumericVar arg1;
3497 NumericVar arg2;
3498 NumericVar result;
3499
3500 if (have_error)
3501 *have_error = false;
3502
3503 /*
3504 * Handle NaN and infinities. We follow POSIX fmod() on this, except that
3505 * POSIX treats x-is-infinite and y-is-zero identically, raising EDOM and
3506 * returning NaN. We choose to throw error only for y-is-zero.
3507 */
3508 if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3509 {
3510 if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3511 return make_result(&const_nan);
3512 if (NUMERIC_IS_INF(num1))
3513 {
3514 if (numeric_sign_internal(num2) == 0)
3515 {
3516 if (have_error)
3517 {
3518 *have_error = true;
3519 return NULL;
3520 }
3521 ereport(ERROR,
3522 (errcode(ERRCODE_DIVISION_BY_ZERO),
3523 errmsg("division by zero")));
3524 }
3525 /* Inf % any nonzero = NaN */
3526 return make_result(&const_nan);
3527 }
3528 /* num2 must be [-]Inf; result is num1 regardless of sign of num2 */
3529 return duplicate_numeric(num1);
3530 }
3531
3532 init_var_from_num(num1, &arg1);
3533 init_var_from_num(num2, &arg2);
3534
3535 init_var(&result);
3536
3537 /*
3538 * If "have_error" is provided, check for division by zero here
3539 */
3540 if (have_error && (arg2.ndigits == 0 || arg2.digits[0] == 0))
3541 {
3542 *have_error = true;
3543 return NULL;
3544 }
3545
3546 mod_var(&arg1, &arg2, &result);
3547
3548 res = make_result_opt_error(&result, NULL);
3549
3550 free_var(&result);
3551
3552 return res;
3553 }
3554
3555
3556 /*
3557 * numeric_inc() -
3558 *
3559 * Increment a number by one
3560 */
3561 Datum
3562 numeric_inc(PG_FUNCTION_ARGS)
3563 {
3564 Numeric num = PG_GETARG_NUMERIC(0);
3565 NumericVar arg;
3566 Numeric res;
3567
3568 /*
3569 * Handle NaN and infinities
3570 */
3571 if (NUMERIC_IS_SPECIAL(num))
3572 PG_RETURN_NUMERIC(duplicate_numeric(num));
3573
3574 /*
3575 * Compute the result and return it
3576 */
3577 init_var_from_num(num, &arg);
3578
3579 add_var(&arg, &const_one, &arg);
3580
3581 res = make_result(&arg);
3582
3583 free_var(&arg);
3584
3585 PG_RETURN_NUMERIC(res);
3586 }
3587
3588
3589 /*
3590 * numeric_smaller() -
3591 *
3592 * Return the smaller of two numbers
3593 */
3594 Datum
3595 numeric_smaller(PG_FUNCTION_ARGS)
3596 {
3597 Numeric num1 = PG_GETARG_NUMERIC(0);
3598 Numeric num2 = PG_GETARG_NUMERIC(1);
3599
3600 /*
3601 * Use cmp_numerics so that this will agree with the comparison operators,
3602 * particularly as regards comparisons involving NaN.
3603 */
3604 if (cmp_numerics(num1, num2) < 0)
3605 PG_RETURN_NUMERIC(num1);
3606 else
3607 PG_RETURN_NUMERIC(num2);
3608 }
3609
3610
3611 /*
3612 * numeric_larger() -
3613 *
3614 * Return the larger of two numbers
3615 */
3616 Datum
3617 numeric_larger(PG_FUNCTION_ARGS)
3618 {
3619 Numeric num1 = PG_GETARG_NUMERIC(0);
3620 Numeric num2 = PG_GETARG_NUMERIC(1);
3621
3622 /*
3623 * Use cmp_numerics so that this will agree with the comparison operators,
3624 * particularly as regards comparisons involving NaN.
3625 */
3626 if (cmp_numerics(num1, num2) > 0)
3627 PG_RETURN_NUMERIC(num1);
3628 else
3629 PG_RETURN_NUMERIC(num2);
3630 }
3631
3632
3633 /* ----------------------------------------------------------------------
3634 *
3635 * Advanced math functions
3636 *
3637 * ----------------------------------------------------------------------
3638 */
3639
3640 /*
3641 * numeric_gcd() -
3642 *
3643 * Calculate the greatest common divisor of two numerics
3644 */
3645 Datum
3646 numeric_gcd(PG_FUNCTION_ARGS)
3647 {
3648 Numeric num1 = PG_GETARG_NUMERIC(0);
3649 Numeric num2 = PG_GETARG_NUMERIC(1);
3650 NumericVar arg1;
3651 NumericVar arg2;
3652 NumericVar result;
3653 Numeric res;
3654
3655 /*
3656 * Handle NaN and infinities: we consider the result to be NaN in all such
3657 * cases.
3658 */
3659 if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3660 PG_RETURN_NUMERIC(make_result(&const_nan));
3661
3662 /*
3663 * Unpack the arguments
3664 */
3665 init_var_from_num(num1, &arg1);
3666 init_var_from_num(num2, &arg2);
3667
3668 init_var(&result);
3669
3670 /*
3671 * Find the GCD and return the result
3672 */
3673 gcd_var(&arg1, &arg2, &result);
3674
3675 res = make_result(&result);
3676
3677 free_var(&result);
3678
3679 PG_RETURN_NUMERIC(res);
3680 }
3681
3682
3683 /*
3684 * numeric_lcm() -
3685 *
3686 * Calculate the least common multiple of two numerics
3687 */
3688 Datum
3689 numeric_lcm(PG_FUNCTION_ARGS)
3690 {
3691 Numeric num1 = PG_GETARG_NUMERIC(0);
3692 Numeric num2 = PG_GETARG_NUMERIC(1);
3693 NumericVar arg1;
3694 NumericVar arg2;
3695 NumericVar result;
3696 Numeric res;
3697
3698 /*
3699 * Handle NaN and infinities: we consider the result to be NaN in all such
3700 * cases.
3701 */
3702 if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3703 PG_RETURN_NUMERIC(make_result(&const_nan));
3704
3705 /*
3706 * Unpack the arguments
3707 */
3708 init_var_from_num(num1, &arg1);
3709 init_var_from_num(num2, &arg2);
3710
3711 init_var(&result);
3712
3713 /*
3714 * Compute the result using lcm(x, y) = abs(x / gcd(x, y) * y), returning
3715 * zero if either input is zero.
3716 *
3717 * Note that the division is guaranteed to be exact, returning an integer
3718 * result, so the LCM is an integral multiple of both x and y. A display
3719 * scale of Min(x.dscale, y.dscale) would be sufficient to represent it,
3720 * but as with other numeric functions, we choose to return a result whose
3721 * display scale is no smaller than either input.
3722 */
3723 if (arg1.ndigits == 0 || arg2.ndigits == 0)
3724 set_var_from_var(&const_zero, &result);
3725 else
3726 {
3727 gcd_var(&arg1, &arg2, &result);
3728 div_var(&arg1, &result, &result, 0, false, true);
3729 mul_var(&arg2, &result, &result, arg2.dscale);
3730 result.sign = NUMERIC_POS;
3731 }
3732
3733 result.dscale = Max(arg1.dscale, arg2.dscale);
3734
3735 res = make_result(&result);
3736
3737 free_var(&result);
3738
3739 PG_RETURN_NUMERIC(res);
3740 }
3741
3742
3743 /*
3744 * numeric_fac()
3745 *
3746 * Compute factorial
3747 */
3748 Datum
3749 numeric_fac(PG_FUNCTION_ARGS)
3750 {
3751 int64 num = PG_GETARG_INT64(0);
3752 Numeric res;
3753 NumericVar fact;
3754 NumericVar result;
3755
3756 if (num < 0)
3757 ereport(ERROR,
3758 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
3759 errmsg("factorial of a negative number is undefined")));
3760 if (num <= 1)
3761 {
3762 res = make_result(&const_one);
3763 PG_RETURN_NUMERIC(res);
3764 }
3765 /* Fail immediately if the result would overflow */
3766 if (num > 32177)
3767 ereport(ERROR,
3768 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
3769 errmsg("value overflows numeric format")));
3770
3771 init_var(&fact);
3772 init_var(&result);
3773
3774 int64_to_numericvar(num, &result);
3775
3776 for (num = num - 1; num > 1; num--)
3777 {
3778 /* this loop can take awhile, so allow it to be interrupted */
3779 CHECK_FOR_INTERRUPTS();
3780
3781 int64_to_numericvar(num, &fact);
3782
3783 mul_var(&result, &fact, &result, 0);
3784 }
3785
3786 res = make_result(&result);
3787
3788 free_var(&fact);
3789 free_var(&result);
3790
3791 PG_RETURN_NUMERIC(res);
3792 }
3793
3794
3795 /*
3796 * numeric_sqrt() -
3797 *
3798 * Compute the square root of a numeric.
3799 */
3800 Datum
3801 numeric_sqrt(PG_FUNCTION_ARGS)
3802 {
3803 Numeric num = PG_GETARG_NUMERIC(0);
3804 Numeric res;
3805 NumericVar arg;
3806 NumericVar result;
3807 int sweight;
3808 int rscale;
3809
3810 /*
3811 * Handle NaN and infinities
3812 */
3813 if (NUMERIC_IS_SPECIAL(num))
3814 {
3815 /* error should match that in sqrt_var() */
3816 if (NUMERIC_IS_NINF(num))
3817 ereport(ERROR,
3818 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
3819 errmsg("cannot take square root of a negative number")));
3820 /* For NAN or PINF, just duplicate the input */
3821 PG_RETURN_NUMERIC(duplicate_numeric(num));
3822 }
3823
3824 /*
3825 * Unpack the argument and determine the result scale. We choose a scale
3826 * to give at least NUMERIC_MIN_SIG_DIGITS significant digits; but in any
3827 * case not less than the input's dscale.
3828 */
3829 init_var_from_num(num, &arg);
3830
3831 init_var(&result);
3832
3833 /*
3834 * Assume the input was normalized, so arg.weight is accurate. The result
3835 * then has at least sweight = floor(arg.weight * DEC_DIGITS / 2 + 1)
3836 * digits before the decimal point. When DEC_DIGITS is even, we can save
3837 * a few cycles, since the division is exact and there is no need to round
3838 * towards negative infinity.
3839 */
3840 #if DEC_DIGITS == ((DEC_DIGITS / 2) * 2)
3841 sweight = arg.weight * DEC_DIGITS / 2 + 1;
3842 #else
3843 if (arg.weight >= 0)
3844 sweight = arg.weight * DEC_DIGITS / 2 + 1;
3845 else
3846 sweight = 1 - (1 - arg.weight * DEC_DIGITS) / 2;
3847 #endif
3848
3849 rscale = NUMERIC_MIN_SIG_DIGITS - sweight;
3850 rscale = Max(rscale, arg.dscale);
3851 rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
3852 rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
3853
3854 /*
3855 * Let sqrt_var() do the calculation and return the result.
3856 */
3857 sqrt_var(&arg, &result, rscale);
3858
3859 res = make_result(&result);
3860
3861 free_var(&result);
3862
3863 PG_RETURN_NUMERIC(res);
3864 }
3865
3866
3867 /*
3868 * numeric_exp() -
3869 *
3870 * Raise e to the power of x
3871 */
3872 Datum
3873 numeric_exp(PG_FUNCTION_ARGS)
3874 {
3875 Numeric num = PG_GETARG_NUMERIC(0);
3876 Numeric res;
3877 NumericVar arg;
3878 NumericVar result;
3879 int rscale;
3880 double val;
3881
3882 /*
3883 * Handle NaN and infinities
3884 */
3885 if (NUMERIC_IS_SPECIAL(num))
3886 {
3887 /* Per POSIX, exp(-Inf) is zero */
3888 if (NUMERIC_IS_NINF(num))
3889 PG_RETURN_NUMERIC(make_result(&const_zero));
3890 /* For NAN or PINF, just duplicate the input */
3891 PG_RETURN_NUMERIC(duplicate_numeric(num));
3892 }
3893
3894 /*
3895 * Unpack the argument and determine the result scale. We choose a scale
3896 * to give at least NUMERIC_MIN_SIG_DIGITS significant digits; but in any
3897 * case not less than the input's dscale.
3898 */
3899 init_var_from_num(num, &arg);
3900
3901 init_var(&result);
3902
3903 /* convert input to float8, ignoring overflow */
3904 val = numericvar_to_double_no_overflow(&arg);
3905
3906 /*
3907 * log10(result) = num * log10(e), so this is approximately the decimal
3908 * weight of the result:
3909 */
3910 val *= 0.434294481903252;
3911
3912 /* limit to something that won't cause integer overflow */
3913 val = Max(val, -NUMERIC_MAX_RESULT_SCALE);
3914 val = Min(val, NUMERIC_MAX_RESULT_SCALE);
3915
3916 rscale = NUMERIC_MIN_SIG_DIGITS - (int) val;
3917 rscale = Max(rscale, arg.dscale);
3918 rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
3919 rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
3920
3921 /*
3922 * Let exp_var() do the calculation and return the result.
3923 */
3924 exp_var(&arg, &result, rscale);
3925
3926 res = make_result(&result);
3927
3928 free_var(&result);
3929
3930 PG_RETURN_NUMERIC(res);
3931 }
3932
3933
3934 /*
3935 * numeric_ln() -
3936 *
3937 * Compute the natural logarithm of x
3938 */
3939 Datum
3940 numeric_ln(PG_FUNCTION_ARGS)
3941 {
3942 Numeric num = PG_GETARG_NUMERIC(0);
3943 Numeric res;
3944 NumericVar arg;
3945 NumericVar result;
3946 int ln_dweight;
3947 int rscale;
3948
3949 /*
3950 * Handle NaN and infinities
3951 */
3952 if (NUMERIC_IS_SPECIAL(num))
3953 {
3954 if (NUMERIC_IS_NINF(num))
3955 ereport(ERROR,
3956 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
3957 errmsg("cannot take logarithm of a negative number")));
3958 /* For NAN or PINF, just duplicate the input */
3959 PG_RETURN_NUMERIC(duplicate_numeric(num));
3960 }
3961
3962 init_var_from_num(num, &arg);
3963 init_var(&result);
3964
3965 /* Estimated dweight of logarithm */
3966 ln_dweight = estimate_ln_dweight(&arg);
3967
3968 rscale = NUMERIC_MIN_SIG_DIGITS - ln_dweight;
3969 rscale = Max(rscale, arg.dscale);
3970 rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
3971 rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
3972
3973 ln_var(&arg, &result, rscale);
3974
3975 res = make_result(&result);
3976
3977 free_var(&result);
3978
3979 PG_RETURN_NUMERIC(res);
3980 }
3981
3982
3983 /*
3984 * numeric_log() -
3985 *
3986 * Compute the logarithm of x in a given base
3987 */
3988 Datum
3989 numeric_log(PG_FUNCTION_ARGS)
3990 {
3991 Numeric num1 = PG_GETARG_NUMERIC(0);
3992 Numeric num2 = PG_GETARG_NUMERIC(1);
3993 Numeric res;
3994 NumericVar arg1;
3995 NumericVar arg2;
3996 NumericVar result;
3997
3998 /*
3999 * Handle NaN and infinities
4000 */
4001 if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
4002 {
4003 int sign1,
4004 sign2;
4005
4006 if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
4007 PG_RETURN_NUMERIC(make_result(&const_nan));
4008 /* fail on negative inputs including -Inf, as log_var would */
4009 sign1 = numeric_sign_internal(num1);
4010 sign2 = numeric_sign_internal(num2);
4011 if (sign1 < 0 || sign2 < 0)
4012 ereport(ERROR,
4013 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
4014 errmsg("cannot take logarithm of a negative number")));
4015 /* fail on zero inputs, as log_var would */
4016 if (sign1 == 0 || sign2 == 0)
4017 ereport(ERROR,
4018 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
4019 errmsg("cannot take logarithm of zero")));
4020 if (NUMERIC_IS_PINF(num1))
4021 {
4022 /* log(Inf, Inf) reduces to Inf/Inf, so it's NaN */
4023 if (NUMERIC_IS_PINF(num2))
4024 PG_RETURN_NUMERIC(make_result(&const_nan));
4025 /* log(Inf, finite-positive) is zero (we don't throw underflow) */
4026 PG_RETURN_NUMERIC(make_result(&const_zero));
4027 }
4028 Assert(NUMERIC_IS_PINF(num2));
4029 /* log(finite-positive, Inf) is Inf */
4030 PG_RETURN_NUMERIC(make_result(&const_pinf));
4031 }
4032
4033 /*
4034 * Initialize things
4035 */
4036 init_var_from_num(num1, &arg1);
4037 init_var_from_num(num2, &arg2);
4038 init_var(&result);
4039
4040 /*
4041 * Call log_var() to compute and return the result; note it handles scale
4042 * selection itself.
4043 */
4044 log_var(&arg1, &arg2, &result);
4045
4046 res = make_result(&result);
4047
4048 free_var(&result);
4049
4050 PG_RETURN_NUMERIC(res);
4051 }
4052
4053
4054 /*
4055 * numeric_power() -
4056 *
4057 * Raise x to the power of y
4058 */
4059 Datum
4060 numeric_power(PG_FUNCTION_ARGS)
4061 {
4062 Numeric num1 = PG_GETARG_NUMERIC(0);
4063 Numeric num2 = PG_GETARG_NUMERIC(1);
4064 Numeric res;
4065 NumericVar arg1;
4066 NumericVar arg2;
4067 NumericVar result;
4068 int sign1,
4069 sign2;
4070
4071 /*
4072 * Handle NaN and infinities
4073 */
4074 if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
4075 {
4076 /*
4077 * We follow the POSIX spec for pow(3), which says that NaN ^ 0 = 1,
4078 * and 1 ^ NaN = 1, while all other cases with NaN inputs yield NaN
4079 * (with no error).
4080 */
4081 if (NUMERIC_IS_NAN(num1))
4082 {
4083 if (!NUMERIC_IS_SPECIAL(num2))
4084 {
4085 init_var_from_num(num2, &arg2);
4086 if (cmp_var(&arg2, &const_zero) == 0)
4087 PG_RETURN_NUMERIC(make_result(&const_one));
4088 }
4089 PG_RETURN_NUMERIC(make_result(&const_nan));
4090 }
4091 if (NUMERIC_IS_NAN(num2))
4092 {
4093 if (!NUMERIC_IS_SPECIAL(num1))
4094 {
4095 init_var_from_num(num1, &arg1);
4096 if (cmp_var(&arg1, &const_one) == 0)
4097 PG_RETURN_NUMERIC(make_result(&const_one));
4098 }
4099 PG_RETURN_NUMERIC(make_result(&const_nan));
4100 }
4101 /* At least one input is infinite, but error rules still apply */
4102 sign1 = numeric_sign_internal(num1);
4103 sign2 = numeric_sign_internal(num2);
4104 if (sign1 == 0 && sign2 < 0)
4105 ereport(ERROR,
4106 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
4107 errmsg("zero raised to a negative power is undefined")));
4108 if (sign1 < 0 && !numeric_is_integral(num2))
4109 ereport(ERROR,
4110 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
4111 errmsg("a negative number raised to a non-integer power yields a complex result")));
4112
4113 /*
4114 * POSIX gives this series of rules for pow(3) with infinite inputs:
4115 *
4116 * For any value of y, if x is +1, 1.0 shall be returned.
4117 */
4118 if (!NUMERIC_IS_SPECIAL(num1))
4119 {
4120 init_var_from_num(num1, &arg1);
4121 if (cmp_var(&arg1, &const_one) == 0)
4122 PG_RETURN_NUMERIC(make_result(&const_one));
4123 }
4124
4125 /*
4126 * For any value of x, if y is [-]0, 1.0 shall be returned.
4127 */
4128 if (sign2 == 0)
4129 PG_RETURN_NUMERIC(make_result(&const_one));
4130
4131 /*
4132 * For any odd integer value of y > 0, if x is [-]0, [-]0 shall be
4133 * returned. For y > 0 and not an odd integer, if x is [-]0, +0 shall
4134 * be returned. (Since we don't deal in minus zero, we need not
4135 * distinguish these two cases.)
4136 */
4137 if (sign1 == 0 && sign2 > 0)
4138 PG_RETURN_NUMERIC(make_result(&const_zero));
4139
4140 /*
4141 * If x is -1, and y is [-]Inf, 1.0 shall be returned.
4142 *
4143 * For |x| < 1, if y is -Inf, +Inf shall be returned.
4144 *
4145 * For |x| > 1, if y is -Inf, +0 shall be returned.
4146 *
4147 * For |x| < 1, if y is +Inf, +0 shall be returned.
4148 *
4149 * For |x| > 1, if y is +Inf, +Inf shall be returned.
4150 */
4151 if (NUMERIC_IS_INF(num2))
4152 {
4153 bool abs_x_gt_one;
4154
4155 if (NUMERIC_IS_SPECIAL(num1))
4156 abs_x_gt_one = true; /* x is either Inf or -Inf */
4157 else
4158 {
4159 init_var_from_num(num1, &arg1);
4160 if (cmp_var(&arg1, &const_minus_one) == 0)
4161 PG_RETURN_NUMERIC(make_result(&const_one));
4162 arg1.sign = NUMERIC_POS; /* now arg1 = abs(x) */
4163 abs_x_gt_one = (cmp_var(&arg1, &const_one) > 0);
4164 }
4165 if (abs_x_gt_one == (sign2 > 0))
4166 PG_RETURN_NUMERIC(make_result(&const_pinf));
4167 else
4168 PG_RETURN_NUMERIC(make_result(&const_zero));
4169 }
4170
4171 /*
4172 * For y < 0, if x is +Inf, +0 shall be returned.
4173 *
4174 * For y > 0, if x is +Inf, +Inf shall be returned.
4175 */
4176 if (NUMERIC_IS_PINF(num1))
4177 {
4178 if (sign2 > 0)
4179 PG_RETURN_NUMERIC(make_result(&const_pinf));
4180 else
4181 PG_RETURN_NUMERIC(make_result(&const_zero));
4182 }
4183
4184 Assert(NUMERIC_IS_NINF(num1));
4185
4186 /*
4187 * For y an odd integer < 0, if x is -Inf, -0 shall be returned. For
4188 * y < 0 and not an odd integer, if x is -Inf, +0 shall be returned.
4189 * (Again, we need not distinguish these two cases.)
4190 */
4191 if (sign2 < 0)
4192 PG_RETURN_NUMERIC(make_result(&const_zero));
4193
4194 /*
4195 * For y an odd integer > 0, if x is -Inf, -Inf shall be returned. For
4196 * y > 0 and not an odd integer, if x is -Inf, +Inf shall be returned.
4197 */
4198 init_var_from_num(num2, &arg2);
4199 if (arg2.ndigits > 0 && arg2.ndigits == arg2.weight + 1 &&
4200 (arg2.digits[arg2.ndigits - 1] & 1))
4201 PG_RETURN_NUMERIC(make_result(&const_ninf));
4202 else
4203 PG_RETURN_NUMERIC(make_result(&const_pinf));
4204 }
4205
4206 /*
4207 * The SQL spec requires that we emit a particular SQLSTATE error code for
4208 * certain error conditions. Specifically, we don't return a
4209 * divide-by-zero error code for 0 ^ -1. Raising a negative number to a
4210 * non-integer power must produce the same error code, but that case is
4211 * handled in power_var().
4212 */
4213 sign1 = numeric_sign_internal(num1);
4214 sign2 = numeric_sign_internal(num2);
4215
4216 if (sign1 == 0 && sign2 < 0)
4217 ereport(ERROR,
4218 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
4219 errmsg("zero raised to a negative power is undefined")));
4220
4221 /*
4222 * Initialize things
4223 */
4224 init_var(&result);
4225 init_var_from_num(num1, &arg1);
4226 init_var_from_num(num2, &arg2);
4227
4228 /*
4229 * Call power_var() to compute and return the result; note it handles
4230 * scale selection itself.
4231 */
4232 power_var(&arg1, &arg2, &result);
4233
4234 res = make_result(&result);
4235
4236 free_var(&result);
4237
4238 PG_RETURN_NUMERIC(res);
4239 }
4240
4241 /*
4242 * numeric_scale() -
4243 *
4244 * Returns the scale, i.e. the count of decimal digits in the fractional part
4245 */
4246 Datum
4247 numeric_scale(PG_FUNCTION_ARGS)
4248 {
4249 Numeric num = PG_GETARG_NUMERIC(0);
4250
4251 if (NUMERIC_IS_SPECIAL(num))
4252 PG_RETURN_NULL();
4253
4254 PG_RETURN_INT32(NUMERIC_DSCALE(num));
4255 }
4256
4257 /*
4258 * Calculate minimum scale for value.
4259 */
4260 static int
4261 get_min_scale(NumericVar *var)
4262 {
4263 int min_scale;
4264 int last_digit_pos;
4265
4266 /*
4267 * Ordinarily, the input value will be "stripped" so that the last
4268 * NumericDigit is nonzero. But we don't want to get into an infinite
4269 * loop if it isn't, so explicitly find the last nonzero digit.
4270 */
4271 last_digit_pos = var->ndigits - 1;
4272 while (last_digit_pos >= 0 &&
4273 var->digits[last_digit_pos] == 0)
4274 last_digit_pos--;
4275
4276 if (last_digit_pos >= 0)
4277 {
4278 /* compute min_scale assuming that last ndigit has no zeroes */
4279 min_scale = (last_digit_pos - var->weight) * DEC_DIGITS;
4280
4281 /*
4282 * We could get a negative result if there are no digits after the
4283 * decimal point. In this case the min_scale must be zero.
4284 */
4285 if (min_scale > 0)
4286 {
4287 /*
4288 * Reduce min_scale if trailing digit(s) in last NumericDigit are
4289 * zero.
4290 */
4291 NumericDigit last_digit = var->digits[last_digit_pos];
4292
4293 while (last_digit % 10 == 0)
4294 {
4295 min_scale--;
4296 last_digit /= 10;
4297 }
4298 }
4299 else
4300 min_scale = 0;
4301 }
4302 else
4303 min_scale = 0; /* result if input is zero */
4304
4305 return min_scale;
4306 }
4307
4308 /*
4309 * Returns minimum scale required to represent supplied value without loss.
4310 */
4311 Datum
4312 numeric_min_scale(PG_FUNCTION_ARGS)
4313 {
4314 Numeric num = PG_GETARG_NUMERIC(0);
4315 NumericVar arg;
4316 int min_scale;
4317
4318 if (NUMERIC_IS_SPECIAL(num))
4319 PG_RETURN_NULL();
4320
4321 init_var_from_num(num, &arg);
4322 min_scale = get_min_scale(&arg);
4323 free_var(&arg);
4324
4325 PG_RETURN_INT32(min_scale);
4326 }
4327
4328 /*
4329 * Reduce scale of numeric value to represent supplied value without loss.
4330 */
4331 Datum
4332 numeric_trim_scale(PG_FUNCTION_ARGS)
4333 {
4334 Numeric num = PG_GETARG_NUMERIC(0);
4335 Numeric res;
4336 NumericVar result;
4337
4338 if (NUMERIC_IS_SPECIAL(num))
4339 PG_RETURN_NUMERIC(duplicate_numeric(num));
4340
4341 init_var_from_num(num, &result);
4342 result.dscale = get_min_scale(&result);
4343 res = make_result(&result);
4344 free_var(&result);
4345
4346 PG_RETURN_NUMERIC(res);
4347 }
4348
4349 /*
4350 * Return a random numeric value in the range [rmin, rmax].
4351 */
4352 Numeric
4353 random_numeric(pg_prng_state *state, Numeric rmin, Numeric rmax)
4354 {
4355 NumericVar rmin_var;
4356 NumericVar rmax_var;
4357 NumericVar result;
4358 Numeric res;
4359
4360 /* Range bounds must not be NaN/infinity */
4361 if (NUMERIC_IS_SPECIAL(rmin))
4362 {
4363 if (NUMERIC_IS_NAN(rmin))
4364 ereport(ERROR,
4365 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4366 errmsg("lower bound cannot be NaN"));
4367 else
4368 ereport(ERROR,
4369 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4370 errmsg("lower bound cannot be infinity"));
4371 }
4372 if (NUMERIC_IS_SPECIAL(rmax))
4373 {
4374 if (NUMERIC_IS_NAN(rmax))
4375 ereport(ERROR,
4376 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4377 errmsg("upper bound cannot be NaN"));
4378 else
4379 ereport(ERROR,
4380 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4381 errmsg("upper bound cannot be infinity"));
4382 }
4383
4384 /* Return a random value in the range [rmin, rmax] */
4385 init_var_from_num(rmin, &rmin_var);
4386 init_var_from_num(rmax, &rmax_var);
4387
4388 init_var(&result);
4389
4390 random_var(state, &rmin_var, &rmax_var, &result);
4391
4392 res = make_result(&result);
4393
4394 free_var(&result);
4395
4396 return res;
4397 }
4398
4399
4400 /* ----------------------------------------------------------------------
4401 *
4402 * Type conversion functions
4403 *
4404 * ----------------------------------------------------------------------
4405 */
4406
4407 Numeric
4408 int64_to_numeric(int64 val)
4409 {
4410 Numeric res;
4411 NumericVar result;
4412
4413 init_var(&result);
4414
4415 int64_to_numericvar(val, &result);
4416
4417 res = make_result(&result);
4418
4419 free_var(&result);
4420
4421 return res;
4422 }
4423
4424 /*
4425 * Convert val1/(10**log10val2) to numeric. This is much faster than normal
4426 * numeric division.
4427 */
4428 Numeric
4429 int64_div_fast_to_numeric(int64 val1, int log10val2)
4430 {
4431 Numeric res;
4432 NumericVar result;
4433 int rscale;
4434 int w;
4435 int m;
4436
4437 init_var(&result);
4438
4439 /* result scale */
4440 rscale = log10val2 < 0 ? 0 : log10val2;
4441
4442 /* how much to decrease the weight by */
4443 w = log10val2 / DEC_DIGITS;
4444 /* how much is left to divide by */
4445 m = log10val2 % DEC_DIGITS;
4446 if (m < 0)
4447 {
4448 m += DEC_DIGITS;
4449 w--;
4450 }
4451
4452 /*
4453 * If there is anything left to divide by (10^m with 0 < m < DEC_DIGITS),
4454 * multiply the dividend by 10^(DEC_DIGITS - m), and shift the weight by
4455 * one more.
4456 */
4457 if (m > 0)
4458 {
4459 #if DEC_DIGITS == 4
4460 static const int pow10[] = {1, 10, 100, 1000};
4461 #elif DEC_DIGITS == 2
4462 static const int pow10[] = {1, 10};
4463 #elif DEC_DIGITS == 1
4464 static const int pow10[] = {1};
4465 #else
4466 #error unsupported NBASE
4467 #endif
4468 int64 factor = pow10[DEC_DIGITS - m];
4469 int64 new_val1;
4470
4471 StaticAssertDecl(lengthof(pow10) == DEC_DIGITS, "mismatch with DEC_DIGITS");
4472
4473 if (unlikely(pg_mul_s64_overflow(val1, factor, &new_val1)))
4474 {
4475 #ifdef HAVE_INT128
4476 /* do the multiplication using 128-bit integers */
4477 int128 tmp;
4478
4479 tmp = (int128) val1 * (int128) factor;
4480
4481 int128_to_numericvar(tmp, &result);
4482 #else
4483 /* do the multiplication using numerics */
4484 NumericVar tmp;
4485
4486 init_var(&tmp);
4487
4488 int64_to_numericvar(val1, &result);
4489 int64_to_numericvar(factor, &tmp);
4490 mul_var(&result, &tmp, &result, 0);
4491
4492 free_var(&tmp);
4493 #endif
4494 }
4495 else
4496 int64_to_numericvar(new_val1, &result);
4497
4498 w++;
4499 }
4500 else
4501 int64_to_numericvar(val1, &result);
4502
4503 result.weight -= w;
4504 result.dscale = rscale;
4505
4506 res = make_result(&result);
4507
4508 free_var(&result);
4509
4510 return res;
4511 }
4512
4513 Datum
4514 int4_numeric(PG_FUNCTION_ARGS)
4515 {
4516 int32 val = PG_GETARG_INT32(0);
4517
4518 PG_RETURN_NUMERIC(int64_to_numeric(val));
4519 }
4520
4521 int32
4522 numeric_int4_opt_error(Numeric num, bool *have_error)
4523 {
4524 NumericVar x;
4525 int32 result;
4526
4527 if (have_error)
4528 *have_error = false;
4529
4530 if (NUMERIC_IS_SPECIAL(num))
4531 {
4532 if (have_error)
4533 {
4534 *have_error = true;
4535 return 0;
4536 }
4537 else
4538 {
4539 if (NUMERIC_IS_NAN(num))
4540 ereport(ERROR,
4541 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4542 errmsg("cannot convert NaN to %s", "integer")));
4543 else
4544 ereport(ERROR,
4545 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4546 errmsg("cannot convert infinity to %s", "integer")));
4547 }
4548 }
4549
4550 /* Convert to variable format, then convert to int4 */
4551 init_var_from_num(num, &x);
4552
4553 if (!numericvar_to_int32(&x, &result))
4554 {
4555 if (have_error)
4556 {
4557 *have_error = true;
4558 return 0;
4559 }
4560 else
4561 {
4562 ereport(ERROR,
4563 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4564 errmsg("integer out of range")));
4565 }
4566 }
4567
4568 return result;
4569 }
4570
4571 Datum
4572 numeric_int4(PG_FUNCTION_ARGS)
4573 {
4574 Numeric num = PG_GETARG_NUMERIC(0);
4575
4576 PG_RETURN_INT32(numeric_int4_opt_error(num, NULL));
4577 }
4578
4579 /*
4580 * Given a NumericVar, convert it to an int32. If the NumericVar
4581 * exceeds the range of an int32, false is returned, otherwise true is returned.
4582 * The input NumericVar is *not* free'd.
4583 */
4584 static bool
4585 numericvar_to_int32(const NumericVar *var, int32 *result)
4586 {
4587 int64 val;
4588
4589 if (!numericvar_to_int64(var, &val))
4590 return false;
4591
4592 if (unlikely(val < PG_INT32_MIN) || unlikely(val > PG_INT32_MAX))
4593 return false;
4594
4595 /* Down-convert to int4 */
4596 *result = (int32) val;
4597
4598 return true;
4599 }
4600
4601 Datum
4602 int8_numeric(PG_FUNCTION_ARGS)
4603 {
4604 int64 val = PG_GETARG_INT64(0);
4605
4606 PG_RETURN_NUMERIC(int64_to_numeric(val));
4607 }
4608
4609 int64
4610 numeric_int8_opt_error(Numeric num, bool *have_error)
4611 {
4612 NumericVar x;
4613 int64 result;
4614
4615 if (have_error)
4616 *have_error = false;
4617
4618 if (NUMERIC_IS_SPECIAL(num))
4619 {
4620 if (have_error)
4621 {
4622 *have_error = true;
4623 return 0;
4624 }
4625 else
4626 {
4627 if (NUMERIC_IS_NAN(num))
4628 ereport(ERROR,
4629 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4630 errmsg("cannot convert NaN to %s", "bigint")));
4631 else
4632 ereport(ERROR,
4633 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4634 errmsg("cannot convert infinity to %s", "bigint")));
4635 }
4636 }
4637
4638 /* Convert to variable format, then convert to int8 */
4639 init_var_from_num(num, &x);
4640
4641 if (!numericvar_to_int64(&x, &result))
4642 {
4643 if (have_error)
4644 {
4645 *have_error = true;
4646 return 0;
4647 }
4648 else
4649 {
4650 ereport(ERROR,
4651 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4652 errmsg("bigint out of range")));
4653 }
4654 }
4655
4656 return result;
4657 }
4658
4659 Datum
4660 numeric_int8(PG_FUNCTION_ARGS)
4661 {
4662 Numeric num = PG_GETARG_NUMERIC(0);
4663
4664 PG_RETURN_INT64(numeric_int8_opt_error(num, NULL));
4665 }
4666
4667
4668 Datum
4669 int2_numeric(PG_FUNCTION_ARGS)
4670 {
4671 int16 val = PG_GETARG_INT16(0);
4672
4673 PG_RETURN_NUMERIC(int64_to_numeric(val));
4674 }
4675
4676
4677 Datum
4678 numeric_int2(PG_FUNCTION_ARGS)
4679 {
4680 Numeric num = PG_GETARG_NUMERIC(0);
4681 NumericVar x;
4682 int64 val;
4683 int16 result;
4684
4685 if (NUMERIC_IS_SPECIAL(num))
4686 {
4687 if (NUMERIC_IS_NAN(num))
4688 ereport(ERROR,
4689 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4690 errmsg("cannot convert NaN to %s", "smallint")));
4691 else
4692 ereport(ERROR,
4693 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4694 errmsg("cannot convert infinity to %s", "smallint")));
4695 }
4696
4697 /* Convert to variable format and thence to int8 */
4698 init_var_from_num(num, &x);
4699
4700 if (!numericvar_to_int64(&x, &val))
4701 ereport(ERROR,
4702 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4703 errmsg("smallint out of range")));
4704
4705 if (unlikely(val < PG_INT16_MIN) || unlikely(val > PG_INT16_MAX))
4706 ereport(ERROR,
4707 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4708 errmsg("smallint out of range")));
4709
4710 /* Down-convert to int2 */
4711 result = (int16) val;
4712
4713 PG_RETURN_INT16(result);
4714 }
4715
4716
4717 Datum
4718 float8_numeric(PG_FUNCTION_ARGS)
4719 {
4720 float8 val = PG_GETARG_FLOAT8(0);
4721 Numeric res;
4722 NumericVar result;
4723 char buf[DBL_DIG + 100];
4724 const char *endptr;
4725
4726 if (isnan(val))
4727 PG_RETURN_NUMERIC(make_result(&const_nan));
4728
4729 if (isinf(val))
4730 {
4731 if (val < 0)
4732 PG_RETURN_NUMERIC(make_result(&const_ninf));
4733 else
4734 PG_RETURN_NUMERIC(make_result(&const_pinf));
4735 }
4736
4737 snprintf(buf, sizeof(buf), "%.*g", DBL_DIG, val);
4738
4739 init_var(&result);
4740
4741 /* Assume we need not worry about leading/trailing spaces */
4742 (void) set_var_from_str(buf, buf, &result, &endptr, NULL);
4743
4744 res = make_result(&result);
4745
4746 free_var(&result);
4747
4748 PG_RETURN_NUMERIC(res);
4749 }
4750
4751
4752 Datum
4753 numeric_float8(PG_FUNCTION_ARGS)
4754 {
4755 Numeric num = PG_GETARG_NUMERIC(0);
4756 char *tmp;
4757 Datum result;
4758
4759 if (NUMERIC_IS_SPECIAL(num))
4760 {
4761 if (NUMERIC_IS_PINF(num))
4762 PG_RETURN_FLOAT8(get_float8_infinity());
4763 else if (NUMERIC_IS_NINF(num))
4764 PG_RETURN_FLOAT8(-get_float8_infinity());
4765 else
4766 PG_RETURN_FLOAT8(get_float8_nan());
4767 }
4768
4769 tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
4770 NumericGetDatum(num)));
4771
4772 result = DirectFunctionCall1(float8in, CStringGetDatum(tmp));
4773
4774 pfree(tmp);
4775
4776 PG_RETURN_DATUM(result);
4777 }
4778
4779
4780 /*
4781 * Convert numeric to float8; if out of range, return +/- HUGE_VAL
4782 *
4783 * (internal helper function, not directly callable from SQL)
4784 */
4785 Datum
4786 numeric_float8_no_overflow(PG_FUNCTION_ARGS)
4787 {
4788 Numeric num = PG_GETARG_NUMERIC(0);
4789 double val;
4790
4791 if (NUMERIC_IS_SPECIAL(num))
4792 {
4793 if (NUMERIC_IS_PINF(num))
4794 val = HUGE_VAL;
4795 else if (NUMERIC_IS_NINF(num))
4796 val = -HUGE_VAL;
4797 else
4798 val = get_float8_nan();
4799 }
4800 else
4801 {
4802 NumericVar x;
4803
4804 init_var_from_num(num, &x);
4805 val = numericvar_to_double_no_overflow(&x);
4806 }
4807
4808 PG_RETURN_FLOAT8(val);
4809 }
4810
4811 Datum
4812 float4_numeric(PG_FUNCTION_ARGS)
4813 {
4814 float4 val = PG_GETARG_FLOAT4(0);
4815 Numeric res;
4816 NumericVar result;
4817 char buf[FLT_DIG + 100];
4818 const char *endptr;
4819
4820 if (isnan(val))
4821 PG_RETURN_NUMERIC(make_result(&const_nan));
4822
4823 if (isinf(val))
4824 {
4825 if (val < 0)
4826 PG_RETURN_NUMERIC(make_result(&const_ninf));
4827 else
4828 PG_RETURN_NUMERIC(make_result(&const_pinf));
4829 }
4830
4831 snprintf(buf, sizeof(buf), "%.*g", FLT_DIG, val);
4832
4833 init_var(&result);
4834
4835 /* Assume we need not worry about leading/trailing spaces */
4836 (void) set_var_from_str(buf, buf, &result, &endptr, NULL);
4837
4838 res = make_result(&result);
4839
4840 free_var(&result);
4841
4842 PG_RETURN_NUMERIC(res);
4843 }
4844
4845
4846 Datum
4847 numeric_float4(PG_FUNCTION_ARGS)
4848 {
4849 Numeric num = PG_GETARG_NUMERIC(0);
4850 char *tmp;
4851 Datum result;
4852
4853 if (NUMERIC_IS_SPECIAL(num))
4854 {
4855 if (NUMERIC_IS_PINF(num))
4856 PG_RETURN_FLOAT4(get_float4_infinity());
4857 else if (NUMERIC_IS_NINF(num))
4858 PG_RETURN_FLOAT4(-get_float4_infinity());
4859 else
4860 PG_RETURN_FLOAT4(get_float4_nan());
4861 }
4862
4863 tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
4864 NumericGetDatum(num)));
4865
4866 result = DirectFunctionCall1(float4in, CStringGetDatum(tmp));
4867
4868 pfree(tmp);
4869
4870 PG_RETURN_DATUM(result);
4871 }
4872
4873
4874 Datum
4875 numeric_pg_lsn(PG_FUNCTION_ARGS)
4876 {
4877 Numeric num = PG_GETARG_NUMERIC(0);
4878 NumericVar x;
4879 XLogRecPtr result;
4880
4881 if (NUMERIC_IS_SPECIAL(num))
4882 {
4883 if (NUMERIC_IS_NAN(num))
4884 ereport(ERROR,
4885 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4886 errmsg("cannot convert NaN to %s", "pg_lsn")));
4887 else
4888 ereport(ERROR,
4889 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4890 errmsg("cannot convert infinity to %s", "pg_lsn")));
4891 }
4892
4893 /* Convert to variable format and thence to pg_lsn */
4894 init_var_from_num(num, &x);
4895
4896 if (!numericvar_to_uint64(&x, (uint64 *) &result))
4897 ereport(ERROR,
4898 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4899 errmsg("pg_lsn out of range")));
4900
4901 PG_RETURN_LSN(result);
4902 }
4903
4904
4905 /* ----------------------------------------------------------------------
4906 *
4907 * Aggregate functions
4908 *
4909 * The transition datatype for all these aggregates is declared as INTERNAL.
4910 * Actually, it's a pointer to a NumericAggState allocated in the aggregate
4911 * context. The digit buffers for the NumericVars will be there too.
4912 *
4913 * On platforms which support 128-bit integers some aggregates instead use a
4914 * 128-bit integer based transition datatype to speed up calculations.
4915 *
4916 * ----------------------------------------------------------------------
4917 */
4918
4919 typedef struct NumericAggState
4920 {
4921 bool calcSumX2; /* if true, calculate sumX2 */
4922 MemoryContext agg_context; /* context we're calculating in */
4923 int64 N; /* count of processed numbers */
4924 NumericSumAccum sumX; /* sum of processed numbers */
4925 NumericSumAccum sumX2; /* sum of squares of processed numbers */
4926 int maxScale; /* maximum scale seen so far */
4927 int64 maxScaleCount; /* number of values seen with maximum scale */
4928 /* These counts are *not* included in N! Use NA_TOTAL_COUNT() as needed */
4929 int64 NaNcount; /* count of NaN values */
4930 int64 pInfcount; /* count of +Inf values */
4931 int64 nInfcount; /* count of -Inf values */
4932 } NumericAggState;
4933
4934 #define NA_TOTAL_COUNT(na) \
4935 ((na)->N + (na)->NaNcount + (na)->pInfcount + (na)->nInfcount)
4936
4937 /*
4938 * Prepare state data for a numeric aggregate function that needs to compute
4939 * sum, count and optionally sum of squares of the input.
4940 */
4941 static NumericAggState *
4942 makeNumericAggState(FunctionCallInfo fcinfo, bool calcSumX2)
4943 {
4944 NumericAggState *state;
4945 MemoryContext agg_context;
4946 MemoryContext old_context;
4947
4948 if (!AggCheckCallContext(fcinfo, &agg_context))
4949 elog(ERROR, "aggregate function called in non-aggregate context");
4950
4951 old_context = MemoryContextSwitchTo(agg_context);
4952
4953 state = (NumericAggState *) palloc0(sizeof(NumericAggState));
4954 state->calcSumX2 = calcSumX2;
4955 state->agg_context = agg_context;
4956
4957 MemoryContextSwitchTo(old_context);
4958
4959 return state;
4960 }
4961
4962 /*
4963 * Like makeNumericAggState(), but allocate the state in the current memory
4964 * context.
4965 */
4966 static NumericAggState *
4967 makeNumericAggStateCurrentContext(bool calcSumX2)
4968 {
4969 NumericAggState *state;
4970
4971 state = (NumericAggState *) palloc0(sizeof(NumericAggState));
4972 state->calcSumX2 = calcSumX2;
4973 state->agg_context = CurrentMemoryContext;
4974
4975 return state;
4976 }
4977
4978 /*
4979 * Accumulate a new input value for numeric aggregate functions.
4980 */
4981 static void
4982 do_numeric_accum(NumericAggState *state, Numeric newval)
4983 {
4984 NumericVar X;
4985 NumericVar X2;
4986 MemoryContext old_context;
4987
4988 /* Count NaN/infinity inputs separately from all else */
4989 if (NUMERIC_IS_SPECIAL(newval))
4990 {
4991 if (NUMERIC_IS_PINF(newval))
4992 state->pInfcount++;
4993 else if (NUMERIC_IS_NINF(newval))
4994 state->nInfcount++;
4995 else
4996 state->NaNcount++;
4997 return;
4998 }
4999
5000 /* load processed number in short-lived context */
5001 init_var_from_num(newval, &X);
5002
5003 /*
5004 * Track the highest input dscale that we've seen, to support inverse
5005 * transitions (see do_numeric_discard).
5006 */
5007 if (X.dscale > state->maxScale)
5008 {
5009 state->maxScale = X.dscale;
5010 state->maxScaleCount = 1;
5011 }
5012 else if (X.dscale == state->maxScale)
5013 state->maxScaleCount++;
5014
5015 /* if we need X^2, calculate that in short-lived context */
5016 if (state->calcSumX2)
5017 {
5018 init_var(&X2);
5019 mul_var(&X, &X, &X2, X.dscale * 2);
5020 }
5021
5022 /* The rest of this needs to work in the aggregate context */
5023 old_context = MemoryContextSwitchTo(state->agg_context);
5024
5025 state->N++;
5026
5027 /* Accumulate sums */
5028 accum_sum_add(&(state->sumX), &X);
5029
5030 if (state->calcSumX2)
5031 accum_sum_add(&(state->sumX2), &X2);
5032
5033 MemoryContextSwitchTo(old_context);
5034 }
5035
5036 /*
5037 * Attempt to remove an input value from the aggregated state.
5038 *
5039 * If the value cannot be removed then the function will return false; the
5040 * possible reasons for failing are described below.
5041 *
5042 * If we aggregate the values 1.01 and 2 then the result will be 3.01.
5043 * If we are then asked to un-aggregate the 1.01 then we must fail as we
5044 * won't be able to tell what the new aggregated value's dscale should be.
5045 * We don't want to return 2.00 (dscale = 2), since the sum's dscale would
5046 * have been zero if we'd really aggregated only 2.
5047 *
5048 * Note: alternatively, we could count the number of inputs with each possible
5049 * dscale (up to some sane limit). Not yet clear if it's worth the trouble.
5050 */
5051 static bool
5052 do_numeric_discard(NumericAggState *state, Numeric newval)
5053 {
5054 NumericVar X;
5055 NumericVar X2;
5056 MemoryContext old_context;
5057
5058 /* Count NaN/infinity inputs separately from all else */
5059 if (NUMERIC_IS_SPECIAL(newval))
5060 {
5061 if (NUMERIC_IS_PINF(newval))
5062 state->pInfcount--;
5063 else if (NUMERIC_IS_NINF(newval))
5064 state->nInfcount--;
5065 else
5066 state->NaNcount--;
5067 return true;
5068 }
5069
5070 /* load processed number in short-lived context */
5071 init_var_from_num(newval, &X);
5072
5073 /*
5074 * state->sumX's dscale is the maximum dscale of any of the inputs.
5075 * Removing the last input with that dscale would require us to recompute
5076 * the maximum dscale of the *remaining* inputs, which we cannot do unless
5077 * no more non-NaN inputs remain at all. So we report a failure instead,
5078 * and force the aggregation to be redone from scratch.
5079 */
5080 if (X.dscale == state->maxScale)
5081 {
5082 if (state->maxScaleCount > 1 || state->maxScale == 0)
5083 {
5084 /*
5085 * Some remaining inputs have same dscale, or dscale hasn't gotten
5086 * above zero anyway
5087 */
5088 state->maxScaleCount--;
5089 }
5090 else if (state->N == 1)
5091 {
5092 /* No remaining non-NaN inputs at all, so reset maxScale */
5093 state->maxScale = 0;
5094 state->maxScaleCount = 0;
5095 }
5096 else
5097 {
5098 /* Correct new maxScale is uncertain, must fail */
5099 return false;
5100 }
5101 }
5102
5103 /* if we need X^2, calculate that in short-lived context */
5104 if (state->calcSumX2)
5105 {
5106 init_var(&X2);
5107 mul_var(&X, &X, &X2, X.dscale * 2);
5108 }
5109
5110 /* The rest of this needs to work in the aggregate context */
5111 old_context = MemoryContextSwitchTo(state->agg_context);
5112
5113 if (state->N-- > 1)
5114 {
5115 /* Negate X, to subtract it from the sum */
5116 X.sign = (X.sign == NUMERIC_POS ? NUMERIC_NEG : NUMERIC_POS);
5117 accum_sum_add(&(state->sumX), &X);
5118
5119 if (state->calcSumX2)
5120 {
5121 /* Negate X^2. X^2 is always positive */
5122 X2.sign = NUMERIC_NEG;
5123 accum_sum_add(&(state->sumX2), &X2);
5124 }
5125 }
5126 else
5127 {
5128 /* Zero the sums */
5129 Assert(state->N == 0);
5130
5131 accum_sum_reset(&state->sumX);
5132 if (state->calcSumX2)
5133 accum_sum_reset(&state->sumX2);
5134 }
5135
5136 MemoryContextSwitchTo(old_context);
5137
5138 return true;
5139 }
5140
5141 /*
5142 * Generic transition function for numeric aggregates that require sumX2.
5143 */
5144 Datum
5145 numeric_accum(PG_FUNCTION_ARGS)
5146 {
5147 NumericAggState *state;
5148
5149 state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5150
5151 /* Create the state data on the first call */
5152 if (state == NULL)
5153 state = makeNumericAggState(fcinfo, true);
5154
5155 if (!PG_ARGISNULL(1))
5156 do_numeric_accum(state, PG_GETARG_NUMERIC(1));
5157
5158 PG_RETURN_POINTER(state);
5159 }
5160
5161 /*
5162 * Generic combine function for numeric aggregates which require sumX2
5163 */
5164 Datum
5165 numeric_combine(PG_FUNCTION_ARGS)
5166 {
5167 NumericAggState *state1;
5168 NumericAggState *state2;
5169 MemoryContext agg_context;
5170 MemoryContext old_context;
5171
5172 if (!AggCheckCallContext(fcinfo, &agg_context))
5173 elog(ERROR, "aggregate function called in non-aggregate context");
5174
5175 state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5176 state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
5177
5178 if (state2 == NULL)
5179 {
5180 /*
5181 * NULL state2 is easy, just return state1, which we know is already
5182 * in the agg_context
5183 */
5184 if (state1 == NULL)
5185 PG_RETURN_NULL();
5186 PG_RETURN_POINTER(state1);
5187 }
5188
5189 /* manually copy all fields from state2 to state1 */
5190 if (state1 == NULL)
5191 {
5192 old_context = MemoryContextSwitchTo(agg_context);
5193
5194 state1 = makeNumericAggStateCurrentContext(true);
5195 state1->N = state2->N;
5196 state1->NaNcount = state2->NaNcount;
5197 state1->pInfcount = state2->pInfcount;
5198 state1->nInfcount = state2->nInfcount;
5199 state1->maxScale = state2->maxScale;
5200 state1->maxScaleCount = state2->maxScaleCount;
5201
5202 accum_sum_copy(&state1->sumX, &state2->sumX);
5203 accum_sum_copy(&state1->sumX2, &state2->sumX2);
5204
5205 MemoryContextSwitchTo(old_context);
5206
5207 PG_RETURN_POINTER(state1);
5208 }
5209
5210 state1->N += state2->N;
5211 state1->NaNcount += state2->NaNcount;
5212 state1->pInfcount += state2->pInfcount;
5213 state1->nInfcount += state2->nInfcount;
5214
5215 if (state2->N > 0)
5216 {
5217 /*
5218 * These are currently only needed for moving aggregates, but let's do
5219 * the right thing anyway...
5220 */
5221 if (state2->maxScale > state1->maxScale)
5222 {
5223 state1->maxScale = state2->maxScale;
5224 state1->maxScaleCount = state2->maxScaleCount;
5225 }
5226 else if (state2->maxScale == state1->maxScale)
5227 state1->maxScaleCount += state2->maxScaleCount;
5228
5229 /* The rest of this needs to work in the aggregate context */
5230 old_context = MemoryContextSwitchTo(agg_context);
5231
5232 /* Accumulate sums */
5233 accum_sum_combine(&state1->sumX, &state2->sumX);
5234 accum_sum_combine(&state1->sumX2, &state2->sumX2);
5235
5236 MemoryContextSwitchTo(old_context);
5237 }
5238 PG_RETURN_POINTER(state1);
5239 }
5240
5241 /*
5242 * Generic transition function for numeric aggregates that don't require sumX2.
5243 */
5244 Datum
5245 numeric_avg_accum(PG_FUNCTION_ARGS)
5246 {
5247 NumericAggState *state;
5248
5249 state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5250
5251 /* Create the state data on the first call */
5252 if (state == NULL)
5253 state = makeNumericAggState(fcinfo, false);
5254
5255 if (!PG_ARGISNULL(1))
5256 do_numeric_accum(state, PG_GETARG_NUMERIC(1));
5257
5258 PG_RETURN_POINTER(state);
5259 }
5260
5261 /*
5262 * Combine function for numeric aggregates which don't require sumX2
5263 */
5264 Datum
5265 numeric_avg_combine(PG_FUNCTION_ARGS)
5266 {
5267 NumericAggState *state1;
5268 NumericAggState *state2;
5269 MemoryContext agg_context;
5270 MemoryContext old_context;
5271
5272 if (!AggCheckCallContext(fcinfo, &agg_context))
5273 elog(ERROR, "aggregate function called in non-aggregate context");
5274
5275 state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5276 state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
5277
5278 if (state2 == NULL)
5279 {
5280 /*
5281 * NULL state2 is easy, just return state1, which we know is already
5282 * in the agg_context
5283 */
5284 if (state1 == NULL)
5285 PG_RETURN_NULL();
5286 PG_RETURN_POINTER(state1);
5287 }
5288
5289 /* manually copy all fields from state2 to state1 */
5290 if (state1 == NULL)
5291 {
5292 old_context = MemoryContextSwitchTo(agg_context);
5293
5294 state1 = makeNumericAggStateCurrentContext(false);
5295 state1->N = state2->N;
5296 state1->NaNcount = state2->NaNcount;
5297 state1->pInfcount = state2->pInfcount;
5298 state1->nInfcount = state2->nInfcount;
5299 state1->maxScale = state2->maxScale;
5300 state1->maxScaleCount = state2->maxScaleCount;
5301
5302 accum_sum_copy(&state1->sumX, &state2->sumX);
5303
5304 MemoryContextSwitchTo(old_context);
5305
5306 PG_RETURN_POINTER(state1);
5307 }
5308
5309 state1->N += state2->N;
5310 state1->NaNcount += state2->NaNcount;
5311 state1->pInfcount += state2->pInfcount;
5312 state1->nInfcount += state2->nInfcount;
5313
5314 if (state2->N > 0)
5315 {
5316 /*
5317 * These are currently only needed for moving aggregates, but let's do
5318 * the right thing anyway...
5319 */
5320 if (state2->maxScale > state1->maxScale)
5321 {
5322 state1->maxScale = state2->maxScale;
5323 state1->maxScaleCount = state2->maxScaleCount;
5324 }
5325 else if (state2->maxScale == state1->maxScale)
5326 state1->maxScaleCount += state2->maxScaleCount;
5327
5328 /* The rest of this needs to work in the aggregate context */
5329 old_context = MemoryContextSwitchTo(agg_context);
5330
5331 /* Accumulate sums */
5332 accum_sum_combine(&state1->sumX, &state2->sumX);
5333
5334 MemoryContextSwitchTo(old_context);
5335 }
5336 PG_RETURN_POINTER(state1);
5337 }
5338
5339 /*
5340 * numeric_avg_serialize
5341 * Serialize NumericAggState for numeric aggregates that don't require
5342 * sumX2.
5343 */
5344 Datum
5345 numeric_avg_serialize(PG_FUNCTION_ARGS)
5346 {
5347 NumericAggState *state;
5348 StringInfoData buf;
5349 bytea *result;
5350 NumericVar tmp_var;
5351
5352 /* Ensure we disallow calling when not in aggregate context */
5353 if (!AggCheckCallContext(fcinfo, NULL))
5354 elog(ERROR, "aggregate function called in non-aggregate context");
5355
5356 state = (NumericAggState *) PG_GETARG_POINTER(0);
5357
5358 init_var(&tmp_var);
5359
5360 pq_begintypsend(&buf);
5361
5362 /* N */
5363 pq_sendint64(&buf, state->N);
5364
5365 /* sumX */
5366 accum_sum_final(&state->sumX, &tmp_var);
5367 numericvar_serialize(&buf, &tmp_var);
5368
5369 /* maxScale */
5370 pq_sendint32(&buf, state->maxScale);
5371
5372 /* maxScaleCount */
5373 pq_sendint64(&buf, state->maxScaleCount);
5374
5375 /* NaNcount */
5376 pq_sendint64(&buf, state->NaNcount);
5377
5378 /* pInfcount */
5379 pq_sendint64(&buf, state->pInfcount);
5380
5381 /* nInfcount */
5382 pq_sendint64(&buf, state->nInfcount);
5383
5384 result = pq_endtypsend(&buf);
5385
5386 free_var(&tmp_var);
5387
5388 PG_RETURN_BYTEA_P(result);
5389 }
5390
5391 /*
5392 * numeric_avg_deserialize
5393 * Deserialize bytea into NumericAggState for numeric aggregates that
5394 * don't require sumX2.
5395 */
5396 Datum
5397 numeric_avg_deserialize(PG_FUNCTION_ARGS)
5398 {
5399 bytea *sstate;
5400 NumericAggState *result;
5401 StringInfoData buf;
5402 NumericVar tmp_var;
5403
5404 if (!AggCheckCallContext(fcinfo, NULL))
5405 elog(ERROR, "aggregate function called in non-aggregate context");
5406
5407 sstate = PG_GETARG_BYTEA_PP(0);
5408
5409 init_var(&tmp_var);
5410
5411 /*
5412 * Initialize a StringInfo so that we can "receive" it using the standard
5413 * recv-function infrastructure.
5414 */
5415 initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
5416 VARSIZE_ANY_EXHDR(sstate));
5417
5418 result = makeNumericAggStateCurrentContext(false);
5419
5420 /* N */
5421 result->N = pq_getmsgint64(&buf);
5422
5423 /* sumX */
5424 numericvar_deserialize(&buf, &tmp_var);
5425 accum_sum_add(&(result->sumX), &tmp_var);
5426
5427 /* maxScale */
5428 result->maxScale = pq_getmsgint(&buf, 4);
5429
5430 /* maxScaleCount */
5431 result->maxScaleCount = pq_getmsgint64(&buf);
5432
5433 /* NaNcount */
5434 result->NaNcount = pq_getmsgint64(&buf);
5435
5436 /* pInfcount */
5437 result->pInfcount = pq_getmsgint64(&buf);
5438
5439 /* nInfcount */
5440 result->nInfcount = pq_getmsgint64(&buf);
5441
5442 pq_getmsgend(&buf);
5443
5444 free_var(&tmp_var);
5445
5446 PG_RETURN_POINTER(result);
5447 }
5448
5449 /*
5450 * numeric_serialize
5451 * Serialization function for NumericAggState for numeric aggregates that
5452 * require sumX2.
5453 */
5454 Datum
5455 numeric_serialize(PG_FUNCTION_ARGS)
5456 {
5457 NumericAggState *state;
5458 StringInfoData buf;
5459 bytea *result;
5460 NumericVar tmp_var;
5461
5462 /* Ensure we disallow calling when not in aggregate context */
5463 if (!AggCheckCallContext(fcinfo, NULL))
5464 elog(ERROR, "aggregate function called in non-aggregate context");
5465
5466 state = (NumericAggState *) PG_GETARG_POINTER(0);
5467
5468 init_var(&tmp_var);
5469
5470 pq_begintypsend(&buf);
5471
5472 /* N */
5473 pq_sendint64(&buf, state->N);
5474
5475 /* sumX */
5476 accum_sum_final(&state->sumX, &tmp_var);
5477 numericvar_serialize(&buf, &tmp_var);
5478
5479 /* sumX2 */
5480 accum_sum_final(&state->sumX2, &tmp_var);
5481 numericvar_serialize(&buf, &tmp_var);
5482
5483 /* maxScale */
5484 pq_sendint32(&buf, state->maxScale);
5485
5486 /* maxScaleCount */
5487 pq_sendint64(&buf, state->maxScaleCount);
5488
5489 /* NaNcount */
5490 pq_sendint64(&buf, state->NaNcount);
5491
5492 /* pInfcount */
5493 pq_sendint64(&buf, state->pInfcount);
5494
5495 /* nInfcount */
5496 pq_sendint64(&buf, state->nInfcount);
5497
5498 result = pq_endtypsend(&buf);
5499
5500 free_var(&tmp_var);
5501
5502 PG_RETURN_BYTEA_P(result);
5503 }
5504
5505 /*
5506 * numeric_deserialize
5507 * Deserialization function for NumericAggState for numeric aggregates that
5508 * require sumX2.
5509 */
5510 Datum
5511 numeric_deserialize(PG_FUNCTION_ARGS)
5512 {
5513 bytea *sstate;
5514 NumericAggState *result;
5515 StringInfoData buf;
5516 NumericVar tmp_var;
5517
5518 if (!AggCheckCallContext(fcinfo, NULL))
5519 elog(ERROR, "aggregate function called in non-aggregate context");
5520
5521 sstate = PG_GETARG_BYTEA_PP(0);
5522
5523 init_var(&tmp_var);
5524
5525 /*
5526 * Initialize a StringInfo so that we can "receive" it using the standard
5527 * recv-function infrastructure.
5528 */
5529 initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
5530 VARSIZE_ANY_EXHDR(sstate));
5531
5532 result = makeNumericAggStateCurrentContext(false);
5533
5534 /* N */
5535 result->N = pq_getmsgint64(&buf);
5536
5537 /* sumX */
5538 numericvar_deserialize(&buf, &tmp_var);
5539 accum_sum_add(&(result->sumX), &tmp_var);
5540
5541 /* sumX2 */
5542 numericvar_deserialize(&buf, &tmp_var);
5543 accum_sum_add(&(result->sumX2), &tmp_var);
5544
5545 /* maxScale */
5546 result->maxScale = pq_getmsgint(&buf, 4);
5547
5548 /* maxScaleCount */
5549 result->maxScaleCount = pq_getmsgint64(&buf);
5550
5551 /* NaNcount */
5552 result->NaNcount = pq_getmsgint64(&buf);
5553
5554 /* pInfcount */
5555 result->pInfcount = pq_getmsgint64(&buf);
5556
5557 /* nInfcount */
5558 result->nInfcount = pq_getmsgint64(&buf);
5559
5560 pq_getmsgend(&buf);
5561
5562 free_var(&tmp_var);
5563
5564 PG_RETURN_POINTER(result);
5565 }
5566
5567 /*
5568 * Generic inverse transition function for numeric aggregates
5569 * (with or without requirement for X^2).
5570 */
5571 Datum
5572 numeric_accum_inv(PG_FUNCTION_ARGS)
5573 {
5574 NumericAggState *state;
5575
5576 state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5577
5578 /* Should not get here with no state */
5579 if (state == NULL)
5580 elog(ERROR, "numeric_accum_inv called with NULL state");
5581
5582 if (!PG_ARGISNULL(1))
5583 {
5584 /* If we fail to perform the inverse transition, return NULL */
5585 if (!do_numeric_discard(state, PG_GETARG_NUMERIC(1)))
5586 PG_RETURN_NULL();
5587 }
5588
5589 PG_RETURN_POINTER(state);
5590 }
5591
5592
5593 /*
5594 * Integer data types in general use Numeric accumulators to share code
5595 * and avoid risk of overflow.
5596 *
5597 * However for performance reasons optimized special-purpose accumulator
5598 * routines are used when possible.
5599 *
5600 * On platforms with 128-bit integer support, the 128-bit routines will be
5601 * used when sum(X) or sum(X*X) fit into 128-bit.
5602 *
5603 * For 16 and 32 bit inputs, the N and sum(X) fit into 64-bit so the 64-bit
5604 * accumulators will be used for SUM and AVG of these data types.
5605 */
5606
5607 #ifdef HAVE_INT128
5608 typedef struct Int128AggState
5609 {
5610 bool calcSumX2; /* if true, calculate sumX2 */
5611 int64 N; /* count of processed numbers */
5612 int128 sumX; /* sum of processed numbers */
5613 int128 sumX2; /* sum of squares of processed numbers */
5614 } Int128AggState;
5615
5616 /*
5617 * Prepare state data for a 128-bit aggregate function that needs to compute
5618 * sum, count and optionally sum of squares of the input.
5619 */
5620 static Int128AggState *
5621 makeInt128AggState(FunctionCallInfo fcinfo, bool calcSumX2)
5622 {
5623 Int128AggState *state;
5624 MemoryContext agg_context;
5625 MemoryContext old_context;
5626
5627 if (!AggCheckCallContext(fcinfo, &agg_context))
5628 elog(ERROR, "aggregate function called in non-aggregate context");
5629
5630 old_context = MemoryContextSwitchTo(agg_context);
5631
5632 state = (Int128AggState *) palloc0(sizeof(Int128AggState));
5633 state->calcSumX2 = calcSumX2;
5634
5635 MemoryContextSwitchTo(old_context);
5636
5637 return state;
5638 }
5639
5640 /*
5641 * Like makeInt128AggState(), but allocate the state in the current memory
5642 * context.
5643 */
5644 static Int128AggState *
5645 makeInt128AggStateCurrentContext(bool calcSumX2)
5646 {
5647 Int128AggState *state;
5648
5649 state = (Int128AggState *) palloc0(sizeof(Int128AggState));
5650 state->calcSumX2 = calcSumX2;
5651
5652 return state;
5653 }
5654
5655 /*
5656 * Accumulate a new input value for 128-bit aggregate functions.
5657 */
5658 static void
5659 do_int128_accum(Int128AggState *state, int128 newval)
5660 {
5661 if (state->calcSumX2)
5662 state->sumX2 += newval * newval;
5663
5664 state->sumX += newval;
5665 state->N++;
5666 }
5667
5668 /*
5669 * Remove an input value from the aggregated state.
5670 */
5671 static void
5672 do_int128_discard(Int128AggState *state, int128 newval)
5673 {
5674 if (state->calcSumX2)
5675 state->sumX2 -= newval * newval;
5676
5677 state->sumX -= newval;
5678 state->N--;
5679 }
5680
5681 typedef Int128AggState PolyNumAggState;
5682 #define makePolyNumAggState makeInt128AggState
5683 #define makePolyNumAggStateCurrentContext makeInt128AggStateCurrentContext
5684 #else
5685 typedef NumericAggState PolyNumAggState;
5686 #define makePolyNumAggState makeNumericAggState
5687 #define makePolyNumAggStateCurrentContext makeNumericAggStateCurrentContext
5688 #endif
5689
5690 Datum
5691 int2_accum(PG_FUNCTION_ARGS)
5692 {
5693 PolyNumAggState *state;
5694
5695 state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
5696
5697 /* Create the state data on the first call */
5698 if (state == NULL)
5699 state = makePolyNumAggState(fcinfo, true);
5700
5701 if (!PG_ARGISNULL(1))
5702 {
5703 #ifdef HAVE_INT128
5704 do_int128_accum(state, (int128) PG_GETARG_INT16(1));
5705 #else
5706 do_numeric_accum(state, int64_to_numeric(PG_GETARG_INT16(1)));
5707 #endif
5708 }
5709
5710 PG_RETURN_POINTER(state);
5711 }
5712
5713 Datum
5714 int4_accum(PG_FUNCTION_ARGS)
5715 {
5716 PolyNumAggState *state;
5717
5718 state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
5719
5720 /* Create the state data on the first call */
5721 if (state == NULL)
5722 state = makePolyNumAggState(fcinfo, true);
5723
5724 if (!PG_ARGISNULL(1))
5725 {
5726 #ifdef HAVE_INT128
5727 do_int128_accum(state, (int128) PG_GETARG_INT32(1));
5728 #else
5729 do_numeric_accum(state, int64_to_numeric(PG_GETARG_INT32(1)));
5730 #endif
5731 }
5732
5733 PG_RETURN_POINTER(state);
5734 }
5735
5736 Datum
5737 int8_accum(PG_FUNCTION_ARGS)
5738 {
5739 NumericAggState *state;
5740
5741 state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5742
5743 /* Create the state data on the first call */
5744 if (state == NULL)
5745 state = makeNumericAggState(fcinfo, true);
5746
5747 if (!PG_ARGISNULL(1))
5748 do_numeric_accum(state, int64_to_numeric(PG_GETARG_INT64(1)));
5749
5750 PG_RETURN_POINTER(state);
5751 }
5752
5753 /*
5754 * Combine function for numeric aggregates which require sumX2
5755 */
5756 Datum
5757 numeric_poly_combine(PG_FUNCTION_ARGS)
5758 {
5759 PolyNumAggState *state1;
5760 PolyNumAggState *state2;
5761 MemoryContext agg_context;
5762 MemoryContext old_context;
5763
5764 if (!AggCheckCallContext(fcinfo, &agg_context))
5765 elog(ERROR, "aggregate function called in non-aggregate context");
5766
5767 state1 = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
5768 state2 = PG_ARGISNULL(1) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(1);
5769
5770 if (state2 == NULL)
5771 {
5772 /*
5773 * NULL state2 is easy, just return state1, which we know is already
5774 * in the agg_context
5775 */
5776 if (state1 == NULL)
5777 PG_RETURN_NULL();
5778 PG_RETURN_POINTER(state1);
5779 }
5780
5781 /* manually copy all fields from state2 to state1 */
5782 if (state1 == NULL)
5783 {
5784 old_context = MemoryContextSwitchTo(agg_context);
5785
5786 state1 = makePolyNumAggState(fcinfo, true);
5787 state1->N = state2->N;
5788
5789 #ifdef HAVE_INT128
5790 state1->sumX = state2->sumX;
5791 state1->sumX2 = state2->sumX2;
5792 #else
5793 accum_sum_copy(&state1->sumX, &state2->sumX);
5794 accum_sum_copy(&state1->sumX2, &state2->sumX2);
5795 #endif
5796
5797 MemoryContextSwitchTo(old_context);
5798
5799 PG_RETURN_POINTER(state1);
5800 }
5801
5802 if (state2->N > 0)
5803 {
5804 state1->N += state2->N;
5805
5806 #ifdef HAVE_INT128
5807 state1->sumX += state2->sumX;
5808 state1->sumX2 += state2->sumX2;
5809 #else
5810 /* The rest of this needs to work in the aggregate context */
5811 old_context = MemoryContextSwitchTo(agg_context);
5812
5813 /* Accumulate sums */
5814 accum_sum_combine(&state1->sumX, &state2->sumX);
5815 accum_sum_combine(&state1->sumX2, &state2->sumX2);
5816
5817 MemoryContextSwitchTo(old_context);
5818 #endif
5819
5820 }
5821 PG_RETURN_POINTER(state1);
5822 }
5823
5824 /*
5825 * numeric_poly_serialize
5826 * Serialize PolyNumAggState into bytea for aggregate functions which
5827 * require sumX2.
5828 */
5829 Datum
5830 numeric_poly_serialize(PG_FUNCTION_ARGS)
5831 {
5832 PolyNumAggState *state;
5833 StringInfoData buf;
5834 bytea *result;
5835 NumericVar tmp_var;
5836
5837 /* Ensure we disallow calling when not in aggregate context */
5838 if (!AggCheckCallContext(fcinfo, NULL))
5839 elog(ERROR, "aggregate function called in non-aggregate context");
5840
5841 state = (PolyNumAggState *) PG_GETARG_POINTER(0);
5842
5843 /*
5844 * If the platform supports int128 then sumX and sumX2 will be a 128 bit
5845 * integer type. Here we'll convert that into a numeric type so that the
5846 * combine state is in the same format for both int128 enabled machines
5847 * and machines which don't support that type. The logic here is that one
5848 * day we might like to send these over to another server for further
5849 * processing and we want a standard format to work with.
5850 */
5851
5852 init_var(&tmp_var);
5853
5854 pq_begintypsend(&buf);
5855
5856 /* N */
5857 pq_sendint64(&buf, state->N);
5858
5859 /* sumX */
5860 #ifdef HAVE_INT128
5861 int128_to_numericvar(state->sumX, &tmp_var);
5862 #else
5863 accum_sum_final(&state->sumX, &tmp_var);
5864 #endif
5865 numericvar_serialize(&buf, &tmp_var);
5866
5867 /* sumX2 */
5868 #ifdef HAVE_INT128
5869 int128_to_numericvar(state->sumX2, &tmp_var);
5870 #else
5871 accum_sum_final(&state->sumX2, &tmp_var);
5872 #endif
5873 numericvar_serialize(&buf, &tmp_var);
5874
5875 result = pq_endtypsend(&buf);
5876
5877 free_var(&tmp_var);
5878
5879 PG_RETURN_BYTEA_P(result);
5880 }
5881
5882 /*
5883 * numeric_poly_deserialize
5884 * Deserialize PolyNumAggState from bytea for aggregate functions which
5885 * require sumX2.
5886 */
5887 Datum
5888 numeric_poly_deserialize(PG_FUNCTION_ARGS)
5889 {
5890 bytea *sstate;
5891 PolyNumAggState *result;
5892 StringInfoData buf;
5893 NumericVar tmp_var;
5894
5895 if (!AggCheckCallContext(fcinfo, NULL))
5896 elog(ERROR, "aggregate function called in non-aggregate context");
5897
5898 sstate = PG_GETARG_BYTEA_PP(0);
5899
5900 init_var(&tmp_var);
5901
5902 /*
5903 * Initialize a StringInfo so that we can "receive" it using the standard
5904 * recv-function infrastructure.
5905 */
5906 initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
5907 VARSIZE_ANY_EXHDR(sstate));
5908
5909 result = makePolyNumAggStateCurrentContext(false);
5910
5911 /* N */
5912 result->N = pq_getmsgint64(&buf);
5913
5914 /* sumX */
5915 numericvar_deserialize(&buf, &tmp_var);
5916 #ifdef HAVE_INT128
5917 numericvar_to_int128(&tmp_var, &result->sumX);
5918 #else
5919 accum_sum_add(&result->sumX, &tmp_var);
5920 #endif
5921
5922 /* sumX2 */
5923 numericvar_deserialize(&buf, &tmp_var);
5924 #ifdef HAVE_INT128
5925 numericvar_to_int128(&tmp_var, &result->sumX2);
5926 #else
5927 accum_sum_add(&result->sumX2, &tmp_var);
5928 #endif
5929
5930 pq_getmsgend(&buf);
5931
5932 free_var(&tmp_var);
5933
5934 PG_RETURN_POINTER(result);
5935 }
5936
5937 /*
5938 * Transition function for int8 input when we don't need sumX2.
5939 */
5940 Datum
5941 int8_avg_accum(PG_FUNCTION_ARGS)
5942 {
5943 PolyNumAggState *state;
5944
5945 state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
5946
5947 /* Create the state data on the first call */
5948 if (state == NULL)
5949 state = makePolyNumAggState(fcinfo, false);
5950
5951 if (!PG_ARGISNULL(1))
5952 {
5953 #ifdef HAVE_INT128
5954 do_int128_accum(state, (int128) PG_GETARG_INT64(1));
5955 #else
5956 do_numeric_accum(state, int64_to_numeric(PG_GETARG_INT64(1)));
5957 #endif
5958 }
5959
5960 PG_RETURN_POINTER(state);
5961 }
5962
5963 /*
5964 * Combine function for PolyNumAggState for aggregates which don't require
5965 * sumX2
5966 */
5967 Datum
5968 int8_avg_combine(PG_FUNCTION_ARGS)
5969 {
5970 PolyNumAggState *state1;
5971 PolyNumAggState *state2;
5972 MemoryContext agg_context;
5973 MemoryContext old_context;
5974
5975 if (!AggCheckCallContext(fcinfo, &agg_context))
5976 elog(ERROR, "aggregate function called in non-aggregate context");
5977
5978 state1 = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
5979 state2 = PG_ARGISNULL(1) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(1);
5980
5981 if (state2 == NULL)
5982 {
5983 /*
5984 * NULL state2 is easy, just return state1, which we know is already
5985 * in the agg_context
5986 */
5987 if (state1 == NULL)
5988 PG_RETURN_NULL();
5989 PG_RETURN_POINTER(state1);
5990 }
5991
5992 /* manually copy all fields from state2 to state1 */
5993 if (state1 == NULL)
5994 {
5995 old_context = MemoryContextSwitchTo(agg_context);
5996
5997 state1 = makePolyNumAggState(fcinfo, false);
5998 state1->N = state2->N;
5999
6000 #ifdef HAVE_INT128
6001 state1->sumX = state2->sumX;
6002 #else
6003 accum_sum_copy(&state1->sumX, &state2->sumX);
6004 #endif
6005 MemoryContextSwitchTo(old_context);
6006
6007 PG_RETURN_POINTER(state1);
6008 }
6009
6010 if (state2->N > 0)
6011 {
6012 state1->N += state2->N;
6013
6014 #ifdef HAVE_INT128
6015 state1->sumX += state2->sumX;
6016 #else
6017 /* The rest of this needs to work in the aggregate context */
6018 old_context = MemoryContextSwitchTo(agg_context);
6019
6020 /* Accumulate sums */
6021 accum_sum_combine(&state1->sumX, &state2->sumX);
6022
6023 MemoryContextSwitchTo(old_context);
6024 #endif
6025
6026 }
6027 PG_RETURN_POINTER(state1);
6028 }
6029
6030 /*
6031 * int8_avg_serialize
6032 * Serialize PolyNumAggState into bytea using the standard
6033 * recv-function infrastructure.
6034 */
6035 Datum
6036 int8_avg_serialize(PG_FUNCTION_ARGS)
6037 {
6038 PolyNumAggState *state;
6039 StringInfoData buf;
6040 bytea *result;
6041 NumericVar tmp_var;
6042
6043 /* Ensure we disallow calling when not in aggregate context */
6044 if (!AggCheckCallContext(fcinfo, NULL))
6045 elog(ERROR, "aggregate function called in non-aggregate context");
6046
6047 state = (PolyNumAggState *) PG_GETARG_POINTER(0);
6048
6049 /*
6050 * If the platform supports int128 then sumX will be a 128 integer type.
6051 * Here we'll convert that into a numeric type so that the combine state
6052 * is in the same format for both int128 enabled machines and machines
6053 * which don't support that type. The logic here is that one day we might
6054 * like to send these over to another server for further processing and we
6055 * want a standard format to work with.
6056 */
6057
6058 init_var(&tmp_var);
6059
6060 pq_begintypsend(&buf);
6061
6062 /* N */
6063 pq_sendint64(&buf, state->N);
6064
6065 /* sumX */
6066 #ifdef HAVE_INT128
6067 int128_to_numericvar(state->sumX, &tmp_var);
6068 #else
6069 accum_sum_final(&state->sumX, &tmp_var);
6070 #endif
6071 numericvar_serialize(&buf, &tmp_var);
6072
6073 result = pq_endtypsend(&buf);
6074
6075 free_var(&tmp_var);
6076
6077 PG_RETURN_BYTEA_P(result);
6078 }
6079
6080 /*
6081 * int8_avg_deserialize
6082 * Deserialize bytea back into PolyNumAggState.
6083 */
6084 Datum
6085 int8_avg_deserialize(PG_FUNCTION_ARGS)
6086 {
6087 bytea *sstate;
6088 PolyNumAggState *result;
6089 StringInfoData buf;
6090 NumericVar tmp_var;
6091
6092 if (!AggCheckCallContext(fcinfo, NULL))
6093 elog(ERROR, "aggregate function called in non-aggregate context");
6094
6095 sstate = PG_GETARG_BYTEA_PP(0);
6096
6097 init_var(&tmp_var);
6098
6099 /*
6100 * Initialize a StringInfo so that we can "receive" it using the standard
6101 * recv-function infrastructure.
6102 */
6103 initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
6104 VARSIZE_ANY_EXHDR(sstate));
6105
6106 result = makePolyNumAggStateCurrentContext(false);
6107
6108 /* N */
6109 result->N = pq_getmsgint64(&buf);
6110
6111 /* sumX */
6112 numericvar_deserialize(&buf, &tmp_var);
6113 #ifdef HAVE_INT128
6114 numericvar_to_int128(&tmp_var, &result->sumX);
6115 #else
6116 accum_sum_add(&result->sumX, &tmp_var);
6117 #endif
6118
6119 pq_getmsgend(&buf);
6120
6121 free_var(&tmp_var);
6122
6123 PG_RETURN_POINTER(result);
6124 }
6125
6126 /*
6127 * Inverse transition functions to go with the above.
6128 */
6129
6130 Datum
6131 int2_accum_inv(PG_FUNCTION_ARGS)
6132 {
6133 PolyNumAggState *state;
6134
6135 state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
6136
6137 /* Should not get here with no state */
6138 if (state == NULL)
6139 elog(ERROR, "int2_accum_inv called with NULL state");
6140
6141 if (!PG_ARGISNULL(1))
6142 {
6143 #ifdef HAVE_INT128
6144 do_int128_discard(state, (int128) PG_GETARG_INT16(1));
6145 #else
6146 /* Should never fail, all inputs have dscale 0 */
6147 if (!do_numeric_discard(state, int64_to_numeric(PG_GETARG_INT16(1))))
6148 elog(ERROR, "do_numeric_discard failed unexpectedly");
6149 #endif
6150 }
6151
6152 PG_RETURN_POINTER(state);
6153 }
6154
6155 Datum
6156 int4_accum_inv(PG_FUNCTION_ARGS)
6157 {
6158 PolyNumAggState *state;
6159
6160 state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
6161
6162 /* Should not get here with no state */
6163 if (state == NULL)
6164 elog(ERROR, "int4_accum_inv called with NULL state");
6165
6166 if (!PG_ARGISNULL(1))
6167 {
6168 #ifdef HAVE_INT128
6169 do_int128_discard(state, (int128) PG_GETARG_INT32(1));
6170 #else
6171 /* Should never fail, all inputs have dscale 0 */
6172 if (!do_numeric_discard(state, int64_to_numeric(PG_GETARG_INT32(1))))
6173 elog(ERROR, "do_numeric_discard failed unexpectedly");
6174 #endif
6175 }
6176
6177 PG_RETURN_POINTER(state);
6178 }
6179
6180 Datum
6181 int8_accum_inv(PG_FUNCTION_ARGS)
6182 {
6183 NumericAggState *state;
6184
6185 state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6186
6187 /* Should not get here with no state */
6188 if (state == NULL)
6189 elog(ERROR, "int8_accum_inv called with NULL state");
6190
6191 if (!PG_ARGISNULL(1))
6192 {
6193 /* Should never fail, all inputs have dscale 0 */
6194 if (!do_numeric_discard(state, int64_to_numeric(PG_GETARG_INT64(1))))
6195 elog(ERROR, "do_numeric_discard failed unexpectedly");
6196 }
6197
6198 PG_RETURN_POINTER(state);
6199 }
6200
6201 Datum
6202 int8_avg_accum_inv(PG_FUNCTION_ARGS)
6203 {
6204 PolyNumAggState *state;
6205
6206 state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
6207
6208 /* Should not get here with no state */
6209 if (state == NULL)
6210 elog(ERROR, "int8_avg_accum_inv called with NULL state");
6211
6212 if (!PG_ARGISNULL(1))
6213 {
6214 #ifdef HAVE_INT128
6215 do_int128_discard(state, (int128) PG_GETARG_INT64(1));
6216 #else
6217 /* Should never fail, all inputs have dscale 0 */
6218 if (!do_numeric_discard(state, int64_to_numeric(PG_GETARG_INT64(1))))
6219 elog(ERROR, "do_numeric_discard failed unexpectedly");
6220 #endif
6221 }
6222
6223 PG_RETURN_POINTER(state);
6224 }
6225
6226 Datum
6227 numeric_poly_sum(PG_FUNCTION_ARGS)
6228 {
6229 #ifdef HAVE_INT128
6230 PolyNumAggState *state;
6231 Numeric res;
6232 NumericVar result;
6233
6234 state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
6235
6236 /* If there were no non-null inputs, return NULL */
6237 if (state == NULL || state->N == 0)
6238 PG_RETURN_NULL();
6239
6240 init_var(&result);
6241
6242 int128_to_numericvar(state->sumX, &result);
6243
6244 res = make_result(&result);
6245
6246 free_var(&result);
6247
6248 PG_RETURN_NUMERIC(res);
6249 #else
6250 return numeric_sum(fcinfo);
6251 #endif
6252 }
6253
6254 Datum
6255 numeric_poly_avg(PG_FUNCTION_ARGS)
6256 {
6257 #ifdef HAVE_INT128
6258 PolyNumAggState *state;
6259 NumericVar result;
6260 Datum countd,
6261 sumd;
6262
6263 state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
6264
6265 /* If there were no non-null inputs, return NULL */
6266 if (state == NULL || state->N == 0)
6267 PG_RETURN_NULL();
6268
6269 init_var(&result);
6270
6271 int128_to_numericvar(state->sumX, &result);
6272
6273 countd = NumericGetDatum(int64_to_numeric(state->N));
6274 sumd = NumericGetDatum(make_result(&result));
6275
6276 free_var(&result);
6277
6278 PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumd, countd));
6279 #else
6280 return numeric_avg(fcinfo);
6281 #endif
6282 }
6283
6284 Datum
6285 numeric_avg(PG_FUNCTION_ARGS)
6286 {
6287 NumericAggState *state;
6288 Datum N_datum;
6289 Datum sumX_datum;
6290 NumericVar sumX_var;
6291
6292 state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6293
6294 /* If there were no non-null inputs, return NULL */
6295 if (state == NULL || NA_TOTAL_COUNT(state) == 0)
6296 PG_RETURN_NULL();
6297
6298 if (state->NaNcount > 0) /* there was at least one NaN input */
6299 PG_RETURN_NUMERIC(make_result(&const_nan));
6300
6301 /* adding plus and minus infinities gives NaN */
6302 if (state->pInfcount > 0 && state->nInfcount > 0)
6303 PG_RETURN_NUMERIC(make_result(&const_nan));
6304 if (state->pInfcount > 0)
6305 PG_RETURN_NUMERIC(make_result(&const_pinf));
6306 if (state->nInfcount > 0)
6307 PG_RETURN_NUMERIC(make_result(&const_ninf));
6308
6309 N_datum = NumericGetDatum(int64_to_numeric(state->N));
6310
6311 init_var(&sumX_var);
6312 accum_sum_final(&state->sumX, &sumX_var);
6313 sumX_datum = NumericGetDatum(make_result(&sumX_var));
6314 free_var(&sumX_var);
6315
6316 PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumX_datum, N_datum));
6317 }
6318
6319 Datum
6320 numeric_sum(PG_FUNCTION_ARGS)
6321 {
6322 NumericAggState *state;
6323 NumericVar sumX_var;
6324 Numeric result;
6325
6326 state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6327
6328 /* If there were no non-null inputs, return NULL */
6329 if (state == NULL || NA_TOTAL_COUNT(state) == 0)
6330 PG_RETURN_NULL();
6331
6332 if (state->NaNcount > 0) /* there was at least one NaN input */
6333 PG_RETURN_NUMERIC(make_result(&const_nan));
6334
6335 /* adding plus and minus infinities gives NaN */
6336 if (state->pInfcount > 0 && state->nInfcount > 0)
6337 PG_RETURN_NUMERIC(make_result(&const_nan));
6338 if (state->pInfcount > 0)
6339 PG_RETURN_NUMERIC(make_result(&const_pinf));
6340 if (state->nInfcount > 0)
6341 PG_RETURN_NUMERIC(make_result(&const_ninf));
6342
6343 init_var(&sumX_var);
6344 accum_sum_final(&state->sumX, &sumX_var);
6345 result = make_result(&sumX_var);
6346 free_var(&sumX_var);
6347
6348 PG_RETURN_NUMERIC(result);
6349 }
6350
6351 /*
6352 * Workhorse routine for the standard deviance and variance
6353 * aggregates. 'state' is aggregate's transition state.
6354 * 'variance' specifies whether we should calculate the
6355 * variance or the standard deviation. 'sample' indicates whether the
6356 * caller is interested in the sample or the population
6357 * variance/stddev.
6358 *
6359 * If appropriate variance statistic is undefined for the input,
6360 * *is_null is set to true and NULL is returned.
6361 */
6362 static Numeric
6363 numeric_stddev_internal(NumericAggState *state,
6364 bool variance, bool sample,
6365 bool *is_null)
6366 {
6367 Numeric res;
6368 NumericVar vN,
6369 vsumX,
6370 vsumX2,
6371 vNminus1;
6372 int64 totCount;
6373 int rscale;
6374
6375 /*
6376 * Sample stddev and variance are undefined when N <= 1; population stddev
6377 * is undefined when N == 0. Return NULL in either case (note that NaNs
6378 * and infinities count as normal inputs for this purpose).
6379 */
6380 if (state == NULL || (totCount = NA_TOTAL_COUNT(state)) == 0)
6381 {
6382 *is_null = true;
6383 return NULL;
6384 }
6385
6386 if (sample && totCount <= 1)
6387 {
6388 *is_null = true;
6389 return NULL;
6390 }
6391
6392 *is_null = false;
6393
6394 /*
6395 * Deal with NaN and infinity cases. By analogy to the behavior of the
6396 * float8 functions, any infinity input produces NaN output.
6397 */
6398 if (state->NaNcount > 0 || state->pInfcount > 0 || state->nInfcount > 0)
6399 return make_result(&const_nan);
6400
6401 /* OK, normal calculation applies */
6402 init_var(&vN);
6403 init_var(&vsumX);
6404 init_var(&vsumX2);
6405
6406 int64_to_numericvar(state->N, &vN);
6407 accum_sum_final(&(state->sumX), &vsumX);
6408 accum_sum_final(&(state->sumX2), &vsumX2);
6409
6410 init_var(&vNminus1);
6411 sub_var(&vN, &const_one, &vNminus1);
6412
6413 /* compute rscale for mul_var calls */
6414 rscale = vsumX.dscale * 2;
6415
6416 mul_var(&vsumX, &vsumX, &vsumX, rscale); /* vsumX = sumX * sumX */
6417 mul_var(&vN, &vsumX2, &vsumX2, rscale); /* vsumX2 = N * sumX2 */
6418 sub_var(&vsumX2, &vsumX, &vsumX2); /* N * sumX2 - sumX * sumX */
6419
6420 if (cmp_var(&vsumX2, &const_zero) <= 0)
6421 {
6422 /* Watch out for roundoff error producing a negative numerator */
6423 res = make_result(&const_zero);
6424 }
6425 else
6426 {
6427 if (sample)
6428 mul_var(&vN, &vNminus1, &vNminus1, 0); /* N * (N - 1) */
6429 else
6430 mul_var(&vN, &vN, &vNminus1, 0); /* N * N */
6431 rscale = select_div_scale(&vsumX2, &vNminus1);
6432 div_var(&vsumX2, &vNminus1, &vsumX, rscale, true, true); /* variance */
6433 if (!variance)
6434 sqrt_var(&vsumX, &vsumX, rscale); /* stddev */
6435
6436 res = make_result(&vsumX);
6437 }
6438
6439 free_var(&vNminus1);
6440 free_var(&vsumX);
6441 free_var(&vsumX2);
6442
6443 return res;
6444 }
6445
6446 Datum
6447 numeric_var_samp(PG_FUNCTION_ARGS)
6448 {
6449 NumericAggState *state;
6450 Numeric res;
6451 bool is_null;
6452
6453 state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6454
6455 res = numeric_stddev_internal(state, true, true, &is_null);
6456
6457 if (is_null)
6458 PG_RETURN_NULL();
6459 else
6460 PG_RETURN_NUMERIC(res);
6461 }
6462
6463 Datum
6464 numeric_stddev_samp(PG_FUNCTION_ARGS)
6465 {
6466 NumericAggState *state;
6467 Numeric res;
6468 bool is_null;
6469
6470 state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6471
6472 res = numeric_stddev_internal(state, false, true, &is_null);
6473
6474 if (is_null)
6475 PG_RETURN_NULL();
6476 else
6477 PG_RETURN_NUMERIC(res);
6478 }
6479
6480 Datum
6481 numeric_var_pop(PG_FUNCTION_ARGS)
6482 {
6483 NumericAggState *state;
6484 Numeric res;
6485 bool is_null;
6486
6487 state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6488
6489 res = numeric_stddev_internal(state, true, false, &is_null);
6490
6491 if (is_null)
6492 PG_RETURN_NULL();
6493 else
6494 PG_RETURN_NUMERIC(res);
6495 }
6496
6497 Datum
6498 numeric_stddev_pop(PG_FUNCTION_ARGS)
6499 {
6500 NumericAggState *state;
6501 Numeric res;
6502 bool is_null;
6503
6504 state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6505
6506 res = numeric_stddev_internal(state, false, false, &is_null);
6507
6508 if (is_null)
6509 PG_RETURN_NULL();
6510 else
6511 PG_RETURN_NUMERIC(res);
6512 }
6513
6514 #ifdef HAVE_INT128
6515 static Numeric
6516 numeric_poly_stddev_internal(Int128AggState *state,
6517 bool variance, bool sample,
6518 bool *is_null)
6519 {
6520 NumericAggState numstate;
6521 Numeric res;
6522
6523 /* Initialize an empty agg state */
6524 memset(&numstate, 0, sizeof(NumericAggState));
6525
6526 if (state)
6527 {
6528 NumericVar tmp_var;
6529
6530 numstate.N = state->N;
6531
6532 init_var(&tmp_var);
6533
6534 int128_to_numericvar(state->sumX, &tmp_var);
6535 accum_sum_add(&numstate.sumX, &tmp_var);
6536
6537 int128_to_numericvar(state->sumX2, &tmp_var);
6538 accum_sum_add(&numstate.sumX2, &tmp_var);
6539
6540 free_var(&tmp_var);
6541 }
6542
6543 res = numeric_stddev_internal(&numstate, variance, sample, is_null);
6544
6545 if (numstate.sumX.ndigits > 0)
6546 {
6547 pfree(numstate.sumX.pos_digits);
6548 pfree(numstate.sumX.neg_digits);
6549 }
6550 if (numstate.sumX2.ndigits > 0)
6551 {
6552 pfree(numstate.sumX2.pos_digits);
6553 pfree(numstate.sumX2.neg_digits);
6554 }
6555
6556 return res;
6557 }
6558 #endif
6559
6560 Datum
6561 numeric_poly_var_samp(PG_FUNCTION_ARGS)
6562 {
6563 #ifdef HAVE_INT128
6564 PolyNumAggState *state;
6565 Numeric res;
6566 bool is_null;
6567
6568 state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
6569
6570 res = numeric_poly_stddev_internal(state, true, true, &is_null);
6571
6572 if (is_null)
6573 PG_RETURN_NULL();
6574 else
6575 PG_RETURN_NUMERIC(res);
6576 #else
6577 return numeric_var_samp(fcinfo);
6578 #endif
6579 }
6580
6581 Datum
6582 numeric_poly_stddev_samp(PG_FUNCTION_ARGS)
6583 {
6584 #ifdef HAVE_INT128
6585 PolyNumAggState *state;
6586 Numeric res;
6587 bool is_null;
6588
6589 state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
6590
6591 res = numeric_poly_stddev_internal(state, false, true, &is_null);
6592
6593 if (is_null)
6594 PG_RETURN_NULL();
6595 else
6596 PG_RETURN_NUMERIC(res);
6597 #else
6598 return numeric_stddev_samp(fcinfo);
6599 #endif
6600 }
6601
6602 Datum
6603 numeric_poly_var_pop(PG_FUNCTION_ARGS)
6604 {
6605 #ifdef HAVE_INT128
6606 PolyNumAggState *state;
6607 Numeric res;
6608 bool is_null;
6609
6610 state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
6611
6612 res = numeric_poly_stddev_internal(state, true, false, &is_null);
6613
6614 if (is_null)
6615 PG_RETURN_NULL();
6616 else
6617 PG_RETURN_NUMERIC(res);
6618 #else
6619 return numeric_var_pop(fcinfo);
6620 #endif
6621 }
6622
6623 Datum
6624 numeric_poly_stddev_pop(PG_FUNCTION_ARGS)
6625 {
6626 #ifdef HAVE_INT128
6627 PolyNumAggState *state;
6628 Numeric res;
6629 bool is_null;
6630
6631 state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
6632
6633 res = numeric_poly_stddev_internal(state, false, false, &is_null);
6634
6635 if (is_null)
6636 PG_RETURN_NULL();
6637 else
6638 PG_RETURN_NUMERIC(res);
6639 #else
6640 return numeric_stddev_pop(fcinfo);
6641 #endif
6642 }
6643
6644 /*
6645 * SUM transition functions for integer datatypes.
6646 *
6647 * To avoid overflow, we use accumulators wider than the input datatype.
6648 * A Numeric accumulator is needed for int8 input; for int4 and int2
6649 * inputs, we use int8 accumulators which should be sufficient for practical
6650 * purposes. (The latter two therefore don't really belong in this file,
6651 * but we keep them here anyway.)
6652 *
6653 * Because SQL defines the SUM() of no values to be NULL, not zero,
6654 * the initial condition of the transition data value needs to be NULL. This
6655 * means we can't rely on ExecAgg to automatically insert the first non-null
6656 * data value into the transition data: it doesn't know how to do the type
6657 * conversion. The upshot is that these routines have to be marked non-strict
6658 * and handle substitution of the first non-null input themselves.
6659 *
6660 * Note: these functions are used only in plain aggregation mode.
6661 * In moving-aggregate mode, we use intX_avg_accum and intX_avg_accum_inv.
6662 */
6663
6664 Datum
6665 int2_sum(PG_FUNCTION_ARGS)
6666 {
6667 int64 newval;
6668
6669 if (PG_ARGISNULL(0))
6670 {
6671 /* No non-null input seen so far... */
6672 if (PG_ARGISNULL(1))
6673 PG_RETURN_NULL(); /* still no non-null */
6674 /* This is the first non-null input. */
6675 newval = (int64) PG_GETARG_INT16(1);
6676 PG_RETURN_INT64(newval);
6677 }
6678
6679 /*
6680 * If we're invoked as an aggregate, we can cheat and modify our first
6681 * parameter in-place to avoid palloc overhead. If not, we need to return
6682 * the new value of the transition variable. (If int8 is pass-by-value,
6683 * then of course this is useless as well as incorrect, so just ifdef it
6684 * out.)
6685 */
6686 #ifndef USE_FLOAT8_BYVAL /* controls int8 too */
6687 if (AggCheckCallContext(fcinfo, NULL))
6688 {
6689 int64 *oldsum = (int64 *) PG_GETARG_POINTER(0);
6690
6691 /* Leave the running sum unchanged in the new input is null */
6692 if (!PG_ARGISNULL(1))
6693 *oldsum = *oldsum + (int64) PG_GETARG_INT16(1);
6694
6695 PG_RETURN_POINTER(oldsum);
6696 }
6697 else
6698 #endif
6699 {
6700 int64 oldsum = PG_GETARG_INT64(0);
6701
6702 /* Leave sum unchanged if new input is null. */
6703 if (PG_ARGISNULL(1))
6704 PG_RETURN_INT64(oldsum);
6705
6706 /* OK to do the addition. */
6707 newval = oldsum + (int64) PG_GETARG_INT16(1);
6708
6709 PG_RETURN_INT64(newval);
6710 }
6711 }
6712
6713 Datum
6714 int4_sum(PG_FUNCTION_ARGS)
6715 {
6716 int64 newval;
6717
6718 if (PG_ARGISNULL(0))
6719 {
6720 /* No non-null input seen so far... */
6721 if (PG_ARGISNULL(1))
6722 PG_RETURN_NULL(); /* still no non-null */
6723 /* This is the first non-null input. */
6724 newval = (int64) PG_GETARG_INT32(1);
6725 PG_RETURN_INT64(newval);
6726 }
6727
6728 /*
6729 * If we're invoked as an aggregate, we can cheat and modify our first
6730 * parameter in-place to avoid palloc overhead. If not, we need to return
6731 * the new value of the transition variable. (If int8 is pass-by-value,
6732 * then of course this is useless as well as incorrect, so just ifdef it
6733 * out.)
6734 */
6735 #ifndef USE_FLOAT8_BYVAL /* controls int8 too */
6736 if (AggCheckCallContext(fcinfo, NULL))
6737 {
6738 int64 *oldsum = (int64 *) PG_GETARG_POINTER(0);
6739
6740 /* Leave the running sum unchanged in the new input is null */
6741 if (!PG_ARGISNULL(1))
6742 *oldsum = *oldsum + (int64) PG_GETARG_INT32(1);
6743
6744 PG_RETURN_POINTER(oldsum);
6745 }
6746 else
6747 #endif
6748 {
6749 int64 oldsum = PG_GETARG_INT64(0);
6750
6751 /* Leave sum unchanged if new input is null. */
6752 if (PG_ARGISNULL(1))
6753 PG_RETURN_INT64(oldsum);
6754
6755 /* OK to do the addition. */
6756 newval = oldsum + (int64) PG_GETARG_INT32(1);
6757
6758 PG_RETURN_INT64(newval);
6759 }
6760 }
6761
6762 /*
6763 * Note: this function is obsolete, it's no longer used for SUM(int8).
6764 */
6765 Datum
6766 int8_sum(PG_FUNCTION_ARGS)
6767 {
6768 Numeric oldsum;
6769
6770 if (PG_ARGISNULL(0))
6771 {
6772 /* No non-null input seen so far... */
6773 if (PG_ARGISNULL(1))
6774 PG_RETURN_NULL(); /* still no non-null */
6775 /* This is the first non-null input. */
6776 PG_RETURN_NUMERIC(int64_to_numeric(PG_GETARG_INT64(1)));
6777 }
6778
6779 /*
6780 * Note that we cannot special-case the aggregate case here, as we do for
6781 * int2_sum and int4_sum: numeric is of variable size, so we cannot modify
6782 * our first parameter in-place.
6783 */
6784
6785 oldsum = PG_GETARG_NUMERIC(0);
6786
6787 /* Leave sum unchanged if new input is null. */
6788 if (PG_ARGISNULL(1))
6789 PG_RETURN_NUMERIC(oldsum);
6790
6791 /* OK to do the addition. */
6792 PG_RETURN_DATUM(DirectFunctionCall2(numeric_add,
6793 NumericGetDatum(oldsum),
6794 NumericGetDatum(int64_to_numeric(PG_GETARG_INT64(1)))));
6795 }
6796
6797
6798 /*
6799 * Routines for avg(int2) and avg(int4). The transition datatype
6800 * is a two-element int8 array, holding count and sum.
6801 *
6802 * These functions are also used for sum(int2) and sum(int4) when
6803 * operating in moving-aggregate mode, since for correct inverse transitions
6804 * we need to count the inputs.
6805 */
6806
6807 typedef struct Int8TransTypeData
6808 {
6809 int64 count;
6810 int64 sum;
6811 } Int8TransTypeData;
6812
6813 Datum
6814 int2_avg_accum(PG_FUNCTION_ARGS)
6815 {
6816 ArrayType *transarray;
6817 int16 newval = PG_GETARG_INT16(1);
6818 Int8TransTypeData *transdata;
6819
6820 /*
6821 * If we're invoked as an aggregate, we can cheat and modify our first
6822 * parameter in-place to reduce palloc overhead. Otherwise we need to make
6823 * a copy of it before scribbling on it.
6824 */
6825 if (AggCheckCallContext(fcinfo, NULL))
6826 transarray = PG_GETARG_ARRAYTYPE_P(0);
6827 else
6828 transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6829
6830 if (ARR_HASNULL(transarray) ||
6831 ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6832 elog(ERROR, "expected 2-element int8 array");
6833
6834 transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6835 transdata->count++;
6836 transdata->sum += newval;
6837
6838 PG_RETURN_ARRAYTYPE_P(transarray);
6839 }
6840
6841 Datum
6842 int4_avg_accum(PG_FUNCTION_ARGS)
6843 {
6844 ArrayType *transarray;
6845 int32 newval = PG_GETARG_INT32(1);
6846 Int8TransTypeData *transdata;
6847
6848 /*
6849 * If we're invoked as an aggregate, we can cheat and modify our first
6850 * parameter in-place to reduce palloc overhead. Otherwise we need to make
6851 * a copy of it before scribbling on it.
6852 */
6853 if (AggCheckCallContext(fcinfo, NULL))
6854 transarray = PG_GETARG_ARRAYTYPE_P(0);
6855 else
6856 transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6857
6858 if (ARR_HASNULL(transarray) ||
6859 ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6860 elog(ERROR, "expected 2-element int8 array");
6861
6862 transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6863 transdata->count++;
6864 transdata->sum += newval;
6865
6866 PG_RETURN_ARRAYTYPE_P(transarray);
6867 }
6868
6869 Datum
6870 int4_avg_combine(PG_FUNCTION_ARGS)
6871 {
6872 ArrayType *transarray1;
6873 ArrayType *transarray2;
6874 Int8TransTypeData *state1;
6875 Int8TransTypeData *state2;
6876
6877 if (!AggCheckCallContext(fcinfo, NULL))
6878 elog(ERROR, "aggregate function called in non-aggregate context");
6879
6880 transarray1 = PG_GETARG_ARRAYTYPE_P(0);
6881 transarray2 = PG_GETARG_ARRAYTYPE_P(1);
6882
6883 if (ARR_HASNULL(transarray1) ||
6884 ARR_SIZE(transarray1) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6885 elog(ERROR, "expected 2-element int8 array");
6886
6887 if (ARR_HASNULL(transarray2) ||
6888 ARR_SIZE(transarray2) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6889 elog(ERROR, "expected 2-element int8 array");
6890
6891 state1 = (Int8TransTypeData *) ARR_DATA_PTR(transarray1);
6892 state2 = (Int8TransTypeData *) ARR_DATA_PTR(transarray2);
6893
6894 state1->count += state2->count;
6895 state1->sum += state2->sum;
6896
6897 PG_RETURN_ARRAYTYPE_P(transarray1);
6898 }
6899
6900 Datum
6901 int2_avg_accum_inv(PG_FUNCTION_ARGS)
6902 {
6903 ArrayType *transarray;
6904 int16 newval = PG_GETARG_INT16(1);
6905 Int8TransTypeData *transdata;
6906
6907 /*
6908 * If we're invoked as an aggregate, we can cheat and modify our first
6909 * parameter in-place to reduce palloc overhead. Otherwise we need to make
6910 * a copy of it before scribbling on it.
6911 */
6912 if (AggCheckCallContext(fcinfo, NULL))
6913 transarray = PG_GETARG_ARRAYTYPE_P(0);
6914 else
6915 transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6916
6917 if (ARR_HASNULL(transarray) ||
6918 ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6919 elog(ERROR, "expected 2-element int8 array");
6920
6921 transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6922 transdata->count--;
6923 transdata->sum -= newval;
6924
6925 PG_RETURN_ARRAYTYPE_P(transarray);
6926 }
6927
6928 Datum
6929 int4_avg_accum_inv(PG_FUNCTION_ARGS)
6930 {
6931 ArrayType *transarray;
6932 int32 newval = PG_GETARG_INT32(1);
6933 Int8TransTypeData *transdata;
6934
6935 /*
6936 * If we're invoked as an aggregate, we can cheat and modify our first
6937 * parameter in-place to reduce palloc overhead. Otherwise we need to make
6938 * a copy of it before scribbling on it.
6939 */
6940 if (AggCheckCallContext(fcinfo, NULL))
6941 transarray = PG_GETARG_ARRAYTYPE_P(0);
6942 else
6943 transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6944
6945 if (ARR_HASNULL(transarray) ||
6946 ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6947 elog(ERROR, "expected 2-element int8 array");
6948
6949 transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6950 transdata->count--;
6951 transdata->sum -= newval;
6952
6953 PG_RETURN_ARRAYTYPE_P(transarray);
6954 }
6955
6956 Datum
6957 int8_avg(PG_FUNCTION_ARGS)
6958 {
6959 ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
6960 Int8TransTypeData *transdata;
6961 Datum countd,
6962 sumd;
6963
6964 if (ARR_HASNULL(transarray) ||
6965 ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6966 elog(ERROR, "expected 2-element int8 array");
6967 transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6968
6969 /* SQL defines AVG of no values to be NULL */
6970 if (transdata->count == 0)
6971 PG_RETURN_NULL();
6972
6973 countd = NumericGetDatum(int64_to_numeric(transdata->count));
6974 sumd = NumericGetDatum(int64_to_numeric(transdata->sum));
6975
6976 PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumd, countd));
6977 }
6978
6979 /*
6980 * SUM(int2) and SUM(int4) both return int8, so we can use this
6981 * final function for both.
6982 */
6983 Datum
6984 int2int4_sum(PG_FUNCTION_ARGS)
6985 {
6986 ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
6987 Int8TransTypeData *transdata;
6988
6989 if (ARR_HASNULL(transarray) ||
6990 ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6991 elog(ERROR, "expected 2-element int8 array");
6992 transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6993
6994 /* SQL defines SUM of no values to be NULL */
6995 if (transdata->count == 0)
6996 PG_RETURN_NULL();
6997
6998 PG_RETURN_DATUM(Int64GetDatumFast(transdata->sum));
6999 }
7000
7001
7002 /* ----------------------------------------------------------------------
7003 *
7004 * Debug support
7005 *
7006 * ----------------------------------------------------------------------
7007 */
7008
7009 #ifdef NUMERIC_DEBUG
7010
7011 /*
7012 * dump_numeric() - Dump a value in the db storage format for debugging
7013 */
7014 static void
7015 dump_numeric(const char *str, Numeric num)
7016 {
7017 NumericDigit *digits = NUMERIC_DIGITS(num);
7018 int ndigits;
7019 int i;
7020
7021 ndigits = NUMERIC_NDIGITS(num);
7022
7023 printf("%s: NUMERIC w=%d d=%d ", str,
7024 NUMERIC_WEIGHT(num), NUMERIC_DSCALE(num));
7025 switch (NUMERIC_SIGN(num))
7026 {
7027 case NUMERIC_POS:
7028 printf("POS");
7029 break;
7030 case NUMERIC_NEG:
7031 printf("NEG");
7032 break;
7033 case NUMERIC_NAN:
7034 printf("NaN");
7035 break;
7036 case NUMERIC_PINF:
7037 printf("Infinity");
7038 break;
7039 case NUMERIC_NINF:
7040 printf("-Infinity");
7041 break;
7042 default:
7043 printf("SIGN=0x%x", NUMERIC_SIGN(num));
7044 break;
7045 }
7046
7047 for (i = 0; i < ndigits; i++)
7048 printf(" %0*d", DEC_DIGITS, digits[i]);
7049 printf("\n");
7050 }
7051
7052
7053 /*
7054 * dump_var() - Dump a value in the variable format for debugging
7055 */
7056 static void
7057 dump_var(const char *str, NumericVar *var)
7058 {
7059 int i;
7060
7061 printf("%s: VAR w=%d d=%d ", str, var->weight, var->dscale);
7062 switch (var->sign)
7063 {
7064 case NUMERIC_POS:
7065 printf("POS");
7066 break;
7067 case NUMERIC_NEG:
7068 printf("NEG");
7069 break;
7070 case NUMERIC_NAN:
7071 printf("NaN");
7072 break;
7073 case NUMERIC_PINF:
7074 printf("Infinity");
7075 break;
7076 case NUMERIC_NINF:
7077 printf("-Infinity");
7078 break;
7079 default:
7080 printf("SIGN=0x%x", var->sign);
7081 break;
7082 }
7083
7084 for (i = 0; i < var->ndigits; i++)
7085 printf(" %0*d", DEC_DIGITS, var->digits[i]);
7086
7087 printf("\n");
7088 }
7089 #endif /* NUMERIC_DEBUG */
7090
7091
7092 /* ----------------------------------------------------------------------
7093 *
7094 * Local functions follow
7095 *
7096 * In general, these do not support "special" (NaN or infinity) inputs;
7097 * callers should handle those possibilities first.
7098 * (There are one or two exceptions, noted in their header comments.)
7099 *
7100 * ----------------------------------------------------------------------
7101 */
7102
7103
7104 /*
7105 * alloc_var() -
7106 *
7107 * Allocate a digit buffer of ndigits digits (plus a spare digit for rounding)
7108 */
7109 static void
7110 alloc_var(NumericVar *var, int ndigits)
7111 {
7112 digitbuf_free(var->buf);
7113 var->buf = digitbuf_alloc(ndigits + 1);
7114 var->buf[0] = 0; /* spare digit for rounding */
7115 var->digits = var->buf + 1;
7116 var->ndigits = ndigits;
7117 }
7118
7119
7120 /*
7121 * free_var() -
7122 *
7123 * Return the digit buffer of a variable to the free pool
7124 */
7125 static void
7126 free_var(NumericVar *var)
7127 {
7128 digitbuf_free(var->buf);
7129 var->buf = NULL;
7130 var->digits = NULL;
7131 var->sign = NUMERIC_NAN;
7132 }
7133
7134
7135 /*
7136 * zero_var() -
7137 *
7138 * Set a variable to ZERO.
7139 * Note: its dscale is not touched.
7140 */
7141 static void
7142 zero_var(NumericVar *var)
7143 {
7144 digitbuf_free(var->buf);
7145 var->buf = NULL;
7146 var->digits = NULL;
7147 var->ndigits = 0;
7148 var->weight = 0; /* by convention; doesn't really matter */
7149 var->sign = NUMERIC_POS; /* anything but NAN... */
7150 }
7151
7152
7153 /*
7154 * set_var_from_str()
7155 *
7156 * Parse a string and put the number into a variable
7157 *
7158 * This function does not handle leading or trailing spaces. It returns
7159 * the end+1 position parsed into *endptr, so that caller can check for
7160 * trailing spaces/garbage if deemed necessary.
7161 *
7162 * cp is the place to actually start parsing; str is what to use in error
7163 * reports. (Typically cp would be the same except advanced over spaces.)
7164 *
7165 * Returns true on success, false on failure (if escontext points to an
7166 * ErrorSaveContext; otherwise errors are thrown).
7167 */
7168 static bool
7169 set_var_from_str(const char *str, const char *cp,
7170 NumericVar *dest, const char **endptr,
7171 Node *escontext)
7172 {
7173 bool have_dp = false;
7174 int i;
7175 unsigned char *decdigits;
7176 int sign = NUMERIC_POS;
7177 int dweight = -1;
7178 int ddigits;
7179 int dscale = 0;
7180 int weight;
7181 int ndigits;
7182 int offset;
7183 NumericDigit *digits;
7184
7185 /*
7186 * We first parse the string to extract decimal digits and determine the
7187 * correct decimal weight. Then convert to NBASE representation.
7188 */
7189 switch (*cp)
7190 {
7191 case '+':
7192 sign = NUMERIC_POS;
7193 cp++;
7194 break;
7195
7196 case '-':
7197 sign = NUMERIC_NEG;
7198 cp++;
7199 break;
7200 }
7201
7202 if (*cp == '.')
7203 {
7204 have_dp = true;
7205 cp++;
7206 }
7207
7208 if (!isdigit((unsigned char) *cp))
7209 goto invalid_syntax;
7210
7211 decdigits = (unsigned char *) palloc(strlen(cp) + DEC_DIGITS * 2);
7212
7213 /* leading padding for digit alignment later */
7214 memset(decdigits, 0, DEC_DIGITS);
7215 i = DEC_DIGITS;
7216
7217 while (*cp)
7218 {
7219 if (isdigit((unsigned char) *cp))
7220 {
7221 decdigits[i++] = *cp++ - '0';
7222 if (!have_dp)
7223 dweight++;
7224 else
7225 dscale++;
7226 }
7227 else if (*cp == '.')
7228 {
7229 if (have_dp)
7230 goto invalid_syntax;
7231 have_dp = true;
7232 cp++;
7233 /* decimal point must not be followed by underscore */
7234 if (*cp == '_')
7235 goto invalid_syntax;
7236 }
7237 else if (*cp == '_')
7238 {
7239 /* underscore must be followed by more digits */
7240 cp++;
7241 if (!isdigit((unsigned char) *cp))
7242 goto invalid_syntax;
7243 }
7244 else
7245 break;
7246 }
7247
7248 ddigits = i - DEC_DIGITS;
7249 /* trailing padding for digit alignment later */
7250 memset(decdigits + i, 0, DEC_DIGITS - 1);
7251
7252 /* Handle exponent, if any */
7253 if (*cp == 'e' || *cp == 'E')
7254 {
7255 int64 exponent = 0;
7256 bool neg = false;
7257
7258 /*
7259 * At this point, dweight and dscale can't be more than about
7260 * INT_MAX/2 due to the MaxAllocSize limit on string length, so
7261 * constraining the exponent similarly should be enough to prevent
7262 * integer overflow in this function. If the value is too large to
7263 * fit in storage format, make_result() will complain about it later;
7264 * for consistency use the same ereport errcode/text as make_result().
7265 */
7266
7267 /* exponent sign */
7268 cp++;
7269 if (*cp == '+')
7270 cp++;
7271 else if (*cp == '-')
7272 {
7273 neg = true;
7274 cp++;
7275 }
7276
7277 /* exponent digits */
7278 if (!isdigit((unsigned char) *cp))
7279 goto invalid_syntax;
7280
7281 while (*cp)
7282 {
7283 if (isdigit((unsigned char) *cp))
7284 {
7285 exponent = exponent * 10 + (*cp++ - '0');
7286 if (exponent > PG_INT32_MAX / 2)
7287 goto out_of_range;
7288 }
7289 else if (*cp == '_')
7290 {
7291 /* underscore must be followed by more digits */
7292 cp++;
7293 if (!isdigit((unsigned char) *cp))
7294 goto invalid_syntax;
7295 }
7296 else
7297 break;
7298 }
7299
7300 if (neg)
7301 exponent = -exponent;
7302
7303 dweight += (int) exponent;
7304 dscale -= (int) exponent;
7305 if (dscale < 0)
7306 dscale = 0;
7307 }
7308
7309 /*
7310 * Okay, convert pure-decimal representation to base NBASE. First we need
7311 * to determine the converted weight and ndigits. offset is the number of
7312 * decimal zeroes to insert before the first given digit to have a
7313 * correctly aligned first NBASE digit.
7314 */
7315 if (dweight >= 0)
7316 weight = (dweight + 1 + DEC_DIGITS - 1) / DEC_DIGITS - 1;
7317 else
7318 weight = -((-dweight - 1) / DEC_DIGITS + 1);
7319 offset = (weight + 1) * DEC_DIGITS - (dweight + 1);
7320 ndigits = (ddigits + offset + DEC_DIGITS - 1) / DEC_DIGITS;
7321
7322 alloc_var(dest, ndigits);
7323 dest->sign = sign;
7324 dest->weight = weight;
7325 dest->dscale = dscale;
7326
7327 i = DEC_DIGITS - offset;
7328 digits = dest->digits;
7329
7330 while (ndigits-- > 0)
7331 {
7332 #if DEC_DIGITS == 4
7333 *digits++ = ((decdigits[i] * 10 + decdigits[i + 1]) * 10 +
7334 decdigits[i + 2]) * 10 + decdigits[i + 3];
7335 #elif DEC_DIGITS == 2
7336 *digits++ = decdigits[i] * 10 + decdigits[i + 1];
7337 #elif DEC_DIGITS == 1
7338 *digits++ = decdigits[i];
7339 #else
7340 #error unsupported NBASE
7341 #endif
7342 i += DEC_DIGITS;
7343 }
7344
7345 pfree(decdigits);
7346
7347 /* Strip any leading/trailing zeroes, and normalize weight if zero */
7348 strip_var(dest);
7349
7350 /* Return end+1 position for caller */
7351 *endptr = cp;
7352
7353 return true;
7354
7355 out_of_range:
7356 ereturn(escontext, false,
7357 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7358 errmsg("value overflows numeric format")));
7359
7360 invalid_syntax:
7361 ereturn(escontext, false,
7362 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
7363 errmsg("invalid input syntax for type %s: \"%s\"",
7364 "numeric", str)));
7365 }
7366
7367
7368 /*
7369 * Return the numeric value of a single hex digit.
7370 */
7371 static inline int
7372 xdigit_value(char dig)
7373 {
7374 return dig >= '0' && dig <= '9' ? dig - '0' :
7375 dig >= 'a' && dig <= 'f' ? dig - 'a' + 10 :
7376 dig >= 'A' && dig <= 'F' ? dig - 'A' + 10 : -1;
7377 }
7378
7379 /*
7380 * set_var_from_non_decimal_integer_str()
7381 *
7382 * Parse a string containing a non-decimal integer
7383 *
7384 * This function does not handle leading or trailing spaces. It returns
7385 * the end+1 position parsed into *endptr, so that caller can check for
7386 * trailing spaces/garbage if deemed necessary.
7387 *
7388 * cp is the place to actually start parsing; str is what to use in error
7389 * reports. The number's sign and base prefix indicator (e.g., "0x") are
7390 * assumed to have already been parsed, so cp should point to the number's
7391 * first digit in the base specified.
7392 *
7393 * base is expected to be 2, 8 or 16.
7394 *
7395 * Returns true on success, false on failure (if escontext points to an
7396 * ErrorSaveContext; otherwise errors are thrown).
7397 */
7398 static bool
7399 set_var_from_non_decimal_integer_str(const char *str, const char *cp, int sign,
7400 int base, NumericVar *dest,
7401 const char **endptr, Node *escontext)
7402 {
7403 const char *firstdigit = cp;
7404 int64 tmp;
7405 int64 mul;
7406 NumericVar tmp_var;
7407
7408 init_var(&tmp_var);
7409
7410 zero_var(dest);
7411
7412 /*
7413 * Process input digits in groups that fit in int64. Here "tmp" is the
7414 * value of the digits in the group, and "mul" is base^n, where n is the
7415 * number of digits in the group. Thus tmp < mul, and we must start a new
7416 * group when mul * base threatens to overflow PG_INT64_MAX.
7417 */
7418 tmp = 0;
7419 mul = 1;
7420
7421 if (base == 16)
7422 {
7423 while (*cp)
7424 {
7425 if (isxdigit((unsigned char) *cp))
7426 {
7427 if (mul > PG_INT64_MAX / 16)
7428 {
7429 /* Add the contribution from this group of digits */
7430 int64_to_numericvar(mul, &tmp_var);
7431 mul_var(dest, &tmp_var, dest, 0);
7432 int64_to_numericvar(tmp, &tmp_var);
7433 add_var(dest, &tmp_var, dest);
7434
7435 /* Result will overflow if weight overflows int16 */
7436 if (dest->weight > NUMERIC_WEIGHT_MAX)
7437 goto out_of_range;
7438
7439 /* Begin a new group */
7440 tmp = 0;
7441 mul = 1;
7442 }
7443
7444 tmp = tmp * 16 + xdigit_value(*cp++);
7445 mul = mul * 16;
7446 }
7447 else if (*cp == '_')
7448 {
7449 /* Underscore must be followed by more digits */
7450 cp++;
7451 if (!isxdigit((unsigned char) *cp))
7452 goto invalid_syntax;
7453 }
7454 else
7455 break;
7456 }
7457 }
7458 else if (base == 8)
7459 {
7460 while (*cp)
7461 {
7462 if (*cp >= '0' && *cp <= '7')
7463 {
7464 if (mul > PG_INT64_MAX / 8)
7465 {
7466 /* Add the contribution from this group of digits */
7467 int64_to_numericvar(mul, &tmp_var);
7468 mul_var(dest, &tmp_var, dest, 0);
7469 int64_to_numericvar(tmp, &tmp_var);
7470 add_var(dest, &tmp_var, dest);
7471
7472 /* Result will overflow if weight overflows int16 */
7473 if (dest->weight > NUMERIC_WEIGHT_MAX)
7474 goto out_of_range;
7475
7476 /* Begin a new group */
7477 tmp = 0;
7478 mul = 1;
7479 }
7480
7481 tmp = tmp * 8 + (*cp++ - '0');
7482 mul = mul * 8;
7483 }
7484 else if (*cp == '_')
7485 {
7486 /* Underscore must be followed by more digits */
7487 cp++;
7488 if (*cp < '0' || *cp > '7')
7489 goto invalid_syntax;
7490 }
7491 else
7492 break;
7493 }
7494 }
7495 else if (base == 2)
7496 {
7497 while (*cp)
7498 {
7499 if (*cp >= '0' && *cp <= '1')
7500 {
7501 if (mul > PG_INT64_MAX / 2)
7502 {
7503 /* Add the contribution from this group of digits */
7504 int64_to_numericvar(mul, &tmp_var);
7505 mul_var(dest, &tmp_var, dest, 0);
7506 int64_to_numericvar(tmp, &tmp_var);
7507 add_var(dest, &tmp_var, dest);
7508
7509 /* Result will overflow if weight overflows int16 */
7510 if (dest->weight > NUMERIC_WEIGHT_MAX)
7511 goto out_of_range;
7512
7513 /* Begin a new group */
7514 tmp = 0;
7515 mul = 1;
7516 }
7517
7518 tmp = tmp * 2 + (*cp++ - '0');
7519 mul = mul * 2;
7520 }
7521 else if (*cp == '_')
7522 {
7523 /* Underscore must be followed by more digits */
7524 cp++;
7525 if (*cp < '0' || *cp > '1')
7526 goto invalid_syntax;
7527 }
7528 else
7529 break;
7530 }
7531 }
7532 else
7533 /* Should never happen; treat as invalid input */
7534 goto invalid_syntax;
7535
7536 /* Check that we got at least one digit */
7537 if (unlikely(cp == firstdigit))
7538 goto invalid_syntax;
7539
7540 /* Add the contribution from the final group of digits */
7541 int64_to_numericvar(mul, &tmp_var);
7542 mul_var(dest, &tmp_var, dest, 0);
7543 int64_to_numericvar(tmp, &tmp_var);
7544 add_var(dest, &tmp_var, dest);
7545
7546 if (dest->weight > NUMERIC_WEIGHT_MAX)
7547 goto out_of_range;
7548
7549 dest->sign = sign;
7550
7551 free_var(&tmp_var);
7552
7553 /* Return end+1 position for caller */
7554 *endptr = cp;
7555
7556 return true;
7557
7558 out_of_range:
7559 ereturn(escontext, false,
7560 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7561 errmsg("value overflows numeric format")));
7562
7563 invalid_syntax:
7564 ereturn(escontext, false,
7565 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
7566 errmsg("invalid input syntax for type %s: \"%s\"",
7567 "numeric", str)));
7568 }
7569
7570
7571 /*
7572 * set_var_from_num() -
7573 *
7574 * Convert the packed db format into a variable
7575 */
7576 static void
7577 set_var_from_num(Numeric num, NumericVar *dest)
7578 {
7579 int ndigits;
7580
7581 ndigits = NUMERIC_NDIGITS(num);
7582
7583 alloc_var(dest, ndigits);
7584
7585 dest->weight = NUMERIC_WEIGHT(num);
7586 dest->sign = NUMERIC_SIGN(num);
7587 dest->dscale = NUMERIC_DSCALE(num);
7588
7589 memcpy(dest->digits, NUMERIC_DIGITS(num), ndigits * sizeof(NumericDigit));
7590 }
7591
7592
7593 /*
7594 * init_var_from_num() -
7595 *
7596 * Initialize a variable from packed db format. The digits array is not
7597 * copied, which saves some cycles when the resulting var is not modified.
7598 * Also, there's no need to call free_var(), as long as you don't assign any
7599 * other value to it (with set_var_* functions, or by using the var as the
7600 * destination of a function like add_var())
7601 *
7602 * CAUTION: Do not modify the digits buffer of a var initialized with this
7603 * function, e.g by calling round_var() or trunc_var(), as the changes will
7604 * propagate to the original Numeric! It's OK to use it as the destination
7605 * argument of one of the calculational functions, though.
7606 */
7607 static void
7608 init_var_from_num(Numeric num, NumericVar *dest)
7609 {
7610 dest->ndigits = NUMERIC_NDIGITS(num);
7611 dest->weight = NUMERIC_WEIGHT(num);
7612 dest->sign = NUMERIC_SIGN(num);
7613 dest->dscale = NUMERIC_DSCALE(num);
7614 dest->digits = NUMERIC_DIGITS(num);
7615 dest->buf = NULL; /* digits array is not palloc'd */
7616 }
7617
7618
7619 /*
7620 * set_var_from_var() -
7621 *
7622 * Copy one variable into another
7623 */
7624 static void
7625 set_var_from_var(const NumericVar *value, NumericVar *dest)
7626 {
7627 NumericDigit *newbuf;
7628
7629 newbuf = digitbuf_alloc(value->ndigits + 1);
7630 newbuf[0] = 0; /* spare digit for rounding */
7631 if (value->ndigits > 0) /* else value->digits might be null */
7632 memcpy(newbuf + 1, value->digits,
7633 value->ndigits * sizeof(NumericDigit));
7634
7635 digitbuf_free(dest->buf);
7636
7637 memmove(dest, value, sizeof(NumericVar));
7638 dest->buf = newbuf;
7639 dest->digits = newbuf + 1;
7640 }
7641
7642
7643 /*
7644 * get_str_from_var() -
7645 *
7646 * Convert a var to text representation (guts of numeric_out).
7647 * The var is displayed to the number of digits indicated by its dscale.
7648 * Returns a palloc'd string.
7649 */
7650 static char *
7651 get_str_from_var(const NumericVar *var)
7652 {
7653 int dscale;
7654 char *str;
7655 char *cp;
7656 char *endcp;
7657 int i;
7658 int d;
7659 NumericDigit dig;
7660
7661 #if DEC_DIGITS > 1
7662 NumericDigit d1;
7663 #endif
7664
7665 dscale = var->dscale;
7666
7667 /*
7668 * Allocate space for the result.
7669 *
7670 * i is set to the # of decimal digits before decimal point. dscale is the
7671 * # of decimal digits we will print after decimal point. We may generate
7672 * as many as DEC_DIGITS-1 excess digits at the end, and in addition we
7673 * need room for sign, decimal point, null terminator.
7674 */
7675 i = (var->weight + 1) * DEC_DIGITS;
7676 if (i <= 0)
7677 i = 1;
7678
7679 str = palloc(i + dscale + DEC_DIGITS + 2);
7680 cp = str;
7681
7682 /*
7683 * Output a dash for negative values
7684 */
7685 if (var->sign == NUMERIC_NEG)
7686 *cp++ = '-';
7687
7688 /*
7689 * Output all digits before the decimal point
7690 */
7691 if (var->weight < 0)
7692 {
7693 d = var->weight + 1;
7694 *cp++ = '0';
7695 }
7696 else
7697 {
7698 for (d = 0; d <= var->weight; d++)
7699 {
7700 dig = (d < var->ndigits) ? var->digits[d] : 0;
7701 /* In the first digit, suppress extra leading decimal zeroes */
7702 #if DEC_DIGITS == 4
7703 {
7704 bool putit = (d > 0);
7705
7706 d1 = dig / 1000;
7707 dig -= d1 * 1000;
7708 putit |= (d1 > 0);
7709 if (putit)
7710 *cp++ = d1 + '0';
7711 d1 = dig / 100;
7712 dig -= d1 * 100;
7713 putit |= (d1 > 0);
7714 if (putit)
7715 *cp++ = d1 + '0';
7716 d1 = dig / 10;
7717 dig -= d1 * 10;
7718 putit |= (d1 > 0);
7719 if (putit)
7720 *cp++ = d1 + '0';
7721 *cp++ = dig + '0';
7722 }
7723 #elif DEC_DIGITS == 2
7724 d1 = dig / 10;
7725 dig -= d1 * 10;
7726 if (d1 > 0 || d > 0)
7727 *cp++ = d1 + '0';
7728 *cp++ = dig + '0';
7729 #elif DEC_DIGITS == 1
7730 *cp++ = dig + '0';
7731 #else
7732 #error unsupported NBASE
7733 #endif
7734 }
7735 }
7736
7737 /*
7738 * If requested, output a decimal point and all the digits that follow it.
7739 * We initially put out a multiple of DEC_DIGITS digits, then truncate if
7740 * needed.
7741 */
7742 if (dscale > 0)
7743 {
7744 *cp++ = '.';
7745 endcp = cp + dscale;
7746 for (i = 0; i < dscale; d++, i += DEC_DIGITS)
7747 {
7748 dig = (d >= 0 && d < var->ndigits) ? var->digits[d] : 0;
7749 #if DEC_DIGITS == 4
7750 d1 = dig / 1000;
7751 dig -= d1 * 1000;
7752 *cp++ = d1 + '0';
7753 d1 = dig / 100;
7754 dig -= d1 * 100;
7755 *cp++ = d1 + '0';
7756 d1 = dig / 10;
7757 dig -= d1 * 10;
7758 *cp++ = d1 + '0';
7759 *cp++ = dig + '0';
7760 #elif DEC_DIGITS == 2
7761 d1 = dig / 10;
7762 dig -= d1 * 10;
7763 *cp++ = d1 + '0';
7764 *cp++ = dig + '0';
7765 #elif DEC_DIGITS == 1
7766 *cp++ = dig + '0';
7767 #else
7768 #error unsupported NBASE
7769 #endif
7770 }
7771 cp = endcp;
7772 }
7773
7774 /*
7775 * terminate the string and return it
7776 */
7777 *cp = '\0';
7778 return str;
7779 }
7780
7781 /*
7782 * get_str_from_var_sci() -
7783 *
7784 * Convert a var to a normalised scientific notation text representation.
7785 * This function does the heavy lifting for numeric_out_sci().
7786 *
7787 * This notation has the general form a * 10^b, where a is known as the
7788 * "significand" and b is known as the "exponent".
7789 *
7790 * Because we can't do superscript in ASCII (and because we want to copy
7791 * printf's behaviour) we display the exponent using E notation, with a
7792 * minimum of two exponent digits.
7793 *
7794 * For example, the value 1234 could be output as 1.2e+03.
7795 *
7796 * We assume that the exponent can fit into an int32.
7797 *
7798 * rscale is the number of decimal digits desired after the decimal point in
7799 * the output, negative values will be treated as meaning zero.
7800 *
7801 * Returns a palloc'd string.
7802 */
7803 static char *
7804 get_str_from_var_sci(const NumericVar *var, int rscale)
7805 {
7806 int32 exponent;
7807 NumericVar tmp_var;
7808 size_t len;
7809 char *str;
7810 char *sig_out;
7811
7812 if (rscale < 0)
7813 rscale = 0;
7814
7815 /*
7816 * Determine the exponent of this number in normalised form.
7817 *
7818 * This is the exponent required to represent the number with only one
7819 * significant digit before the decimal place.
7820 */
7821 if (var->ndigits > 0)
7822 {
7823 exponent = (var->weight + 1) * DEC_DIGITS;
7824
7825 /*
7826 * Compensate for leading decimal zeroes in the first numeric digit by
7827 * decrementing the exponent.
7828 */
7829 exponent -= DEC_DIGITS - (int) log10(var->digits[0]);
7830 }
7831 else
7832 {
7833 /*
7834 * If var has no digits, then it must be zero.
7835 *
7836 * Zero doesn't technically have a meaningful exponent in normalised
7837 * notation, but we just display the exponent as zero for consistency
7838 * of output.
7839 */
7840 exponent = 0;
7841 }
7842
7843 /*
7844 * Divide var by 10^exponent to get the significand, rounding to rscale
7845 * decimal digits in the process.
7846 */
7847 init_var(&tmp_var);
7848
7849 power_ten_int(exponent, &tmp_var);
7850 div_var(var, &tmp_var, &tmp_var, rscale, true, true);
7851 sig_out = get_str_from_var(&tmp_var);
7852
7853 free_var(&tmp_var);
7854
7855 /*
7856 * Allocate space for the result.
7857 *
7858 * In addition to the significand, we need room for the exponent
7859 * decoration ("e"), the sign of the exponent, up to 10 digits for the
7860 * exponent itself, and of course the null terminator.
7861 */
7862 len = strlen(sig_out) + 13;
7863 str = palloc(len);
7864 snprintf(str, len, "%se%+03d", sig_out, exponent);
7865
7866 pfree(sig_out);
7867
7868 return str;
7869 }
7870
7871
7872 /*
7873 * numericvar_serialize - serialize NumericVar to binary format
7874 *
7875 * At variable level, no checks are performed on the weight or dscale, allowing
7876 * us to pass around intermediate values with higher precision than supported
7877 * by the numeric type. Note: this is incompatible with numeric_send/recv(),
7878 * which use 16-bit integers for these fields.
7879 */
7880 static void
7881 numericvar_serialize(StringInfo buf, const NumericVar *var)
7882 {
7883 int i;
7884
7885 pq_sendint32(buf, var->ndigits);
7886 pq_sendint32(buf, var->weight);
7887 pq_sendint32(buf, var->sign);
7888 pq_sendint32(buf, var->dscale);
7889 for (i = 0; i < var->ndigits; i++)
7890 pq_sendint16(buf, var->digits[i]);
7891 }
7892
7893 /*
7894 * numericvar_deserialize - deserialize binary format to NumericVar
7895 */
7896 static void
7897 numericvar_deserialize(StringInfo buf, NumericVar *var)
7898 {
7899 int len,
7900 i;
7901
7902 len = pq_getmsgint(buf, sizeof(int32));
7903
7904 alloc_var(var, len); /* sets var->ndigits */
7905
7906 var->weight = pq_getmsgint(buf, sizeof(int32));
7907 var->sign = pq_getmsgint(buf, sizeof(int32));
7908 var->dscale = pq_getmsgint(buf, sizeof(int32));
7909 for (i = 0; i < len; i++)
7910 var->digits[i] = pq_getmsgint(buf, sizeof(int16));
7911 }
7912
7913
7914 /*
7915 * duplicate_numeric() - copy a packed-format Numeric
7916 *
7917 * This will handle NaN and Infinity cases.
7918 */
7919 static Numeric
7920 duplicate_numeric(Numeric num)
7921 {
7922 Numeric res;
7923
7924 res = (Numeric) palloc(VARSIZE(num));
7925 memcpy(res, num, VARSIZE(num));
7926 return res;
7927 }
7928
7929 /*
7930 * make_result_opt_error() -
7931 *
7932 * Create the packed db numeric format in palloc()'d memory from
7933 * a variable. This will handle NaN and Infinity cases.
7934 *
7935 * If "have_error" isn't NULL, on overflow *have_error is set to true and
7936 * NULL is returned. This is helpful when caller needs to handle errors.
7937 */
7938 static Numeric
7939 make_result_opt_error(const NumericVar *var, bool *have_error)
7940 {
7941 Numeric result;
7942 NumericDigit *digits = var->digits;
7943 int weight = var->weight;
7944 int sign = var->sign;
7945 int n;
7946 Size len;
7947
7948 if (have_error)
7949 *have_error = false;
7950
7951 if ((sign & NUMERIC_SIGN_MASK) == NUMERIC_SPECIAL)
7952 {
7953 /*
7954 * Verify valid special value. This could be just an Assert, perhaps,
7955 * but it seems worthwhile to expend a few cycles to ensure that we
7956 * never write any nonzero reserved bits to disk.
7957 */
7958 if (!(sign == NUMERIC_NAN ||
7959 sign == NUMERIC_PINF ||
7960 sign == NUMERIC_NINF))
7961 elog(ERROR, "invalid numeric sign value 0x%x", sign);
7962
7963 result = (Numeric) palloc(NUMERIC_HDRSZ_SHORT);
7964
7965 SET_VARSIZE(result, NUMERIC_HDRSZ_SHORT);
7966 result->choice.n_header = sign;
7967 /* the header word is all we need */
7968
7969 dump_numeric("make_result()", result);
7970 return result;
7971 }
7972
7973 n = var->ndigits;
7974
7975 /* truncate leading zeroes */
7976 while (n > 0 && *digits == 0)
7977 {
7978 digits++;
7979 weight--;
7980 n--;
7981 }
7982 /* truncate trailing zeroes */
7983 while (n > 0 && digits[n - 1] == 0)
7984 n--;
7985
7986 /* If zero result, force to weight=0 and positive sign */
7987 if (n == 0)
7988 {
7989 weight = 0;
7990 sign = NUMERIC_POS;
7991 }
7992
7993 /* Build the result */
7994 if (NUMERIC_CAN_BE_SHORT(var->dscale, weight))
7995 {
7996 len = NUMERIC_HDRSZ_SHORT + n * sizeof(NumericDigit);
7997 result = (Numeric) palloc(len);
7998 SET_VARSIZE(result, len);
7999 result->choice.n_short.n_header =
8000 (sign == NUMERIC_NEG ? (NUMERIC_SHORT | NUMERIC_SHORT_SIGN_MASK)
8001 : NUMERIC_SHORT)
8002 | (var->dscale << NUMERIC_SHORT_DSCALE_SHIFT)
8003 | (weight < 0 ? NUMERIC_SHORT_WEIGHT_SIGN_MASK : 0)
8004 | (weight & NUMERIC_SHORT_WEIGHT_MASK);
8005 }
8006 else
8007 {
8008 len = NUMERIC_HDRSZ + n * sizeof(NumericDigit);
8009 result = (Numeric) palloc(len);
8010 SET_VARSIZE(result, len);
8011 result->choice.n_long.n_sign_dscale =
8012 sign | (var->dscale & NUMERIC_DSCALE_MASK);
8013 result->choice.n_long.n_weight = weight;
8014 }
8015
8016 Assert(NUMERIC_NDIGITS(result) == n);
8017 if (n > 0)
8018 memcpy(NUMERIC_DIGITS(result), digits, n * sizeof(NumericDigit));
8019
8020 /* Check for overflow of int16 fields */
8021 if (NUMERIC_WEIGHT(result) != weight ||
8022 NUMERIC_DSCALE(result) != var->dscale)
8023 {
8024 if (have_error)
8025 {
8026 *have_error = true;
8027 return NULL;
8028 }
8029 else
8030 {
8031 ereport(ERROR,
8032 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
8033 errmsg("value overflows numeric format")));
8034 }
8035 }
8036
8037 dump_numeric("make_result()", result);
8038 return result;
8039 }
8040
8041
8042 /*
8043 * make_result() -
8044 *
8045 * An interface to make_result_opt_error() without "have_error" argument.
8046 */
8047 static Numeric
8048 make_result(const NumericVar *var)
8049 {
8050 return make_result_opt_error(var, NULL);
8051 }
8052
8053
8054 /*
8055 * apply_typmod() -
8056 *
8057 * Do bounds checking and rounding according to the specified typmod.
8058 * Note that this is only applied to normal finite values.
8059 *
8060 * Returns true on success, false on failure (if escontext points to an
8061 * ErrorSaveContext; otherwise errors are thrown).
8062 */
8063 static bool
8064 apply_typmod(NumericVar *var, int32 typmod, Node *escontext)
8065 {
8066 int precision;
8067 int scale;
8068 int maxdigits;
8069 int ddigits;
8070 int i;
8071
8072 /* Do nothing if we have an invalid typmod */
8073 if (!is_valid_numeric_typmod(typmod))
8074 return true;
8075
8076 precision = numeric_typmod_precision(typmod);
8077 scale = numeric_typmod_scale(typmod);
8078 maxdigits = precision - scale;
8079
8080 /* Round to target scale (and set var->dscale) */
8081 round_var(var, scale);
8082
8083 /* but don't allow var->dscale to be negative */
8084 if (var->dscale < 0)
8085 var->dscale = 0;
8086
8087 /*
8088 * Check for overflow - note we can't do this before rounding, because
8089 * rounding could raise the weight. Also note that the var's weight could
8090 * be inflated by leading zeroes, which will be stripped before storage
8091 * but perhaps might not have been yet. In any case, we must recognize a
8092 * true zero, whose weight doesn't mean anything.
8093 */
8094 ddigits = (var->weight + 1) * DEC_DIGITS;
8095 if (ddigits > maxdigits)
8096 {
8097 /* Determine true weight; and check for all-zero result */
8098 for (i = 0; i < var->ndigits; i++)
8099 {
8100 NumericDigit dig = var->digits[i];
8101
8102 if (dig)
8103 {
8104 /* Adjust for any high-order decimal zero digits */
8105 #if DEC_DIGITS == 4
8106 if (dig < 10)
8107 ddigits -= 3;
8108 else if (dig < 100)
8109 ddigits -= 2;
8110 else if (dig < 1000)
8111 ddigits -= 1;
8112 #elif DEC_DIGITS == 2
8113 if (dig < 10)
8114 ddigits -= 1;
8115 #elif DEC_DIGITS == 1
8116 /* no adjustment */
8117 #else
8118 #error unsupported NBASE
8119 #endif
8120 if (ddigits > maxdigits)
8121 ereturn(escontext, false,
8122 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
8123 errmsg("numeric field overflow"),
8124 errdetail("A field with precision %d, scale %d must round to an absolute value less than %s%d.",
8125 precision, scale,
8126 /* Display 10^0 as 1 */
8127 maxdigits ? "10^" : "",
8128 maxdigits ? maxdigits : 1
8129 )));
8130 break;
8131 }
8132 ddigits -= DEC_DIGITS;
8133 }
8134 }
8135
8136 return true;
8137 }
8138
8139 /*
8140 * apply_typmod_special() -
8141 *
8142 * Do bounds checking according to the specified typmod, for an Inf or NaN.
8143 * For convenience of most callers, the value is presented in packed form.
8144 *
8145 * Returns true on success, false on failure (if escontext points to an
8146 * ErrorSaveContext; otherwise errors are thrown).
8147 */
8148 static bool
8149 apply_typmod_special(Numeric num, int32 typmod, Node *escontext)
8150 {
8151 int precision;
8152 int scale;
8153
8154 Assert(NUMERIC_IS_SPECIAL(num)); /* caller error if not */
8155
8156 /*
8157 * NaN is allowed regardless of the typmod; that's rather dubious perhaps,
8158 * but it's a longstanding behavior. Inf is rejected if we have any
8159 * typmod restriction, since an infinity shouldn't be claimed to fit in
8160 * any finite number of digits.
8161 */
8162 if (NUMERIC_IS_NAN(num))
8163 return true;
8164
8165 /* Do nothing if we have a default typmod (-1) */
8166 if (!is_valid_numeric_typmod(typmod))
8167 return true;
8168
8169 precision = numeric_typmod_precision(typmod);
8170 scale = numeric_typmod_scale(typmod);
8171
8172 ereturn(escontext, false,
8173 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
8174 errmsg("numeric field overflow"),
8175 errdetail("A field with precision %d, scale %d cannot hold an infinite value.",
8176 precision, scale)));
8177 }
8178
8179
8180 /*
8181 * Convert numeric to int8, rounding if needed.
8182 *
8183 * If overflow, return false (no error is raised). Return true if okay.
8184 */
8185 static bool
8186 numericvar_to_int64(const NumericVar *var, int64 *result)
8187 {
8188 NumericDigit *digits;
8189 int ndigits;
8190 int weight;
8191 int i;
8192 int64 val;
8193 bool neg;
8194 NumericVar rounded;
8195
8196 /* Round to nearest integer */
8197 init_var(&rounded);
8198 set_var_from_var(var, &rounded);
8199 round_var(&rounded, 0);
8200
8201 /* Check for zero input */
8202 strip_var(&rounded);
8203 ndigits = rounded.ndigits;
8204 if (ndigits == 0)
8205 {
8206 *result = 0;
8207 free_var(&rounded);
8208 return true;
8209 }
8210
8211 /*
8212 * For input like 10000000000, we must treat stripped digits as real. So
8213 * the loop assumes there are weight+1 digits before the decimal point.
8214 */
8215 weight = rounded.weight;
8216 Assert(weight >= 0 && ndigits <= weight + 1);
8217
8218 /*
8219 * Construct the result. To avoid issues with converting a value
8220 * corresponding to INT64_MIN (which can't be represented as a positive 64
8221 * bit two's complement integer), accumulate value as a negative number.
8222 */
8223 digits = rounded.digits;
8224 neg = (rounded.sign == NUMERIC_NEG);
8225 val = -digits[0];
8226 for (i = 1; i <= weight; i++)
8227 {
8228 if (unlikely(pg_mul_s64_overflow(val, NBASE, &val)))
8229 {
8230 free_var(&rounded);
8231 return false;
8232 }
8233
8234 if (i < ndigits)
8235 {
8236 if (unlikely(pg_sub_s64_overflow(val, digits[i], &val)))
8237 {
8238 free_var(&rounded);
8239 return false;
8240 }
8241 }
8242 }
8243
8244 free_var(&rounded);
8245
8246 if (!neg)
8247 {
8248 if (unlikely(val == PG_INT64_MIN))
8249 return false;
8250 val = -val;
8251 }
8252 *result = val;
8253
8254 return true;
8255 }
8256
8257 /*
8258 * Convert int8 value to numeric.
8259 */
8260 static void
8261 int64_to_numericvar(int64 val, NumericVar *var)
8262 {
8263 uint64 uval,
8264 newuval;
8265 NumericDigit *ptr;
8266 int ndigits;
8267
8268 /* int64 can require at most 19 decimal digits; add one for safety */
8269 alloc_var(var, 20 / DEC_DIGITS);
8270 if (val < 0)
8271 {
8272 var->sign = NUMERIC_NEG;
8273 uval = pg_abs_s64(val);
8274 }
8275 else
8276 {
8277 var->sign = NUMERIC_POS;
8278 uval = val;
8279 }
8280 var->dscale = 0;
8281 if (val == 0)
8282 {
8283 var->ndigits = 0;
8284 var->weight = 0;
8285 return;
8286 }
8287 ptr = var->digits + var->ndigits;
8288 ndigits = 0;
8289 do
8290 {
8291 ptr--;
8292 ndigits++;
8293 newuval = uval / NBASE;
8294 *ptr = uval - newuval * NBASE;
8295 uval = newuval;
8296 } while (uval);
8297 var->digits = ptr;
8298 var->ndigits = ndigits;
8299 var->weight = ndigits - 1;
8300 }
8301
8302 /*
8303 * Convert numeric to uint64, rounding if needed.
8304 *
8305 * If overflow, return false (no error is raised). Return true if okay.
8306 */
8307 static bool
8308 numericvar_to_uint64(const NumericVar *var, uint64 *result)
8309 {
8310 NumericDigit *digits;
8311 int ndigits;
8312 int weight;
8313 int i;
8314 uint64 val;
8315 NumericVar rounded;
8316
8317 /* Round to nearest integer */
8318 init_var(&rounded);
8319 set_var_from_var(var, &rounded);
8320 round_var(&rounded, 0);
8321
8322 /* Check for zero input */
8323 strip_var(&rounded);
8324 ndigits = rounded.ndigits;
8325 if (ndigits == 0)
8326 {
8327 *result = 0;
8328 free_var(&rounded);
8329 return true;
8330 }
8331
8332 /* Check for negative input */
8333 if (rounded.sign == NUMERIC_NEG)
8334 {
8335 free_var(&rounded);
8336 return false;
8337 }
8338
8339 /*
8340 * For input like 10000000000, we must treat stripped digits as real. So
8341 * the loop assumes there are weight+1 digits before the decimal point.
8342 */
8343 weight = rounded.weight;
8344 Assert(weight >= 0 && ndigits <= weight + 1);
8345
8346 /* Construct the result */
8347 digits = rounded.digits;
8348 val = digits[0];
8349 for (i = 1; i <= weight; i++)
8350 {
8351 if (unlikely(pg_mul_u64_overflow(val, NBASE, &val)))
8352 {
8353 free_var(&rounded);
8354 return false;
8355 }
8356
8357 if (i < ndigits)
8358 {
8359 if (unlikely(pg_add_u64_overflow(val, digits[i], &val)))
8360 {
8361 free_var(&rounded);
8362 return false;
8363 }
8364 }
8365 }
8366
8367 free_var(&rounded);
8368
8369 *result = val;
8370
8371 return true;
8372 }
8373
8374 #ifdef HAVE_INT128
8375 /*
8376 * Convert numeric to int128, rounding if needed.
8377 *
8378 * If overflow, return false (no error is raised). Return true if okay.
8379 */
8380 static bool
8381 numericvar_to_int128(const NumericVar *var, int128 *result)
8382 {
8383 NumericDigit *digits;
8384 int ndigits;
8385 int weight;
8386 int i;
8387 int128 val,
8388 oldval;
8389 bool neg;
8390 NumericVar rounded;
8391
8392 /* Round to nearest integer */
8393 init_var(&rounded);
8394 set_var_from_var(var, &rounded);
8395 round_var(&rounded, 0);
8396
8397 /* Check for zero input */
8398 strip_var(&rounded);
8399 ndigits = rounded.ndigits;
8400 if (ndigits == 0)
8401 {
8402 *result = 0;
8403 free_var(&rounded);
8404 return true;
8405 }
8406
8407 /*
8408 * For input like 10000000000, we must treat stripped digits as real. So
8409 * the loop assumes there are weight+1 digits before the decimal point.
8410 */
8411 weight = rounded.weight;
8412 Assert(weight >= 0 && ndigits <= weight + 1);
8413
8414 /* Construct the result */
8415 digits = rounded.digits;
8416 neg = (rounded.sign == NUMERIC_NEG);
8417 val = digits[0];
8418 for (i = 1; i <= weight; i++)
8419 {
8420 oldval = val;
8421 val *= NBASE;
8422 if (i < ndigits)
8423 val += digits[i];
8424
8425 /*
8426 * The overflow check is a bit tricky because we want to accept
8427 * INT128_MIN, which will overflow the positive accumulator. We can
8428 * detect this case easily though because INT128_MIN is the only
8429 * nonzero value for which -val == val (on a two's complement machine,
8430 * anyway).
8431 */
8432 if ((val / NBASE) != oldval) /* possible overflow? */
8433 {
8434 if (!neg || (-val) != val || val == 0 || oldval < 0)
8435 {
8436 free_var(&rounded);
8437 return false;
8438 }
8439 }
8440 }
8441
8442 free_var(&rounded);
8443
8444 *result = neg ? -val : val;
8445 return true;
8446 }
8447
8448 /*
8449 * Convert 128 bit integer to numeric.
8450 */
8451 static void
8452 int128_to_numericvar(int128 val, NumericVar *var)
8453 {
8454 uint128 uval,
8455 newuval;
8456 NumericDigit *ptr;
8457 int ndigits;
8458
8459 /* int128 can require at most 39 decimal digits; add one for safety */
8460 alloc_var(var, 40 / DEC_DIGITS);
8461 if (val < 0)
8462 {
8463 var->sign = NUMERIC_NEG;
8464 uval = -val;
8465 }
8466 else
8467 {
8468 var->sign = NUMERIC_POS;
8469 uval = val;
8470 }
8471 var->dscale = 0;
8472 if (val == 0)
8473 {
8474 var->ndigits = 0;
8475 var->weight = 0;
8476 return;
8477 }
8478 ptr = var->digits + var->ndigits;
8479 ndigits = 0;
8480 do
8481 {
8482 ptr--;
8483 ndigits++;
8484 newuval = uval / NBASE;
8485 *ptr = uval - newuval * NBASE;
8486 uval = newuval;
8487 } while (uval);
8488 var->digits = ptr;
8489 var->ndigits = ndigits;
8490 var->weight = ndigits - 1;
8491 }
8492 #endif
8493
8494 /*
8495 * Convert a NumericVar to float8; if out of range, return +/- HUGE_VAL
8496 */
8497 static double
8498 numericvar_to_double_no_overflow(const NumericVar *var)
8499 {
8500 char *tmp;
8501 double val;
8502 char *endptr;
8503
8504 tmp = get_str_from_var(var);
8505
8506 /* unlike float8in, we ignore ERANGE from strtod */
8507 val = strtod(tmp, &endptr);
8508 if (*endptr != '\0')
8509 {
8510 /* shouldn't happen ... */
8511 ereport(ERROR,
8512 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
8513 errmsg("invalid input syntax for type %s: \"%s\"",
8514 "double precision", tmp)));
8515 }
8516
8517 pfree(tmp);
8518
8519 return val;
8520 }
8521
8522
8523 /*
8524 * cmp_var() -
8525 *
8526 * Compare two values on variable level. We assume zeroes have been
8527 * truncated to no digits.
8528 */
8529 static int
8530 cmp_var(const NumericVar *var1, const NumericVar *var2)
8531 {
8532 return cmp_var_common(var1->digits, var1->ndigits,
8533 var1->weight, var1->sign,
8534 var2->digits, var2->ndigits,
8535 var2->weight, var2->sign);
8536 }
8537
8538 /*
8539 * cmp_var_common() -
8540 *
8541 * Main routine of cmp_var(). This function can be used by both
8542 * NumericVar and Numeric.
8543 */
8544 static int
8545 cmp_var_common(const NumericDigit *var1digits, int var1ndigits,
8546 int var1weight, int var1sign,
8547 const NumericDigit *var2digits, int var2ndigits,
8548 int var2weight, int var2sign)
8549 {
8550 if (var1ndigits == 0)
8551 {
8552 if (var2ndigits == 0)
8553 return 0;
8554 if (var2sign == NUMERIC_NEG)
8555 return 1;
8556 return -1;
8557 }
8558 if (var2ndigits == 0)
8559 {
8560 if (var1sign == NUMERIC_POS)
8561 return 1;
8562 return -1;
8563 }
8564
8565 if (var1sign == NUMERIC_POS)
8566 {
8567 if (var2sign == NUMERIC_NEG)
8568 return 1;
8569 return cmp_abs_common(var1digits, var1ndigits, var1weight,
8570 var2digits, var2ndigits, var2weight);
8571 }
8572
8573 if (var2sign == NUMERIC_POS)
8574 return -1;
8575
8576 return cmp_abs_common(var2digits, var2ndigits, var2weight,
8577 var1digits, var1ndigits, var1weight);
8578 }
8579
8580
8581 /*
8582 * add_var() -
8583 *
8584 * Full version of add functionality on variable level (handling signs).
8585 * result might point to one of the operands too without danger.
8586 */
8587 static void
8588 add_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
8589 {
8590 /*
8591 * Decide on the signs of the two variables what to do
8592 */
8593 if (var1->sign == NUMERIC_POS)
8594 {
8595 if (var2->sign == NUMERIC_POS)
8596 {
8597 /*
8598 * Both are positive result = +(ABS(var1) + ABS(var2))
8599 */
8600 add_abs(var1, var2, result);
8601 result->sign = NUMERIC_POS;
8602 }
8603 else
8604 {
8605 /*
8606 * var1 is positive, var2 is negative Must compare absolute values
8607 */
8608 switch (cmp_abs(var1, var2))
8609 {
8610 case 0:
8611 /* ----------
8612 * ABS(var1) == ABS(var2)
8613 * result = ZERO
8614 * ----------
8615 */
8616 zero_var(result);
8617 result->dscale = Max(var1->dscale, var2->dscale);
8618 break;
8619
8620 case 1:
8621 /* ----------
8622 * ABS(var1) > ABS(var2)
8623 * result = +(ABS(var1) - ABS(var2))
8624 * ----------
8625 */
8626 sub_abs(var1, var2, result);
8627 result->sign = NUMERIC_POS;
8628 break;
8629
8630 case -1:
8631 /* ----------
8632 * ABS(var1) < ABS(var2)
8633 * result = -(ABS(var2) - ABS(var1))
8634 * ----------
8635 */
8636 sub_abs(var2, var1, result);
8637 result->sign = NUMERIC_NEG;
8638 break;
8639 }
8640 }
8641 }
8642 else
8643 {
8644 if (var2->sign == NUMERIC_POS)
8645 {
8646 /* ----------
8647 * var1 is negative, var2 is positive
8648 * Must compare absolute values
8649 * ----------
8650 */
8651 switch (cmp_abs(var1, var2))
8652 {
8653 case 0:
8654 /* ----------
8655 * ABS(var1) == ABS(var2)
8656 * result = ZERO
8657 * ----------
8658 */
8659 zero_var(result);
8660 result->dscale = Max(var1->dscale, var2->dscale);
8661 break;
8662
8663 case 1:
8664 /* ----------
8665 * ABS(var1) > ABS(var2)
8666 * result = -(ABS(var1) - ABS(var2))
8667 * ----------
8668 */
8669 sub_abs(var1, var2, result);
8670 result->sign = NUMERIC_NEG;
8671 break;
8672
8673 case -1:
8674 /* ----------
8675 * ABS(var1) < ABS(var2)
8676 * result = +(ABS(var2) - ABS(var1))
8677 * ----------
8678 */
8679 sub_abs(var2, var1, result);
8680 result->sign = NUMERIC_POS;
8681 break;
8682 }
8683 }
8684 else
8685 {
8686 /* ----------
8687 * Both are negative
8688 * result = -(ABS(var1) + ABS(var2))
8689 * ----------
8690 */
8691 add_abs(var1, var2, result);
8692 result->sign = NUMERIC_NEG;
8693 }
8694 }
8695 }
8696
8697
8698 /*
8699 * sub_var() -
8700 *
8701 * Full version of sub functionality on variable level (handling signs).
8702 * result might point to one of the operands too without danger.
8703 */
8704 static void
8705 sub_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
8706 {
8707 /*
8708 * Decide on the signs of the two variables what to do
8709 */
8710 if (var1->sign == NUMERIC_POS)
8711 {
8712 if (var2->sign == NUMERIC_NEG)
8713 {
8714 /* ----------
8715 * var1 is positive, var2 is negative
8716 * result = +(ABS(var1) + ABS(var2))
8717 * ----------
8718 */
8719 add_abs(var1, var2, result);
8720 result->sign = NUMERIC_POS;
8721 }
8722 else
8723 {
8724 /* ----------
8725 * Both are positive
8726 * Must compare absolute values
8727 * ----------
8728 */
8729 switch (cmp_abs(var1, var2))
8730 {
8731 case 0:
8732 /* ----------
8733 * ABS(var1) == ABS(var2)
8734 * result = ZERO
8735 * ----------
8736 */
8737 zero_var(result);
8738 result->dscale = Max(var1->dscale, var2->dscale);
8739 break;
8740
8741 case 1:
8742 /* ----------
8743 * ABS(var1) > ABS(var2)
8744 * result = +(ABS(var1) - ABS(var2))
8745 * ----------
8746 */
8747 sub_abs(var1, var2, result);
8748 result->sign = NUMERIC_POS;
8749 break;
8750
8751 case -1:
8752 /* ----------
8753 * ABS(var1) < ABS(var2)
8754 * result = -(ABS(var2) - ABS(var1))
8755 * ----------
8756 */
8757 sub_abs(var2, var1, result);
8758 result->sign = NUMERIC_NEG;
8759 break;
8760 }
8761 }
8762 }
8763 else
8764 {
8765 if (var2->sign == NUMERIC_NEG)
8766 {
8767 /* ----------
8768 * Both are negative
8769 * Must compare absolute values
8770 * ----------
8771 */
8772 switch (cmp_abs(var1, var2))
8773 {
8774 case 0:
8775 /* ----------
8776 * ABS(var1) == ABS(var2)
8777 * result = ZERO
8778 * ----------
8779 */
8780 zero_var(result);
8781 result->dscale = Max(var1->dscale, var2->dscale);
8782 break;
8783
8784 case 1:
8785 /* ----------
8786 * ABS(var1) > ABS(var2)
8787 * result = -(ABS(var1) - ABS(var2))
8788 * ----------
8789 */
8790 sub_abs(var1, var2, result);
8791 result->sign = NUMERIC_NEG;
8792 break;
8793
8794 case -1:
8795 /* ----------
8796 * ABS(var1) < ABS(var2)
8797 * result = +(ABS(var2) - ABS(var1))
8798 * ----------
8799 */
8800 sub_abs(var2, var1, result);
8801 result->sign = NUMERIC_POS;
8802 break;
8803 }
8804 }
8805 else
8806 {
8807 /* ----------
8808 * var1 is negative, var2 is positive
8809 * result = -(ABS(var1) + ABS(var2))
8810 * ----------
8811 */
8812 add_abs(var1, var2, result);
8813 result->sign = NUMERIC_NEG;
8814 }
8815 }
8816 }
8817
8818
8819 /*
8820 * mul_var() -
8821 *
8822 * Multiplication on variable level. Product of var1 * var2 is stored
8823 * in result. Result is rounded to no more than rscale fractional digits.
8824 */
8825 static void
8826 mul_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result,
8827 int rscale)
8828 {
8829 int res_ndigits;
8830 int res_ndigitpairs;
8831 int res_sign;
8832 int res_weight;
8833 int pair_offset;
8834 int maxdigits;
8835 int maxdigitpairs;
8836 uint64 *dig,
8837 *dig_i1_off;
8838 uint64 maxdig;
8839 uint64 carry;
8840 uint64 newdig;
8841 int var1ndigits;
8842 int var2ndigits;
8843 int var1ndigitpairs;
8844 int var2ndigitpairs;
8845 NumericDigit *var1digits;
8846 NumericDigit *var2digits;
8847 uint32 var1digitpair;
8848 uint32 *var2digitpairs;
8849 NumericDigit *res_digits;
8850 int i,
8851 i1,
8852 i2,
8853 i2limit;
8854
8855 /*
8856 * Arrange for var1 to be the shorter of the two numbers. This improves
8857 * performance because the inner multiplication loop is much simpler than
8858 * the outer loop, so it's better to have a smaller number of iterations
8859 * of the outer loop. This also reduces the number of times that the
8860 * accumulator array needs to be normalized.
8861 */
8862 if (var1->ndigits > var2->ndigits)
8863 {
8864 const NumericVar *tmp = var1;
8865
8866 var1 = var2;
8867 var2 = tmp;
8868 }
8869
8870 /* copy these values into local vars for speed in inner loop */
8871 var1ndigits = var1->ndigits;
8872 var2ndigits = var2->ndigits;
8873 var1digits = var1->digits;
8874 var2digits = var2->digits;
8875
8876 if (var1ndigits == 0)
8877 {
8878 /* one or both inputs is zero; so is result */
8879 zero_var(result);
8880 result->dscale = rscale;
8881 return;
8882 }
8883
8884 /*
8885 * If var1 has 1-6 digits and the exact result was requested, delegate to
8886 * mul_var_short() which uses a faster direct multiplication algorithm.
8887 */
8888 if (var1ndigits <= 6 && rscale == var1->dscale + var2->dscale)
8889 {
8890 mul_var_short(var1, var2, result);
8891 return;
8892 }
8893
8894 /* Determine result sign */
8895 if (var1->sign == var2->sign)
8896 res_sign = NUMERIC_POS;
8897 else
8898 res_sign = NUMERIC_NEG;
8899
8900 /*
8901 * Determine the number of result digits to compute and the (maximum
8902 * possible) result weight. If the exact result would have more than
8903 * rscale fractional digits, truncate the computation with
8904 * MUL_GUARD_DIGITS guard digits, i.e., ignore input digits that would
8905 * only contribute to the right of that. (This will give the exact
8906 * rounded-to-rscale answer unless carries out of the ignored positions
8907 * would have propagated through more than MUL_GUARD_DIGITS digits.)
8908 *
8909 * Note: an exact computation could not produce more than var1ndigits +
8910 * var2ndigits digits, but we allocate at least one extra output digit in
8911 * case rscale-driven rounding produces a carry out of the highest exact
8912 * digit.
8913 *
8914 * The computation itself is done using base-NBASE^2 arithmetic, so we
8915 * actually process the input digits in pairs, producing a base-NBASE^2
8916 * intermediate result. This significantly improves performance, since
8917 * schoolbook multiplication is O(N^2) in the number of input digits, and
8918 * working in base NBASE^2 effectively halves "N".
8919 *
8920 * Note: in a truncated computation, we must compute at least one extra
8921 * output digit to ensure that all the guard digits are fully computed.
8922 */
8923 /* digit pairs in each input */
8924 var1ndigitpairs = (var1ndigits + 1) / 2;
8925 var2ndigitpairs = (var2ndigits + 1) / 2;
8926
8927 /* digits in exact result */
8928 res_ndigits = var1ndigits + var2ndigits;
8929
8930 /* digit pairs in exact result with at least one extra output digit */
8931 res_ndigitpairs = res_ndigits / 2 + 1;
8932
8933 /* pair offset to align result to end of dig[] */
8934 pair_offset = res_ndigitpairs - var1ndigitpairs - var2ndigitpairs + 1;
8935
8936 /* maximum possible result weight (odd-length inputs shifted up below) */
8937 res_weight = var1->weight + var2->weight + 1 + 2 * res_ndigitpairs -
8938 res_ndigits - (var1ndigits & 1) - (var2ndigits & 1);
8939
8940 /* rscale-based truncation with at least one extra output digit */
8941 maxdigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS +
8942 MUL_GUARD_DIGITS;
8943 maxdigitpairs = maxdigits / 2 + 1;
8944
8945 res_ndigitpairs = Min(res_ndigitpairs, maxdigitpairs);
8946 res_ndigits = 2 * res_ndigitpairs;
8947
8948 /*
8949 * In the computation below, digit pair i1 of var1 and digit pair i2 of
8950 * var2 are multiplied and added to digit i1+i2+pair_offset of dig[]. Thus
8951 * input digit pairs with index >= res_ndigitpairs - pair_offset don't
8952 * contribute to the result, and can be ignored.
8953 */
8954 if (res_ndigitpairs <= pair_offset)
8955 {
8956 /* All input digits will be ignored; so result is zero */
8957 zero_var(result);
8958 result->dscale = rscale;
8959 return;
8960 }
8961 var1ndigitpairs = Min(var1ndigitpairs, res_ndigitpairs - pair_offset);
8962 var2ndigitpairs = Min(var2ndigitpairs, res_ndigitpairs - pair_offset);
8963
8964 /*
8965 * We do the arithmetic in an array "dig[]" of unsigned 64-bit integers.
8966 * Since PG_UINT64_MAX is much larger than NBASE^4, this gives us a lot of
8967 * headroom to avoid normalizing carries immediately.
8968 *
8969 * maxdig tracks the maximum possible value of any dig[] entry; when this
8970 * threatens to exceed PG_UINT64_MAX, we take the time to propagate
8971 * carries. Furthermore, we need to ensure that overflow doesn't occur
8972 * during the carry propagation passes either. The carry values could be
8973 * as much as PG_UINT64_MAX / NBASE^2, so really we must normalize when
8974 * digits threaten to exceed PG_UINT64_MAX - PG_UINT64_MAX / NBASE^2.
8975 *
8976 * To avoid overflow in maxdig itself, it actually represents the maximum
8977 * possible value divided by NBASE^2-1, i.e., at the top of the loop it is
8978 * known that no dig[] entry exceeds maxdig * (NBASE^2-1).
8979 *
8980 * The conversion of var1 to base NBASE^2 is done on the fly, as each new
8981 * digit is required. The digits of var2 are converted upfront, and
8982 * stored at the end of dig[]. To avoid loss of precision, the input
8983 * digits are aligned with the start of digit pair array, effectively
8984 * shifting them up (multiplying by NBASE) if the inputs have an odd
8985 * number of NBASE digits.
8986 */
8987 dig = (uint64 *) palloc(res_ndigitpairs * sizeof(uint64) +
8988 var2ndigitpairs * sizeof(uint32));
8989
8990 /* convert var2 to base NBASE^2, shifting up if its length is odd */
8991 var2digitpairs = (uint32 *) (dig + res_ndigitpairs);
8992
8993 for (i2 = 0; i2 < var2ndigitpairs - 1; i2++)
8994 var2digitpairs[i2] = var2digits[2 * i2] * NBASE + var2digits[2 * i2 + 1];
8995
8996 if (2 * i2 + 1 < var2ndigits)
8997 var2digitpairs[i2] = var2digits[2 * i2] * NBASE + var2digits[2 * i2 + 1];
8998 else
8999 var2digitpairs[i2] = var2digits[2 * i2] * NBASE;
9000
9001 /*
9002 * Start by multiplying var2 by the least significant contributing digit
9003 * pair from var1, storing the results at the end of dig[], and filling
9004 * the leading digits with zeros.
9005 *
9006 * The loop here is the same as the inner loop below, except that we set
9007 * the results in dig[], rather than adding to them. This is the
9008 * performance bottleneck for multiplication, so we want to keep it simple
9009 * enough so that it can be auto-vectorized. Accordingly, process the
9010 * digits left-to-right even though schoolbook multiplication would
9011 * suggest right-to-left. Since we aren't propagating carries in this
9012 * loop, the order does not matter.
9013 */
9014 i1 = var1ndigitpairs - 1;
9015 if (2 * i1 + 1 < var1ndigits)
9016 var1digitpair = var1digits[2 * i1] * NBASE + var1digits[2 * i1 + 1];
9017 else
9018 var1digitpair = var1digits[2 * i1] * NBASE;
9019 maxdig = var1digitpair;
9020
9021 i2limit = Min(var2ndigitpairs, res_ndigitpairs - i1 - pair_offset);
9022 dig_i1_off = &dig[i1 + pair_offset];
9023
9024 memset(dig, 0, (i1 + pair_offset) * sizeof(uint64));
9025 for (i2 = 0; i2 < i2limit; i2++)
9026 dig_i1_off[i2] = (uint64) var1digitpair * var2digitpairs[i2];
9027
9028 /*
9029 * Next, multiply var2 by the remaining digit pairs from var1, adding the
9030 * results to dig[] at the appropriate offsets, and normalizing whenever
9031 * there is a risk of any dig[] entry overflowing.
9032 */
9033 for (i1 = i1 - 1; i1 >= 0; i1--)
9034 {
9035 var1digitpair = var1digits[2 * i1] * NBASE + var1digits[2 * i1 + 1];
9036 if (var1digitpair == 0)
9037 continue;
9038
9039 /* Time to normalize? */
9040 maxdig += var1digitpair;
9041 if (maxdig > (PG_UINT64_MAX - PG_UINT64_MAX / NBASE_SQR) / (NBASE_SQR - 1))
9042 {
9043 /* Yes, do it (to base NBASE^2) */
9044 carry = 0;
9045 for (i = res_ndigitpairs - 1; i >= 0; i--)
9046 {
9047 newdig = dig[i] + carry;
9048 if (newdig >= NBASE_SQR)
9049 {
9050 carry = newdig / NBASE_SQR;
9051 newdig -= carry * NBASE_SQR;
9052 }
9053 else
9054 carry = 0;
9055 dig[i] = newdig;
9056 }
9057 Assert(carry == 0);
9058 /* Reset maxdig to indicate new worst-case */
9059 maxdig = 1 + var1digitpair;
9060 }
9061
9062 /* Multiply and add */
9063 i2limit = Min(var2ndigitpairs, res_ndigitpairs - i1 - pair_offset);
9064 dig_i1_off = &dig[i1 + pair_offset];
9065
9066 for (i2 = 0; i2 < i2limit; i2++)
9067 dig_i1_off[i2] += (uint64) var1digitpair * var2digitpairs[i2];
9068 }
9069
9070 /*
9071 * Now we do a final carry propagation pass to normalize back to base
9072 * NBASE^2, and construct the base-NBASE result digits. Note that this is
9073 * still done at full precision w/guard digits.
9074 */
9075 alloc_var(result, res_ndigits);
9076 res_digits = result->digits;
9077 carry = 0;
9078 for (i = res_ndigitpairs - 1; i >= 0; i--)
9079 {
9080 newdig = dig[i] + carry;
9081 if (newdig >= NBASE_SQR)
9082 {
9083 carry = newdig / NBASE_SQR;
9084 newdig -= carry * NBASE_SQR;
9085 }
9086 else
9087 carry = 0;
9088 res_digits[2 * i + 1] = (NumericDigit) ((uint32) newdig % NBASE);
9089 res_digits[2 * i] = (NumericDigit) ((uint32) newdig / NBASE);
9090 }
9091 Assert(carry == 0);
9092
9093 pfree(dig);
9094
9095 /*
9096 * Finally, round the result to the requested precision.
9097 */
9098 result->weight = res_weight;
9099 result->sign = res_sign;
9100
9101 /* Round to target rscale (and set result->dscale) */
9102 round_var(result, rscale);
9103
9104 /* Strip leading and trailing zeroes */
9105 strip_var(result);
9106 }
9107
9108
9109 /*
9110 * mul_var_short() -
9111 *
9112 * Special-case multiplication function used when var1 has 1-6 digits, var2
9113 * has at least as many digits as var1, and the exact product var1 * var2 is
9114 * requested.
9115 */
9116 static void
9117 mul_var_short(const NumericVar *var1, const NumericVar *var2,
9118 NumericVar *result)
9119 {
9120 int var1ndigits = var1->ndigits;
9121 int var2ndigits = var2->ndigits;
9122 NumericDigit *var1digits = var1->digits;
9123 NumericDigit *var2digits = var2->digits;
9124 int res_sign;
9125 int res_weight;
9126 int res_ndigits;
9127 NumericDigit *res_buf;
9128 NumericDigit *res_digits;
9129 uint32 carry = 0;
9130 uint32 term;
9131
9132 /* Check preconditions */
9133 Assert(var1ndigits >= 1);
9134 Assert(var1ndigits <= 6);
9135 Assert(var2ndigits >= var1ndigits);
9136
9137 /*
9138 * Determine the result sign, weight, and number of digits to calculate.
9139 * The weight figured here is correct if the product has no leading zero
9140 * digits; otherwise strip_var() will fix things up. Note that, unlike
9141 * mul_var(), we do not need to allocate an extra output digit, because we
9142 * are not rounding here.
9143 */
9144 if (var1->sign == var2->sign)
9145 res_sign = NUMERIC_POS;
9146 else
9147 res_sign = NUMERIC_NEG;
9148 res_weight = var1->weight + var2->weight + 1;
9149 res_ndigits = var1ndigits + var2ndigits;
9150
9151 /* Allocate result digit array */
9152 res_buf = digitbuf_alloc(res_ndigits + 1);
9153 res_buf[0] = 0; /* spare digit for later rounding */
9154 res_digits = res_buf + 1;
9155
9156 /*
9157 * Compute the result digits in reverse, in one pass, propagating the
9158 * carry up as we go. The i'th result digit consists of the sum of the
9159 * products var1digits[i1] * var2digits[i2] for which i = i1 + i2 + 1.
9160 */
9161 #define PRODSUM1(v1,i1,v2,i2) ((v1)[(i1)] * (v2)[(i2)])
9162 #define PRODSUM2(v1,i1,v2,i2) (PRODSUM1(v1,i1,v2,i2) + (v1)[(i1)+1] * (v2)[(i2)-1])
9163 #define PRODSUM3(v1,i1,v2,i2) (PRODSUM2(v1,i1,v2,i2) + (v1)[(i1)+2] * (v2)[(i2)-2])
9164 #define PRODSUM4(v1,i1,v2,i2) (PRODSUM3(v1,i1,v2,i2) + (v1)[(i1)+3] * (v2)[(i2)-3])
9165 #define PRODSUM5(v1,i1,v2,i2) (PRODSUM4(v1,i1,v2,i2) + (v1)[(i1)+4] * (v2)[(i2)-4])
9166 #define PRODSUM6(v1,i1,v2,i2) (PRODSUM5(v1,i1,v2,i2) + (v1)[(i1)+5] * (v2)[(i2)-5])
9167
9168 switch (var1ndigits)
9169 {
9170 case 1:
9171 /* ---------
9172 * 1-digit case:
9173 * var1ndigits = 1
9174 * var2ndigits >= 1
9175 * res_ndigits = var2ndigits + 1
9176 * ----------
9177 */
9178 for (int i = var2ndigits - 1; i >= 0; i--)
9179 {
9180 term = PRODSUM1(var1digits, 0, var2digits, i) + carry;
9181 res_digits[i + 1] = (NumericDigit) (term % NBASE);
9182 carry = term / NBASE;
9183 }
9184 res_digits[0] = (NumericDigit) carry;
9185 break;
9186
9187 case 2:
9188 /* ---------
9189 * 2-digit case:
9190 * var1ndigits = 2
9191 * var2ndigits >= 2
9192 * res_ndigits = var2ndigits + 2
9193 * ----------
9194 */
9195 /* last result digit and carry */
9196 term = PRODSUM1(var1digits, 1, var2digits, var2ndigits - 1);
9197 res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
9198 carry = term / NBASE;
9199
9200 /* remaining digits, except for the first two */
9201 for (int i = var2ndigits - 1; i >= 1; i--)
9202 {
9203 term = PRODSUM2(var1digits, 0, var2digits, i) + carry;
9204 res_digits[i + 1] = (NumericDigit) (term % NBASE);
9205 carry = term / NBASE;
9206 }
9207 break;
9208
9209 case 3:
9210 /* ---------
9211 * 3-digit case:
9212 * var1ndigits = 3
9213 * var2ndigits >= 3
9214 * res_ndigits = var2ndigits + 3
9215 * ----------
9216 */
9217 /* last two result digits */
9218 term = PRODSUM1(var1digits, 2, var2digits, var2ndigits - 1);
9219 res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
9220 carry = term / NBASE;
9221
9222 term = PRODSUM2(var1digits, 1, var2digits, var2ndigits - 1) + carry;
9223 res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
9224 carry = term / NBASE;
9225
9226 /* remaining digits, except for the first three */
9227 for (int i = var2ndigits - 1; i >= 2; i--)
9228 {
9229 term = PRODSUM3(var1digits, 0, var2digits, i) + carry;
9230 res_digits[i + 1] = (NumericDigit) (term % NBASE);
9231 carry = term / NBASE;
9232 }
9233 break;
9234
9235 case 4:
9236 /* ---------
9237 * 4-digit case:
9238 * var1ndigits = 4
9239 * var2ndigits >= 4
9240 * res_ndigits = var2ndigits + 4
9241 * ----------
9242 */
9243 /* last three result digits */
9244 term = PRODSUM1(var1digits, 3, var2digits, var2ndigits - 1);
9245 res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
9246 carry = term / NBASE;
9247
9248 term = PRODSUM2(var1digits, 2, var2digits, var2ndigits - 1) + carry;
9249 res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
9250 carry = term / NBASE;
9251
9252 term = PRODSUM3(var1digits, 1, var2digits, var2ndigits - 1) + carry;
9253 res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
9254 carry = term / NBASE;
9255
9256 /* remaining digits, except for the first four */
9257 for (int i = var2ndigits - 1; i >= 3; i--)
9258 {
9259 term = PRODSUM4(var1digits, 0, var2digits, i) + carry;
9260 res_digits[i + 1] = (NumericDigit) (term % NBASE);
9261 carry = term / NBASE;
9262 }
9263 break;
9264
9265 case 5:
9266 /* ---------
9267 * 5-digit case:
9268 * var1ndigits = 5
9269 * var2ndigits >= 5
9270 * res_ndigits = var2ndigits + 5
9271 * ----------
9272 */
9273 /* last four result digits */
9274 term = PRODSUM1(var1digits, 4, var2digits, var2ndigits - 1);
9275 res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
9276 carry = term / NBASE;
9277
9278 term = PRODSUM2(var1digits, 3, var2digits, var2ndigits - 1) + carry;
9279 res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
9280 carry = term / NBASE;
9281
9282 term = PRODSUM3(var1digits, 2, var2digits, var2ndigits - 1) + carry;
9283 res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
9284 carry = term / NBASE;
9285
9286 term = PRODSUM4(var1digits, 1, var2digits, var2ndigits - 1) + carry;
9287 res_digits[res_ndigits - 4] = (NumericDigit) (term % NBASE);
9288 carry = term / NBASE;
9289
9290 /* remaining digits, except for the first five */
9291 for (int i = var2ndigits - 1; i >= 4; i--)
9292 {
9293 term = PRODSUM5(var1digits, 0, var2digits, i) + carry;
9294 res_digits[i + 1] = (NumericDigit) (term % NBASE);
9295 carry = term / NBASE;
9296 }
9297 break;
9298
9299 case 6:
9300 /* ---------
9301 * 6-digit case:
9302 * var1ndigits = 6
9303 * var2ndigits >= 6
9304 * res_ndigits = var2ndigits + 6
9305 * ----------
9306 */
9307 /* last five result digits */
9308 term = PRODSUM1(var1digits, 5, var2digits, var2ndigits - 1);
9309 res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
9310 carry = term / NBASE;
9311
9312 term = PRODSUM2(var1digits, 4, var2digits, var2ndigits - 1) + carry;
9313 res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
9314 carry = term / NBASE;
9315
9316 term = PRODSUM3(var1digits, 3, var2digits, var2ndigits - 1) + carry;
9317 res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
9318 carry = term / NBASE;
9319
9320 term = PRODSUM4(var1digits, 2, var2digits, var2ndigits - 1) + carry;
9321 res_digits[res_ndigits - 4] = (NumericDigit) (term % NBASE);
9322 carry = term / NBASE;
9323
9324 term = PRODSUM5(var1digits, 1, var2digits, var2ndigits - 1) + carry;
9325 res_digits[res_ndigits - 5] = (NumericDigit) (term % NBASE);
9326 carry = term / NBASE;
9327
9328 /* remaining digits, except for the first six */
9329 for (int i = var2ndigits - 1; i >= 5; i--)
9330 {
9331 term = PRODSUM6(var1digits, 0, var2digits, i) + carry;
9332 res_digits[i + 1] = (NumericDigit) (term % NBASE);
9333 carry = term / NBASE;
9334 }
9335 break;
9336 }
9337
9338 /*
9339 * Finally, for var1ndigits > 1, compute the remaining var1ndigits most
9340 * significant result digits.
9341 */
9342 switch (var1ndigits)
9343 {
9344 case 6:
9345 term = PRODSUM5(var1digits, 0, var2digits, 4) + carry;
9346 res_digits[5] = (NumericDigit) (term % NBASE);
9347 carry = term / NBASE;
9348 /* FALLTHROUGH */
9349 case 5:
9350 term = PRODSUM4(var1digits, 0, var2digits, 3) + carry;
9351 res_digits[4] = (NumericDigit) (term % NBASE);
9352 carry = term / NBASE;
9353 /* FALLTHROUGH */
9354 case 4:
9355 term = PRODSUM3(var1digits, 0, var2digits, 2) + carry;
9356 res_digits[3] = (NumericDigit) (term % NBASE);
9357 carry = term / NBASE;
9358 /* FALLTHROUGH */
9359 case 3:
9360 term = PRODSUM2(var1digits, 0, var2digits, 1) + carry;
9361 res_digits[2] = (NumericDigit) (term % NBASE);
9362 carry = term / NBASE;
9363 /* FALLTHROUGH */
9364 case 2:
9365 term = PRODSUM1(var1digits, 0, var2digits, 0) + carry;
9366 res_digits[1] = (NumericDigit) (term % NBASE);
9367 res_digits[0] = (NumericDigit) (term / NBASE);
9368 break;
9369 }
9370
9371 /* Store the product in result */
9372 digitbuf_free(result->buf);
9373 result->ndigits = res_ndigits;
9374 result->buf = res_buf;
9375 result->digits = res_digits;
9376 result->weight = res_weight;
9377 result->sign = res_sign;
9378 result->dscale = var1->dscale + var2->dscale;
9379
9380 /* Strip leading and trailing zeroes */
9381 strip_var(result);
9382 }
9383
9384
9385 /*
9386 * div_var() -
9387 *
9388 * Compute the quotient var1 / var2 to rscale fractional digits.
9389 *
9390 * If "round" is true, the result is rounded at the rscale'th digit; if
9391 * false, it is truncated (towards zero) at that digit.
9392 *
9393 * If "exact" is true, the exact result is computed to the specified rscale;
9394 * if false, successive quotient digits are approximated up to rscale plus
9395 * DIV_GUARD_DIGITS extra digits, ignoring all contributions from digits to
9396 * the right of that, before rounding or truncating to the specified rscale.
9397 * This can be significantly faster, and usually gives the same result as the
9398 * exact computation, but it may occasionally be off by one in the final
9399 * digit, if contributions from the ignored digits would have propagated
9400 * through the guard digits. This is good enough for the transcendental
9401 * functions, where small errors are acceptable.
9402 */
9403 static void
9404 div_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result,
9405 int rscale, bool round, bool exact)
9406 {
9407 int var1ndigits = var1->ndigits;
9408 int var2ndigits = var2->ndigits;
9409 int res_sign;
9410 int res_weight;
9411 int res_ndigits;
9412 int var1ndigitpairs;
9413 int var2ndigitpairs;
9414 int res_ndigitpairs;
9415 int div_ndigitpairs;
9416 int64 *dividend;
9417 int32 *divisor;
9418 double fdivisor,
9419 fdivisorinverse,
9420 fdividend,
9421 fquotient;
9422 int64 maxdiv;
9423 int qi;
9424 int32 qdigit;
9425 int64 carry;
9426 int64 newdig;
9427 int64 *remainder;
9428 NumericDigit *res_digits;
9429 int i;
9430
9431 /*
9432 * First of all division by zero check; we must not be handed an
9433 * unnormalized divisor.
9434 */
9435 if (var2ndigits == 0 || var2->digits[0] == 0)
9436 ereport(ERROR,
9437 (errcode(ERRCODE_DIVISION_BY_ZERO),
9438 errmsg("division by zero")));
9439
9440 /*
9441 * If the divisor has just one or two digits, delegate to div_var_int(),
9442 * which uses fast short division.
9443 *
9444 * Similarly, on platforms with 128-bit integer support, delegate to
9445 * div_var_int64() for divisors with three or four digits.
9446 */
9447 if (var2ndigits <= 2)
9448 {
9449 int idivisor;
9450 int idivisor_weight;
9451
9452 idivisor = var2->digits[0];
9453 idivisor_weight = var2->weight;
9454 if (var2ndigits == 2)
9455 {
9456 idivisor = idivisor * NBASE + var2->digits[1];
9457 idivisor_weight--;
9458 }
9459 if (var2->sign == NUMERIC_NEG)
9460 idivisor = -idivisor;
9461
9462 div_var_int(var1, idivisor, idivisor_weight, result, rscale, round);
9463 return;
9464 }
9465 #ifdef HAVE_INT128
9466 if (var2ndigits <= 4)
9467 {
9468 int64 idivisor;
9469 int idivisor_weight;
9470
9471 idivisor = var2->digits[0];
9472 idivisor_weight = var2->weight;
9473 for (i = 1; i < var2ndigits; i++)
9474 {
9475 idivisor = idivisor * NBASE + var2->digits[i];
9476 idivisor_weight--;
9477 }
9478 if (var2->sign == NUMERIC_NEG)
9479 idivisor = -idivisor;
9480
9481 div_var_int64(var1, idivisor, idivisor_weight, result, rscale, round);
9482 return;
9483 }
9484 #endif
9485
9486 /*
9487 * Otherwise, perform full long division.
9488 */
9489
9490 /* Result zero check */
9491 if (var1ndigits == 0)
9492 {
9493 zero_var(result);
9494 result->dscale = rscale;
9495 return;
9496 }
9497
9498 /*
9499 * The approximate computation can be significantly faster than the exact
9500 * one, since the working dividend is var2ndigitpairs base-NBASE^2 digits
9501 * shorter below. However, that comes with the tradeoff of computing
9502 * DIV_GUARD_DIGITS extra base-NBASE result digits. Ignoring all other
9503 * overheads, that suggests that, in theory, the approximate computation
9504 * will only be faster than the exact one when var2ndigits is greater than
9505 * 2 * (DIV_GUARD_DIGITS + 1), independent of the size of var1.
9506 *
9507 * Thus, we're better off doing an exact computation when var2 is shorter
9508 * than this. Empirically, it has been found that the exact threshold is
9509 * a little higher, due to other overheads in the outer division loop.
9510 */
9511 if (var2ndigits <= 2 * (DIV_GUARD_DIGITS + 2))
9512 exact = true;
9513
9514 /*
9515 * Determine the result sign, weight and number of digits to calculate.
9516 * The weight figured here is correct if the emitted quotient has no
9517 * leading zero digits; otherwise strip_var() will fix things up.
9518 */
9519 if (var1->sign == var2->sign)
9520 res_sign = NUMERIC_POS;
9521 else
9522 res_sign = NUMERIC_NEG;
9523 res_weight = var1->weight - var2->weight + 1;
9524 /* The number of accurate result digits we need to produce: */
9525 res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
9526 /* ... but always at least 1 */
9527 res_ndigits = Max(res_ndigits, 1);
9528 /* If rounding needed, figure one more digit to ensure correct result */
9529 if (round)
9530 res_ndigits++;
9531 /* Add guard digits for roundoff error when producing approx result */
9532 if (!exact)
9533 res_ndigits += DIV_GUARD_DIGITS;
9534
9535 /*
9536 * The computation itself is done using base-NBASE^2 arithmetic, so we
9537 * actually process the input digits in pairs, producing a base-NBASE^2
9538 * intermediate result. This significantly improves performance, since
9539 * the computation is O(N^2) in the number of input digits, and working in
9540 * base NBASE^2 effectively halves "N".
9541 */
9542 var1ndigitpairs = (var1ndigits + 1) / 2;
9543 var2ndigitpairs = (var2ndigits + 1) / 2;
9544 res_ndigitpairs = (res_ndigits + 1) / 2;
9545 res_ndigits = 2 * res_ndigitpairs;
9546
9547 /*
9548 * We do the arithmetic in an array "dividend[]" of signed 64-bit
9549 * integers. Since PG_INT64_MAX is much larger than NBASE^4, this gives
9550 * us a lot of headroom to avoid normalizing carries immediately.
9551 *
9552 * When performing an exact computation, the working dividend requires
9553 * res_ndigitpairs + var2ndigitpairs digits. If var1 is larger than that,
9554 * the extra digits do not contribute to the result, and are ignored.
9555 *
9556 * When performing an approximate computation, the working dividend only
9557 * requires res_ndigitpairs digits (which includes the extra guard
9558 * digits). All input digits beyond that are ignored.
9559 */
9560 if (exact)
9561 {
9562 div_ndigitpairs = res_ndigitpairs + var2ndigitpairs;
9563 var1ndigitpairs = Min(var1ndigitpairs, div_ndigitpairs);
9564 }
9565 else
9566 {
9567 div_ndigitpairs = res_ndigitpairs;
9568 var1ndigitpairs = Min(var1ndigitpairs, div_ndigitpairs);
9569 var2ndigitpairs = Min(var2ndigitpairs, div_ndigitpairs);
9570 }
9571
9572 /*
9573 * Allocate room for the working dividend (div_ndigitpairs 64-bit digits)
9574 * plus the divisor (var2ndigitpairs 32-bit base-NBASE^2 digits).
9575 *
9576 * For convenience, we allocate one extra dividend digit, which is set to
9577 * zero and not counted in div_ndigitpairs, so that the main loop below
9578 * can safely read and write the (qi+1)'th digit in the approximate case.
9579 */
9580 dividend = (int64 *) palloc((div_ndigitpairs + 1) * sizeof(int64) +
9581 var2ndigitpairs * sizeof(int32));
9582 divisor = (int32 *) (dividend + div_ndigitpairs + 1);
9583
9584 /* load var1 into dividend[0 .. var1ndigitpairs-1], zeroing the rest */
9585 for (i = 0; i < var1ndigitpairs - 1; i++)
9586 dividend[i] = var1->digits[2 * i] * NBASE + var1->digits[2 * i + 1];
9587
9588 if (2 * i + 1 < var1ndigits)
9589 dividend[i] = var1->digits[2 * i] * NBASE + var1->digits[2 * i + 1];
9590 else
9591 dividend[i] = var1->digits[2 * i] * NBASE;
9592
9593 memset(dividend + i + 1, 0, (div_ndigitpairs - i) * sizeof(int64));
9594
9595 /* load var2 into divisor[0 .. var2ndigitpairs-1] */
9596 for (i = 0; i < var2ndigitpairs - 1; i++)
9597 divisor[i] = var2->digits[2 * i] * NBASE + var2->digits[2 * i + 1];
9598
9599 if (2 * i + 1 < var2ndigits)
9600 divisor[i] = var2->digits[2 * i] * NBASE + var2->digits[2 * i + 1];
9601 else
9602 divisor[i] = var2->digits[2 * i] * NBASE;
9603
9604 /*
9605 * We estimate each quotient digit using floating-point arithmetic, taking
9606 * the first 2 base-NBASE^2 digits of the (current) dividend and divisor.
9607 * This must be float to avoid overflow.
9608 *
9609 * Since the floating-point dividend and divisor use 4 base-NBASE input
9610 * digits, they include roughly 40-53 bits of information from their
9611 * respective inputs (assuming NBASE is 10000), which fits well in IEEE
9612 * double-precision variables. The relative error in the floating-point
9613 * quotient digit will then be less than around 2/NBASE^3, so the
9614 * estimated base-NBASE^2 quotient digit will typically be correct, and
9615 * should not be off by more than one from the correct value.
9616 */
9617 fdivisor = (double) divisor[0] * NBASE_SQR;
9618 if (var2ndigitpairs > 1)
9619 fdivisor += (double) divisor[1];
9620 fdivisorinverse = 1.0 / fdivisor;
9621
9622 /*
9623 * maxdiv tracks the maximum possible absolute value of any dividend[]
9624 * entry; when this threatens to exceed PG_INT64_MAX, we take the time to
9625 * propagate carries. Furthermore, we need to ensure that overflow
9626 * doesn't occur during the carry propagation passes either. The carry
9627 * values may have an absolute value as high as PG_INT64_MAX/NBASE^2 + 1,
9628 * so really we must normalize when digits threaten to exceed PG_INT64_MAX
9629 * - PG_INT64_MAX/NBASE^2 - 1.
9630 *
9631 * To avoid overflow in maxdiv itself, it represents the max absolute
9632 * value divided by NBASE^2-1, i.e., at the top of the loop it is known
9633 * that no dividend[] entry has an absolute value exceeding maxdiv *
9634 * (NBASE^2-1).
9635 *
9636 * Actually, though, that holds good only for dividend[] entries after
9637 * dividend[qi]; the adjustment done at the bottom of the loop may cause
9638 * dividend[qi + 1] to exceed the maxdiv limit, so that dividend[qi] in
9639 * the next iteration is beyond the limit. This does not cause problems,
9640 * as explained below.
9641 */
9642 maxdiv = 1;
9643
9644 /*
9645 * Outer loop computes next quotient digit, which goes in dividend[qi].
9646 */
9647 for (qi = 0; qi < res_ndigitpairs; qi++)
9648 {
9649 /* Approximate the current dividend value */
9650 fdividend = (double) dividend[qi] * NBASE_SQR;
9651 fdividend += (double) dividend[qi + 1];
9652
9653 /* Compute the (approximate) quotient digit */
9654 fquotient = fdividend * fdivisorinverse;
9655 qdigit = (fquotient >= 0.0) ? ((int32) fquotient) :
9656 (((int32) fquotient) - 1); /* truncate towards -infinity */
9657
9658 if (qdigit != 0)
9659 {
9660 /* Do we need to normalize now? */
9661 maxdiv += i64abs(qdigit);
9662 if (maxdiv > (PG_INT64_MAX - PG_INT64_MAX / NBASE_SQR - 1) / (NBASE_SQR - 1))
9663 {
9664 /*
9665 * Yes, do it. Note that if var2ndigitpairs is much smaller
9666 * than div_ndigitpairs, we can save a significant amount of
9667 * effort here by noting that we only need to normalise those
9668 * dividend[] entries touched where prior iterations
9669 * subtracted multiples of the divisor.
9670 */
9671 carry = 0;
9672 for (i = Min(qi + var2ndigitpairs - 2, div_ndigitpairs - 1); i > qi; i--)
9673 {
9674 newdig = dividend[i] + carry;
9675 if (newdig < 0)
9676 {
9677 carry = -((-newdig - 1) / NBASE_SQR) - 1;
9678 newdig -= carry * NBASE_SQR;
9679 }
9680 else if (newdig >= NBASE_SQR)
9681 {
9682 carry = newdig / NBASE_SQR;
9683 newdig -= carry * NBASE_SQR;
9684 }
9685 else
9686 carry = 0;
9687 dividend[i] = newdig;
9688 }
9689 dividend[qi] += carry;
9690
9691 /*
9692 * All the dividend[] digits except possibly dividend[qi] are
9693 * now in the range 0..NBASE^2-1. We do not need to consider
9694 * dividend[qi] in the maxdiv value anymore, so we can reset
9695 * maxdiv to 1.
9696 */
9697 maxdiv = 1;
9698
9699 /*
9700 * Recompute the quotient digit since new info may have
9701 * propagated into the top two dividend digits.
9702 */
9703 fdividend = (double) dividend[qi] * NBASE_SQR;
9704 fdividend += (double) dividend[qi + 1];
9705 fquotient = fdividend * fdivisorinverse;
9706 qdigit = (fquotient >= 0.0) ? ((int32) fquotient) :
9707 (((int32) fquotient) - 1); /* truncate towards -infinity */
9708
9709 maxdiv += i64abs(qdigit);
9710 }
9711
9712 /*
9713 * Subtract off the appropriate multiple of the divisor.
9714 *
9715 * The digits beyond dividend[qi] cannot overflow, because we know
9716 * they will fall within the maxdiv limit. As for dividend[qi]
9717 * itself, note that qdigit is approximately trunc(dividend[qi] /
9718 * divisor[0]), which would make the new value simply dividend[qi]
9719 * mod divisor[0]. The lower-order terms in qdigit can change
9720 * this result by not more than about twice PG_INT64_MAX/NBASE^2,
9721 * so overflow is impossible.
9722 *
9723 * This inner loop is the performance bottleneck for division, so
9724 * code it in the same way as the inner loop of mul_var() so that
9725 * it can be auto-vectorized.
9726 */
9727 if (qdigit != 0)
9728 {
9729 int istop = Min(var2ndigitpairs, div_ndigitpairs - qi);
9730 int64 *dividend_qi = &dividend[qi];
9731
9732 for (i = 0; i < istop; i++)
9733 dividend_qi[i] -= (int64) qdigit * divisor[i];
9734 }
9735 }
9736
9737 /*
9738 * The dividend digit we are about to replace might still be nonzero.
9739 * Fold it into the next digit position.
9740 *
9741 * There is no risk of overflow here, although proving that requires
9742 * some care. Much as with the argument for dividend[qi] not
9743 * overflowing, if we consider the first two terms in the numerator
9744 * and denominator of qdigit, we can see that the final value of
9745 * dividend[qi + 1] will be approximately a remainder mod
9746 * (divisor[0]*NBASE^2 + divisor[1]). Accounting for the lower-order
9747 * terms is a bit complicated but ends up adding not much more than
9748 * PG_INT64_MAX/NBASE^2 to the possible range. Thus, dividend[qi + 1]
9749 * cannot overflow here, and in its role as dividend[qi] in the next
9750 * loop iteration, it can't be large enough to cause overflow in the
9751 * carry propagation step (if any), either.
9752 *
9753 * But having said that: dividend[qi] can be more than
9754 * PG_INT64_MAX/NBASE^2, as noted above, which means that the product
9755 * dividend[qi] * NBASE^2 *can* overflow. When that happens, adding
9756 * it to dividend[qi + 1] will always cause a canceling overflow so
9757 * that the end result is correct. We could avoid the intermediate
9758 * overflow by doing the multiplication and addition using unsigned
9759 * int64 arithmetic, which is modulo 2^64, but so far there appears no
9760 * need.
9761 */
9762 dividend[qi + 1] += dividend[qi] * NBASE_SQR;
9763
9764 dividend[qi] = qdigit;
9765 }
9766
9767 /*
9768 * If an exact result was requested, use the remainder to correct the
9769 * approximate quotient. The remainder is in dividend[], immediately
9770 * after the quotient digits. Note, however, that although the remainder
9771 * starts at dividend[qi = res_ndigitpairs], the first digit is the result
9772 * of folding two remainder digits into one above, and the remainder
9773 * currently only occupies var2ndigitpairs - 1 digits (the last digit of
9774 * the working dividend was untouched by the computation above). Thus we
9775 * expand the remainder down by one base-NBASE^2 digit when we normalize
9776 * it, so that it completely fills the last var2ndigitpairs digits of the
9777 * dividend array.
9778 */
9779 if (exact)
9780 {
9781 /* Normalize the remainder, expanding it down by one digit */
9782 remainder = &dividend[qi];
9783 carry = 0;
9784 for (i = var2ndigitpairs - 2; i >= 0; i--)
9785 {
9786 newdig = remainder[i] + carry;
9787 if (newdig < 0)
9788 {
9789 carry = -((-newdig - 1) / NBASE_SQR) - 1;
9790 newdig -= carry * NBASE_SQR;
9791 }
9792 else if (newdig >= NBASE_SQR)
9793 {
9794 carry = newdig / NBASE_SQR;
9795 newdig -= carry * NBASE_SQR;
9796 }
9797 else
9798 carry = 0;
9799 remainder[i + 1] = newdig;
9800 }
9801 remainder[0] = carry;
9802
9803 if (remainder[0] < 0)
9804 {
9805 /*
9806 * The remainder is negative, so the approximate quotient is too
9807 * large. Correct by reducing the quotient by one and adding the
9808 * divisor to the remainder until the remainder is positive. We
9809 * expect the quotient to be off by at most one, which has been
9810 * borne out in all testing, but not conclusively proven, so we
9811 * allow for larger corrections, just in case.
9812 */
9813 do
9814 {
9815 /* Add the divisor to the remainder */
9816 carry = 0;
9817 for (i = var2ndigitpairs - 1; i > 0; i--)
9818 {
9819 newdig = remainder[i] + divisor[i] + carry;
9820 if (newdig >= NBASE_SQR)
9821 {
9822 remainder[i] = newdig - NBASE_SQR;
9823 carry = 1;
9824 }
9825 else
9826 {
9827 remainder[i] = newdig;
9828 carry = 0;
9829 }
9830 }
9831 remainder[0] += divisor[0] + carry;
9832
9833 /* Subtract 1 from the quotient (propagating carries later) */
9834 dividend[qi - 1]--;
9835
9836 } while (remainder[0] < 0);
9837 }
9838 else
9839 {
9840 /*
9841 * The remainder is nonnegative. If it's greater than or equal to
9842 * the divisor, then the approximate quotient is too small and
9843 * must be corrected. As above, we don't expect to have to apply
9844 * more than one correction, but allow for it just in case.
9845 */
9846 while (true)
9847 {
9848 bool less = false;
9849
9850 /* Is remainder < divisor? */
9851 for (i = 0; i < var2ndigitpairs; i++)
9852 {
9853 if (remainder[i] < divisor[i])
9854 {
9855 less = true;
9856 break;
9857 }
9858 if (remainder[i] > divisor[i])
9859 break; /* remainder > divisor */
9860 }
9861 if (less)
9862 break; /* quotient is correct */
9863
9864 /* Subtract the divisor from the remainder */
9865 carry = 0;
9866 for (i = var2ndigitpairs - 1; i > 0; i--)
9867 {
9868 newdig = remainder[i] - divisor[i] + carry;
9869 if (newdig < 0)
9870 {
9871 remainder[i] = newdig + NBASE_SQR;
9872 carry = -1;
9873 }
9874 else
9875 {
9876 remainder[i] = newdig;
9877 carry = 0;
9878 }
9879 }
9880 remainder[0] = remainder[0] - divisor[0] + carry;
9881
9882 /* Add 1 to the quotient (propagating carries later) */
9883 dividend[qi - 1]++;
9884 }
9885 }
9886 }
9887
9888 /*
9889 * Because the quotient digits were estimates that might have been off by
9890 * one (and we didn't bother propagating carries when adjusting the
9891 * quotient above), some quotient digits might be out of range, so do a
9892 * final carry propagation pass to normalize back to base NBASE^2, and
9893 * construct the base-NBASE result digits. Note that this is still done
9894 * at full precision w/guard digits.
9895 */
9896 alloc_var(result, res_ndigits);
9897 res_digits = result->digits;
9898 carry = 0;
9899 for (i = res_ndigitpairs - 1; i >= 0; i--)
9900 {
9901 newdig = dividend[i] + carry;
9902 if (newdig < 0)
9903 {
9904 carry = -((-newdig - 1) / NBASE_SQR) - 1;
9905 newdig -= carry * NBASE_SQR;
9906 }
9907 else if (newdig >= NBASE_SQR)
9908 {
9909 carry = newdig / NBASE_SQR;
9910 newdig -= carry * NBASE_SQR;
9911 }
9912 else
9913 carry = 0;
9914 res_digits[2 * i + 1] = (NumericDigit) ((uint32) newdig % NBASE);
9915 res_digits[2 * i] = (NumericDigit) ((uint32) newdig / NBASE);
9916 }
9917 Assert(carry == 0);
9918
9919 pfree(dividend);
9920
9921 /*
9922 * Finally, round or truncate the result to the requested precision.
9923 */
9924 result->weight = res_weight;
9925 result->sign = res_sign;
9926
9927 /* Round or truncate to target rscale (and set result->dscale) */
9928 if (round)
9929 round_var(result, rscale);
9930 else
9931 trunc_var(result, rscale);
9932
9933 /* Strip leading and trailing zeroes */
9934 strip_var(result);
9935 }
9936
9937
9938 /*
9939 * div_var_int() -
9940 *
9941 * Divide a numeric variable by a 32-bit integer with the specified weight.
9942 * The quotient var / (ival * NBASE^ival_weight) is stored in result.
9943 */
9944 static void
9945 div_var_int(const NumericVar *var, int ival, int ival_weight,
9946 NumericVar *result, int rscale, bool round)
9947 {
9948 NumericDigit *var_digits = var->digits;
9949 int var_ndigits = var->ndigits;
9950 int res_sign;
9951 int res_weight;
9952 int res_ndigits;
9953 NumericDigit *res_buf;
9954 NumericDigit *res_digits;
9955 uint32 divisor;
9956 int i;
9957
9958 /* Guard against division by zero */
9959 if (ival == 0)
9960 ereport(ERROR,
9961 errcode(ERRCODE_DIVISION_BY_ZERO),
9962 errmsg("division by zero"));
9963
9964 /* Result zero check */
9965 if (var_ndigits == 0)
9966 {
9967 zero_var(result);
9968 result->dscale = rscale;
9969 return;
9970 }
9971
9972 /*
9973 * Determine the result sign, weight and number of digits to calculate.
9974 * The weight figured here is correct if the emitted quotient has no
9975 * leading zero digits; otherwise strip_var() will fix things up.
9976 */
9977 if (var->sign == NUMERIC_POS)
9978 res_sign = ival > 0 ? NUMERIC_POS : NUMERIC_NEG;
9979 else
9980 res_sign = ival > 0 ? NUMERIC_NEG : NUMERIC_POS;
9981 res_weight = var->weight - ival_weight;
9982 /* The number of accurate result digits we need to produce: */
9983 res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
9984 /* ... but always at least 1 */
9985 res_ndigits = Max(res_ndigits, 1);
9986 /* If rounding needed, figure one more digit to ensure correct result */
9987 if (round)
9988 res_ndigits++;
9989
9990 res_buf = digitbuf_alloc(res_ndigits + 1);
9991 res_buf[0] = 0; /* spare digit for later rounding */
9992 res_digits = res_buf + 1;
9993
9994 /*
9995 * Now compute the quotient digits. This is the short division algorithm
9996 * described in Knuth volume 2, section 4.3.1 exercise 16, except that we
9997 * allow the divisor to exceed the internal base.
9998 *
9999 * In this algorithm, the carry from one digit to the next is at most
10000 * divisor - 1. Therefore, while processing the next digit, carry may
10001 * become as large as divisor * NBASE - 1, and so it requires a 64-bit
10002 * integer if this exceeds UINT_MAX.
10003 */
10004 divisor = abs(ival);
10005
10006 if (divisor <= UINT_MAX / NBASE)
10007 {
10008 /* carry cannot overflow 32 bits */
10009 uint32 carry = 0;
10010
10011 for (i = 0; i < res_ndigits; i++)
10012 {
10013 carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
10014 res_digits[i] = (NumericDigit) (carry / divisor);
10015 carry = carry % divisor;
10016 }
10017 }
10018 else
10019 {
10020 /* carry may exceed 32 bits */
10021 uint64 carry = 0;
10022
10023 for (i = 0; i < res_ndigits; i++)
10024 {
10025 carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
10026 res_digits[i] = (NumericDigit) (carry / divisor);
10027 carry = carry % divisor;
10028 }
10029 }
10030
10031 /* Store the quotient in result */
10032 digitbuf_free(result->buf);
10033 result->ndigits = res_ndigits;
10034 result->buf = res_buf;
10035 result->digits = res_digits;
10036 result->weight = res_weight;
10037 result->sign = res_sign;
10038
10039 /* Round or truncate to target rscale (and set result->dscale) */
10040 if (round)
10041 round_var(result, rscale);
10042 else
10043 trunc_var(result, rscale);
10044
10045 /* Strip leading/trailing zeroes */
10046 strip_var(result);
10047 }
10048
10049
10050 #ifdef HAVE_INT128
10051 /*
10052 * div_var_int64() -
10053 *
10054 * Divide a numeric variable by a 64-bit integer with the specified weight.
10055 * The quotient var / (ival * NBASE^ival_weight) is stored in result.
10056 *
10057 * This duplicates the logic in div_var_int(), so any changes made there
10058 * should be made here too.
10059 */
10060 static void
10061 div_var_int64(const NumericVar *var, int64 ival, int ival_weight,
10062 NumericVar *result, int rscale, bool round)
10063 {
10064 NumericDigit *var_digits = var->digits;
10065 int var_ndigits = var->ndigits;
10066 int res_sign;
10067 int res_weight;
10068 int res_ndigits;
10069 NumericDigit *res_buf;
10070 NumericDigit *res_digits;
10071 uint64 divisor;
10072 int i;
10073
10074 /* Guard against division by zero */
10075 if (ival == 0)
10076 ereport(ERROR,
10077 errcode(ERRCODE_DIVISION_BY_ZERO),
10078 errmsg("division by zero"));
10079
10080 /* Result zero check */
10081 if (var_ndigits == 0)
10082 {
10083 zero_var(result);
10084 result->dscale = rscale;
10085 return;
10086 }
10087
10088 /*
10089 * Determine the result sign, weight and number of digits to calculate.
10090 * The weight figured here is correct if the emitted quotient has no
10091 * leading zero digits; otherwise strip_var() will fix things up.
10092 */
10093 if (var->sign == NUMERIC_POS)
10094 res_sign = ival > 0 ? NUMERIC_POS : NUMERIC_NEG;
10095 else
10096 res_sign = ival > 0 ? NUMERIC_NEG : NUMERIC_POS;
10097 res_weight = var->weight - ival_weight;
10098 /* The number of accurate result digits we need to produce: */
10099 res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
10100 /* ... but always at least 1 */
10101 res_ndigits = Max(res_ndigits, 1);
10102 /* If rounding needed, figure one more digit to ensure correct result */
10103 if (round)
10104 res_ndigits++;
10105
10106 res_buf = digitbuf_alloc(res_ndigits + 1);
10107 res_buf[0] = 0; /* spare digit for later rounding */
10108 res_digits = res_buf + 1;
10109
10110 /*
10111 * Now compute the quotient digits. This is the short division algorithm
10112 * described in Knuth volume 2, section 4.3.1 exercise 16, except that we
10113 * allow the divisor to exceed the internal base.
10114 *
10115 * In this algorithm, the carry from one digit to the next is at most
10116 * divisor - 1. Therefore, while processing the next digit, carry may
10117 * become as large as divisor * NBASE - 1, and so it requires a 128-bit
10118 * integer if this exceeds PG_UINT64_MAX.
10119 */
10120 divisor = i64abs(ival);
10121
10122 if (divisor <= PG_UINT64_MAX / NBASE)
10123 {
10124 /* carry cannot overflow 64 bits */
10125 uint64 carry = 0;
10126
10127 for (i = 0; i < res_ndigits; i++)
10128 {
10129 carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
10130 res_digits[i] = (NumericDigit) (carry / divisor);
10131 carry = carry % divisor;
10132 }
10133 }
10134 else
10135 {
10136 /* carry may exceed 64 bits */
10137 uint128 carry = 0;
10138
10139 for (i = 0; i < res_ndigits; i++)
10140 {
10141 carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
10142 res_digits[i] = (NumericDigit) (carry / divisor);
10143 carry = carry % divisor;
10144 }
10145 }
10146
10147 /* Store the quotient in result */
10148 digitbuf_free(result->buf);
10149 result->ndigits = res_ndigits;
10150 result->buf = res_buf;
10151 result->digits = res_digits;
10152 result->weight = res_weight;
10153 result->sign = res_sign;
10154
10155 /* Round or truncate to target rscale (and set result->dscale) */
10156 if (round)
10157 round_var(result, rscale);
10158 else
10159 trunc_var(result, rscale);
10160
10161 /* Strip leading/trailing zeroes */
10162 strip_var(result);
10163 }
10164 #endif
10165
10166
10167 /*
10168 * Default scale selection for division
10169 *
10170 * Returns the appropriate result scale for the division result.
10171 */
10172 static int
10173 select_div_scale(const NumericVar *var1, const NumericVar *var2)
10174 {
10175 int weight1,
10176 weight2,
10177 qweight,
10178 i;
10179 NumericDigit firstdigit1,
10180 firstdigit2;
10181 int rscale;
10182
10183 /*
10184 * The result scale of a division isn't specified in any SQL standard. For
10185 * PostgreSQL we select a result scale that will give at least
10186 * NUMERIC_MIN_SIG_DIGITS significant digits, so that numeric gives a
10187 * result no less accurate than float8; but use a scale not less than
10188 * either input's display scale.
10189 */
10190
10191 /* Get the actual (normalized) weight and first digit of each input */
10192
10193 weight1 = 0; /* values to use if var1 is zero */
10194 firstdigit1 = 0;
10195 for (i = 0; i < var1->ndigits; i++)
10196 {
10197 firstdigit1 = var1->digits[i];
10198 if (firstdigit1 != 0)
10199 {
10200 weight1 = var1->weight - i;
10201 break;
10202 }
10203 }
10204
10205 weight2 = 0; /* values to use if var2 is zero */
10206 firstdigit2 = 0;
10207 for (i = 0; i < var2->ndigits; i++)
10208 {
10209 firstdigit2 = var2->digits[i];
10210 if (firstdigit2 != 0)
10211 {
10212 weight2 = var2->weight - i;
10213 break;
10214 }
10215 }
10216
10217 /*
10218 * Estimate weight of quotient. If the two first digits are equal, we
10219 * can't be sure, but assume that var1 is less than var2.
10220 */
10221 qweight = weight1 - weight2;
10222 if (firstdigit1 <= firstdigit2)
10223 qweight--;
10224
10225 /* Select result scale */
10226 rscale = NUMERIC_MIN_SIG_DIGITS - qweight * DEC_DIGITS;
10227 rscale = Max(rscale, var1->dscale);
10228 rscale = Max(rscale, var2->dscale);
10229 rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
10230 rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
10231
10232 return rscale;
10233 }
10234
10235
10236 /*
10237 * mod_var() -
10238 *
10239 * Calculate the modulo of two numerics at variable level
10240 */
10241 static void
10242 mod_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
10243 {
10244 NumericVar tmp;
10245
10246 init_var(&tmp);
10247
10248 /* ---------
10249 * We do this using the equation
10250 * mod(x,y) = x - trunc(x/y)*y
10251 * div_var can be persuaded to give us trunc(x/y) directly.
10252 * ----------
10253 */
10254 div_var(var1, var2, &tmp, 0, false, true);
10255
10256 mul_var(var2, &tmp, &tmp, var2->dscale);
10257
10258 sub_var(var1, &tmp, result);
10259
10260 free_var(&tmp);
10261 }
10262
10263
10264 /*
10265 * div_mod_var() -
10266 *
10267 * Calculate the truncated integer quotient and numeric remainder of two
10268 * numeric variables. The remainder is precise to var2's dscale.
10269 */
10270 static void
10271 div_mod_var(const NumericVar *var1, const NumericVar *var2,
10272 NumericVar *quot, NumericVar *rem)
10273 {
10274 NumericVar q;
10275 NumericVar r;
10276
10277 init_var(&q);
10278 init_var(&r);
10279
10280 /*
10281 * Use div_var() with exact = false to get an initial estimate for the
10282 * integer quotient (truncated towards zero). This might be slightly
10283 * inaccurate, but we correct it below.
10284 */
10285 div_var(var1, var2, &q, 0, false, false);
10286
10287 /* Compute initial estimate of remainder using the quotient estimate. */
10288 mul_var(var2, &q, &r, var2->dscale);
10289 sub_var(var1, &r, &r);
10290
10291 /*
10292 * Adjust the results if necessary --- the remainder should have the same
10293 * sign as var1, and its absolute value should be less than the absolute
10294 * value of var2.
10295 */
10296 while (r.ndigits != 0 && r.sign != var1->sign)
10297 {
10298 /* The absolute value of the quotient is too large */
10299 if (var1->sign == var2->sign)
10300 {
10301 sub_var(&q, &const_one, &q);
10302 add_var(&r, var2, &r);
10303 }
10304 else
10305 {
10306 add_var(&q, &const_one, &q);
10307 sub_var(&r, var2, &r);
10308 }
10309 }
10310
10311 while (cmp_abs(&r, var2) >= 0)
10312 {
10313 /* The absolute value of the quotient is too small */
10314 if (var1->sign == var2->sign)
10315 {
10316 add_var(&q, &const_one, &q);
10317 sub_var(&r, var2, &r);
10318 }
10319 else
10320 {
10321 sub_var(&q, &const_one, &q);
10322 add_var(&r, var2, &r);
10323 }
10324 }
10325
10326 set_var_from_var(&q, quot);
10327 set_var_from_var(&r, rem);
10328
10329 free_var(&q);
10330 free_var(&r);
10331 }
10332
10333
10334 /*
10335 * ceil_var() -
10336 *
10337 * Return the smallest integer greater than or equal to the argument
10338 * on variable level
10339 */
10340 static void
10341 ceil_var(const NumericVar *var, NumericVar *result)
10342 {
10343 NumericVar tmp;
10344
10345 init_var(&tmp);
10346 set_var_from_var(var, &tmp);
10347
10348 trunc_var(&tmp, 0);
10349
10350 if (var->sign == NUMERIC_POS && cmp_var(var, &tmp) != 0)
10351 add_var(&tmp, &const_one, &tmp);
10352
10353 set_var_from_var(&tmp, result);
10354 free_var(&tmp);
10355 }
10356
10357
10358 /*
10359 * floor_var() -
10360 *
10361 * Return the largest integer equal to or less than the argument
10362 * on variable level
10363 */
10364 static void
10365 floor_var(const NumericVar *var, NumericVar *result)
10366 {
10367 NumericVar tmp;
10368
10369 init_var(&tmp);
10370 set_var_from_var(var, &tmp);
10371
10372 trunc_var(&tmp, 0);
10373
10374 if (var->sign == NUMERIC_NEG && cmp_var(var, &tmp) != 0)
10375 sub_var(&tmp, &const_one, &tmp);
10376
10377 set_var_from_var(&tmp, result);
10378 free_var(&tmp);
10379 }
10380
10381
10382 /*
10383 * gcd_var() -
10384 *
10385 * Calculate the greatest common divisor of two numerics at variable level
10386 */
10387 static void
10388 gcd_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
10389 {
10390 int res_dscale;
10391 int cmp;
10392 NumericVar tmp_arg;
10393 NumericVar mod;
10394
10395 res_dscale = Max(var1->dscale, var2->dscale);
10396
10397 /*
10398 * Arrange for var1 to be the number with the greater absolute value.
10399 *
10400 * This would happen automatically in the loop below, but avoids an
10401 * expensive modulo operation.
10402 */
10403 cmp = cmp_abs(var1, var2);
10404 if (cmp < 0)
10405 {
10406 const NumericVar *tmp = var1;
10407
10408 var1 = var2;
10409 var2 = tmp;
10410 }
10411
10412 /*
10413 * Also avoid the taking the modulo if the inputs have the same absolute
10414 * value, or if the smaller input is zero.
10415 */
10416 if (cmp == 0 || var2->ndigits == 0)
10417 {
10418 set_var_from_var(var1, result);
10419 result->sign = NUMERIC_POS;
10420 result->dscale = res_dscale;
10421 return;
10422 }
10423
10424 init_var(&tmp_arg);
10425 init_var(&mod);
10426
10427 /* Use the Euclidean algorithm to find the GCD */
10428 set_var_from_var(var1, &tmp_arg);
10429 set_var_from_var(var2, result);
10430
10431 for (;;)
10432 {
10433 /* this loop can take a while, so allow it to be interrupted */
10434 CHECK_FOR_INTERRUPTS();
10435
10436 mod_var(&tmp_arg, result, &mod);
10437 if (mod.ndigits == 0)
10438 break;
10439 set_var_from_var(result, &tmp_arg);
10440 set_var_from_var(&mod, result);
10441 }
10442 result->sign = NUMERIC_POS;
10443 result->dscale = res_dscale;
10444
10445 free_var(&tmp_arg);
10446 free_var(&mod);
10447 }
10448
10449
10450 /*
10451 * sqrt_var() -
10452 *
10453 * Compute the square root of x using the Karatsuba Square Root algorithm.
10454 * NOTE: we allow rscale < 0 here, implying rounding before the decimal
10455 * point.
10456 */
10457 static void
10458 sqrt_var(const NumericVar *arg, NumericVar *result, int rscale)
10459 {
10460 int stat;
10461 int res_weight;
10462 int res_ndigits;
10463 int src_ndigits;
10464 int step;
10465 int ndigits[32];
10466 int blen;
10467 int64 arg_int64;
10468 int src_idx;
10469 int64 s_int64;
10470 int64 r_int64;
10471 NumericVar s_var;
10472 NumericVar r_var;
10473 NumericVar a0_var;
10474 NumericVar a1_var;
10475 NumericVar q_var;
10476 NumericVar u_var;
10477
10478 stat = cmp_var(arg, &const_zero);
10479 if (stat == 0)
10480 {
10481 zero_var(result);
10482 result->dscale = rscale;
10483 return;
10484 }
10485
10486 /*
10487 * SQL2003 defines sqrt() in terms of power, so we need to emit the right
10488 * SQLSTATE error code if the operand is negative.
10489 */
10490 if (stat < 0)
10491 ereport(ERROR,
10492 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
10493 errmsg("cannot take square root of a negative number")));
10494
10495 init_var(&s_var);
10496 init_var(&r_var);
10497 init_var(&a0_var);
10498 init_var(&a1_var);
10499 init_var(&q_var);
10500 init_var(&u_var);
10501
10502 /*
10503 * The result weight is half the input weight, rounded towards minus
10504 * infinity --- res_weight = floor(arg->weight / 2).
10505 */
10506 if (arg->weight >= 0)
10507 res_weight = arg->weight / 2;
10508 else
10509 res_weight = -((-arg->weight - 1) / 2 + 1);
10510
10511 /*
10512 * Number of NBASE digits to compute. To ensure correct rounding, compute
10513 * at least 1 extra decimal digit. We explicitly allow rscale to be
10514 * negative here, but must always compute at least 1 NBASE digit. Thus
10515 * res_ndigits = res_weight + 1 + ceil((rscale + 1) / DEC_DIGITS) or 1.
10516 */
10517 if (rscale + 1 >= 0)
10518 res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS) / DEC_DIGITS;
10519 else
10520 res_ndigits = res_weight + 1 - (-rscale - 1) / DEC_DIGITS;
10521 res_ndigits = Max(res_ndigits, 1);
10522
10523 /*
10524 * Number of source NBASE digits logically required to produce a result
10525 * with this precision --- every digit before the decimal point, plus 2
10526 * for each result digit after the decimal point (or minus 2 for each
10527 * result digit we round before the decimal point).
10528 */
10529 src_ndigits = arg->weight + 1 + (res_ndigits - res_weight - 1) * 2;
10530 src_ndigits = Max(src_ndigits, 1);
10531
10532 /* ----------
10533 * From this point on, we treat the input and the result as integers and
10534 * compute the integer square root and remainder using the Karatsuba
10535 * Square Root algorithm, which may be written recursively as follows:
10536 *
10537 * SqrtRem(n = a3*b^3 + a2*b^2 + a1*b + a0):
10538 * [ for some base b, and coefficients a0,a1,a2,a3 chosen so that
10539 * 0 <= a0,a1,a2 < b and a3 >= b/4 ]
10540 * Let (s,r) = SqrtRem(a3*b + a2)
10541 * Let (q,u) = DivRem(r*b + a1, 2*s)
10542 * Let s = s*b + q
10543 * Let r = u*b + a0 - q^2
10544 * If r < 0 Then
10545 * Let r = r + s
10546 * Let s = s - 1
10547 * Let r = r + s
10548 * Return (s,r)
10549 *
10550 * See "Karatsuba Square Root", Paul Zimmermann, INRIA Research Report
10551 * RR-3805, November 1999. At the time of writing this was available
10552 * on the net at <https://hal.inria.fr/inria-00072854>.
10553 *
10554 * The way to read the assumption "n = a3*b^3 + a2*b^2 + a1*b + a0" is
10555 * "choose a base b such that n requires at least four base-b digits to
10556 * express; then those digits are a3,a2,a1,a0, with a3 possibly larger
10557 * than b". For optimal performance, b should have approximately a
10558 * quarter the number of digits in the input, so that the outer square
10559 * root computes roughly twice as many digits as the inner one. For
10560 * simplicity, we choose b = NBASE^blen, an integer power of NBASE.
10561 *
10562 * We implement the algorithm iteratively rather than recursively, to
10563 * allow the working variables to be reused. With this approach, each
10564 * digit of the input is read precisely once --- src_idx tracks the number
10565 * of input digits used so far.
10566 *
10567 * The array ndigits[] holds the number of NBASE digits of the input that
10568 * will have been used at the end of each iteration, which roughly doubles
10569 * each time. Note that the array elements are stored in reverse order,
10570 * so if the final iteration requires src_ndigits = 37 input digits, the
10571 * array will contain [37,19,11,7,5,3], and we would start by computing
10572 * the square root of the 3 most significant NBASE digits.
10573 *
10574 * In each iteration, we choose blen to be the largest integer for which
10575 * the input number has a3 >= b/4, when written in the form above. In
10576 * general, this means blen = src_ndigits / 4 (truncated), but if
10577 * src_ndigits is a multiple of 4, that might lead to the coefficient a3
10578 * being less than b/4 (if the first input digit is less than NBASE/4), in
10579 * which case we choose blen = src_ndigits / 4 - 1. The number of digits
10580 * in the inner square root is then src_ndigits - 2*blen. So, for
10581 * example, if we have src_ndigits = 26 initially, the array ndigits[]
10582 * will be either [26,14,8,4] or [26,14,8,6,4], depending on the size of
10583 * the first input digit.
10584 *
10585 * Additionally, we can put an upper bound on the number of steps required
10586 * as follows --- suppose that the number of source digits is an n-bit
10587 * number in the range [2^(n-1), 2^n-1], then blen will be in the range
10588 * [2^(n-3)-1, 2^(n-2)-1] and the number of digits in the inner square
10589 * root will be in the range [2^(n-2), 2^(n-1)+1]. In the next step, blen
10590 * will be in the range [2^(n-4)-1, 2^(n-3)] and the number of digits in
10591 * the next inner square root will be in the range [2^(n-3), 2^(n-2)+1].
10592 * This pattern repeats, and in the worst case the array ndigits[] will
10593 * contain [2^n-1, 2^(n-1)+1, 2^(n-2)+1, ... 9, 5, 3], and the computation
10594 * will require n steps. Therefore, since all digit array sizes are
10595 * signed 32-bit integers, the number of steps required is guaranteed to
10596 * be less than 32.
10597 * ----------
10598 */
10599 step = 0;
10600 while ((ndigits[step] = src_ndigits) > 4)
10601 {
10602 /* Choose b so that a3 >= b/4, as described above */
10603 blen = src_ndigits / 4;
10604 if (blen * 4 == src_ndigits && arg->digits[0] < NBASE / 4)
10605 blen--;
10606
10607 /* Number of digits in the next step (inner square root) */
10608 src_ndigits -= 2 * blen;
10609 step++;
10610 }
10611
10612 /*
10613 * First iteration (innermost square root and remainder):
10614 *
10615 * Here src_ndigits <= 4, and the input fits in an int64. Its square root
10616 * has at most 9 decimal digits, so estimate it using double precision
10617 * arithmetic, which will in fact almost certainly return the correct
10618 * result with no further correction required.
10619 */
10620 arg_int64 = arg->digits[0];
10621 for (src_idx = 1; src_idx < src_ndigits; src_idx++)
10622 {
10623 arg_int64 *= NBASE;
10624 if (src_idx < arg->ndigits)
10625 arg_int64 += arg->digits[src_idx];
10626 }
10627
10628 s_int64 = (int64) sqrt((double) arg_int64);
10629 r_int64 = arg_int64 - s_int64 * s_int64;
10630
10631 /*
10632 * Use Newton's method to correct the result, if necessary.
10633 *
10634 * This uses integer division with truncation to compute the truncated
10635 * integer square root by iterating using the formula x -> (x + n/x) / 2.
10636 * This is known to converge to isqrt(n), unless n+1 is a perfect square.
10637 * If n+1 is a perfect square, the sequence will oscillate between the two
10638 * values isqrt(n) and isqrt(n)+1, so we can be assured of convergence by
10639 * checking the remainder.
10640 */
10641 while (r_int64 < 0 || r_int64 > 2 * s_int64)
10642 {
10643 s_int64 = (s_int64 + arg_int64 / s_int64) / 2;
10644 r_int64 = arg_int64 - s_int64 * s_int64;
10645 }
10646
10647 /*
10648 * Iterations with src_ndigits <= 8:
10649 *
10650 * The next 1 or 2 iterations compute larger (outer) square roots with
10651 * src_ndigits <= 8, so the result still fits in an int64 (even though the
10652 * input no longer does) and we can continue to compute using int64
10653 * variables to avoid more expensive numeric computations.
10654 *
10655 * It is fairly easy to see that there is no risk of the intermediate
10656 * values below overflowing 64-bit integers. In the worst case, the
10657 * previous iteration will have computed a 3-digit square root (of a
10658 * 6-digit input less than NBASE^6 / 4), so at the start of this
10659 * iteration, s will be less than NBASE^3 / 2 = 10^12 / 2, and r will be
10660 * less than 10^12. In this case, blen will be 1, so numer will be less
10661 * than 10^17, and denom will be less than 10^12 (and hence u will also be
10662 * less than 10^12). Finally, since q^2 = u*b + a0 - r, we can also be
10663 * sure that q^2 < 10^17. Therefore all these quantities fit comfortably
10664 * in 64-bit integers.
10665 */
10666 step--;
10667 while (step >= 0 && (src_ndigits = ndigits[step]) <= 8)
10668 {
10669 int b;
10670 int a0;
10671 int a1;
10672 int i;
10673 int64 numer;
10674 int64 denom;
10675 int64 q;
10676 int64 u;
10677
10678 blen = (src_ndigits - src_idx) / 2;
10679
10680 /* Extract a1 and a0, and compute b */
10681 a0 = 0;
10682 a1 = 0;
10683 b = 1;
10684
10685 for (i = 0; i < blen; i++, src_idx++)
10686 {
10687 b *= NBASE;
10688 a1 *= NBASE;
10689 if (src_idx < arg->ndigits)
10690 a1 += arg->digits[src_idx];
10691 }
10692
10693 for (i = 0; i < blen; i++, src_idx++)
10694 {
10695 a0 *= NBASE;
10696 if (src_idx < arg->ndigits)
10697 a0 += arg->digits[src_idx];
10698 }
10699
10700 /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
10701 numer = r_int64 * b + a1;
10702 denom = 2 * s_int64;
10703 q = numer / denom;
10704 u = numer - q * denom;
10705
10706 /* Compute s = s*b + q and r = u*b + a0 - q^2 */
10707 s_int64 = s_int64 * b + q;
10708 r_int64 = u * b + a0 - q * q;
10709
10710 if (r_int64 < 0)
10711 {
10712 /* s is too large by 1; set r += s, s--, r += s */
10713 r_int64 += s_int64;
10714 s_int64--;
10715 r_int64 += s_int64;
10716 }
10717
10718 Assert(src_idx == src_ndigits); /* All input digits consumed */
10719 step--;
10720 }
10721
10722 /*
10723 * On platforms with 128-bit integer support, we can further delay the
10724 * need to use numeric variables.
10725 */
10726 #ifdef HAVE_INT128
10727 if (step >= 0)
10728 {
10729 int128 s_int128;
10730 int128 r_int128;
10731
10732 s_int128 = s_int64;
10733 r_int128 = r_int64;
10734
10735 /*
10736 * Iterations with src_ndigits <= 16:
10737 *
10738 * The result fits in an int128 (even though the input doesn't) so we
10739 * use int128 variables to avoid more expensive numeric computations.
10740 */
10741 while (step >= 0 && (src_ndigits = ndigits[step]) <= 16)
10742 {
10743 int64 b;
10744 int64 a0;
10745 int64 a1;
10746 int64 i;
10747 int128 numer;
10748 int128 denom;
10749 int128 q;
10750 int128 u;
10751
10752 blen = (src_ndigits - src_idx) / 2;
10753
10754 /* Extract a1 and a0, and compute b */
10755 a0 = 0;
10756 a1 = 0;
10757 b = 1;
10758
10759 for (i = 0; i < blen; i++, src_idx++)
10760 {
10761 b *= NBASE;
10762 a1 *= NBASE;
10763 if (src_idx < arg->ndigits)
10764 a1 += arg->digits[src_idx];
10765 }
10766
10767 for (i = 0; i < blen; i++, src_idx++)
10768 {
10769 a0 *= NBASE;
10770 if (src_idx < arg->ndigits)
10771 a0 += arg->digits[src_idx];
10772 }
10773
10774 /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
10775 numer = r_int128 * b + a1;
10776 denom = 2 * s_int128;
10777 q = numer / denom;
10778 u = numer - q * denom;
10779
10780 /* Compute s = s*b + q and r = u*b + a0 - q^2 */
10781 s_int128 = s_int128 * b + q;
10782 r_int128 = u * b + a0 - q * q;
10783
10784 if (r_int128 < 0)
10785 {
10786 /* s is too large by 1; set r += s, s--, r += s */
10787 r_int128 += s_int128;
10788 s_int128--;
10789 r_int128 += s_int128;
10790 }
10791
10792 Assert(src_idx == src_ndigits); /* All input digits consumed */
10793 step--;
10794 }
10795
10796 /*
10797 * All remaining iterations require numeric variables. Convert the
10798 * integer values to NumericVar and continue. Note that in the final
10799 * iteration we don't need the remainder, so we can save a few cycles
10800 * there by not fully computing it.
10801 */
10802 int128_to_numericvar(s_int128, &s_var);
10803 if (step >= 0)
10804 int128_to_numericvar(r_int128, &r_var);
10805 }
10806 else
10807 {
10808 int64_to_numericvar(s_int64, &s_var);
10809 /* step < 0, so we certainly don't need r */
10810 }
10811 #else /* !HAVE_INT128 */
10812 int64_to_numericvar(s_int64, &s_var);
10813 if (step >= 0)
10814 int64_to_numericvar(r_int64, &r_var);
10815 #endif /* HAVE_INT128 */
10816
10817 /*
10818 * The remaining iterations with src_ndigits > 8 (or 16, if have int128)
10819 * use numeric variables.
10820 */
10821 while (step >= 0)
10822 {
10823 int tmp_len;
10824
10825 src_ndigits = ndigits[step];
10826 blen = (src_ndigits - src_idx) / 2;
10827
10828 /* Extract a1 and a0 */
10829 if (src_idx < arg->ndigits)
10830 {
10831 tmp_len = Min(blen, arg->ndigits - src_idx);
10832 alloc_var(&a1_var, tmp_len);
10833 memcpy(a1_var.digits, arg->digits + src_idx,
10834 tmp_len * sizeof(NumericDigit));
10835 a1_var.weight = blen - 1;
10836 a1_var.sign = NUMERIC_POS;
10837 a1_var.dscale = 0;
10838 strip_var(&a1_var);
10839 }
10840 else
10841 {
10842 zero_var(&a1_var);
10843 a1_var.dscale = 0;
10844 }
10845 src_idx += blen;
10846
10847 if (src_idx < arg->ndigits)
10848 {
10849 tmp_len = Min(blen, arg->ndigits - src_idx);
10850 alloc_var(&a0_var, tmp_len);
10851 memcpy(a0_var.digits, arg->digits + src_idx,
10852 tmp_len * sizeof(NumericDigit));
10853 a0_var.weight = blen - 1;
10854 a0_var.sign = NUMERIC_POS;
10855 a0_var.dscale = 0;
10856 strip_var(&a0_var);
10857 }
10858 else
10859 {
10860 zero_var(&a0_var);
10861 a0_var.dscale = 0;
10862 }
10863 src_idx += blen;
10864
10865 /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
10866 set_var_from_var(&r_var, &q_var);
10867 q_var.weight += blen;
10868 add_var(&q_var, &a1_var, &q_var);
10869 add_var(&s_var, &s_var, &u_var);
10870 div_mod_var(&q_var, &u_var, &q_var, &u_var);
10871
10872 /* Compute s = s*b + q */
10873 s_var.weight += blen;
10874 add_var(&s_var, &q_var, &s_var);
10875
10876 /*
10877 * Compute r = u*b + a0 - q^2.
10878 *
10879 * In the final iteration, we don't actually need r; we just need to
10880 * know whether it is negative, so that we know whether to adjust s.
10881 * So instead of the final subtraction we can just compare.
10882 */
10883 u_var.weight += blen;
10884 add_var(&u_var, &a0_var, &u_var);
10885 mul_var(&q_var, &q_var, &q_var, 0);
10886
10887 if (step > 0)
10888 {
10889 /* Need r for later iterations */
10890 sub_var(&u_var, &q_var, &r_var);
10891 if (r_var.sign == NUMERIC_NEG)
10892 {
10893 /* s is too large by 1; set r += s, s--, r += s */
10894 add_var(&r_var, &s_var, &r_var);
10895 sub_var(&s_var, &const_one, &s_var);
10896 add_var(&r_var, &s_var, &r_var);
10897 }
10898 }
10899 else
10900 {
10901 /* Don't need r anymore, except to test if s is too large by 1 */
10902 if (cmp_var(&u_var, &q_var) < 0)
10903 sub_var(&s_var, &const_one, &s_var);
10904 }
10905
10906 Assert(src_idx == src_ndigits); /* All input digits consumed */
10907 step--;
10908 }
10909
10910 /*
10911 * Construct the final result, rounding it to the requested precision.
10912 */
10913 set_var_from_var(&s_var, result);
10914 result->weight = res_weight;
10915 result->sign = NUMERIC_POS;
10916
10917 /* Round to target rscale (and set result->dscale) */
10918 round_var(result, rscale);
10919
10920 /* Strip leading and trailing zeroes */
10921 strip_var(result);
10922
10923 free_var(&s_var);
10924 free_var(&r_var);
10925 free_var(&a0_var);
10926 free_var(&a1_var);
10927 free_var(&q_var);
10928 free_var(&u_var);
10929 }
10930
10931
10932 /*
10933 * exp_var() -
10934 *
10935 * Raise e to the power of x, computed to rscale fractional digits
10936 */
10937 static void
10938 exp_var(const NumericVar *arg, NumericVar *result, int rscale)
10939 {
10940 NumericVar x;
10941 NumericVar elem;
10942 int ni;
10943 double val;
10944 int dweight;
10945 int ndiv2;
10946 int sig_digits;
10947 int local_rscale;
10948
10949 init_var(&x);
10950 init_var(&elem);
10951
10952 set_var_from_var(arg, &x);
10953
10954 /*
10955 * Estimate the dweight of the result using floating point arithmetic, so
10956 * that we can choose an appropriate local rscale for the calculation.
10957 */
10958 val = numericvar_to_double_no_overflow(&x);
10959
10960 /* Guard against overflow/underflow */
10961 /* If you change this limit, see also power_var()'s limit */
10962 if (fabs(val) >= NUMERIC_MAX_RESULT_SCALE * 3)
10963 {
10964 if (val > 0)
10965 ereport(ERROR,
10966 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
10967 errmsg("value overflows numeric format")));
10968 zero_var(result);
10969 result->dscale = rscale;
10970 return;
10971 }
10972
10973 /* decimal weight = log10(e^x) = x * log10(e) */
10974 dweight = (int) (val * 0.434294481903252);
10975
10976 /*
10977 * Reduce x to the range -0.01 <= x <= 0.01 (approximately) by dividing by
10978 * 2^ndiv2, to improve the convergence rate of the Taylor series.
10979 *
10980 * Note that the overflow check above ensures that fabs(x) < 6000, which
10981 * means that ndiv2 <= 20 here.
10982 */
10983 if (fabs(val) > 0.01)
10984 {
10985 ndiv2 = 1;
10986 val /= 2;
10987
10988 while (fabs(val) > 0.01)
10989 {
10990 ndiv2++;
10991 val /= 2;
10992 }
10993
10994 local_rscale = x.dscale + ndiv2;
10995 div_var_int(&x, 1 << ndiv2, 0, &x, local_rscale, true);
10996 }
10997 else
10998 ndiv2 = 0;
10999
11000 /*
11001 * Set the scale for the Taylor series expansion. The final result has
11002 * (dweight + rscale + 1) significant digits. In addition, we have to
11003 * raise the Taylor series result to the power 2^ndiv2, which introduces
11004 * an error of up to around log10(2^ndiv2) digits, so work with this many
11005 * extra digits of precision (plus a few more for good measure).
11006 */
11007 sig_digits = 1 + dweight + rscale + (int) (ndiv2 * 0.301029995663981);
11008 sig_digits = Max(sig_digits, 0) + 8;
11009
11010 local_rscale = sig_digits - 1;
11011
11012 /*
11013 * Use the Taylor series
11014 *
11015 * exp(x) = 1 + x + x^2/2! + x^3/3! + ...
11016 *
11017 * Given the limited range of x, this should converge reasonably quickly.
11018 * We run the series until the terms fall below the local_rscale limit.
11019 */
11020 add_var(&const_one, &x, result);
11021
11022 mul_var(&x, &x, &elem, local_rscale);
11023 ni = 2;
11024 div_var_int(&elem, ni, 0, &elem, local_rscale, true);
11025
11026 while (elem.ndigits != 0)
11027 {
11028 add_var(result, &elem, result);
11029
11030 mul_var(&elem, &x, &elem, local_rscale);
11031 ni++;
11032 div_var_int(&elem, ni, 0, &elem, local_rscale, true);
11033 }
11034
11035 /*
11036 * Compensate for the argument range reduction. Since the weight of the
11037 * result doubles with each multiplication, we can reduce the local rscale
11038 * as we proceed.
11039 */
11040 while (ndiv2-- > 0)
11041 {
11042 local_rscale = sig_digits - result->weight * 2 * DEC_DIGITS;
11043 local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11044 mul_var(result, result, result, local_rscale);
11045 }
11046
11047 /* Round to requested rscale */
11048 round_var(result, rscale);
11049
11050 free_var(&x);
11051 free_var(&elem);
11052 }
11053
11054
11055 /*
11056 * Estimate the dweight of the most significant decimal digit of the natural
11057 * logarithm of a number.
11058 *
11059 * Essentially, we're approximating log10(abs(ln(var))). This is used to
11060 * determine the appropriate rscale when computing natural logarithms.
11061 *
11062 * Note: many callers call this before range-checking the input. Therefore,
11063 * we must be robust against values that are invalid to apply ln() to.
11064 * We don't wish to throw an error here, so just return zero in such cases.
11065 */
11066 static int
11067 estimate_ln_dweight(const NumericVar *var)
11068 {
11069 int ln_dweight;
11070
11071 /* Caller should fail on ln(negative), but for the moment return zero */
11072 if (var->sign != NUMERIC_POS)
11073 return 0;
11074
11075 if (cmp_var(var, &const_zero_point_nine) >= 0 &&
11076 cmp_var(var, &const_one_point_one) <= 0)
11077 {
11078 /*
11079 * 0.9 <= var <= 1.1
11080 *
11081 * ln(var) has a negative weight (possibly very large). To get a
11082 * reasonably accurate result, estimate it using ln(1+x) ~= x.
11083 */
11084 NumericVar x;
11085
11086 init_var(&x);
11087 sub_var(var, &const_one, &x);
11088
11089 if (x.ndigits > 0)
11090 {
11091 /* Use weight of most significant decimal digit of x */
11092 ln_dweight = x.weight * DEC_DIGITS + (int) log10(x.digits[0]);
11093 }
11094 else
11095 {
11096 /* x = 0. Since ln(1) = 0 exactly, we don't need extra digits */
11097 ln_dweight = 0;
11098 }
11099
11100 free_var(&x);
11101 }
11102 else
11103 {
11104 /*
11105 * Estimate the logarithm using the first couple of digits from the
11106 * input number. This will give an accurate result whenever the input
11107 * is not too close to 1.
11108 */
11109 if (var->ndigits > 0)
11110 {
11111 int digits;
11112 int dweight;
11113 double ln_var;
11114
11115 digits = var->digits[0];
11116 dweight = var->weight * DEC_DIGITS;
11117
11118 if (var->ndigits > 1)
11119 {
11120 digits = digits * NBASE + var->digits[1];
11121 dweight -= DEC_DIGITS;
11122 }
11123
11124 /*----------
11125 * We have var ~= digits * 10^dweight
11126 * so ln(var) ~= ln(digits) + dweight * ln(10)
11127 *----------
11128 */
11129 ln_var = log((double) digits) + dweight * 2.302585092994046;
11130 ln_dweight = (int) log10(fabs(ln_var));
11131 }
11132 else
11133 {
11134 /* Caller should fail on ln(0), but for the moment return zero */
11135 ln_dweight = 0;
11136 }
11137 }
11138
11139 return ln_dweight;
11140 }
11141
11142
11143 /*
11144 * ln_var() -
11145 *
11146 * Compute the natural log of x
11147 */
11148 static void
11149 ln_var(const NumericVar *arg, NumericVar *result, int rscale)
11150 {
11151 NumericVar x;
11152 NumericVar xx;
11153 int ni;
11154 NumericVar elem;
11155 NumericVar fact;
11156 int nsqrt;
11157 int local_rscale;
11158 int cmp;
11159
11160 cmp = cmp_var(arg, &const_zero);
11161 if (cmp == 0)
11162 ereport(ERROR,
11163 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
11164 errmsg("cannot take logarithm of zero")));
11165 else if (cmp < 0)
11166 ereport(ERROR,
11167 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
11168 errmsg("cannot take logarithm of a negative number")));
11169
11170 init_var(&x);
11171 init_var(&xx);
11172 init_var(&elem);
11173 init_var(&fact);
11174
11175 set_var_from_var(arg, &x);
11176 set_var_from_var(&const_two, &fact);
11177
11178 /*
11179 * Reduce input into range 0.9 < x < 1.1 with repeated sqrt() operations.
11180 *
11181 * The final logarithm will have up to around rscale+6 significant digits.
11182 * Each sqrt() will roughly halve the weight of x, so adjust the local
11183 * rscale as we work so that we keep this many significant digits at each
11184 * step (plus a few more for good measure).
11185 *
11186 * Note that we allow local_rscale < 0 during this input reduction
11187 * process, which implies rounding before the decimal point. sqrt_var()
11188 * explicitly supports this, and it significantly reduces the work
11189 * required to reduce very large inputs to the required range. Once the
11190 * input reduction is complete, x.weight will be 0 and its display scale
11191 * will be non-negative again.
11192 */
11193 nsqrt = 0;
11194 while (cmp_var(&x, &const_zero_point_nine) <= 0)
11195 {
11196 local_rscale = rscale - x.weight * DEC_DIGITS / 2 + 8;
11197 sqrt_var(&x, &x, local_rscale);
11198 mul_var(&fact, &const_two, &fact, 0);
11199 nsqrt++;
11200 }
11201 while (cmp_var(&x, &const_one_point_one) >= 0)
11202 {
11203 local_rscale = rscale - x.weight * DEC_DIGITS / 2 + 8;
11204 sqrt_var(&x, &x, local_rscale);
11205 mul_var(&fact, &const_two, &fact, 0);
11206 nsqrt++;
11207 }
11208
11209 /*
11210 * We use the Taylor series for 0.5 * ln((1+z)/(1-z)),
11211 *
11212 * z + z^3/3 + z^5/5 + ...
11213 *
11214 * where z = (x-1)/(x+1) is in the range (approximately) -0.053 .. 0.048
11215 * due to the above range-reduction of x.
11216 *
11217 * The convergence of this is not as fast as one would like, but is
11218 * tolerable given that z is small.
11219 *
11220 * The Taylor series result will be multiplied by 2^(nsqrt+1), which has a
11221 * decimal weight of (nsqrt+1) * log10(2), so work with this many extra
11222 * digits of precision (plus a few more for good measure).
11223 */
11224 local_rscale = rscale + (int) ((nsqrt + 1) * 0.301029995663981) + 8;
11225
11226 sub_var(&x, &const_one, result);
11227 add_var(&x, &const_one, &elem);
11228 div_var(result, &elem, result, local_rscale, true, false);
11229 set_var_from_var(result, &xx);
11230 mul_var(result, result, &x, local_rscale);
11231
11232 ni = 1;
11233
11234 for (;;)
11235 {
11236 ni += 2;
11237 mul_var(&xx, &x, &xx, local_rscale);
11238 div_var_int(&xx, ni, 0, &elem, local_rscale, true);
11239
11240 if (elem.ndigits == 0)
11241 break;
11242
11243 add_var(result, &elem, result);
11244
11245 if (elem.weight < (result->weight - local_rscale * 2 / DEC_DIGITS))
11246 break;
11247 }
11248
11249 /* Compensate for argument range reduction, round to requested rscale */
11250 mul_var(result, &fact, result, rscale);
11251
11252 free_var(&x);
11253 free_var(&xx);
11254 free_var(&elem);
11255 free_var(&fact);
11256 }
11257
11258
11259 /*
11260 * log_var() -
11261 *
11262 * Compute the logarithm of num in a given base.
11263 *
11264 * Note: this routine chooses dscale of the result.
11265 */
11266 static void
11267 log_var(const NumericVar *base, const NumericVar *num, NumericVar *result)
11268 {
11269 NumericVar ln_base;
11270 NumericVar ln_num;
11271 int ln_base_dweight;
11272 int ln_num_dweight;
11273 int result_dweight;
11274 int rscale;
11275 int ln_base_rscale;
11276 int ln_num_rscale;
11277
11278 init_var(&ln_base);
11279 init_var(&ln_num);
11280
11281 /* Estimated dweights of ln(base), ln(num) and the final result */
11282 ln_base_dweight = estimate_ln_dweight(base);
11283 ln_num_dweight = estimate_ln_dweight(num);
11284 result_dweight = ln_num_dweight - ln_base_dweight;
11285
11286 /*
11287 * Select the scale of the result so that it will have at least
11288 * NUMERIC_MIN_SIG_DIGITS significant digits and is not less than either
11289 * input's display scale.
11290 */
11291 rscale = NUMERIC_MIN_SIG_DIGITS - result_dweight;
11292 rscale = Max(rscale, base->dscale);
11293 rscale = Max(rscale, num->dscale);
11294 rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
11295 rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
11296
11297 /*
11298 * Set the scales for ln(base) and ln(num) so that they each have more
11299 * significant digits than the final result.
11300 */
11301 ln_base_rscale = rscale + result_dweight - ln_base_dweight + 8;
11302 ln_base_rscale = Max(ln_base_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11303
11304 ln_num_rscale = rscale + result_dweight - ln_num_dweight + 8;
11305 ln_num_rscale = Max(ln_num_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11306
11307 /* Form natural logarithms */
11308 ln_var(base, &ln_base, ln_base_rscale);
11309 ln_var(num, &ln_num, ln_num_rscale);
11310
11311 /* Divide and round to the required scale */
11312 div_var(&ln_num, &ln_base, result, rscale, true, false);
11313
11314 free_var(&ln_num);
11315 free_var(&ln_base);
11316 }
11317
11318
11319 /*
11320 * power_var() -
11321 *
11322 * Raise base to the power of exp
11323 *
11324 * Note: this routine chooses dscale of the result.
11325 */
11326 static void
11327 power_var(const NumericVar *base, const NumericVar *exp, NumericVar *result)
11328 {
11329 int res_sign;
11330 NumericVar abs_base;
11331 NumericVar ln_base;
11332 NumericVar ln_num;
11333 int ln_dweight;
11334 int rscale;
11335 int sig_digits;
11336 int local_rscale;
11337 double val;
11338
11339 /* If exp can be represented as an integer, use power_var_int */
11340 if (exp->ndigits == 0 || exp->ndigits <= exp->weight + 1)
11341 {
11342 /* exact integer, but does it fit in int? */
11343 int64 expval64;
11344
11345 if (numericvar_to_int64(exp, &expval64))
11346 {
11347 if (expval64 >= PG_INT32_MIN && expval64 <= PG_INT32_MAX)
11348 {
11349 /* Okay, use power_var_int */
11350 power_var_int(base, (int) expval64, exp->dscale, result);
11351 return;
11352 }
11353 }
11354 }
11355
11356 /*
11357 * This avoids log(0) for cases of 0 raised to a non-integer. 0 ^ 0 is
11358 * handled by power_var_int().
11359 */
11360 if (cmp_var(base, &const_zero) == 0)
11361 {
11362 set_var_from_var(&const_zero, result);
11363 result->dscale = NUMERIC_MIN_SIG_DIGITS; /* no need to round */
11364 return;
11365 }
11366
11367 init_var(&abs_base);
11368 init_var(&ln_base);
11369 init_var(&ln_num);
11370
11371 /*
11372 * If base is negative, insist that exp be an integer. The result is then
11373 * positive if exp is even and negative if exp is odd.
11374 */
11375 if (base->sign == NUMERIC_NEG)
11376 {
11377 /*
11378 * Check that exp is an integer. This error code is defined by the
11379 * SQL standard, and matches other errors in numeric_power().
11380 */
11381 if (exp->ndigits > 0 && exp->ndigits > exp->weight + 1)
11382 ereport(ERROR,
11383 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
11384 errmsg("a negative number raised to a non-integer power yields a complex result")));
11385
11386 /* Test if exp is odd or even */
11387 if (exp->ndigits > 0 && exp->ndigits == exp->weight + 1 &&
11388 (exp->digits[exp->ndigits - 1] & 1))
11389 res_sign = NUMERIC_NEG;
11390 else
11391 res_sign = NUMERIC_POS;
11392
11393 /* Then work with abs(base) below */
11394 set_var_from_var(base, &abs_base);
11395 abs_base.sign = NUMERIC_POS;
11396 base = &abs_base;
11397 }
11398 else
11399 res_sign = NUMERIC_POS;
11400
11401 /*----------
11402 * Decide on the scale for the ln() calculation. For this we need an
11403 * estimate of the weight of the result, which we obtain by doing an
11404 * initial low-precision calculation of exp * ln(base).
11405 *
11406 * We want result = e ^ (exp * ln(base))
11407 * so result dweight = log10(result) = exp * ln(base) * log10(e)
11408 *
11409 * We also perform a crude overflow test here so that we can exit early if
11410 * the full-precision result is sure to overflow, and to guard against
11411 * integer overflow when determining the scale for the real calculation.
11412 * exp_var() supports inputs up to NUMERIC_MAX_RESULT_SCALE * 3, so the
11413 * result will overflow if exp * ln(base) >= NUMERIC_MAX_RESULT_SCALE * 3.
11414 * Since the values here are only approximations, we apply a small fuzz
11415 * factor to this overflow test and let exp_var() determine the exact
11416 * overflow threshold so that it is consistent for all inputs.
11417 *----------
11418 */
11419 ln_dweight = estimate_ln_dweight(base);
11420
11421 /*
11422 * Set the scale for the low-precision calculation, computing ln(base) to
11423 * around 8 significant digits. Note that ln_dweight may be as small as
11424 * -NUMERIC_DSCALE_MAX, so the scale may exceed NUMERIC_MAX_DISPLAY_SCALE
11425 * here.
11426 */
11427 local_rscale = 8 - ln_dweight;
11428 local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11429
11430 ln_var(base, &ln_base, local_rscale);
11431
11432 mul_var(&ln_base, exp, &ln_num, local_rscale);
11433
11434 val = numericvar_to_double_no_overflow(&ln_num);
11435
11436 /* initial overflow/underflow test with fuzz factor */
11437 if (fabs(val) > NUMERIC_MAX_RESULT_SCALE * 3.01)
11438 {
11439 if (val > 0)
11440 ereport(ERROR,
11441 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
11442 errmsg("value overflows numeric format")));
11443 zero_var(result);
11444 result->dscale = NUMERIC_MAX_DISPLAY_SCALE;
11445 return;
11446 }
11447
11448 val *= 0.434294481903252; /* approximate decimal result weight */
11449
11450 /* choose the result scale */
11451 rscale = NUMERIC_MIN_SIG_DIGITS - (int) val;
11452 rscale = Max(rscale, base->dscale);
11453 rscale = Max(rscale, exp->dscale);
11454 rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
11455 rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
11456
11457 /* significant digits required in the result */
11458 sig_digits = rscale + (int) val;
11459 sig_digits = Max(sig_digits, 0);
11460
11461 /* set the scale for the real exp * ln(base) calculation */
11462 local_rscale = sig_digits - ln_dweight + 8;
11463 local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11464
11465 /* and do the real calculation */
11466
11467 ln_var(base, &ln_base, local_rscale);
11468
11469 mul_var(&ln_base, exp, &ln_num, local_rscale);
11470
11471 exp_var(&ln_num, result, rscale);
11472
11473 if (res_sign == NUMERIC_NEG && result->ndigits > 0)
11474 result->sign = NUMERIC_NEG;
11475
11476 free_var(&ln_num);
11477 free_var(&ln_base);
11478 free_var(&abs_base);
11479 }
11480
11481 /*
11482 * power_var_int() -
11483 *
11484 * Raise base to the power of exp, where exp is an integer.
11485 *
11486 * Note: this routine chooses dscale of the result.
11487 */
11488 static void
11489 power_var_int(const NumericVar *base, int exp, int exp_dscale,
11490 NumericVar *result)
11491 {
11492 double f;
11493 int p;
11494 int i;
11495 int rscale;
11496 int sig_digits;
11497 unsigned int mask;
11498 bool neg;
11499 NumericVar base_prod;
11500 int local_rscale;
11501
11502 /*
11503 * Choose the result scale. For this we need an estimate of the decimal
11504 * weight of the result, which we obtain by approximating using double
11505 * precision arithmetic.
11506 *
11507 * We also perform crude overflow/underflow tests here so that we can exit
11508 * early if the result is sure to overflow/underflow, and to guard against
11509 * integer overflow when choosing the result scale.
11510 */
11511 if (base->ndigits != 0)
11512 {
11513 /*----------
11514 * Choose f (double) and p (int) such that base ~= f * 10^p.
11515 * Then log10(result) = log10(base^exp) ~= exp * (log10(f) + p).
11516 *----------
11517 */
11518 f = base->digits[0];
11519 p = base->weight * DEC_DIGITS;
11520
11521 for (i = 1; i < base->ndigits && i * DEC_DIGITS < 16; i++)
11522 {
11523 f = f * NBASE + base->digits[i];
11524 p -= DEC_DIGITS;
11525 }
11526
11527 f = exp * (log10(f) + p); /* approximate decimal result weight */
11528 }
11529 else
11530 f = 0; /* result is 0 or 1 (weight 0), or error */
11531
11532 /* overflow/underflow tests with fuzz factors */
11533 if (f > (NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS)
11534 ereport(ERROR,
11535 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
11536 errmsg("value overflows numeric format")));
11537 if (f + 1 < -NUMERIC_MAX_DISPLAY_SCALE)
11538 {
11539 zero_var(result);
11540 result->dscale = NUMERIC_MAX_DISPLAY_SCALE;
11541 return;
11542 }
11543
11544 /*
11545 * Choose the result scale in the same way as power_var(), so it has at
11546 * least NUMERIC_MIN_SIG_DIGITS significant digits and is not less than
11547 * either input's display scale.
11548 */
11549 rscale = NUMERIC_MIN_SIG_DIGITS - (int) f;
11550 rscale = Max(rscale, base->dscale);
11551 rscale = Max(rscale, exp_dscale);
11552 rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
11553 rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
11554
11555 /* Handle some common special cases, as well as corner cases */
11556 switch (exp)
11557 {
11558 case 0:
11559
11560 /*
11561 * While 0 ^ 0 can be either 1 or indeterminate (error), we treat
11562 * it as 1 because most programming languages do this. SQL:2003
11563 * also requires a return value of 1.
11564 * https://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_zero_power
11565 */
11566 set_var_from_var(&const_one, result);
11567 result->dscale = rscale; /* no need to round */
11568 return;
11569 case 1:
11570 set_var_from_var(base, result);
11571 round_var(result, rscale);
11572 return;
11573 case -1:
11574 div_var(&const_one, base, result, rscale, true, true);
11575 return;
11576 case 2:
11577 mul_var(base, base, result, rscale);
11578 return;
11579 default:
11580 break;
11581 }
11582
11583 /* Handle the special case where the base is zero */
11584 if (base->ndigits == 0)
11585 {
11586 if (exp < 0)
11587 ereport(ERROR,
11588 (errcode(ERRCODE_DIVISION_BY_ZERO),
11589 errmsg("division by zero")));
11590 zero_var(result);
11591 result->dscale = rscale;
11592 return;
11593 }
11594
11595 /*
11596 * The general case repeatedly multiplies base according to the bit
11597 * pattern of exp.
11598 *
11599 * The local rscale used for each multiplication is varied to keep a fixed
11600 * number of significant digits, sufficient to give the required result
11601 * scale.
11602 */
11603
11604 /*
11605 * Approximate number of significant digits in the result. Note that the
11606 * underflow test above, together with the choice of rscale, ensures that
11607 * this approximation is necessarily > 0.
11608 */
11609 sig_digits = 1 + rscale + (int) f;
11610
11611 /*
11612 * The multiplications to produce the result may introduce an error of up
11613 * to around log10(abs(exp)) digits, so work with this many extra digits
11614 * of precision (plus a few more for good measure).
11615 */
11616 sig_digits += (int) log(fabs((double) exp)) + 8;
11617
11618 /*
11619 * Now we can proceed with the multiplications.
11620 */
11621 neg = (exp < 0);
11622 mask = pg_abs_s32(exp);
11623
11624 init_var(&base_prod);
11625 set_var_from_var(base, &base_prod);
11626
11627 if (mask & 1)
11628 set_var_from_var(base, result);
11629 else
11630 set_var_from_var(&const_one, result);
11631
11632 while ((mask >>= 1) > 0)
11633 {
11634 /*
11635 * Do the multiplications using rscales large enough to hold the
11636 * results to the required number of significant digits, but don't
11637 * waste time by exceeding the scales of the numbers themselves.
11638 */
11639 local_rscale = sig_digits - 2 * base_prod.weight * DEC_DIGITS;
11640 local_rscale = Min(local_rscale, 2 * base_prod.dscale);
11641 local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11642
11643 mul_var(&base_prod, &base_prod, &base_prod, local_rscale);
11644
11645 if (mask & 1)
11646 {
11647 local_rscale = sig_digits -
11648 (base_prod.weight + result->weight) * DEC_DIGITS;
11649 local_rscale = Min(local_rscale,
11650 base_prod.dscale + result->dscale);
11651 local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11652
11653 mul_var(&base_prod, result, result, local_rscale);
11654 }
11655
11656 /*
11657 * When abs(base) > 1, the number of digits to the left of the decimal
11658 * point in base_prod doubles at each iteration, so if exp is large we
11659 * could easily spend large amounts of time and memory space doing the
11660 * multiplications. But once the weight exceeds what will fit in
11661 * int16, the final result is guaranteed to overflow (or underflow, if
11662 * exp < 0), so we can give up before wasting too many cycles.
11663 */
11664 if (base_prod.weight > NUMERIC_WEIGHT_MAX ||
11665 result->weight > NUMERIC_WEIGHT_MAX)
11666 {
11667 /* overflow, unless neg, in which case result should be 0 */
11668 if (!neg)
11669 ereport(ERROR,
11670 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
11671 errmsg("value overflows numeric format")));
11672 zero_var(result);
11673 neg = false;
11674 break;
11675 }
11676 }
11677
11678 free_var(&base_prod);
11679
11680 /* Compensate for input sign, and round to requested rscale */
11681 if (neg)
11682 div_var(&const_one, result, result, rscale, true, false);
11683 else
11684 round_var(result, rscale);
11685 }
11686
11687 /*
11688 * power_ten_int() -
11689 *
11690 * Raise ten to the power of exp, where exp is an integer. Note that unlike
11691 * power_var_int(), this does no overflow/underflow checking or rounding.
11692 */
11693 static void
11694 power_ten_int(int exp, NumericVar *result)
11695 {
11696 /* Construct the result directly, starting from 10^0 = 1 */
11697 set_var_from_var(&const_one, result);
11698
11699 /* Scale needed to represent the result exactly */
11700 result->dscale = exp < 0 ? -exp : 0;
11701
11702 /* Base-NBASE weight of result and remaining exponent */
11703 if (exp >= 0)
11704 result->weight = exp / DEC_DIGITS;
11705 else
11706 result->weight = (exp + 1) / DEC_DIGITS - 1;
11707
11708 exp -= result->weight * DEC_DIGITS;
11709
11710 /* Final adjustment of the result's single NBASE digit */
11711 while (exp-- > 0)
11712 result->digits[0] *= 10;
11713 }
11714
11715 /*
11716 * random_var() - return a random value in the range [rmin, rmax].
11717 */
11718 static void
11719 random_var(pg_prng_state *state, const NumericVar *rmin,
11720 const NumericVar *rmax, NumericVar *result)
11721 {
11722 int rscale;
11723 NumericVar rlen;
11724 int res_ndigits;
11725 int n;
11726 int pow10;
11727 int i;
11728 uint64 rlen64;
11729 int rlen64_ndigits;
11730
11731 rscale = Max(rmin->dscale, rmax->dscale);
11732
11733 /* Compute rlen = rmax - rmin and check the range bounds */
11734 init_var(&rlen);
11735 sub_var(rmax, rmin, &rlen);
11736
11737 if (rlen.sign == NUMERIC_NEG)
11738 ereport(ERROR,
11739 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
11740 errmsg("lower bound must be less than or equal to upper bound"));
11741
11742 /* Special case for an empty range */
11743 if (rlen.ndigits == 0)
11744 {
11745 set_var_from_var(rmin, result);
11746 result->dscale = rscale;
11747 free_var(&rlen);
11748 return;
11749 }
11750
11751 /*
11752 * Otherwise, select a random value in the range [0, rlen = rmax - rmin],
11753 * and shift it to the required range by adding rmin.
11754 */
11755
11756 /* Required result digits */
11757 res_ndigits = rlen.weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
11758
11759 /*
11760 * To get the required rscale, the final result digit must be a multiple
11761 * of pow10 = 10^n, where n = (-rscale) mod DEC_DIGITS.
11762 */
11763 n = ((rscale + DEC_DIGITS - 1) / DEC_DIGITS) * DEC_DIGITS - rscale;
11764 pow10 = 1;
11765 for (i = 0; i < n; i++)
11766 pow10 *= 10;
11767
11768 /*
11769 * To choose a random value uniformly from the range [0, rlen], we choose
11770 * from the slightly larger range [0, rlen2], where rlen2 is formed from
11771 * rlen by copying the first 4 NBASE digits, and setting all remaining
11772 * decimal digits to "9".
11773 *
11774 * Without loss of generality, we can ignore the weight of rlen2 and treat
11775 * it as a pure integer for the purposes of this discussion. The process
11776 * above gives rlen2 + 1 = rlen64 * 10^N, for some integer N, where rlen64
11777 * is a 64-bit integer formed from the first 4 NBASE digits copied from
11778 * rlen. Since this trivially factors into smaller pieces that fit in
11779 * 64-bit integers, the task of choosing a random value uniformly from the
11780 * rlen2 + 1 possible values in [0, rlen2] is much simpler.
11781 *
11782 * If the random value selected is too large, it is rejected, and we try
11783 * again until we get a result <= rlen, ensuring that the overall result
11784 * is uniform (no particular value is any more likely than any other).
11785 *
11786 * Since rlen64 holds 4 NBASE digits from rlen, it contains at least
11787 * DEC_DIGITS * 3 + 1 decimal digits (i.e., at least 13 decimal digits,
11788 * when DEC_DIGITS is 4). Therefore the probability of needing to reject
11789 * the value chosen and retry is less than 1e-13.
11790 */
11791 rlen64 = (uint64) rlen.digits[0];
11792 rlen64_ndigits = 1;
11793 while (rlen64_ndigits < res_ndigits && rlen64_ndigits < 4)
11794 {
11795 rlen64 *= NBASE;
11796 if (rlen64_ndigits < rlen.ndigits)
11797 rlen64 += rlen.digits[rlen64_ndigits];
11798 rlen64_ndigits++;
11799 }
11800
11801 /* Loop until we get a result <= rlen */
11802 do
11803 {
11804 NumericDigit *res_digits;
11805 uint64 rand;
11806 int whole_ndigits;
11807
11808 alloc_var(result, res_ndigits);
11809 result->sign = NUMERIC_POS;
11810 result->weight = rlen.weight;
11811 result->dscale = rscale;
11812 res_digits = result->digits;
11813
11814 /*
11815 * Set the first rlen64_ndigits using a random value in [0, rlen64].
11816 *
11817 * If this is the whole result, and rscale is not a multiple of
11818 * DEC_DIGITS (pow10 from above is not 1), then we need this to be a
11819 * multiple of pow10.
11820 */
11821 if (rlen64_ndigits == res_ndigits && pow10 != 1)
11822 rand = pg_prng_uint64_range(state, 0, rlen64 / pow10) * pow10;
11823 else
11824 rand = pg_prng_uint64_range(state, 0, rlen64);
11825
11826 for (i = rlen64_ndigits - 1; i >= 0; i--)
11827 {
11828 res_digits[i] = (NumericDigit) (rand % NBASE);
11829 rand = rand / NBASE;
11830 }
11831
11832 /*
11833 * Set the remaining digits to random values in range [0, NBASE),
11834 * noting that the last digit needs to be a multiple of pow10.
11835 */
11836 whole_ndigits = res_ndigits;
11837 if (pow10 != 1)
11838 whole_ndigits--;
11839
11840 /* Set whole digits in groups of 4 for best performance */
11841 i = rlen64_ndigits;
11842 while (i < whole_ndigits - 3)
11843 {
11844 rand = pg_prng_uint64_range(state, 0,
11845 (uint64) NBASE * NBASE * NBASE * NBASE - 1);
11846 res_digits[i++] = (NumericDigit) (rand % NBASE);
11847 rand = rand / NBASE;
11848 res_digits[i++] = (NumericDigit) (rand % NBASE);
11849 rand = rand / NBASE;
11850 res_digits[i++] = (NumericDigit) (rand % NBASE);
11851 rand = rand / NBASE;
11852 res_digits[i++] = (NumericDigit) rand;
11853 }
11854
11855 /* Remaining whole digits */
11856 while (i < whole_ndigits)
11857 {
11858 rand = pg_prng_uint64_range(state, 0, NBASE - 1);
11859 res_digits[i++] = (NumericDigit) rand;
11860 }
11861
11862 /* Final partial digit (multiple of pow10) */
11863 if (i < res_ndigits)
11864 {
11865 rand = pg_prng_uint64_range(state, 0, NBASE / pow10 - 1) * pow10;
11866 res_digits[i] = (NumericDigit) rand;
11867 }
11868
11869 /* Remove leading/trailing zeroes */
11870 strip_var(result);
11871
11872 /* If result > rlen, try again */
11873
11874 } while (cmp_var(result, &rlen) > 0);
11875
11876 /* Offset the result to the required range */
11877 add_var(result, rmin, result);
11878
11879 free_var(&rlen);
11880 }
11881
11882
11883 /* ----------------------------------------------------------------------
11884 *
11885 * Following are the lowest level functions that operate unsigned
11886 * on the variable level
11887 *
11888 * ----------------------------------------------------------------------
11889 */
11890
11891
11892 /* ----------
11893 * cmp_abs() -
11894 *
11895 * Compare the absolute values of var1 and var2
11896 * Returns: -1 for ABS(var1) < ABS(var2)
11897 * 0 for ABS(var1) == ABS(var2)
11898 * 1 for ABS(var1) > ABS(var2)
11899 * ----------
11900 */
11901 static int
11902 cmp_abs(const NumericVar *var1, const NumericVar *var2)
11903 {
11904 return cmp_abs_common(var1->digits, var1->ndigits, var1->weight,
11905 var2->digits, var2->ndigits, var2->weight);
11906 }
11907
11908 /* ----------
11909 * cmp_abs_common() -
11910 *
11911 * Main routine of cmp_abs(). This function can be used by both
11912 * NumericVar and Numeric.
11913 * ----------
11914 */
11915 static int
11916 cmp_abs_common(const NumericDigit *var1digits, int var1ndigits, int var1weight,
11917 const NumericDigit *var2digits, int var2ndigits, int var2weight)
11918 {
11919 int i1 = 0;
11920 int i2 = 0;
11921
11922 /* Check any digits before the first common digit */
11923
11924 while (var1weight > var2weight && i1 < var1ndigits)
11925 {
11926 if (var1digits[i1++] != 0)
11927 return 1;
11928 var1weight--;
11929 }
11930 while (var2weight > var1weight && i2 < var2ndigits)
11931 {
11932 if (var2digits[i2++] != 0)
11933 return -1;
11934 var2weight--;
11935 }
11936
11937 /* At this point, either w1 == w2 or we've run out of digits */
11938
11939 if (var1weight == var2weight)
11940 {
11941 while (i1 < var1ndigits && i2 < var2ndigits)
11942 {
11943 int stat = var1digits[i1++] - var2digits[i2++];
11944
11945 if (stat)
11946 {
11947 if (stat > 0)
11948 return 1;
11949 return -1;
11950 }
11951 }
11952 }
11953
11954 /*
11955 * At this point, we've run out of digits on one side or the other; so any
11956 * remaining nonzero digits imply that side is larger
11957 */
11958 while (i1 < var1ndigits)
11959 {
11960 if (var1digits[i1++] != 0)
11961 return 1;
11962 }
11963 while (i2 < var2ndigits)
11964 {
11965 if (var2digits[i2++] != 0)
11966 return -1;
11967 }
11968
11969 return 0;
11970 }
11971
11972
11973 /*
11974 * add_abs() -
11975 *
11976 * Add the absolute values of two variables into result.
11977 * result might point to one of the operands without danger.
11978 */
11979 static void
11980 add_abs(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
11981 {
11982 NumericDigit *res_buf;
11983 NumericDigit *res_digits;
11984 int res_ndigits;
11985 int res_weight;
11986 int res_rscale,
11987 rscale1,
11988 rscale2;
11989 int res_dscale;
11990 int i,
11991 i1,
11992 i2;
11993 int carry = 0;
11994
11995 /* copy these values into local vars for speed in inner loop */
11996 int var1ndigits = var1->ndigits;
11997 int var2ndigits = var2->ndigits;
11998 NumericDigit *var1digits = var1->digits;
11999 NumericDigit *var2digits = var2->digits;
12000
12001 res_weight = Max(var1->weight, var2->weight) + 1;
12002
12003 res_dscale = Max(var1->dscale, var2->dscale);
12004
12005 /* Note: here we are figuring rscale in base-NBASE digits */
12006 rscale1 = var1->ndigits - var1->weight - 1;
12007 rscale2 = var2->ndigits - var2->weight - 1;
12008 res_rscale = Max(rscale1, rscale2);
12009
12010 res_ndigits = res_rscale + res_weight + 1;
12011 if (res_ndigits <= 0)
12012 res_ndigits = 1;
12013
12014 res_buf = digitbuf_alloc(res_ndigits + 1);
12015 res_buf[0] = 0; /* spare digit for later rounding */
12016 res_digits = res_buf + 1;
12017
12018 i1 = res_rscale + var1->weight + 1;
12019 i2 = res_rscale + var2->weight + 1;
12020 for (i = res_ndigits - 1; i >= 0; i--)
12021 {
12022 i1--;
12023 i2--;
12024 if (i1 >= 0 && i1 < var1ndigits)
12025 carry += var1digits[i1];
12026 if (i2 >= 0 && i2 < var2ndigits)
12027 carry += var2digits[i2];
12028
12029 if (carry >= NBASE)
12030 {
12031 res_digits[i] = carry - NBASE;
12032 carry = 1;
12033 }
12034 else
12035 {
12036 res_digits[i] = carry;
12037 carry = 0;
12038 }
12039 }
12040
12041 Assert(carry == 0); /* else we failed to allow for carry out */
12042
12043 digitbuf_free(result->buf);
12044 result->ndigits = res_ndigits;
12045 result->buf = res_buf;
12046 result->digits = res_digits;
12047 result->weight = res_weight;
12048 result->dscale = res_dscale;
12049
12050 /* Remove leading/trailing zeroes */
12051 strip_var(result);
12052 }
12053
12054
12055 /*
12056 * sub_abs()
12057 *
12058 * Subtract the absolute value of var2 from the absolute value of var1
12059 * and store in result. result might point to one of the operands
12060 * without danger.
12061 *
12062 * ABS(var1) MUST BE GREATER OR EQUAL ABS(var2) !!!
12063 */
12064 static void
12065 sub_abs(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
12066 {
12067 NumericDigit *res_buf;
12068 NumericDigit *res_digits;
12069 int res_ndigits;
12070 int res_weight;
12071 int res_rscale,
12072 rscale1,
12073 rscale2;
12074 int res_dscale;
12075 int i,
12076 i1,
12077 i2;
12078 int borrow = 0;
12079
12080 /* copy these values into local vars for speed in inner loop */
12081 int var1ndigits = var1->ndigits;
12082 int var2ndigits = var2->ndigits;
12083 NumericDigit *var1digits = var1->digits;
12084 NumericDigit *var2digits = var2->digits;
12085
12086 res_weight = var1->weight;
12087
12088 res_dscale = Max(var1->dscale, var2->dscale);
12089
12090 /* Note: here we are figuring rscale in base-NBASE digits */
12091 rscale1 = var1->ndigits - var1->weight - 1;
12092 rscale2 = var2->ndigits - var2->weight - 1;
12093 res_rscale = Max(rscale1, rscale2);
12094
12095 res_ndigits = res_rscale + res_weight + 1;
12096 if (res_ndigits <= 0)
12097 res_ndigits = 1;
12098
12099 res_buf = digitbuf_alloc(res_ndigits + 1);
12100 res_buf[0] = 0; /* spare digit for later rounding */
12101 res_digits = res_buf + 1;
12102
12103 i1 = res_rscale + var1->weight + 1;
12104 i2 = res_rscale + var2->weight + 1;
12105 for (i = res_ndigits - 1; i >= 0; i--)
12106 {
12107 i1--;
12108 i2--;
12109 if (i1 >= 0 && i1 < var1ndigits)
12110 borrow += var1digits[i1];
12111 if (i2 >= 0 && i2 < var2ndigits)
12112 borrow -= var2digits[i2];
12113
12114 if (borrow < 0)
12115 {
12116 res_digits[i] = borrow + NBASE;
12117 borrow = -1;
12118 }
12119 else
12120 {
12121 res_digits[i] = borrow;
12122 borrow = 0;
12123 }
12124 }
12125
12126 Assert(borrow == 0); /* else caller gave us var1 < var2 */
12127
12128 digitbuf_free(result->buf);
12129 result->ndigits = res_ndigits;
12130 result->buf = res_buf;
12131 result->digits = res_digits;
12132 result->weight = res_weight;
12133 result->dscale = res_dscale;
12134
12135 /* Remove leading/trailing zeroes */
12136 strip_var(result);
12137 }
12138
12139 /*
12140 * round_var
12141 *
12142 * Round the value of a variable to no more than rscale decimal digits
12143 * after the decimal point. NOTE: we allow rscale < 0 here, implying
12144 * rounding before the decimal point.
12145 */
12146 static void
12147 round_var(NumericVar *var, int rscale)
12148 {
12149 NumericDigit *digits = var->digits;
12150 int di;
12151 int ndigits;
12152 int carry;
12153
12154 var->dscale = rscale;
12155
12156 /* decimal digits wanted */
12157 di = (var->weight + 1) * DEC_DIGITS + rscale;
12158
12159 /*
12160 * If di = 0, the value loses all digits, but could round up to 1 if its
12161 * first extra digit is >= 5. If di < 0 the result must be 0.
12162 */
12163 if (di < 0)
12164 {
12165 var->ndigits = 0;
12166 var->weight = 0;
12167 var->sign = NUMERIC_POS;
12168 }
12169 else
12170 {
12171 /* NBASE digits wanted */
12172 ndigits = (di + DEC_DIGITS - 1) / DEC_DIGITS;
12173
12174 /* 0, or number of decimal digits to keep in last NBASE digit */
12175 di %= DEC_DIGITS;
12176
12177 if (ndigits < var->ndigits ||
12178 (ndigits == var->ndigits && di > 0))
12179 {
12180 var->ndigits = ndigits;
12181
12182 #if DEC_DIGITS == 1
12183 /* di must be zero */
12184 carry = (digits[ndigits] >= HALF_NBASE) ? 1 : 0;
12185 #else
12186 if (di == 0)
12187 carry = (digits[ndigits] >= HALF_NBASE) ? 1 : 0;
12188 else
12189 {
12190 /* Must round within last NBASE digit */
12191 int extra,
12192 pow10;
12193
12194 #if DEC_DIGITS == 4
12195 pow10 = round_powers[di];
12196 #elif DEC_DIGITS == 2
12197 pow10 = 10;
12198 #else
12199 #error unsupported NBASE
12200 #endif
12201 extra = digits[--ndigits] % pow10;
12202 digits[ndigits] -= extra;
12203 carry = 0;
12204 if (extra >= pow10 / 2)
12205 {
12206 pow10 += digits[ndigits];
12207 if (pow10 >= NBASE)
12208 {
12209 pow10 -= NBASE;
12210 carry = 1;
12211 }
12212 digits[ndigits] = pow10;
12213 }
12214 }
12215 #endif
12216
12217 /* Propagate carry if needed */
12218 while (carry)
12219 {
12220 carry += digits[--ndigits];
12221 if (carry >= NBASE)
12222 {
12223 digits[ndigits] = carry - NBASE;
12224 carry = 1;
12225 }
12226 else
12227 {
12228 digits[ndigits] = carry;
12229 carry = 0;
12230 }
12231 }
12232
12233 if (ndigits < 0)
12234 {
12235 Assert(ndigits == -1); /* better not have added > 1 digit */
12236 Assert(var->digits > var->buf);
12237 var->digits--;
12238 var->ndigits++;
12239 var->weight++;
12240 }
12241 }
12242 }
12243 }
12244
12245 /*
12246 * trunc_var
12247 *
12248 * Truncate (towards zero) the value of a variable at rscale decimal digits
12249 * after the decimal point. NOTE: we allow rscale < 0 here, implying
12250 * truncation before the decimal point.
12251 */
12252 static void
12253 trunc_var(NumericVar *var, int rscale)
12254 {
12255 int di;
12256 int ndigits;
12257
12258 var->dscale = rscale;
12259
12260 /* decimal digits wanted */
12261 di = (var->weight + 1) * DEC_DIGITS + rscale;
12262
12263 /*
12264 * If di <= 0, the value loses all digits.
12265 */
12266 if (di <= 0)
12267 {
12268 var->ndigits = 0;
12269 var->weight = 0;
12270 var->sign = NUMERIC_POS;
12271 }
12272 else
12273 {
12274 /* NBASE digits wanted */
12275 ndigits = (di + DEC_DIGITS - 1) / DEC_DIGITS;
12276
12277 if (ndigits <= var->ndigits)
12278 {
12279 var->ndigits = ndigits;
12280
12281 #if DEC_DIGITS == 1
12282 /* no within-digit stuff to worry about */
12283 #else
12284 /* 0, or number of decimal digits to keep in last NBASE digit */
12285 di %= DEC_DIGITS;
12286
12287 if (di > 0)
12288 {
12289 /* Must truncate within last NBASE digit */
12290 NumericDigit *digits = var->digits;
12291 int extra,
12292 pow10;
12293
12294 #if DEC_DIGITS == 4
12295 pow10 = round_powers[di];
12296 #elif DEC_DIGITS == 2
12297 pow10 = 10;
12298 #else
12299 #error unsupported NBASE
12300 #endif
12301 extra = digits[--ndigits] % pow10;
12302 digits[ndigits] -= extra;
12303 }
12304 #endif
12305 }
12306 }
12307 }
12308
12309 /*
12310 * strip_var
12311 *
12312 * Strip any leading and trailing zeroes from a numeric variable
12313 */
12314 static void
12315 strip_var(NumericVar *var)
12316 {
12317 NumericDigit *digits = var->digits;
12318 int ndigits = var->ndigits;
12319
12320 /* Strip leading zeroes */
12321 while (ndigits > 0 && *digits == 0)
12322 {
12323 digits++;
12324 var->weight--;
12325 ndigits--;
12326 }
12327
12328 /* Strip trailing zeroes */
12329 while (ndigits > 0 && digits[ndigits - 1] == 0)
12330 ndigits--;
12331
12332 /* If it's zero, normalize the sign and weight */
12333 if (ndigits == 0)
12334 {
12335 var->sign = NUMERIC_POS;
12336 var->weight = 0;
12337 }
12338
12339 var->digits = digits;
12340 var->ndigits = ndigits;
12341 }
12342
12343
12344 /* ----------------------------------------------------------------------
12345 *
12346 * Fast sum accumulator functions
12347 *
12348 * ----------------------------------------------------------------------
12349 */
12350
12351 /*
12352 * Reset the accumulator's value to zero. The buffers to hold the digits
12353 * are not free'd.
12354 */
12355 static void
12356 accum_sum_reset(NumericSumAccum *accum)
12357 {
12358 int i;
12359
12360 accum->dscale = 0;
12361 for (i = 0; i < accum->ndigits; i++)
12362 {
12363 accum->pos_digits[i] = 0;
12364 accum->neg_digits[i] = 0;
12365 }
12366 }
12367
12368 /*
12369 * Accumulate a new value.
12370 */
12371 static void
12372 accum_sum_add(NumericSumAccum *accum, const NumericVar *val)
12373 {
12374 int32 *accum_digits;
12375 int i,
12376 val_i;
12377 int val_ndigits;
12378 NumericDigit *val_digits;
12379
12380 /*
12381 * If we have accumulated too many values since the last carry
12382 * propagation, do it now, to avoid overflowing. (We could allow more
12383 * than NBASE - 1, if we reserved two extra digits, rather than one, for
12384 * carry propagation. But even with NBASE - 1, this needs to be done so
12385 * seldom, that the performance difference is negligible.)
12386 */
12387 if (accum->num_uncarried == NBASE - 1)
12388 accum_sum_carry(accum);
12389
12390 /*
12391 * Adjust the weight or scale of the old value, so that it can accommodate
12392 * the new value.
12393 */
12394 accum_sum_rescale(accum, val);
12395
12396 /* */
12397 if (val->sign == NUMERIC_POS)
12398 accum_digits = accum->pos_digits;
12399 else
12400 accum_digits = accum->neg_digits;
12401
12402 /* copy these values into local vars for speed in loop */
12403 val_ndigits = val->ndigits;
12404 val_digits = val->digits;
12405
12406 i = accum->weight - val->weight;
12407 for (val_i = 0; val_i < val_ndigits; val_i++)
12408 {
12409 accum_digits[i] += (int32) val_digits[val_i];
12410 i++;
12411 }
12412
12413 accum->num_uncarried++;
12414 }
12415
12416 /*
12417 * Propagate carries.
12418 */
12419 static void
12420 accum_sum_carry(NumericSumAccum *accum)
12421 {
12422 int i;
12423 int ndigits;
12424 int32 *dig;
12425 int32 carry;
12426 int32 newdig = 0;
12427
12428 /*
12429 * If no new values have been added since last carry propagation, nothing
12430 * to do.
12431 */
12432 if (accum->num_uncarried == 0)
12433 return;
12434
12435 /*
12436 * We maintain that the weight of the accumulator is always one larger
12437 * than needed to hold the current value, before carrying, to make sure
12438 * there is enough space for the possible extra digit when carry is
12439 * propagated. We cannot expand the buffer here, unless we require
12440 * callers of accum_sum_final() to switch to the right memory context.
12441 */
12442 Assert(accum->pos_digits[0] == 0 && accum->neg_digits[0] == 0);
12443
12444 ndigits = accum->ndigits;
12445
12446 /* Propagate carry in the positive sum */
12447 dig = accum->pos_digits;
12448 carry = 0;
12449 for (i = ndigits - 1; i >= 0; i--)
12450 {
12451 newdig = dig[i] + carry;
12452 if (newdig >= NBASE)
12453 {
12454 carry = newdig / NBASE;
12455 newdig -= carry * NBASE;
12456 }
12457 else
12458 carry = 0;
12459 dig[i] = newdig;
12460 }
12461 /* Did we use up the digit reserved for carry propagation? */
12462 if (newdig > 0)
12463 accum->have_carry_space = false;
12464
12465 /* And the same for the negative sum */
12466 dig = accum->neg_digits;
12467 carry = 0;
12468 for (i = ndigits - 1; i >= 0; i--)
12469 {
12470 newdig = dig[i] + carry;
12471 if (newdig >= NBASE)
12472 {
12473 carry = newdig / NBASE;
12474 newdig -= carry * NBASE;
12475 }
12476 else
12477 carry = 0;
12478 dig[i] = newdig;
12479 }
12480 if (newdig > 0)
12481 accum->have_carry_space = false;
12482
12483 accum->num_uncarried = 0;
12484 }
12485
12486 /*
12487 * Re-scale accumulator to accommodate new value.
12488 *
12489 * If the new value has more digits than the current digit buffers in the
12490 * accumulator, enlarge the buffers.
12491 */
12492 static void
12493 accum_sum_rescale(NumericSumAccum *accum, const NumericVar *val)
12494 {
12495 int old_weight = accum->weight;
12496 int old_ndigits = accum->ndigits;
12497 int accum_ndigits;
12498 int accum_weight;
12499 int accum_rscale;
12500 int val_rscale;
12501
12502 accum_weight = old_weight;
12503 accum_ndigits = old_ndigits;
12504
12505 /*
12506 * Does the new value have a larger weight? If so, enlarge the buffers,
12507 * and shift the existing value to the new weight, by adding leading
12508 * zeros.
12509 *
12510 * We enforce that the accumulator always has a weight one larger than
12511 * needed for the inputs, so that we have space for an extra digit at the
12512 * final carry-propagation phase, if necessary.
12513 */
12514 if (val->weight >= accum_weight)
12515 {
12516 accum_weight = val->weight + 1;
12517 accum_ndigits = accum_ndigits + (accum_weight - old_weight);
12518 }
12519
12520 /*
12521 * Even though the new value is small, we might've used up the space
12522 * reserved for the carry digit in the last call to accum_sum_carry(). If
12523 * so, enlarge to make room for another one.
12524 */
12525 else if (!accum->have_carry_space)
12526 {
12527 accum_weight++;
12528 accum_ndigits++;
12529 }
12530
12531 /* Is the new value wider on the right side? */
12532 accum_rscale = accum_ndigits - accum_weight - 1;
12533 val_rscale = val->ndigits - val->weight - 1;
12534 if (val_rscale > accum_rscale)
12535 accum_ndigits = accum_ndigits + (val_rscale - accum_rscale);
12536
12537 if (accum_ndigits != old_ndigits ||
12538 accum_weight != old_weight)
12539 {
12540 int32 *new_pos_digits;
12541 int32 *new_neg_digits;
12542 int weightdiff;
12543
12544 weightdiff = accum_weight - old_weight;
12545
12546 new_pos_digits = palloc0(accum_ndigits * sizeof(int32));
12547 new_neg_digits = palloc0(accum_ndigits * sizeof(int32));
12548
12549 if (accum->pos_digits)
12550 {
12551 memcpy(&new_pos_digits[weightdiff], accum->pos_digits,
12552 old_ndigits * sizeof(int32));
12553 pfree(accum->pos_digits);
12554
12555 memcpy(&new_neg_digits[weightdiff], accum->neg_digits,
12556 old_ndigits * sizeof(int32));
12557 pfree(accum->neg_digits);
12558 }
12559
12560 accum->pos_digits = new_pos_digits;
12561 accum->neg_digits = new_neg_digits;
12562
12563 accum->weight = accum_weight;
12564 accum->ndigits = accum_ndigits;
12565
12566 Assert(accum->pos_digits[0] == 0 && accum->neg_digits[0] == 0);
12567 accum->have_carry_space = true;
12568 }
12569
12570 if (val->dscale > accum->dscale)
12571 accum->dscale = val->dscale;
12572 }
12573
12574 /*
12575 * Return the current value of the accumulator. This perform final carry
12576 * propagation, and adds together the positive and negative sums.
12577 *
12578 * Unlike all the other routines, the caller is not required to switch to
12579 * the memory context that holds the accumulator.
12580 */
12581 static void
12582 accum_sum_final(NumericSumAccum *accum, NumericVar *result)
12583 {
12584 int i;
12585 NumericVar pos_var;
12586 NumericVar neg_var;
12587
12588 if (accum->ndigits == 0)
12589 {
12590 set_var_from_var(&const_zero, result);
12591 return;
12592 }
12593
12594 /* Perform final carry */
12595 accum_sum_carry(accum);
12596
12597 /* Create NumericVars representing the positive and negative sums */
12598 init_var(&pos_var);
12599 init_var(&neg_var);
12600
12601 pos_var.ndigits = neg_var.ndigits = accum->ndigits;
12602 pos_var.weight = neg_var.weight = accum->weight;
12603 pos_var.dscale = neg_var.dscale = accum->dscale;
12604 pos_var.sign = NUMERIC_POS;
12605 neg_var.sign = NUMERIC_NEG;
12606
12607 pos_var.buf = pos_var.digits = digitbuf_alloc(accum->ndigits);
12608 neg_var.buf = neg_var.digits = digitbuf_alloc(accum->ndigits);
12609
12610 for (i = 0; i < accum->ndigits; i++)
12611 {
12612 Assert(accum->pos_digits[i] < NBASE);
12613 pos_var.digits[i] = (int16) accum->pos_digits[i];
12614
12615 Assert(accum->neg_digits[i] < NBASE);
12616 neg_var.digits[i] = (int16) accum->neg_digits[i];
12617 }
12618
12619 /* And add them together */
12620 add_var(&pos_var, &neg_var, result);
12621
12622 /* Remove leading/trailing zeroes */
12623 strip_var(result);
12624 }
12625
12626 /*
12627 * Copy an accumulator's state.
12628 *
12629 * 'dst' is assumed to be uninitialized beforehand. No attempt is made at
12630 * freeing old values.
12631 */
12632 static void
12633 accum_sum_copy(NumericSumAccum *dst, NumericSumAccum *src)
12634 {
12635 dst->pos_digits = palloc(src->ndigits * sizeof(int32));
12636 dst->neg_digits = palloc(src->ndigits * sizeof(int32));
12637
12638 memcpy(dst->pos_digits, src->pos_digits, src->ndigits * sizeof(int32));
12639 memcpy(dst->neg_digits, src->neg_digits, src->ndigits * sizeof(int32));
12640 dst->num_uncarried = src->num_uncarried;
12641 dst->ndigits = src->ndigits;
12642 dst->weight = src->weight;
12643 dst->dscale = src->dscale;
12644 }
12645
12646 /*
12647 * Add the current value of 'accum2' into 'accum'.
12648 */
12649 static void
12650 accum_sum_combine(NumericSumAccum *accum, NumericSumAccum *accum2)
12651 {
12652 NumericVar tmp_var;
12653
12654 init_var(&tmp_var);
12655
12656 accum_sum_final(accum2, &tmp_var);
12657 accum_sum_add(accum, &tmp_var);
12658
12659 free_var(&tmp_var);
12660 }