Branch data Line data Source code
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-2026, 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 "common/int128.h"
32 : : #include "funcapi.h"
33 : : #include "lib/hyperloglog.h"
34 : : #include "libpq/pqformat.h"
35 : : #include "miscadmin.h"
36 : : #include "nodes/nodeFuncs.h"
37 : : #include "nodes/supportnodes.h"
38 : : #include "optimizer/optimizer.h"
39 : : #include "utils/array.h"
40 : : #include "utils/builtins.h"
41 : : #include "utils/float.h"
42 : : #include "utils/guc.h"
43 : : #include "utils/numeric.h"
44 : : #include "utils/pg_lsn.h"
45 : : #include "utils/sortsupport.h"
46 : :
47 : : /* ----------
48 : : * Uncomment the following to enable compilation of dump_numeric()
49 : : * and dump_var() and to get a dump of any result produced by make_result().
50 : : * ----------
51 : : */
52 : : /* #define NUMERIC_DEBUG */
53 : :
54 : :
55 : : /* ----------
56 : : * Local data types
57 : : *
58 : : * Numeric values are represented in a base-NBASE floating point format.
59 : : * Each "digit" ranges from 0 to NBASE-1. The type NumericDigit is signed
60 : : * and wide enough to store a digit. We assume that NBASE*NBASE can fit in
61 : : * an int. Although the purely calculational routines could handle any even
62 : : * NBASE that's less than sqrt(INT_MAX), in practice we are only interested
63 : : * in NBASE a power of ten, so that I/O conversions and decimal rounding
64 : : * are easy. Also, it's actually more efficient if NBASE is rather less than
65 : : * sqrt(INT_MAX), so that there is "headroom" for mul_var and div_var to
66 : : * postpone processing carries.
67 : : *
68 : : * Values of NBASE other than 10000 are considered of historical interest only
69 : : * and are no longer supported in any sense; no mechanism exists for the client
70 : : * to discover the base, so every client supporting binary mode expects the
71 : : * base-10000 format. If you plan to change this, also note the numeric
72 : : * abbreviation code, which assumes NBASE=10000.
73 : : * ----------
74 : : */
75 : :
76 : : #if 0
77 : : #define NBASE 10
78 : : #define HALF_NBASE 5
79 : : #define DEC_DIGITS 1 /* decimal digits per NBASE digit */
80 : : #define MUL_GUARD_DIGITS 4 /* these are measured in NBASE digits */
81 : : #define DIV_GUARD_DIGITS 8
82 : :
83 : : typedef signed char NumericDigit;
84 : : #endif
85 : :
86 : : #if 0
87 : : #define NBASE 100
88 : : #define HALF_NBASE 50
89 : : #define DEC_DIGITS 2 /* decimal digits per NBASE digit */
90 : : #define MUL_GUARD_DIGITS 3 /* these are measured in NBASE digits */
91 : : #define DIV_GUARD_DIGITS 6
92 : :
93 : : typedef signed char NumericDigit;
94 : : #endif
95 : :
96 : : #if 1
97 : : #define NBASE 10000
98 : : #define HALF_NBASE 5000
99 : : #define DEC_DIGITS 4 /* decimal digits per NBASE digit */
100 : : #define MUL_GUARD_DIGITS 2 /* these are measured in NBASE digits */
101 : : #define DIV_GUARD_DIGITS 4
102 : :
103 : : typedef int16 NumericDigit;
104 : : #endif
105 : :
106 : : #define NBASE_SQR (NBASE * NBASE)
107 : :
108 : : /*
109 : : * The Numeric type as stored on disk.
110 : : *
111 : : * If the high bits of the first word of a NumericChoice (n_header, or
112 : : * n_short.n_header, or n_long.n_sign_dscale) are NUMERIC_SHORT, then the
113 : : * numeric follows the NumericShort format; if they are NUMERIC_POS or
114 : : * NUMERIC_NEG, it follows the NumericLong format. If they are NUMERIC_SPECIAL,
115 : : * the value is a NaN or Infinity. We currently always store SPECIAL values
116 : : * using just two bytes (i.e. only n_header), but previous releases used only
117 : : * the NumericLong format, so we might find 4-byte NaNs (though not infinities)
118 : : * on disk if a database has been migrated using pg_upgrade. In either case,
119 : : * the low-order bits of a special value's header are reserved and currently
120 : : * should always be set to zero.
121 : : *
122 : : * In the NumericShort format, the remaining 14 bits of the header word
123 : : * (n_short.n_header) are allocated as follows: 1 for sign (positive or
124 : : * negative), 6 for dynamic scale, and 7 for weight. In practice, most
125 : : * commonly-encountered values can be represented this way.
126 : : *
127 : : * In the NumericLong format, the remaining 14 bits of the header word
128 : : * (n_long.n_sign_dscale) represent the display scale; and the weight is
129 : : * stored separately in n_weight.
130 : : *
131 : : * NOTE: by convention, values in the packed form have been stripped of
132 : : * all leading and trailing zero digits (where a "digit" is of base NBASE).
133 : : * In particular, if the value is zero, there will be no digits at all!
134 : : * The weight is arbitrary in that case, but we normally set it to zero.
135 : : */
136 : :
137 : : struct NumericShort
138 : : {
139 : : uint16 n_header; /* Sign + display scale + weight */
140 : : NumericDigit n_data[FLEXIBLE_ARRAY_MEMBER]; /* Digits */
141 : : };
142 : :
143 : : struct NumericLong
144 : : {
145 : : uint16 n_sign_dscale; /* Sign + display scale */
146 : : int16 n_weight; /* Weight of 1st digit */
147 : : NumericDigit n_data[FLEXIBLE_ARRAY_MEMBER]; /* Digits */
148 : : };
149 : :
150 : : union NumericChoice
151 : : {
152 : : uint16 n_header; /* Header word */
153 : : struct NumericLong n_long; /* Long form (4-byte header) */
154 : : struct NumericShort n_short; /* Short form (2-byte header) */
155 : : };
156 : :
157 : : struct NumericData
158 : : {
159 : : int32 vl_len_; /* varlena header (do not touch directly!) */
160 : : union NumericChoice choice; /* choice of format */
161 : : };
162 : :
163 : :
164 : : /*
165 : : * Interpretation of high bits.
166 : : */
167 : :
168 : : #define NUMERIC_SIGN_MASK 0xC000
169 : : #define NUMERIC_POS 0x0000
170 : : #define NUMERIC_NEG 0x4000
171 : : #define NUMERIC_SHORT 0x8000
172 : : #define NUMERIC_SPECIAL 0xC000
173 : :
174 : : #define NUMERIC_FLAGBITS(n) ((n)->choice.n_header & NUMERIC_SIGN_MASK)
175 : : #define NUMERIC_IS_SHORT(n) (NUMERIC_FLAGBITS(n) == NUMERIC_SHORT)
176 : : #define NUMERIC_IS_SPECIAL(n) (NUMERIC_FLAGBITS(n) == NUMERIC_SPECIAL)
177 : :
178 : : #define NUMERIC_HDRSZ (VARHDRSZ + sizeof(uint16) + sizeof(int16))
179 : : #define NUMERIC_HDRSZ_SHORT (VARHDRSZ + sizeof(uint16))
180 : :
181 : : /*
182 : : * If the flag bits are NUMERIC_SHORT or NUMERIC_SPECIAL, we want the short
183 : : * header; otherwise, we want the long one. Instead of testing against each
184 : : * value, we can just look at the high bit, for a slight efficiency gain.
185 : : */
186 : : #define NUMERIC_HEADER_IS_SHORT(n) (((n)->choice.n_header & 0x8000) != 0)
187 : : #define NUMERIC_HEADER_SIZE(n) \
188 : : (VARHDRSZ + sizeof(uint16) + \
189 : : (NUMERIC_HEADER_IS_SHORT(n) ? 0 : sizeof(int16)))
190 : :
191 : : /*
192 : : * Definitions for special values (NaN, positive infinity, negative infinity).
193 : : *
194 : : * The two bits after the NUMERIC_SPECIAL bits are 00 for NaN, 01 for positive
195 : : * infinity, 11 for negative infinity. (This makes the sign bit match where
196 : : * it is in a short-format value, though we make no use of that at present.)
197 : : * We could mask off the remaining bits before testing the active bits, but
198 : : * currently those bits must be zeroes, so masking would just add cycles.
199 : : */
200 : : #define NUMERIC_EXT_SIGN_MASK 0xF000 /* high bits plus NaN/Inf flag bits */
201 : : #define NUMERIC_NAN 0xC000
202 : : #define NUMERIC_PINF 0xD000
203 : : #define NUMERIC_NINF 0xF000
204 : : #define NUMERIC_INF_SIGN_MASK 0x2000
205 : :
206 : : #define NUMERIC_EXT_FLAGBITS(n) ((n)->choice.n_header & NUMERIC_EXT_SIGN_MASK)
207 : : #define NUMERIC_IS_NAN(n) ((n)->choice.n_header == NUMERIC_NAN)
208 : : #define NUMERIC_IS_PINF(n) ((n)->choice.n_header == NUMERIC_PINF)
209 : : #define NUMERIC_IS_NINF(n) ((n)->choice.n_header == NUMERIC_NINF)
210 : : #define NUMERIC_IS_INF(n) \
211 : : (((n)->choice.n_header & ~NUMERIC_INF_SIGN_MASK) == NUMERIC_PINF)
212 : :
213 : : /*
214 : : * Short format definitions.
215 : : */
216 : :
217 : : #define NUMERIC_SHORT_SIGN_MASK 0x2000
218 : : #define NUMERIC_SHORT_DSCALE_MASK 0x1F80
219 : : #define NUMERIC_SHORT_DSCALE_SHIFT 7
220 : : #define NUMERIC_SHORT_DSCALE_MAX \
221 : : (NUMERIC_SHORT_DSCALE_MASK >> NUMERIC_SHORT_DSCALE_SHIFT)
222 : : #define NUMERIC_SHORT_WEIGHT_SIGN_MASK 0x0040
223 : : #define NUMERIC_SHORT_WEIGHT_MASK 0x003F
224 : : #define NUMERIC_SHORT_WEIGHT_MAX NUMERIC_SHORT_WEIGHT_MASK
225 : : #define NUMERIC_SHORT_WEIGHT_MIN (-(NUMERIC_SHORT_WEIGHT_MASK+1))
226 : :
227 : : /*
228 : : * Extract sign, display scale, weight. These macros extract field values
229 : : * suitable for the NumericVar format from the Numeric (on-disk) format.
230 : : *
231 : : * Note that we don't trouble to ensure that dscale and weight read as zero
232 : : * for an infinity; however, that doesn't matter since we never convert
233 : : * "special" numerics to NumericVar form. Only the constants defined below
234 : : * (const_nan, etc) ever represent a non-finite value as a NumericVar.
235 : : */
236 : :
237 : : #define NUMERIC_DSCALE_MASK 0x3FFF
238 : : #define NUMERIC_DSCALE_MAX NUMERIC_DSCALE_MASK
239 : :
240 : : #define NUMERIC_SIGN(n) \
241 : : (NUMERIC_IS_SHORT(n) ? \
242 : : (((n)->choice.n_short.n_header & NUMERIC_SHORT_SIGN_MASK) ? \
243 : : NUMERIC_NEG : NUMERIC_POS) : \
244 : : (NUMERIC_IS_SPECIAL(n) ? \
245 : : NUMERIC_EXT_FLAGBITS(n) : NUMERIC_FLAGBITS(n)))
246 : : #define NUMERIC_DSCALE(n) (NUMERIC_HEADER_IS_SHORT((n)) ? \
247 : : ((n)->choice.n_short.n_header & NUMERIC_SHORT_DSCALE_MASK) \
248 : : >> NUMERIC_SHORT_DSCALE_SHIFT \
249 : : : ((n)->choice.n_long.n_sign_dscale & NUMERIC_DSCALE_MASK))
250 : : #define NUMERIC_WEIGHT(n) (NUMERIC_HEADER_IS_SHORT((n)) ? \
251 : : (((n)->choice.n_short.n_header & NUMERIC_SHORT_WEIGHT_SIGN_MASK ? \
252 : : ~NUMERIC_SHORT_WEIGHT_MASK : 0) \
253 : : | ((n)->choice.n_short.n_header & NUMERIC_SHORT_WEIGHT_MASK)) \
254 : : : ((n)->choice.n_long.n_weight))
255 : :
256 : : /*
257 : : * Maximum weight of a stored Numeric value (based on the use of int16 for the
258 : : * weight in NumericLong). Note that intermediate values held in NumericVar
259 : : * and NumericSumAccum variables may have much larger weights.
260 : : */
261 : : #define NUMERIC_WEIGHT_MAX PG_INT16_MAX
262 : :
263 : : /* ----------
264 : : * NumericVar is the format we use for arithmetic. The digit-array part
265 : : * is the same as the NumericData storage format, but the header is more
266 : : * complex.
267 : : *
268 : : * The value represented by a NumericVar is determined by the sign, weight,
269 : : * ndigits, and digits[] array. If it is a "special" value (NaN or Inf)
270 : : * then only the sign field matters; ndigits should be zero, and the weight
271 : : * and dscale fields are ignored.
272 : : *
273 : : * Note: the first digit of a NumericVar's value is assumed to be multiplied
274 : : * by NBASE ** weight. Another way to say it is that there are weight+1
275 : : * digits before the decimal point. It is possible to have weight < 0.
276 : : *
277 : : * buf points at the physical start of the palloc'd digit buffer for the
278 : : * NumericVar. digits points at the first digit in actual use (the one
279 : : * with the specified weight). We normally leave an unused digit or two
280 : : * (preset to zeroes) between buf and digits, so that there is room to store
281 : : * a carry out of the top digit without reallocating space. We just need to
282 : : * decrement digits (and increment weight) to make room for the carry digit.
283 : : * (There is no such extra space in a numeric value stored in the database,
284 : : * only in a NumericVar in memory.)
285 : : *
286 : : * If buf is NULL then the digit buffer isn't actually palloc'd and should
287 : : * not be freed --- see the constants below for an example.
288 : : *
289 : : * dscale, or display scale, is the nominal precision expressed as number
290 : : * of digits after the decimal point (it must always be >= 0 at present).
291 : : * dscale may be more than the number of physically stored fractional digits,
292 : : * implying that we have suppressed storage of significant trailing zeroes.
293 : : * It should never be less than the number of stored digits, since that would
294 : : * imply hiding digits that are present. NOTE that dscale is always expressed
295 : : * in *decimal* digits, and so it may correspond to a fractional number of
296 : : * base-NBASE digits --- divide by DEC_DIGITS to convert to NBASE digits.
297 : : *
298 : : * rscale, or result scale, is the target precision for a computation.
299 : : * Like dscale it is expressed as number of *decimal* digits after the decimal
300 : : * point, and is always >= 0 at present.
301 : : * Note that rscale is not stored in variables --- it's figured on-the-fly
302 : : * from the dscales of the inputs.
303 : : *
304 : : * While we consistently use "weight" to refer to the base-NBASE weight of
305 : : * a numeric value, it is convenient in some scale-related calculations to
306 : : * make use of the base-10 weight (ie, the approximate log10 of the value).
307 : : * To avoid confusion, such a decimal-units weight is called a "dweight".
308 : : *
309 : : * NB: All the variable-level functions are written in a style that makes it
310 : : * possible to give one and the same variable as argument and destination.
311 : : * This is feasible because the digit buffer is separate from the variable.
312 : : * ----------
313 : : */
314 : : typedef struct NumericVar
315 : : {
316 : : int ndigits; /* # of digits in digits[] - can be 0! */
317 : : int weight; /* weight of first digit */
318 : : int sign; /* NUMERIC_POS, _NEG, _NAN, _PINF, or _NINF */
319 : : int dscale; /* display scale */
320 : : NumericDigit *buf; /* start of palloc'd space for digits[] */
321 : : NumericDigit *digits; /* base-NBASE digits */
322 : : } NumericVar;
323 : :
324 : :
325 : : /* ----------
326 : : * Data for generate_series
327 : : * ----------
328 : : */
329 : : typedef struct
330 : : {
331 : : NumericVar current;
332 : : NumericVar stop;
333 : : NumericVar step;
334 : : } generate_series_numeric_fctx;
335 : :
336 : :
337 : : /* ----------
338 : : * Sort support.
339 : : * ----------
340 : : */
341 : : typedef struct
342 : : {
343 : : void *buf; /* buffer for short varlenas */
344 : : int64 input_count; /* number of non-null values seen */
345 : : bool estimating; /* true if estimating cardinality */
346 : :
347 : : hyperLogLogState abbr_card; /* cardinality estimator */
348 : : } NumericSortSupport;
349 : :
350 : :
351 : : /* ----------
352 : : * Fast sum accumulator.
353 : : *
354 : : * NumericSumAccum is used to implement SUM(), and other standard aggregates
355 : : * that track the sum of input values. It uses 32-bit integers to store the
356 : : * digits, instead of the normal 16-bit integers (with NBASE=10000). This
357 : : * way, we can safely accumulate up to NBASE - 1 values without propagating
358 : : * carry, before risking overflow of any of the digits. 'num_uncarried'
359 : : * tracks how many values have been accumulated without propagating carry.
360 : : *
361 : : * Positive and negative values are accumulated separately, in 'pos_digits'
362 : : * and 'neg_digits'. This is simpler and faster than deciding whether to add
363 : : * or subtract from the current value, for each new value (see sub_var() for
364 : : * the logic we avoid by doing this). Both buffers are of same size, and
365 : : * have the same weight and scale. In accum_sum_final(), the positive and
366 : : * negative sums are added together to produce the final result.
367 : : *
368 : : * When a new value has a larger ndigits or weight than the accumulator
369 : : * currently does, the accumulator is enlarged to accommodate the new value.
370 : : * We normally have one zero digit reserved for carry propagation, and that
371 : : * is indicated by the 'have_carry_space' flag. When accum_sum_carry() uses
372 : : * up the reserved digit, it clears the 'have_carry_space' flag. The next
373 : : * call to accum_sum_add() will enlarge the buffer, to make room for the
374 : : * extra digit, and set the flag again.
375 : : *
376 : : * To initialize a new accumulator, simply reset all fields to zeros.
377 : : *
378 : : * The accumulator does not handle NaNs.
379 : : * ----------
380 : : */
381 : : typedef struct NumericSumAccum
382 : : {
383 : : int ndigits;
384 : : int weight;
385 : : int dscale;
386 : : int num_uncarried;
387 : : bool have_carry_space;
388 : : int32 *pos_digits;
389 : : int32 *neg_digits;
390 : : } NumericSumAccum;
391 : :
392 : :
393 : : /*
394 : : * We define our own macros for packing and unpacking abbreviated-key
395 : : * representations, just to have a notational indication that that's
396 : : * what we're doing. Now that sizeof(Datum) is always 8, we can rely
397 : : * on fitting an int64 into Datum.
398 : : *
399 : : * The range of abbreviations for finite values is from +PG_INT64_MAX
400 : : * to -PG_INT64_MAX. NaN has the abbreviation PG_INT64_MIN, and we
401 : : * define the sort ordering to make that work out properly (see further
402 : : * comments below). PINF and NINF share the abbreviations of the largest
403 : : * and smallest finite abbreviation classes.
404 : : */
405 : : #define NumericAbbrevGetDatum(X) Int64GetDatum(X)
406 : : #define DatumGetNumericAbbrev(X) DatumGetInt64(X)
407 : : #define NUMERIC_ABBREV_NAN NumericAbbrevGetDatum(PG_INT64_MIN)
408 : : #define NUMERIC_ABBREV_PINF NumericAbbrevGetDatum(-PG_INT64_MAX)
409 : : #define NUMERIC_ABBREV_NINF NumericAbbrevGetDatum(PG_INT64_MAX)
410 : :
411 : :
412 : : /* ----------
413 : : * Some preinitialized constants
414 : : * ----------
415 : : */
416 : : static const NumericDigit const_zero_data[1] = {0};
417 : : static const NumericVar const_zero =
418 : : {0, 0, NUMERIC_POS, 0, NULL, unconstify_constexpr(NumericDigit *, const_zero_data)};
419 : :
420 : : static const NumericDigit const_one_data[1] = {1};
421 : : static const NumericVar const_one =
422 : : {1, 0, NUMERIC_POS, 0, NULL, unconstify_constexpr(NumericDigit *, const_one_data)};
423 : :
424 : : static const NumericVar const_minus_one =
425 : : {1, 0, NUMERIC_NEG, 0, NULL, unconstify_constexpr(NumericDigit *, const_one_data)};
426 : :
427 : : static const NumericDigit const_two_data[1] = {2};
428 : : static const NumericVar const_two =
429 : : {1, 0, NUMERIC_POS, 0, NULL, unconstify_constexpr(NumericDigit *, const_two_data)};
430 : :
431 : : #if DEC_DIGITS == 4
432 : : static const NumericDigit const_zero_point_nine_data[1] = {9000};
433 : : #elif DEC_DIGITS == 2
434 : : static const NumericDigit const_zero_point_nine_data[1] = {90};
435 : : #elif DEC_DIGITS == 1
436 : : static const NumericDigit const_zero_point_nine_data[1] = {9};
437 : : #endif
438 : : static const NumericVar const_zero_point_nine =
439 : : {1, -1, NUMERIC_POS, 1, NULL, unconstify_constexpr(NumericDigit *, const_zero_point_nine_data)};
440 : :
441 : : #if DEC_DIGITS == 4
442 : : static const NumericDigit const_one_point_one_data[2] = {1, 1000};
443 : : #elif DEC_DIGITS == 2
444 : : static const NumericDigit const_one_point_one_data[2] = {1, 10};
445 : : #elif DEC_DIGITS == 1
446 : : static const NumericDigit const_one_point_one_data[2] = {1, 1};
447 : : #endif
448 : : static const NumericVar const_one_point_one =
449 : : {2, 0, NUMERIC_POS, 1, NULL, unconstify_constexpr(NumericDigit *, const_one_point_one_data)};
450 : :
451 : : static const NumericVar const_nan =
452 : : {0, 0, NUMERIC_NAN, 0, NULL, NULL};
453 : :
454 : : static const NumericVar const_pinf =
455 : : {0, 0, NUMERIC_PINF, 0, NULL, NULL};
456 : :
457 : : static const NumericVar const_ninf =
458 : : {0, 0, NUMERIC_NINF, 0, NULL, NULL};
459 : :
460 : : #if DEC_DIGITS == 4
461 : : static const int round_powers[4] = {0, 1000, 100, 10};
462 : : #endif
463 : :
464 : :
465 : : /* ----------
466 : : * Local functions
467 : : * ----------
468 : : */
469 : :
470 : : #ifdef NUMERIC_DEBUG
471 : : static void dump_numeric(const char *str, Numeric num);
472 : : static void dump_var(const char *str, NumericVar *var);
473 : : #else
474 : : #define dump_numeric(s,n)
475 : : #define dump_var(s,v)
476 : : #endif
477 : :
478 : : #define digitbuf_alloc(ndigits) \
479 : : (palloc_array(NumericDigit, (ndigits)))
480 : : #define digitbuf_free(buf) \
481 : : do { \
482 : : if ((buf) != NULL) \
483 : : pfree(buf); \
484 : : } while (0)
485 : :
486 : : #define init_var(v) memset(v, 0, sizeof(NumericVar))
487 : :
488 : : #define NUMERIC_DIGITS(num) (NUMERIC_HEADER_IS_SHORT(num) ? \
489 : : (num)->choice.n_short.n_data : (num)->choice.n_long.n_data)
490 : : #define NUMERIC_NDIGITS(num) \
491 : : ((VARSIZE(num) - NUMERIC_HEADER_SIZE(num)) / sizeof(NumericDigit))
492 : : #define NUMERIC_CAN_BE_SHORT(scale,weight) \
493 : : ((scale) <= NUMERIC_SHORT_DSCALE_MAX && \
494 : : (weight) <= NUMERIC_SHORT_WEIGHT_MAX && \
495 : : (weight) >= NUMERIC_SHORT_WEIGHT_MIN)
496 : :
497 : : static void alloc_var(NumericVar *var, int ndigits);
498 : : static void free_var(NumericVar *var);
499 : : static void zero_var(NumericVar *var);
500 : :
501 : : static bool set_var_from_str(const char *str, const char *cp,
502 : : NumericVar *dest, const char **endptr,
503 : : Node *escontext);
504 : : static bool set_var_from_non_decimal_integer_str(const char *str,
505 : : const char *cp, int sign,
506 : : int base, NumericVar *dest,
507 : : const char **endptr,
508 : : Node *escontext);
509 : : static void set_var_from_num(Numeric num, NumericVar *dest);
510 : : static void init_var_from_num(Numeric num, NumericVar *dest);
511 : : static void set_var_from_var(const NumericVar *value, NumericVar *dest);
512 : : static char *get_str_from_var(const NumericVar *var);
513 : : static char *get_str_from_var_sci(const NumericVar *var, int rscale);
514 : :
515 : : static void numericvar_serialize(StringInfo buf, const NumericVar *var);
516 : : static void numericvar_deserialize(StringInfo buf, NumericVar *var);
517 : :
518 : : static Numeric duplicate_numeric(Numeric num);
519 : : static Numeric make_result(const NumericVar *var);
520 : : static Numeric make_result_safe(const NumericVar *var, Node *escontext);
521 : :
522 : : static bool apply_typmod(NumericVar *var, int32 typmod, Node *escontext);
523 : : static bool apply_typmod_special(Numeric num, int32 typmod, Node *escontext);
524 : :
525 : : static bool numericvar_to_int32(const NumericVar *var, int32 *result);
526 : : static bool numericvar_to_int64(const NumericVar *var, int64 *result);
527 : : static void int64_to_numericvar(int64 val, NumericVar *var);
528 : : static bool numericvar_to_uint64(const NumericVar *var, uint64 *result);
529 : : static void int128_to_numericvar(INT128 val, NumericVar *var);
530 : : static double numericvar_to_double_no_overflow(const NumericVar *var);
531 : :
532 : : static Datum numeric_abbrev_convert(Datum original_datum, SortSupport ssup);
533 : : static bool numeric_abbrev_abort(int memtupcount, SortSupport ssup);
534 : : static int numeric_fast_cmp(Datum x, Datum y, SortSupport ssup);
535 : : static int numeric_cmp_abbrev(Datum x, Datum y, SortSupport ssup);
536 : :
537 : : static Datum numeric_abbrev_convert_var(const NumericVar *var,
538 : : NumericSortSupport *nss);
539 : :
540 : : static int cmp_numerics(Numeric num1, Numeric num2);
541 : : static int cmp_var(const NumericVar *var1, const NumericVar *var2);
542 : : static int cmp_var_common(const NumericDigit *var1digits, int var1ndigits,
543 : : int var1weight, int var1sign,
544 : : const NumericDigit *var2digits, int var2ndigits,
545 : : int var2weight, int var2sign);
546 : : static void add_var(const NumericVar *var1, const NumericVar *var2,
547 : : NumericVar *result);
548 : : static void sub_var(const NumericVar *var1, const NumericVar *var2,
549 : : NumericVar *result);
550 : : static void mul_var(const NumericVar *var1, const NumericVar *var2,
551 : : NumericVar *result,
552 : : int rscale);
553 : : static void mul_var_short(const NumericVar *var1, const NumericVar *var2,
554 : : NumericVar *result);
555 : : static void div_var(const NumericVar *var1, const NumericVar *var2,
556 : : NumericVar *result, int rscale, bool round, bool exact);
557 : : static void div_var_int(const NumericVar *var, int ival, int ival_weight,
558 : : NumericVar *result, int rscale, bool round);
559 : : #ifdef HAVE_INT128
560 : : static void div_var_int64(const NumericVar *var, int64 ival, int ival_weight,
561 : : NumericVar *result, int rscale, bool round);
562 : : #endif
563 : : static int select_div_scale(const NumericVar *var1, const NumericVar *var2);
564 : : static void mod_var(const NumericVar *var1, const NumericVar *var2,
565 : : NumericVar *result);
566 : : static void div_mod_var(const NumericVar *var1, const NumericVar *var2,
567 : : NumericVar *quot, NumericVar *rem);
568 : : static void ceil_var(const NumericVar *var, NumericVar *result);
569 : : static void floor_var(const NumericVar *var, NumericVar *result);
570 : :
571 : : static void gcd_var(const NumericVar *var1, const NumericVar *var2,
572 : : NumericVar *result);
573 : : static void sqrt_var(const NumericVar *arg, NumericVar *result, int rscale);
574 : : static void exp_var(const NumericVar *arg, NumericVar *result, int rscale);
575 : : static int estimate_ln_dweight(const NumericVar *var);
576 : : static void ln_var(const NumericVar *arg, NumericVar *result, int rscale);
577 : : static void log_var(const NumericVar *base, const NumericVar *num,
578 : : NumericVar *result);
579 : : static void power_var(const NumericVar *base, const NumericVar *exp,
580 : : NumericVar *result);
581 : : static void power_var_int(const NumericVar *base, int exp, int exp_dscale,
582 : : NumericVar *result);
583 : : static void power_ten_int(int exp, NumericVar *result);
584 : : static void random_var(pg_prng_state *state, const NumericVar *rmin,
585 : : const NumericVar *rmax, NumericVar *result);
586 : :
587 : : static int cmp_abs(const NumericVar *var1, const NumericVar *var2);
588 : : static int cmp_abs_common(const NumericDigit *var1digits, int var1ndigits,
589 : : int var1weight,
590 : : const NumericDigit *var2digits, int var2ndigits,
591 : : int var2weight);
592 : : static void add_abs(const NumericVar *var1, const NumericVar *var2,
593 : : NumericVar *result);
594 : : static void sub_abs(const NumericVar *var1, const NumericVar *var2,
595 : : NumericVar *result);
596 : : static void round_var(NumericVar *var, int rscale);
597 : : static void trunc_var(NumericVar *var, int rscale);
598 : : static void strip_var(NumericVar *var);
599 : : static void compute_bucket(Numeric operand, Numeric bound1, Numeric bound2,
600 : : const NumericVar *count_var,
601 : : NumericVar *result_var);
602 : :
603 : : static void accum_sum_add(NumericSumAccum *accum, const NumericVar *val);
604 : : static void accum_sum_rescale(NumericSumAccum *accum, const NumericVar *val);
605 : : static void accum_sum_carry(NumericSumAccum *accum);
606 : : static void accum_sum_reset(NumericSumAccum *accum);
607 : : static void accum_sum_final(NumericSumAccum *accum, NumericVar *result);
608 : : static void accum_sum_copy(NumericSumAccum *dst, NumericSumAccum *src);
609 : : static void accum_sum_combine(NumericSumAccum *accum, NumericSumAccum *accum2);
610 : :
611 : :
612 : : /* ----------------------------------------------------------------------
613 : : *
614 : : * Input-, output- and rounding-functions
615 : : *
616 : : * ----------------------------------------------------------------------
617 : : */
618 : :
619 : :
620 : : /*
621 : : * numeric_in() -
622 : : *
623 : : * Input function for numeric data type
624 : : */
625 : : Datum
626 : 102850 : numeric_in(PG_FUNCTION_ARGS)
627 : : {
628 : 102850 : char *str = PG_GETARG_CSTRING(0);
629 : : #ifdef NOT_USED
630 : : Oid typelem = PG_GETARG_OID(1);
631 : : #endif
632 : 102850 : int32 typmod = PG_GETARG_INT32(2);
633 : 102850 : Node *escontext = fcinfo->context;
634 : : Numeric res;
635 : : const char *cp;
636 : : const char *numstart;
637 : : int sign;
638 : :
639 : : /* Skip leading spaces */
640 : 102850 : cp = str;
641 [ + + ]: 119130 : while (*cp)
642 : : {
643 [ + + ]: 119118 : if (!isspace((unsigned char) *cp))
644 : 102838 : break;
645 : 16280 : cp++;
646 : : }
647 : :
648 : : /*
649 : : * Process the number's sign. This duplicates logic in set_var_from_str(),
650 : : * but it's worth doing here, since it simplifies the handling of
651 : : * infinities and non-decimal integers.
652 : : */
653 : 102850 : numstart = cp;
654 : 102850 : sign = NUMERIC_POS;
655 : :
656 [ + + ]: 102850 : if (*cp == '+')
657 : 32 : cp++;
658 [ + + ]: 102818 : else if (*cp == '-')
659 : : {
660 : 2512 : sign = NUMERIC_NEG;
661 : 2512 : cp++;
662 : : }
663 : :
664 : : /*
665 : : * Check for NaN and infinities. We recognize the same strings allowed by
666 : : * float8in().
667 : : *
668 : : * Since all other legal inputs have a digit or a decimal point after the
669 : : * sign, we need only check for NaN/infinity if that's not the case.
670 : : */
671 [ + + + + ]: 102850 : if (!isdigit((unsigned char) *cp) && *cp != '.')
672 : : {
673 : : /*
674 : : * The number must be NaN or infinity; anything else can only be a
675 : : * syntax error. Note that NaN mustn't have a sign.
676 : : */
677 [ + + ]: 1209 : if (pg_strncasecmp(numstart, "NaN", 3) == 0)
678 : : {
679 : 397 : res = make_result(&const_nan);
680 : 397 : cp = numstart + 3;
681 : : }
682 [ + + ]: 812 : else if (pg_strncasecmp(cp, "Infinity", 8) == 0)
683 : : {
684 [ + + ]: 339 : res = make_result(sign == NUMERIC_POS ? &const_pinf : &const_ninf);
685 : 339 : cp += 8;
686 : : }
687 [ + + ]: 473 : else if (pg_strncasecmp(cp, "inf", 3) == 0)
688 : : {
689 [ + + ]: 400 : res = make_result(sign == NUMERIC_POS ? &const_pinf : &const_ninf);
690 : 400 : cp += 3;
691 : : }
692 : : else
693 : 73 : goto invalid_syntax;
694 : :
695 : : /*
696 : : * Check for trailing junk; there should be nothing left but spaces.
697 : : *
698 : : * We intentionally do this check before applying the typmod because
699 : : * we would like to throw any trailing-junk syntax error before any
700 : : * semantic error resulting from apply_typmod_special().
701 : : */
702 [ + + ]: 1164 : while (*cp)
703 : : {
704 [ - + ]: 28 : if (!isspace((unsigned char) *cp))
705 : 0 : goto invalid_syntax;
706 : 28 : cp++;
707 : : }
708 : :
709 [ - + ]: 1136 : if (!apply_typmod_special(res, typmod, escontext))
710 : 0 : PG_RETURN_NULL();
711 : : }
712 : : else
713 : : {
714 : : /*
715 : : * We have a normal numeric value, which may be a non-decimal integer
716 : : * or a regular decimal number.
717 : : */
718 : : NumericVar value;
719 : : int base;
720 : :
721 : 101641 : init_var(&value);
722 : :
723 : : /*
724 : : * Determine the number's base by looking for a non-decimal prefix
725 : : * indicator ("0x", "0o", or "0b").
726 : : */
727 [ + + ]: 101641 : if (cp[0] == '0')
728 : : {
729 [ + + + + ]: 31934 : switch (cp[1])
730 : : {
731 : 48 : case 'x':
732 : : case 'X':
733 : 48 : base = 16;
734 : 48 : break;
735 : 28 : case 'o':
736 : : case 'O':
737 : 28 : base = 8;
738 : 28 : break;
739 : 28 : case 'b':
740 : : case 'B':
741 : 28 : base = 2;
742 : 28 : break;
743 : 31830 : default:
744 : 31830 : base = 10;
745 : : }
746 : : }
747 : : else
748 : 69707 : base = 10;
749 : :
750 : : /* Parse the rest of the number and apply the sign */
751 [ + + ]: 101641 : if (base == 10)
752 : : {
753 [ - + ]: 101537 : if (!set_var_from_str(str, cp, &value, &cp, escontext))
754 : 16 : PG_RETURN_NULL();
755 : 101505 : value.sign = sign;
756 : : }
757 : : else
758 : : {
759 [ - + ]: 104 : if (!set_var_from_non_decimal_integer_str(str, cp + 2, sign, base,
760 : : &value, &cp, escontext))
761 : 0 : PG_RETURN_NULL();
762 : : }
763 : :
764 : : /*
765 : : * Should be nothing left but spaces. As above, throw any typmod error
766 : : * after finishing syntax check.
767 : : */
768 [ + + ]: 101649 : while (*cp)
769 : : {
770 [ + + ]: 100 : if (!isspace((unsigned char) *cp))
771 : 48 : goto invalid_syntax;
772 : 52 : cp++;
773 : : }
774 : :
775 [ + + ]: 101549 : if (!apply_typmod(&value, typmod, escontext))
776 : 16 : PG_RETURN_NULL();
777 : :
778 : 101533 : res = make_result_safe(&value, escontext);
779 : :
780 : 101533 : free_var(&value);
781 : : }
782 : :
783 : 102669 : PG_RETURN_NUMERIC(res);
784 : :
785 : 121 : invalid_syntax:
786 [ + + ]: 121 : ereturn(escontext, (Datum) 0,
787 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
788 : : errmsg("invalid input syntax for type %s: \"%s\"",
789 : : "numeric", str)));
790 : : }
791 : :
792 : :
793 : : /*
794 : : * numeric_out() -
795 : : *
796 : : * Output function for numeric data type
797 : : */
798 : : Datum
799 : 536688 : numeric_out(PG_FUNCTION_ARGS)
800 : : {
801 : 536688 : Numeric num = PG_GETARG_NUMERIC(0);
802 : : NumericVar x;
803 : : char *str;
804 : :
805 : : /*
806 : : * Handle NaN and infinities
807 : : */
808 [ + + ]: 536688 : if (NUMERIC_IS_SPECIAL(num))
809 : : {
810 [ + + ]: 2348 : if (NUMERIC_IS_PINF(num))
811 : 688 : PG_RETURN_CSTRING(pstrdup("Infinity"));
812 [ + + ]: 1660 : else if (NUMERIC_IS_NINF(num))
813 : 440 : PG_RETURN_CSTRING(pstrdup("-Infinity"));
814 : : else
815 : 1220 : PG_RETURN_CSTRING(pstrdup("NaN"));
816 : : }
817 : :
818 : : /*
819 : : * Get the number in the variable format.
820 : : */
821 : 534340 : init_var_from_num(num, &x);
822 : :
823 : 534340 : str = get_str_from_var(&x);
824 : :
825 : 534340 : PG_RETURN_CSTRING(str);
826 : : }
827 : :
828 : : /*
829 : : * numeric_is_nan() -
830 : : *
831 : : * Is Numeric value a NaN?
832 : : */
833 : : bool
834 : 5296 : numeric_is_nan(Numeric num)
835 : : {
836 : 5296 : return NUMERIC_IS_NAN(num);
837 : : }
838 : :
839 : : /*
840 : : * numeric_is_inf() -
841 : : *
842 : : * Is Numeric value an infinity?
843 : : */
844 : : bool
845 : 1722 : numeric_is_inf(Numeric num)
846 : : {
847 : 1722 : return NUMERIC_IS_INF(num);
848 : : }
849 : :
850 : : /*
851 : : * numeric_is_integral() -
852 : : *
853 : : * Is Numeric value integral?
854 : : */
855 : : static bool
856 : 54 : numeric_is_integral(Numeric num)
857 : : {
858 : : NumericVar arg;
859 : :
860 : : /* Reject NaN, but infinities are considered integral */
861 [ + + ]: 54 : if (NUMERIC_IS_SPECIAL(num))
862 : : {
863 [ - + ]: 25 : if (NUMERIC_IS_NAN(num))
864 : 0 : return false;
865 : 25 : return true;
866 : : }
867 : :
868 : : /* Integral if there are no digits to the right of the decimal point */
869 : 29 : init_var_from_num(num, &arg);
870 : :
871 [ + + + + ]: 29 : return (arg.ndigits == 0 || arg.ndigits <= arg.weight + 1);
872 : : }
873 : :
874 : : /*
875 : : * make_numeric_typmod() -
876 : : *
877 : : * Pack numeric precision and scale values into a typmod. The upper 16 bits
878 : : * are used for the precision (though actually not all these bits are needed,
879 : : * since the maximum allowed precision is 1000). The lower 16 bits are for
880 : : * the scale, but since the scale is constrained to the range [-1000, 1000],
881 : : * we use just the lower 11 of those 16 bits, and leave the remaining 5 bits
882 : : * unset, for possible future use.
883 : : *
884 : : * For purely historical reasons VARHDRSZ is then added to the result, thus
885 : : * the unused space in the upper 16 bits is not all as freely available as it
886 : : * might seem. (We can't let the result overflow to a negative int32, as
887 : : * other parts of the system would interpret that as not-a-valid-typmod.)
888 : : */
889 : : static inline int32
890 : 1087 : make_numeric_typmod(int precision, int scale)
891 : : {
892 : 1087 : return ((precision << 16) | (scale & 0x7ff)) + VARHDRSZ;
893 : : }
894 : :
895 : : /*
896 : : * Because of the offset, valid numeric typmods are at least VARHDRSZ
897 : : */
898 : : static inline bool
899 : 118848 : is_valid_numeric_typmod(int32 typmod)
900 : : {
901 : 118848 : return typmod >= (int32) VARHDRSZ;
902 : : }
903 : :
904 : : /*
905 : : * numeric_typmod_precision() -
906 : : *
907 : : * Extract the precision from a numeric typmod --- see make_numeric_typmod().
908 : : */
909 : : static inline int
910 : 32945 : numeric_typmod_precision(int32 typmod)
911 : : {
912 : 32945 : return ((typmod - VARHDRSZ) >> 16) & 0xffff;
913 : : }
914 : :
915 : : /*
916 : : * numeric_typmod_scale() -
917 : : *
918 : : * Extract the scale from a numeric typmod --- see make_numeric_typmod().
919 : : *
920 : : * Note that the scale may be negative, so we must do sign extension when
921 : : * unpacking it. We do this using the bit hack (x^1024)-1024, which sign
922 : : * extends an 11-bit two's complement number x.
923 : : */
924 : : static inline int
925 : 28030 : numeric_typmod_scale(int32 typmod)
926 : : {
927 : 28030 : return (((typmod - VARHDRSZ) & 0x7ff) ^ 1024) - 1024;
928 : : }
929 : :
930 : : /*
931 : : * numeric_maximum_size() -
932 : : *
933 : : * Maximum size of a numeric with given typmod, or -1 if unlimited/unknown.
934 : : */
935 : : int32
936 : 4915 : numeric_maximum_size(int32 typmod)
937 : : {
938 : : int precision;
939 : : int numeric_digits;
940 : :
941 [ - + ]: 4915 : if (!is_valid_numeric_typmod(typmod))
942 : 0 : return -1;
943 : :
944 : : /* precision (ie, max # of digits) is in upper bits of typmod */
945 : 4915 : precision = numeric_typmod_precision(typmod);
946 : :
947 : : /*
948 : : * This formula computes the maximum number of NumericDigits we could need
949 : : * in order to store the specified number of decimal digits. Because the
950 : : * weight is stored as a number of NumericDigits rather than a number of
951 : : * decimal digits, it's possible that the first NumericDigit will contain
952 : : * only a single decimal digit. Thus, the first two decimal digits can
953 : : * require two NumericDigits to store, but it isn't until we reach
954 : : * DEC_DIGITS + 2 decimal digits that we potentially need a third
955 : : * NumericDigit.
956 : : */
957 : 4915 : numeric_digits = (precision + 2 * (DEC_DIGITS - 1)) / DEC_DIGITS;
958 : :
959 : : /*
960 : : * In most cases, the size of a numeric will be smaller than the value
961 : : * computed below, because the varlena header will typically get toasted
962 : : * down to a single byte before being stored on disk, and it may also be
963 : : * possible to use a short numeric header. But our job here is to compute
964 : : * the worst case.
965 : : */
966 : 4915 : return NUMERIC_HDRSZ + (numeric_digits * sizeof(NumericDigit));
967 : : }
968 : :
969 : : /*
970 : : * numeric_out_sci() -
971 : : *
972 : : * Output function for numeric data type in scientific notation.
973 : : */
974 : : char *
975 : 164 : numeric_out_sci(Numeric num, int scale)
976 : : {
977 : : NumericVar x;
978 : : char *str;
979 : :
980 : : /*
981 : : * Handle NaN and infinities
982 : : */
983 [ + + ]: 164 : if (NUMERIC_IS_SPECIAL(num))
984 : : {
985 [ + + ]: 12 : if (NUMERIC_IS_PINF(num))
986 : 4 : return pstrdup("Infinity");
987 [ + + ]: 8 : else if (NUMERIC_IS_NINF(num))
988 : 4 : return pstrdup("-Infinity");
989 : : else
990 : 4 : return pstrdup("NaN");
991 : : }
992 : :
993 : 152 : init_var_from_num(num, &x);
994 : :
995 : 152 : str = get_str_from_var_sci(&x, scale);
996 : :
997 : 152 : return str;
998 : : }
999 : :
1000 : : /*
1001 : : * numeric_normalize() -
1002 : : *
1003 : : * Output function for numeric data type, suppressing insignificant trailing
1004 : : * zeroes and then any trailing decimal point. The intent of this is to
1005 : : * produce strings that are equal if and only if the input numeric values
1006 : : * compare equal.
1007 : : */
1008 : : char *
1009 : 25634 : numeric_normalize(Numeric num)
1010 : : {
1011 : : NumericVar x;
1012 : : char *str;
1013 : : int last;
1014 : :
1015 : : /*
1016 : : * Handle NaN and infinities
1017 : : */
1018 [ - + ]: 25634 : if (NUMERIC_IS_SPECIAL(num))
1019 : : {
1020 [ # # ]: 0 : if (NUMERIC_IS_PINF(num))
1021 : 0 : return pstrdup("Infinity");
1022 [ # # ]: 0 : else if (NUMERIC_IS_NINF(num))
1023 : 0 : return pstrdup("-Infinity");
1024 : : else
1025 : 0 : return pstrdup("NaN");
1026 : : }
1027 : :
1028 : 25634 : init_var_from_num(num, &x);
1029 : :
1030 : 25634 : str = get_str_from_var(&x);
1031 : :
1032 : : /* If there's no decimal point, there's certainly nothing to remove. */
1033 [ + + ]: 25634 : if (strchr(str, '.') != NULL)
1034 : : {
1035 : : /*
1036 : : * Back up over trailing fractional zeroes. Since there is a decimal
1037 : : * point, this loop will terminate safely.
1038 : : */
1039 : 31 : last = strlen(str) - 1;
1040 [ + + ]: 62 : while (str[last] == '0')
1041 : 31 : last--;
1042 : :
1043 : : /* We want to get rid of the decimal point too, if it's now last. */
1044 [ + - ]: 31 : if (str[last] == '.')
1045 : 31 : last--;
1046 : :
1047 : : /* Delete whatever we backed up over. */
1048 : 31 : str[last + 1] = '\0';
1049 : : }
1050 : :
1051 : 25634 : return str;
1052 : : }
1053 : :
1054 : : /*
1055 : : * numeric_recv - converts external binary format to numeric
1056 : : *
1057 : : * External format is a sequence of int16's:
1058 : : * ndigits, weight, sign, dscale, NumericDigits.
1059 : : */
1060 : : Datum
1061 : 51 : numeric_recv(PG_FUNCTION_ARGS)
1062 : : {
1063 : 51 : StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
1064 : :
1065 : : #ifdef NOT_USED
1066 : : Oid typelem = PG_GETARG_OID(1);
1067 : : #endif
1068 : 51 : int32 typmod = PG_GETARG_INT32(2);
1069 : : NumericVar value;
1070 : : Numeric res;
1071 : : int len,
1072 : : i;
1073 : :
1074 : 51 : init_var(&value);
1075 : :
1076 : 51 : len = (uint16) pq_getmsgint(buf, sizeof(uint16));
1077 : :
1078 : 51 : alloc_var(&value, len);
1079 : :
1080 : 51 : value.weight = (int16) pq_getmsgint(buf, sizeof(int16));
1081 : : /* we allow any int16 for weight --- OK? */
1082 : :
1083 : 51 : value.sign = (uint16) pq_getmsgint(buf, sizeof(uint16));
1084 [ - + ]: 51 : if (!(value.sign == NUMERIC_POS ||
1085 [ # # ]: 0 : value.sign == NUMERIC_NEG ||
1086 [ # # ]: 0 : value.sign == NUMERIC_NAN ||
1087 [ # # ]: 0 : value.sign == NUMERIC_PINF ||
1088 [ # # ]: 0 : value.sign == NUMERIC_NINF))
1089 [ # # ]: 0 : ereport(ERROR,
1090 : : (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1091 : : errmsg("invalid sign in external \"numeric\" value")));
1092 : :
1093 : 51 : value.dscale = (uint16) pq_getmsgint(buf, sizeof(uint16));
1094 [ - + ]: 51 : if ((value.dscale & NUMERIC_DSCALE_MASK) != value.dscale)
1095 [ # # ]: 0 : ereport(ERROR,
1096 : : (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1097 : : errmsg("invalid scale in external \"numeric\" value")));
1098 : :
1099 [ + + ]: 137 : for (i = 0; i < len; i++)
1100 : : {
1101 : 86 : NumericDigit d = pq_getmsgint(buf, sizeof(NumericDigit));
1102 : :
1103 [ + - - + ]: 86 : if (d < 0 || d >= NBASE)
1104 [ # # ]: 0 : ereport(ERROR,
1105 : : (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1106 : : errmsg("invalid digit in external \"numeric\" value")));
1107 : 86 : value.digits[i] = d;
1108 : : }
1109 : :
1110 : : /*
1111 : : * If the given dscale would hide any digits, truncate those digits away.
1112 : : * We could alternatively throw an error, but that would take a bunch of
1113 : : * extra code (about as much as trunc_var involves), and it might cause
1114 : : * client compatibility issues. Be careful not to apply trunc_var to
1115 : : * special values, as it could do the wrong thing; we don't need it
1116 : : * anyway, since make_result will ignore all but the sign field.
1117 : : *
1118 : : * After doing that, be sure to check the typmod restriction.
1119 : : */
1120 [ - + ]: 51 : if (value.sign == NUMERIC_POS ||
1121 [ # # ]: 0 : value.sign == NUMERIC_NEG)
1122 : : {
1123 : 51 : trunc_var(&value, value.dscale);
1124 : :
1125 : 51 : (void) apply_typmod(&value, typmod, NULL);
1126 : :
1127 : 51 : res = make_result(&value);
1128 : : }
1129 : : else
1130 : : {
1131 : : /* apply_typmod_special wants us to make the Numeric first */
1132 : 0 : res = make_result(&value);
1133 : :
1134 : 0 : (void) apply_typmod_special(res, typmod, NULL);
1135 : : }
1136 : :
1137 : 51 : free_var(&value);
1138 : :
1139 : 51 : PG_RETURN_NUMERIC(res);
1140 : : }
1141 : :
1142 : : /*
1143 : : * numeric_send - converts numeric to binary format
1144 : : */
1145 : : Datum
1146 : 35 : numeric_send(PG_FUNCTION_ARGS)
1147 : : {
1148 : 35 : Numeric num = PG_GETARG_NUMERIC(0);
1149 : : NumericVar x;
1150 : : StringInfoData buf;
1151 : : int i;
1152 : :
1153 : 35 : init_var_from_num(num, &x);
1154 : :
1155 : 35 : pq_begintypsend(&buf);
1156 : :
1157 : 35 : pq_sendint16(&buf, x.ndigits);
1158 : 35 : pq_sendint16(&buf, x.weight);
1159 : 35 : pq_sendint16(&buf, x.sign);
1160 : 35 : pq_sendint16(&buf, x.dscale);
1161 [ + + ]: 97 : for (i = 0; i < x.ndigits; i++)
1162 : 62 : pq_sendint16(&buf, x.digits[i]);
1163 : :
1164 : 35 : PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
1165 : : }
1166 : :
1167 : :
1168 : : /*
1169 : : * numeric_support()
1170 : : *
1171 : : * Planner support function for the numeric() length coercion function.
1172 : : *
1173 : : * Flatten calls that solely represent increases in allowable precision.
1174 : : * Scale changes mutate every datum, so they are unoptimizable. Some values,
1175 : : * e.g. 1E-1001, can only fit into an unconstrained numeric, so a change from
1176 : : * an unconstrained numeric to any constrained numeric is also unoptimizable.
1177 : : */
1178 : : Datum
1179 : 427 : numeric_support(PG_FUNCTION_ARGS)
1180 : : {
1181 : 427 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
1182 : 427 : Node *ret = NULL;
1183 : :
1184 [ + + ]: 427 : if (IsA(rawreq, SupportRequestSimplify))
1185 : : {
1186 : 187 : SupportRequestSimplify *req = (SupportRequestSimplify *) rawreq;
1187 : 187 : FuncExpr *expr = req->fcall;
1188 : : Node *typmod;
1189 : :
1190 : : Assert(list_length(expr->args) >= 2);
1191 : :
1192 : 187 : typmod = (Node *) lsecond(expr->args);
1193 : :
1194 [ + - + - ]: 187 : if (IsA(typmod, Const) && !((Const *) typmod)->constisnull)
1195 : : {
1196 : 187 : Node *source = (Node *) linitial(expr->args);
1197 : 187 : int32 old_typmod = exprTypmod(source);
1198 : 187 : int32 new_typmod = DatumGetInt32(((Const *) typmod)->constvalue);
1199 : 187 : int32 old_scale = numeric_typmod_scale(old_typmod);
1200 : 187 : int32 new_scale = numeric_typmod_scale(new_typmod);
1201 : 187 : int32 old_precision = numeric_typmod_precision(old_typmod);
1202 : 187 : int32 new_precision = numeric_typmod_precision(new_typmod);
1203 : :
1204 : : /*
1205 : : * If new_typmod is invalid, the destination is unconstrained;
1206 : : * that's always OK. If old_typmod is valid, the source is
1207 : : * constrained, and we're OK if the scale is unchanged and the
1208 : : * precision is not decreasing. See further notes in function
1209 : : * header comment.
1210 : : */
1211 [ + - + + ]: 374 : if (!is_valid_numeric_typmod(new_typmod) ||
1212 [ + + ]: 196 : (is_valid_numeric_typmod(old_typmod) &&
1213 [ + - ]: 4 : new_scale == old_scale && new_precision >= old_precision))
1214 : 4 : ret = relabel_to_typmod(source, new_typmod);
1215 : : }
1216 : : }
1217 : :
1218 : 427 : PG_RETURN_POINTER(ret);
1219 : : }
1220 : :
1221 : : /*
1222 : : * numeric() -
1223 : : *
1224 : : * This is a special function called by the Postgres database system
1225 : : * before a value is stored in a tuple's attribute. The precision and
1226 : : * scale of the attribute have to be applied on the value.
1227 : : */
1228 : : Datum
1229 : 8091 : numeric (PG_FUNCTION_ARGS)
1230 : : {
1231 : 8091 : Numeric num = PG_GETARG_NUMERIC(0);
1232 : 8091 : int32 typmod = PG_GETARG_INT32(1);
1233 : : Numeric new;
1234 : : int precision;
1235 : : int scale;
1236 : : int ddigits;
1237 : : int maxdigits;
1238 : : int dscale;
1239 : : NumericVar var;
1240 : :
1241 : : /*
1242 : : * Handle NaN and infinities: if apply_typmod_special doesn't complain,
1243 : : * just return a copy of the input.
1244 : : */
1245 [ + + ]: 8091 : if (NUMERIC_IS_SPECIAL(num))
1246 : : {
1247 [ - + ]: 172 : if (!apply_typmod_special(num, typmod, fcinfo->context))
1248 : 0 : PG_RETURN_NULL();
1249 : 160 : PG_RETURN_NUMERIC(duplicate_numeric(num));
1250 : : }
1251 : :
1252 : : /*
1253 : : * If the value isn't a valid type modifier, simply return a copy of the
1254 : : * input value
1255 : : */
1256 [ - + ]: 7919 : if (!is_valid_numeric_typmod(typmod))
1257 : 0 : PG_RETURN_NUMERIC(duplicate_numeric(num));
1258 : :
1259 : : /*
1260 : : * Get the precision and scale out of the typmod value
1261 : : */
1262 : 7919 : precision = numeric_typmod_precision(typmod);
1263 : 7919 : scale = numeric_typmod_scale(typmod);
1264 : 7919 : maxdigits = precision - scale;
1265 : :
1266 : : /* The target display scale is non-negative */
1267 : 7919 : dscale = Max(scale, 0);
1268 : :
1269 : : /*
1270 : : * If the number is certainly in bounds and due to the target scale no
1271 : : * rounding could be necessary, just make a copy of the input and modify
1272 : : * its scale fields, unless the larger scale forces us to abandon the
1273 : : * short representation. (Note we assume the existing dscale is
1274 : : * honest...)
1275 : : */
1276 [ + + + + ]: 7919 : ddigits = (NUMERIC_WEIGHT(num) + 1) * DEC_DIGITS;
1277 [ + + + + : 7919 : if (ddigits <= maxdigits && scale >= NUMERIC_DSCALE(num)
+ + ]
1278 [ + - + - : 4839 : && (NUMERIC_CAN_BE_SHORT(dscale, NUMERIC_WEIGHT(num))
+ + + - -
- + - + +
- + - - ]
1279 [ # # ]: 0 : || !NUMERIC_IS_SHORT(num)))
1280 : : {
1281 : 4839 : new = duplicate_numeric(num);
1282 [ + - ]: 4839 : if (NUMERIC_IS_SHORT(num))
1283 : 4839 : new->choice.n_short.n_header =
1284 : 4839 : (num->choice.n_short.n_header & ~NUMERIC_SHORT_DSCALE_MASK)
1285 : 4839 : | (dscale << NUMERIC_SHORT_DSCALE_SHIFT);
1286 : : else
1287 [ # # # # ]: 0 : new->choice.n_long.n_sign_dscale = NUMERIC_SIGN(new) |
1288 : 0 : ((uint16) dscale & NUMERIC_DSCALE_MASK);
1289 : 4839 : PG_RETURN_NUMERIC(new);
1290 : : }
1291 : :
1292 : : /*
1293 : : * We really need to fiddle with things - unpack the number into a
1294 : : * variable and let apply_typmod() do it.
1295 : : */
1296 : 3080 : init_var(&var);
1297 : :
1298 : 3080 : set_var_from_num(num, &var);
1299 [ - + ]: 3080 : if (!apply_typmod(&var, typmod, fcinfo->context))
1300 : 0 : PG_RETURN_NULL();
1301 : 3032 : new = make_result_safe(&var, fcinfo->context);
1302 : :
1303 : 3032 : free_var(&var);
1304 : :
1305 : 3032 : PG_RETURN_NUMERIC(new);
1306 : : }
1307 : :
1308 : : /*
1309 : : * make_numeric_typmod_safe() -
1310 : : *
1311 : : * Validate a numeric precision/scale and pack them into a typmod value,
1312 : : * with soft error handling.
1313 : : */
1314 : : int32
1315 : 1132 : make_numeric_typmod_safe(int32 precision, int32 scale, Node *escontext)
1316 : : {
1317 [ + + + + ]: 1132 : if (precision < 1 || precision > NUMERIC_MAX_PRECISION)
1318 [ + + ]: 29 : ereturn(escontext, -1,
1319 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1320 : : errmsg("NUMERIC precision %d must be between 1 and %d",
1321 : : precision, NUMERIC_MAX_PRECISION)));
1322 [ + + + + ]: 1103 : if (scale < NUMERIC_MIN_SCALE || scale > NUMERIC_MAX_SCALE)
1323 [ + + ]: 16 : ereturn(escontext, -1,
1324 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1325 : : errmsg("NUMERIC scale %d must be between %d and %d",
1326 : : scale, NUMERIC_MIN_SCALE, NUMERIC_MAX_SCALE)));
1327 : :
1328 : 1087 : return make_numeric_typmod(precision, scale);
1329 : : }
1330 : :
1331 : : Datum
1332 : 1055 : numerictypmodin(PG_FUNCTION_ARGS)
1333 : : {
1334 : 1055 : ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
1335 : : int32 *tl;
1336 : : int n;
1337 : : int32 typmod;
1338 : :
1339 : 1055 : tl = ArrayGetIntegerTypmods(ta, &n);
1340 : :
1341 [ + + ]: 1055 : if (n == 2)
1342 : 1043 : typmod = make_numeric_typmod_safe(tl[0], tl[1], NULL);
1343 [ + + ]: 12 : else if (n == 1)
1344 : : {
1345 : : /* scale defaults to zero */
1346 : 4 : typmod = make_numeric_typmod_safe(tl[0], 0, NULL);
1347 : : }
1348 : : else
1349 : : {
1350 [ + - ]: 8 : ereport(ERROR,
1351 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1352 : : errmsg("invalid NUMERIC type modifier")));
1353 : : typmod = 0; /* keep compiler quiet */
1354 : : }
1355 : :
1356 : 1047 : PG_RETURN_INT32(typmod);
1357 : : }
1358 : :
1359 : : Datum
1360 : 209 : numerictypmodout(PG_FUNCTION_ARGS)
1361 : : {
1362 : 209 : int32 typmod = PG_GETARG_INT32(0);
1363 : 209 : char *res = (char *) palloc(64);
1364 : :
1365 [ + - ]: 209 : if (is_valid_numeric_typmod(typmod))
1366 : 209 : snprintf(res, 64, "(%d,%d)",
1367 : : numeric_typmod_precision(typmod),
1368 : : numeric_typmod_scale(typmod));
1369 : : else
1370 : 0 : *res = '\0';
1371 : :
1372 : 209 : PG_RETURN_CSTRING(res);
1373 : : }
1374 : :
1375 : :
1376 : : /* ----------------------------------------------------------------------
1377 : : *
1378 : : * Sign manipulation, rounding and the like
1379 : : *
1380 : : * ----------------------------------------------------------------------
1381 : : */
1382 : :
1383 : : Datum
1384 : 13004 : numeric_abs(PG_FUNCTION_ARGS)
1385 : : {
1386 : 13004 : Numeric num = PG_GETARG_NUMERIC(0);
1387 : : Numeric res;
1388 : :
1389 : : /*
1390 : : * Do it the easy way directly on the packed format
1391 : : */
1392 : 13004 : res = duplicate_numeric(num);
1393 : :
1394 [ + + ]: 13004 : if (NUMERIC_IS_SHORT(num))
1395 : 12960 : res->choice.n_short.n_header =
1396 : 12960 : num->choice.n_short.n_header & ~NUMERIC_SHORT_SIGN_MASK;
1397 [ + + ]: 44 : else if (NUMERIC_IS_SPECIAL(num))
1398 : : {
1399 : : /* This changes -Inf to Inf, and doesn't affect NaN */
1400 : 12 : res->choice.n_short.n_header =
1401 : 12 : num->choice.n_short.n_header & ~NUMERIC_INF_SIGN_MASK;
1402 : : }
1403 : : else
1404 [ - + ]: 32 : res->choice.n_long.n_sign_dscale = NUMERIC_POS | NUMERIC_DSCALE(num);
1405 : :
1406 : 13004 : PG_RETURN_NUMERIC(res);
1407 : : }
1408 : :
1409 : :
1410 : : Datum
1411 : 631 : numeric_uminus(PG_FUNCTION_ARGS)
1412 : : {
1413 : 631 : Numeric num = PG_GETARG_NUMERIC(0);
1414 : : Numeric res;
1415 : :
1416 : : /*
1417 : : * Do it the easy way directly on the packed format
1418 : : */
1419 : 631 : res = duplicate_numeric(num);
1420 : :
1421 [ + + ]: 631 : if (NUMERIC_IS_SPECIAL(num))
1422 : : {
1423 : : /* Flip the sign, if it's Inf or -Inf */
1424 [ + + ]: 84 : if (!NUMERIC_IS_NAN(num))
1425 : 56 : res->choice.n_short.n_header =
1426 : 56 : num->choice.n_short.n_header ^ NUMERIC_INF_SIGN_MASK;
1427 : : }
1428 : :
1429 : : /*
1430 : : * The packed format is known to be totally zero digit trimmed always. So
1431 : : * once we've eliminated specials, we can identify a zero by the fact that
1432 : : * there are no digits at all. Do nothing to a zero.
1433 : : */
1434 [ + - + + ]: 547 : else if (NUMERIC_NDIGITS(num) != 0)
1435 : : {
1436 : : /* Else, flip the sign */
1437 [ + - ]: 471 : if (NUMERIC_IS_SHORT(num))
1438 : 471 : res->choice.n_short.n_header =
1439 : 471 : num->choice.n_short.n_header ^ NUMERIC_SHORT_SIGN_MASK;
1440 [ # # # # : 0 : else if (NUMERIC_SIGN(num) == NUMERIC_POS)
# # ]
1441 : 0 : res->choice.n_long.n_sign_dscale =
1442 [ # # ]: 0 : NUMERIC_NEG | NUMERIC_DSCALE(num);
1443 : : else
1444 : 0 : res->choice.n_long.n_sign_dscale =
1445 [ # # ]: 0 : NUMERIC_POS | NUMERIC_DSCALE(num);
1446 : : }
1447 : :
1448 : 631 : PG_RETURN_NUMERIC(res);
1449 : : }
1450 : :
1451 : :
1452 : : Datum
1453 : 0 : numeric_uplus(PG_FUNCTION_ARGS)
1454 : : {
1455 : 0 : Numeric num = PG_GETARG_NUMERIC(0);
1456 : :
1457 : 0 : PG_RETURN_NUMERIC(duplicate_numeric(num));
1458 : : }
1459 : :
1460 : :
1461 : : /*
1462 : : * numeric_sign_internal() -
1463 : : *
1464 : : * Returns -1 if the argument is less than 0, 0 if the argument is equal
1465 : : * to 0, and 1 if the argument is greater than zero. Caller must have
1466 : : * taken care of the NaN case, but we can handle infinities here.
1467 : : */
1468 : : static int
1469 : 2494 : numeric_sign_internal(Numeric num)
1470 : : {
1471 [ + + ]: 2494 : if (NUMERIC_IS_SPECIAL(num))
1472 : : {
1473 : : Assert(!NUMERIC_IS_NAN(num));
1474 : : /* Must be Inf or -Inf */
1475 [ + + ]: 232 : if (NUMERIC_IS_PINF(num))
1476 : 138 : return 1;
1477 : : else
1478 : 94 : return -1;
1479 : : }
1480 : :
1481 : : /*
1482 : : * The packed format is known to be totally zero digit trimmed always. So
1483 : : * once we've eliminated specials, we can identify a zero by the fact that
1484 : : * there are no digits at all.
1485 : : */
1486 [ + + + + ]: 2262 : else if (NUMERIC_NDIGITS(num) == 0)
1487 : 161 : return 0;
1488 [ + + - + : 2101 : else if (NUMERIC_SIGN(num) == NUMERIC_NEG)
+ + ]
1489 : 511 : return -1;
1490 : : else
1491 : 1590 : return 1;
1492 : : }
1493 : :
1494 : : /*
1495 : : * numeric_sign() -
1496 : : *
1497 : : * returns -1 if the argument is less than 0, 0 if the argument is equal
1498 : : * to 0, and 1 if the argument is greater than zero.
1499 : : */
1500 : : Datum
1501 : 32 : numeric_sign(PG_FUNCTION_ARGS)
1502 : : {
1503 : 32 : Numeric num = PG_GETARG_NUMERIC(0);
1504 : :
1505 : : /*
1506 : : * Handle NaN (infinities can be handled normally)
1507 : : */
1508 [ + + ]: 32 : if (NUMERIC_IS_NAN(num))
1509 : 4 : PG_RETURN_NUMERIC(make_result(&const_nan));
1510 : :
1511 [ + + + - ]: 28 : switch (numeric_sign_internal(num))
1512 : : {
1513 : 4 : case 0:
1514 : 4 : PG_RETURN_NUMERIC(make_result(&const_zero));
1515 : 12 : case 1:
1516 : 12 : PG_RETURN_NUMERIC(make_result(&const_one));
1517 : 12 : case -1:
1518 : 12 : PG_RETURN_NUMERIC(make_result(&const_minus_one));
1519 : : }
1520 : :
1521 : : Assert(false);
1522 : 0 : return (Datum) 0;
1523 : : }
1524 : :
1525 : :
1526 : : /*
1527 : : * numeric_round() -
1528 : : *
1529 : : * Round a value to have 'scale' digits after the decimal point.
1530 : : * We allow negative 'scale', implying rounding before the decimal
1531 : : * point --- Oracle interprets rounding that way.
1532 : : */
1533 : : Datum
1534 : 5221 : numeric_round(PG_FUNCTION_ARGS)
1535 : : {
1536 : 5221 : Numeric num = PG_GETARG_NUMERIC(0);
1537 : 5221 : int32 scale = PG_GETARG_INT32(1);
1538 : : Numeric res;
1539 : : NumericVar arg;
1540 : :
1541 : : /*
1542 : : * Handle NaN and infinities
1543 : : */
1544 [ + + ]: 5221 : if (NUMERIC_IS_SPECIAL(num))
1545 : 64 : PG_RETURN_NUMERIC(duplicate_numeric(num));
1546 : :
1547 : : /*
1548 : : * Limit the scale value to avoid possible overflow in calculations.
1549 : : *
1550 : : * These limits are based on the maximum number of digits a Numeric value
1551 : : * can have before and after the decimal point, but we must allow for one
1552 : : * extra digit before the decimal point, in case the most significant
1553 : : * digit rounds up; we must check if that causes Numeric overflow.
1554 : : */
1555 : 5157 : scale = Max(scale, -(NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS - 1);
1556 : 5157 : scale = Min(scale, NUMERIC_DSCALE_MAX);
1557 : :
1558 : : /*
1559 : : * Unpack the argument and round it at the proper digit position
1560 : : */
1561 : 5157 : init_var(&arg);
1562 : 5157 : set_var_from_num(num, &arg);
1563 : :
1564 : 5157 : round_var(&arg, scale);
1565 : :
1566 : : /* We don't allow negative output dscale */
1567 [ + + ]: 5157 : if (scale < 0)
1568 : 149 : arg.dscale = 0;
1569 : :
1570 : : /*
1571 : : * Return the rounded result
1572 : : */
1573 : 5157 : res = make_result(&arg);
1574 : :
1575 : 5153 : free_var(&arg);
1576 : 5153 : PG_RETURN_NUMERIC(res);
1577 : : }
1578 : :
1579 : :
1580 : : /*
1581 : : * numeric_trunc() -
1582 : : *
1583 : : * Truncate a value to have 'scale' digits after the decimal point.
1584 : : * We allow negative 'scale', implying a truncation before the decimal
1585 : : * point --- Oracle interprets truncation that way.
1586 : : */
1587 : : Datum
1588 : 442 : numeric_trunc(PG_FUNCTION_ARGS)
1589 : : {
1590 : 442 : Numeric num = PG_GETARG_NUMERIC(0);
1591 : 442 : int32 scale = PG_GETARG_INT32(1);
1592 : : Numeric res;
1593 : : NumericVar arg;
1594 : :
1595 : : /*
1596 : : * Handle NaN and infinities
1597 : : */
1598 [ + + ]: 442 : if (NUMERIC_IS_SPECIAL(num))
1599 : 24 : PG_RETURN_NUMERIC(duplicate_numeric(num));
1600 : :
1601 : : /*
1602 : : * Limit the scale value to avoid possible overflow in calculations.
1603 : : *
1604 : : * These limits are based on the maximum number of digits a Numeric value
1605 : : * can have before and after the decimal point.
1606 : : */
1607 : 418 : scale = Max(scale, -(NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS);
1608 : 418 : scale = Min(scale, NUMERIC_DSCALE_MAX);
1609 : :
1610 : : /*
1611 : : * Unpack the argument and truncate it at the proper digit position
1612 : : */
1613 : 418 : init_var(&arg);
1614 : 418 : set_var_from_num(num, &arg);
1615 : :
1616 : 418 : trunc_var(&arg, scale);
1617 : :
1618 : : /* We don't allow negative output dscale */
1619 [ + + ]: 418 : if (scale < 0)
1620 : 20 : arg.dscale = 0;
1621 : :
1622 : : /*
1623 : : * Return the truncated result
1624 : : */
1625 : 418 : res = make_result(&arg);
1626 : :
1627 : 418 : free_var(&arg);
1628 : 418 : PG_RETURN_NUMERIC(res);
1629 : : }
1630 : :
1631 : :
1632 : : /*
1633 : : * numeric_ceil() -
1634 : : *
1635 : : * Return the smallest integer greater than or equal to the argument
1636 : : */
1637 : : Datum
1638 : 148 : numeric_ceil(PG_FUNCTION_ARGS)
1639 : : {
1640 : 148 : Numeric num = PG_GETARG_NUMERIC(0);
1641 : : Numeric res;
1642 : : NumericVar result;
1643 : :
1644 : : /*
1645 : : * Handle NaN and infinities
1646 : : */
1647 [ + + ]: 148 : if (NUMERIC_IS_SPECIAL(num))
1648 : 12 : PG_RETURN_NUMERIC(duplicate_numeric(num));
1649 : :
1650 : 136 : init_var_from_num(num, &result);
1651 : 136 : ceil_var(&result, &result);
1652 : :
1653 : 136 : res = make_result(&result);
1654 : 136 : free_var(&result);
1655 : :
1656 : 136 : PG_RETURN_NUMERIC(res);
1657 : : }
1658 : :
1659 : :
1660 : : /*
1661 : : * numeric_floor() -
1662 : : *
1663 : : * Return the largest integer equal to or less than the argument
1664 : : */
1665 : : Datum
1666 : 84 : numeric_floor(PG_FUNCTION_ARGS)
1667 : : {
1668 : 84 : Numeric num = PG_GETARG_NUMERIC(0);
1669 : : Numeric res;
1670 : : NumericVar result;
1671 : :
1672 : : /*
1673 : : * Handle NaN and infinities
1674 : : */
1675 [ + + ]: 84 : if (NUMERIC_IS_SPECIAL(num))
1676 : 12 : PG_RETURN_NUMERIC(duplicate_numeric(num));
1677 : :
1678 : 72 : init_var_from_num(num, &result);
1679 : 72 : floor_var(&result, &result);
1680 : :
1681 : 72 : res = make_result(&result);
1682 : 72 : free_var(&result);
1683 : :
1684 : 72 : PG_RETURN_NUMERIC(res);
1685 : : }
1686 : :
1687 : :
1688 : : /*
1689 : : * generate_series_numeric() -
1690 : : *
1691 : : * Generate series of numeric.
1692 : : */
1693 : : Datum
1694 : 80256 : generate_series_numeric(PG_FUNCTION_ARGS)
1695 : : {
1696 : 80256 : return generate_series_step_numeric(fcinfo);
1697 : : }
1698 : :
1699 : : Datum
1700 : 80556 : generate_series_step_numeric(PG_FUNCTION_ARGS)
1701 : : {
1702 : : generate_series_numeric_fctx *fctx;
1703 : : FuncCallContext *funcctx;
1704 : : MemoryContext oldcontext;
1705 : :
1706 [ + + ]: 80556 : if (SRF_IS_FIRSTCALL())
1707 : : {
1708 : 116 : Numeric start_num = PG_GETARG_NUMERIC(0);
1709 : 116 : Numeric stop_num = PG_GETARG_NUMERIC(1);
1710 : 116 : NumericVar steploc = const_one;
1711 : :
1712 : : /* Reject NaN and infinities in start and stop values */
1713 [ + + ]: 116 : if (NUMERIC_IS_SPECIAL(start_num))
1714 : : {
1715 [ + + ]: 8 : if (NUMERIC_IS_NAN(start_num))
1716 [ + - ]: 4 : ereport(ERROR,
1717 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1718 : : errmsg("start value cannot be NaN")));
1719 : : else
1720 [ + - ]: 4 : ereport(ERROR,
1721 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1722 : : errmsg("start value cannot be infinity")));
1723 : : }
1724 [ + + ]: 108 : if (NUMERIC_IS_SPECIAL(stop_num))
1725 : : {
1726 [ + + ]: 8 : if (NUMERIC_IS_NAN(stop_num))
1727 [ + - ]: 4 : ereport(ERROR,
1728 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1729 : : errmsg("stop value cannot be NaN")));
1730 : : else
1731 [ + - ]: 4 : ereport(ERROR,
1732 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1733 : : errmsg("stop value cannot be infinity")));
1734 : : }
1735 : :
1736 : : /* see if we were given an explicit step size */
1737 [ + + ]: 100 : if (PG_NARGS() == 3)
1738 : : {
1739 : 48 : Numeric step_num = PG_GETARG_NUMERIC(2);
1740 : :
1741 [ + + ]: 48 : if (NUMERIC_IS_SPECIAL(step_num))
1742 : : {
1743 [ + + ]: 8 : if (NUMERIC_IS_NAN(step_num))
1744 [ + - ]: 4 : ereport(ERROR,
1745 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1746 : : errmsg("step size cannot be NaN")));
1747 : : else
1748 [ + - ]: 4 : ereport(ERROR,
1749 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1750 : : errmsg("step size cannot be infinity")));
1751 : : }
1752 : :
1753 : 40 : init_var_from_num(step_num, &steploc);
1754 : :
1755 [ + + ]: 40 : if (cmp_var(&steploc, &const_zero) == 0)
1756 [ + - ]: 4 : ereport(ERROR,
1757 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1758 : : errmsg("step size cannot equal zero")));
1759 : : }
1760 : :
1761 : : /* create a function context for cross-call persistence */
1762 : 88 : funcctx = SRF_FIRSTCALL_INIT();
1763 : :
1764 : : /*
1765 : : * Switch to memory context appropriate for multiple function calls.
1766 : : */
1767 : 88 : oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1768 : :
1769 : : /* allocate memory for user context */
1770 : 88 : fctx = palloc_object(generate_series_numeric_fctx);
1771 : :
1772 : : /*
1773 : : * Use fctx to keep state from call to call. Seed current with the
1774 : : * original start value. We must copy the start_num and stop_num
1775 : : * values rather than pointing to them, since we may have detoasted
1776 : : * them in the per-call context.
1777 : : */
1778 : 88 : init_var(&fctx->current);
1779 : 88 : init_var(&fctx->stop);
1780 : 88 : init_var(&fctx->step);
1781 : :
1782 : 88 : set_var_from_num(start_num, &fctx->current);
1783 : 88 : set_var_from_num(stop_num, &fctx->stop);
1784 : 88 : set_var_from_var(&steploc, &fctx->step);
1785 : :
1786 : 88 : funcctx->user_fctx = fctx;
1787 : 88 : MemoryContextSwitchTo(oldcontext);
1788 : : }
1789 : :
1790 : : /* stuff done on every call of the function */
1791 : 80528 : funcctx = SRF_PERCALL_SETUP();
1792 : :
1793 : : /*
1794 : : * Get the saved state and use current state as the result of this
1795 : : * iteration.
1796 : : */
1797 : 80528 : fctx = funcctx->user_fctx;
1798 : :
1799 [ + + + + ]: 160936 : if ((fctx->step.sign == NUMERIC_POS &&
1800 : 80408 : cmp_var(&fctx->current, &fctx->stop) <= 0) ||
1801 [ + + + + ]: 320 : (fctx->step.sign == NUMERIC_NEG &&
1802 : 120 : cmp_var(&fctx->current, &fctx->stop) >= 0))
1803 : : {
1804 : 80440 : Numeric result = make_result(&fctx->current);
1805 : :
1806 : : /* switch to memory context appropriate for iteration calculation */
1807 : 80440 : oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1808 : :
1809 : : /* increment current in preparation for next iteration */
1810 : 80440 : add_var(&fctx->current, &fctx->step, &fctx->current);
1811 : 80440 : MemoryContextSwitchTo(oldcontext);
1812 : :
1813 : : /* do when there is more left to send */
1814 : 80440 : SRF_RETURN_NEXT(funcctx, NumericGetDatum(result));
1815 : : }
1816 : : else
1817 : : /* do when there is no more left */
1818 : 88 : SRF_RETURN_DONE(funcctx);
1819 : : }
1820 : :
1821 : : /*
1822 : : * Planner support function for generate_series(numeric, numeric [, numeric])
1823 : : */
1824 : : Datum
1825 : 535 : generate_series_numeric_support(PG_FUNCTION_ARGS)
1826 : : {
1827 : 535 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
1828 : 535 : Node *ret = NULL;
1829 : :
1830 [ + + ]: 535 : if (IsA(rawreq, SupportRequestRows))
1831 : : {
1832 : : /* Try to estimate the number of rows returned */
1833 : 130 : SupportRequestRows *req = (SupportRequestRows *) rawreq;
1834 : :
1835 [ + - ]: 130 : if (is_funcclause(req->node)) /* be paranoid */
1836 : : {
1837 : 130 : List *args = ((FuncExpr *) req->node)->args;
1838 : : Node *arg1,
1839 : : *arg2,
1840 : : *arg3;
1841 : :
1842 : : /* We can use estimated argument values here */
1843 : 130 : arg1 = estimate_expression_value(req->root, linitial(args));
1844 : 130 : arg2 = estimate_expression_value(req->root, lsecond(args));
1845 [ + + ]: 130 : if (list_length(args) >= 3)
1846 : 85 : arg3 = estimate_expression_value(req->root, lthird(args));
1847 : : else
1848 : 45 : arg3 = NULL;
1849 : :
1850 : : /*
1851 : : * If any argument is constant NULL, we can safely assume that
1852 : : * zero rows are returned. Otherwise, if they're all non-NULL
1853 : : * constants, we can calculate the number of rows that will be
1854 : : * returned.
1855 : : */
1856 [ + + ]: 130 : if ((IsA(arg1, Const) &&
1857 [ + - ]: 125 : ((Const *) arg1)->constisnull) ||
1858 [ + + ]: 130 : (IsA(arg2, Const) &&
1859 [ + - + + ]: 130 : ((Const *) arg2)->constisnull) ||
1860 [ + + ]: 85 : (arg3 != NULL && IsA(arg3, Const) &&
1861 [ - + ]: 80 : ((Const *) arg3)->constisnull))
1862 : : {
1863 : 0 : req->rows = 0;
1864 : 0 : ret = (Node *) req;
1865 : : }
1866 [ + + ]: 130 : else if (IsA(arg1, Const) &&
1867 [ + + + + ]: 125 : IsA(arg2, Const) &&
1868 [ + + ]: 85 : (arg3 == NULL || IsA(arg3, Const)))
1869 : : {
1870 : : Numeric start_num;
1871 : : Numeric stop_num;
1872 : 115 : NumericVar step = const_one;
1873 : :
1874 : : /*
1875 : : * If any argument is NaN or infinity, generate_series() will
1876 : : * error out, so we needn't produce an estimate.
1877 : : */
1878 : 115 : start_num = DatumGetNumeric(((Const *) arg1)->constvalue);
1879 : 115 : stop_num = DatumGetNumeric(((Const *) arg2)->constvalue);
1880 : :
1881 [ + + ]: 115 : if (NUMERIC_IS_SPECIAL(start_num) ||
1882 [ + + ]: 100 : NUMERIC_IS_SPECIAL(stop_num))
1883 : 40 : PG_RETURN_POINTER(NULL);
1884 : :
1885 [ + + ]: 90 : if (arg3)
1886 : : {
1887 : : Numeric step_num;
1888 : :
1889 : 55 : step_num = DatumGetNumeric(((Const *) arg3)->constvalue);
1890 : :
1891 [ + + ]: 55 : if (NUMERIC_IS_SPECIAL(step_num))
1892 : 15 : PG_RETURN_POINTER(NULL);
1893 : :
1894 : 40 : init_var_from_num(step_num, &step);
1895 : : }
1896 : :
1897 : : /*
1898 : : * The number of rows that will be returned is given by
1899 : : * floor((stop - start) / step) + 1, if the sign of step
1900 : : * matches the sign of stop - start. Otherwise, no rows will
1901 : : * be returned.
1902 : : */
1903 [ + + ]: 75 : if (cmp_var(&step, &const_zero) != 0)
1904 : : {
1905 : : NumericVar start;
1906 : : NumericVar stop;
1907 : : NumericVar res;
1908 : :
1909 : 65 : init_var_from_num(start_num, &start);
1910 : 65 : init_var_from_num(stop_num, &stop);
1911 : :
1912 : 65 : init_var(&res);
1913 : 65 : sub_var(&stop, &start, &res);
1914 : :
1915 [ + + ]: 65 : if (step.sign != res.sign)
1916 : : {
1917 : : /* no rows will be returned */
1918 : 5 : req->rows = 0;
1919 : 5 : ret = (Node *) req;
1920 : : }
1921 : : else
1922 : : {
1923 [ + + ]: 60 : if (arg3)
1924 : 25 : div_var(&res, &step, &res, 0, false, false);
1925 : : else
1926 : 35 : trunc_var(&res, 0); /* step = 1 */
1927 : :
1928 : 60 : req->rows = numericvar_to_double_no_overflow(&res) + 1;
1929 : 60 : ret = (Node *) req;
1930 : : }
1931 : :
1932 : 65 : free_var(&res);
1933 : : }
1934 : : }
1935 : : }
1936 : : }
1937 : :
1938 : 495 : PG_RETURN_POINTER(ret);
1939 : : }
1940 : :
1941 : :
1942 : : /*
1943 : : * Implements the numeric version of the width_bucket() function
1944 : : * defined by SQL2003. See also width_bucket_float8().
1945 : : *
1946 : : * 'bound1' and 'bound2' are the lower and upper bounds of the
1947 : : * histogram's range, respectively. 'count' is the number of buckets
1948 : : * in the histogram. width_bucket() returns an integer indicating the
1949 : : * bucket number that 'operand' belongs to in an equiwidth histogram
1950 : : * with the specified characteristics. An operand smaller than the
1951 : : * lower bound is assigned to bucket 0. An operand greater than or equal
1952 : : * to the upper bound is assigned to an additional bucket (with number
1953 : : * count+1). We don't allow the histogram bounds to be NaN or +/- infinity,
1954 : : * but we do allow those values for the operand (taking NaN to be larger
1955 : : * than any other value, as we do in comparisons).
1956 : : */
1957 : : Datum
1958 : 529 : width_bucket_numeric(PG_FUNCTION_ARGS)
1959 : : {
1960 : 529 : Numeric operand = PG_GETARG_NUMERIC(0);
1961 : 529 : Numeric bound1 = PG_GETARG_NUMERIC(1);
1962 : 529 : Numeric bound2 = PG_GETARG_NUMERIC(2);
1963 : 529 : int32 count = PG_GETARG_INT32(3);
1964 : : NumericVar count_var;
1965 : : NumericVar result_var;
1966 : : int32 result;
1967 : :
1968 [ + + ]: 529 : if (count <= 0)
1969 [ + - ]: 8 : ereport(ERROR,
1970 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
1971 : : errmsg("count must be greater than zero")));
1972 : :
1973 [ + + + + ]: 521 : if (NUMERIC_IS_SPECIAL(bound1) || NUMERIC_IS_SPECIAL(bound2))
1974 : : {
1975 [ + + - + ]: 16 : if (NUMERIC_IS_NAN(bound1) || NUMERIC_IS_NAN(bound2))
1976 [ + - ]: 4 : ereport(ERROR,
1977 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
1978 : : errmsg("lower and upper bounds cannot be NaN")));
1979 : :
1980 [ + + + - ]: 12 : if (NUMERIC_IS_INF(bound1) || NUMERIC_IS_INF(bound2))
1981 [ + - ]: 12 : ereport(ERROR,
1982 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
1983 : : errmsg("lower and upper bounds must be finite")));
1984 : : }
1985 : :
1986 : 505 : init_var(&result_var);
1987 : 505 : init_var(&count_var);
1988 : :
1989 : : /* Convert 'count' to a numeric, for ease of use later */
1990 : 505 : int64_to_numericvar((int64) count, &count_var);
1991 : :
1992 [ + + + - ]: 505 : switch (cmp_numerics(bound1, bound2))
1993 : : {
1994 : 4 : case 0:
1995 [ + - ]: 4 : ereport(ERROR,
1996 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
1997 : : errmsg("lower bound cannot equal upper bound")));
1998 : : break;
1999 : :
2000 : : /* bound1 < bound2 */
2001 : 372 : case -1:
2002 [ + + ]: 372 : if (cmp_numerics(operand, bound1) < 0)
2003 : 77 : set_var_from_var(&const_zero, &result_var);
2004 [ + + ]: 295 : else if (cmp_numerics(operand, bound2) >= 0)
2005 : 78 : add_var(&count_var, &const_one, &result_var);
2006 : : else
2007 : 217 : compute_bucket(operand, bound1, bound2, &count_var,
2008 : : &result_var);
2009 : 372 : break;
2010 : :
2011 : : /* bound1 > bound2 */
2012 : 129 : case 1:
2013 [ + + ]: 129 : if (cmp_numerics(operand, bound1) > 0)
2014 : 8 : set_var_from_var(&const_zero, &result_var);
2015 [ + + ]: 121 : else if (cmp_numerics(operand, bound2) <= 0)
2016 : 16 : add_var(&count_var, &const_one, &result_var);
2017 : : else
2018 : 105 : compute_bucket(operand, bound1, bound2, &count_var,
2019 : : &result_var);
2020 : 129 : break;
2021 : : }
2022 : :
2023 : : /* if result exceeds the range of a legal int4, we ereport here */
2024 [ - + ]: 501 : if (!numericvar_to_int32(&result_var, &result))
2025 [ # # ]: 0 : ereport(ERROR,
2026 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
2027 : : errmsg("integer out of range")));
2028 : :
2029 : 501 : free_var(&count_var);
2030 : 501 : free_var(&result_var);
2031 : :
2032 : 501 : PG_RETURN_INT32(result);
2033 : : }
2034 : :
2035 : : /*
2036 : : * 'operand' is inside the bucket range, so determine the correct
2037 : : * bucket for it to go in. The calculations performed by this function
2038 : : * are derived directly from the SQL2003 spec. Note however that we
2039 : : * multiply by count before dividing, to avoid unnecessary roundoff error.
2040 : : */
2041 : : static void
2042 : 322 : compute_bucket(Numeric operand, Numeric bound1, Numeric bound2,
2043 : : const NumericVar *count_var, NumericVar *result_var)
2044 : : {
2045 : : NumericVar bound1_var;
2046 : : NumericVar bound2_var;
2047 : : NumericVar operand_var;
2048 : :
2049 : 322 : init_var_from_num(bound1, &bound1_var);
2050 : 322 : init_var_from_num(bound2, &bound2_var);
2051 : 322 : init_var_from_num(operand, &operand_var);
2052 : :
2053 : : /*
2054 : : * Per spec, bound1 is inclusive and bound2 is exclusive, and so we have
2055 : : * bound1 <= operand < bound2 or bound1 >= operand > bound2. Either way,
2056 : : * the result is ((operand - bound1) * count) / (bound2 - bound1) + 1,
2057 : : * where the quotient is computed using floor division (i.e., division to
2058 : : * zero decimal places with truncation), which guarantees that the result
2059 : : * is in the range [1, count]. Reversing the bounds doesn't affect the
2060 : : * computation, because the signs cancel out when dividing.
2061 : : */
2062 : 322 : sub_var(&operand_var, &bound1_var, &operand_var);
2063 : 322 : sub_var(&bound2_var, &bound1_var, &bound2_var);
2064 : :
2065 : 322 : mul_var(&operand_var, count_var, &operand_var,
2066 : 322 : operand_var.dscale + count_var->dscale);
2067 : 322 : div_var(&operand_var, &bound2_var, result_var, 0, false, true);
2068 : 322 : add_var(result_var, &const_one, result_var);
2069 : :
2070 : 322 : free_var(&bound1_var);
2071 : 322 : free_var(&bound2_var);
2072 : 322 : free_var(&operand_var);
2073 : 322 : }
2074 : :
2075 : : /* ----------------------------------------------------------------------
2076 : : *
2077 : : * Comparison functions
2078 : : *
2079 : : * Note: btree indexes need these routines not to leak memory; therefore,
2080 : : * be careful to free working copies of toasted datums. Most places don't
2081 : : * need to be so careful.
2082 : : *
2083 : : * Sort support:
2084 : : *
2085 : : * We implement the sortsupport strategy routine in order to get the benefit of
2086 : : * abbreviation. The ordinary numeric comparison can be quite slow as a result
2087 : : * of palloc/pfree cycles (due to detoasting packed values for alignment);
2088 : : * while this could be worked on itself, the abbreviation strategy gives more
2089 : : * speedup in many common cases.
2090 : : *
2091 : : * The abbreviated format is an int64. The representation is negated relative
2092 : : * to the original value, because we use the largest negative value for NaN,
2093 : : * which sorts higher than other values. We convert the absolute value of the
2094 : : * numeric to a 63-bit positive value, and then negate it if the original
2095 : : * number was positive.
2096 : : *
2097 : : * We abort the abbreviation process if the abbreviation cardinality is below
2098 : : * 0.01% of the row count (1 per 10k non-null rows). The actual break-even
2099 : : * point is somewhat below that, perhaps 1 per 30k (at 1 per 100k there's a
2100 : : * very small penalty), but we don't want to build up too many abbreviated
2101 : : * values before first testing for abort, so we take the slightly pessimistic
2102 : : * number. We make no attempt to estimate the cardinality of the real values,
2103 : : * since it plays no part in the cost model here (if the abbreviation is equal,
2104 : : * the cost of comparing equal and unequal underlying values is comparable).
2105 : : * We discontinue even checking for abort (saving us the hashing overhead) if
2106 : : * the estimated cardinality gets to 100k; that would be enough to support many
2107 : : * billions of rows while doing no worse than breaking even.
2108 : : *
2109 : : * ----------------------------------------------------------------------
2110 : : */
2111 : :
2112 : : /*
2113 : : * Sort support strategy routine.
2114 : : */
2115 : : Datum
2116 : 806 : numeric_sortsupport(PG_FUNCTION_ARGS)
2117 : : {
2118 : 806 : SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
2119 : :
2120 : 806 : ssup->comparator = numeric_fast_cmp;
2121 : :
2122 [ + + ]: 806 : if (ssup->abbreviate)
2123 : : {
2124 : : NumericSortSupport *nss;
2125 : 171 : MemoryContext oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
2126 : :
2127 : 171 : nss = palloc_object(NumericSortSupport);
2128 : :
2129 : : /*
2130 : : * palloc a buffer for handling unaligned packed values in addition to
2131 : : * the support struct
2132 : : */
2133 : 171 : nss->buf = palloc(VARATT_SHORT_MAX + VARHDRSZ + 1);
2134 : :
2135 : 171 : nss->input_count = 0;
2136 : 171 : nss->estimating = true;
2137 : 171 : initHyperLogLog(&nss->abbr_card, 10);
2138 : :
2139 : 171 : ssup->ssup_extra = nss;
2140 : :
2141 : 171 : ssup->abbrev_full_comparator = ssup->comparator;
2142 : 171 : ssup->comparator = numeric_cmp_abbrev;
2143 : 171 : ssup->abbrev_converter = numeric_abbrev_convert;
2144 : 171 : ssup->abbrev_abort = numeric_abbrev_abort;
2145 : :
2146 : 171 : MemoryContextSwitchTo(oldcontext);
2147 : : }
2148 : :
2149 : 806 : PG_RETURN_VOID();
2150 : : }
2151 : :
2152 : : /*
2153 : : * Abbreviate a numeric datum, handling NaNs and detoasting
2154 : : * (must not leak memory!)
2155 : : */
2156 : : static Datum
2157 : 12779 : numeric_abbrev_convert(Datum original_datum, SortSupport ssup)
2158 : : {
2159 : 12779 : NumericSortSupport *nss = ssup->ssup_extra;
2160 : 12779 : void *original_varatt = PG_DETOAST_DATUM_PACKED(original_datum);
2161 : : Numeric value;
2162 : : Datum result;
2163 : :
2164 : 12779 : nss->input_count += 1;
2165 : :
2166 : : /*
2167 : : * This is to handle packed datums without needing a palloc/pfree cycle;
2168 : : * we keep and reuse a buffer large enough to handle any short datum.
2169 : : */
2170 [ + + ]: 12779 : if (VARATT_IS_SHORT(original_varatt))
2171 : : {
2172 : 679 : void *buf = nss->buf;
2173 : 679 : Size sz = VARSIZE_SHORT(original_varatt) - VARHDRSZ_SHORT;
2174 : :
2175 : : Assert(sz <= VARATT_SHORT_MAX - VARHDRSZ_SHORT);
2176 : :
2177 : 679 : SET_VARSIZE(buf, VARHDRSZ + sz);
2178 : 679 : memcpy(VARDATA(buf), VARDATA_SHORT(original_varatt), sz);
2179 : :
2180 : 679 : value = (Numeric) buf;
2181 : : }
2182 : : else
2183 : 12100 : value = (Numeric) original_varatt;
2184 : :
2185 [ + + ]: 12779 : if (NUMERIC_IS_SPECIAL(value))
2186 : : {
2187 [ + + ]: 100 : if (NUMERIC_IS_PINF(value))
2188 : 32 : result = NUMERIC_ABBREV_PINF;
2189 [ + + ]: 68 : else if (NUMERIC_IS_NINF(value))
2190 : 32 : result = NUMERIC_ABBREV_NINF;
2191 : : else
2192 : 36 : result = NUMERIC_ABBREV_NAN;
2193 : : }
2194 : : else
2195 : : {
2196 : : NumericVar var;
2197 : :
2198 : 12679 : init_var_from_num(value, &var);
2199 : :
2200 : 12679 : result = numeric_abbrev_convert_var(&var, nss);
2201 : : }
2202 : :
2203 : : /* should happen only for external/compressed toasts */
2204 [ - + ]: 12779 : if (original_varatt != DatumGetPointer(original_datum))
2205 : 0 : pfree(original_varatt);
2206 : :
2207 : 12779 : return result;
2208 : : }
2209 : :
2210 : : /*
2211 : : * Consider whether to abort abbreviation.
2212 : : *
2213 : : * We pay no attention to the cardinality of the non-abbreviated data. There is
2214 : : * no reason to do so: unlike text, we have no fast check for equal values, so
2215 : : * we pay the full overhead whenever the abbreviations are equal regardless of
2216 : : * whether the underlying values are also equal.
2217 : : */
2218 : : static bool
2219 : 96 : numeric_abbrev_abort(int memtupcount, SortSupport ssup)
2220 : : {
2221 : 96 : NumericSortSupport *nss = ssup->ssup_extra;
2222 : : double abbr_card;
2223 : :
2224 [ - + - - : 96 : if (memtupcount < 10000 || nss->input_count < 10000 || !nss->estimating)
- - ]
2225 : 96 : return false;
2226 : :
2227 : 0 : abbr_card = estimateHyperLogLog(&nss->abbr_card);
2228 : :
2229 : : /*
2230 : : * If we have >100k distinct values, then even if we were sorting many
2231 : : * billion rows we'd likely still break even, and the penalty of undoing
2232 : : * that many rows of abbrevs would probably not be worth it. Stop even
2233 : : * counting at that point.
2234 : : */
2235 [ # # ]: 0 : if (abbr_card > 100000.0)
2236 : : {
2237 [ # # ]: 0 : if (trace_sort)
2238 [ # # ]: 0 : elog(LOG,
2239 : : "numeric_abbrev: estimation ends at cardinality %f"
2240 : : " after " INT64_FORMAT " values (%d rows)",
2241 : : abbr_card, nss->input_count, memtupcount);
2242 : 0 : nss->estimating = false;
2243 : 0 : return false;
2244 : : }
2245 : :
2246 : : /*
2247 : : * Target minimum cardinality is 1 per ~10k of non-null inputs. (The
2248 : : * break even point is somewhere between one per 100k rows, where
2249 : : * abbreviation has a very slight penalty, and 1 per 10k where it wins by
2250 : : * a measurable percentage.) We use the relatively pessimistic 10k
2251 : : * threshold, and add a 0.5 row fudge factor, because it allows us to
2252 : : * abort earlier on genuinely pathological data where we've had exactly
2253 : : * one abbreviated value in the first 10k (non-null) rows.
2254 : : */
2255 [ # # ]: 0 : if (abbr_card < nss->input_count / 10000.0 + 0.5)
2256 : : {
2257 [ # # ]: 0 : if (trace_sort)
2258 [ # # ]: 0 : elog(LOG,
2259 : : "numeric_abbrev: aborting abbreviation at cardinality %f"
2260 : : " below threshold %f after " INT64_FORMAT " values (%d rows)",
2261 : : abbr_card, nss->input_count / 10000.0 + 0.5,
2262 : : nss->input_count, memtupcount);
2263 : 0 : return true;
2264 : : }
2265 : :
2266 [ # # ]: 0 : if (trace_sort)
2267 [ # # ]: 0 : elog(LOG,
2268 : : "numeric_abbrev: cardinality %f"
2269 : : " after " INT64_FORMAT " values (%d rows)",
2270 : : abbr_card, nss->input_count, memtupcount);
2271 : :
2272 : 0 : return false;
2273 : : }
2274 : :
2275 : : /*
2276 : : * Non-fmgr interface to the comparison routine to allow sortsupport to elide
2277 : : * the fmgr call. The saving here is small given how slow numeric comparisons
2278 : : * are, but it is a required part of the sort support API when abbreviations
2279 : : * are performed.
2280 : : *
2281 : : * Two palloc/pfree cycles could be saved here by using persistent buffers for
2282 : : * aligning short-varlena inputs, but this has not so far been considered to
2283 : : * be worth the effort.
2284 : : */
2285 : : static int
2286 : 17216389 : numeric_fast_cmp(Datum x, Datum y, SortSupport ssup)
2287 : : {
2288 : 17216389 : Numeric nx = DatumGetNumeric(x);
2289 : 17216389 : Numeric ny = DatumGetNumeric(y);
2290 : : int result;
2291 : :
2292 : 17216389 : result = cmp_numerics(nx, ny);
2293 : :
2294 [ + + ]: 17216389 : if (nx != DatumGetPointer(x))
2295 : 7409856 : pfree(nx);
2296 [ + + ]: 17216389 : if (ny != DatumGetPointer(y))
2297 : 7409852 : pfree(ny);
2298 : :
2299 : 17216389 : return result;
2300 : : }
2301 : :
2302 : : /*
2303 : : * Compare abbreviations of values. (Abbreviations may be equal where the true
2304 : : * values differ, but if the abbreviations differ, they must reflect the
2305 : : * ordering of the true values.)
2306 : : */
2307 : : static int
2308 : 124968 : numeric_cmp_abbrev(Datum x, Datum y, SortSupport ssup)
2309 : : {
2310 : : /*
2311 : : * NOTE WELL: this is intentionally backwards, because the abbreviation is
2312 : : * negated relative to the original value, to handle NaN/infinity cases.
2313 : : */
2314 [ + + ]: 124968 : if (DatumGetNumericAbbrev(x) < DatumGetNumericAbbrev(y))
2315 : 64891 : return 1;
2316 [ + + ]: 60077 : if (DatumGetNumericAbbrev(x) > DatumGetNumericAbbrev(y))
2317 : 59927 : return -1;
2318 : 150 : return 0;
2319 : : }
2320 : :
2321 : : /*
2322 : : * Abbreviate a NumericVar into the 64-bit sortsupport size.
2323 : : *
2324 : : * The 31-bit value is constructed as:
2325 : : *
2326 : : * 0 + 7bits digit weight + 24 bits digit value
2327 : : *
2328 : : * where the digit weight is in single decimal digits, not digit words, and
2329 : : * stored in excess-44 representation[1]. The 24-bit digit value is the 7 most
2330 : : * significant decimal digits of the value converted to binary. Values whose
2331 : : * weights would fall outside the representable range are rounded off to zero
2332 : : * (which is also used to represent actual zeros) or to 0x7FFFFFFF (which
2333 : : * otherwise cannot occur). Abbreviation therefore fails to gain any advantage
2334 : : * where values are outside the range 10^-44 to 10^83, which is not considered
2335 : : * to be a serious limitation, or when values are of the same magnitude and
2336 : : * equal in the first 7 decimal digits, which is considered to be an
2337 : : * unavoidable limitation given the available bits. (Stealing three more bits
2338 : : * to compare another digit would narrow the range of representable weights by
2339 : : * a factor of 8, which starts to look like a real limiting factor.)
2340 : : *
2341 : : * (The value 44 for the excess is essentially arbitrary)
2342 : : *
2343 : : * The 63-bit value is constructed as:
2344 : : *
2345 : : * 0 + 7bits weight + 4 x 14-bit packed digit words
2346 : : *
2347 : : * The weight in this case is again stored in excess-44, but this time it is
2348 : : * the original weight in digit words (i.e. powers of 10000). The first four
2349 : : * digit words of the value (if present; trailing zeros are assumed as needed)
2350 : : * are packed into 14 bits each to form the rest of the value. Again,
2351 : : * out-of-range values are rounded off to 0 or 0x7FFFFFFFFFFFFFFF. The
2352 : : * representable range in this case is 10^-176 to 10^332, which is considered
2353 : : * to be good enough for all practical purposes, and comparison of 4 words
2354 : : * means that at least 13 decimal digits are compared, which is considered to
2355 : : * be a reasonable compromise between effectiveness and efficiency in computing
2356 : : * the abbreviation.
2357 : : *
2358 : : * (The value 44 for the excess is even more arbitrary here, it was chosen just
2359 : : * to match the value used in the 31-bit case)
2360 : : *
2361 : : * [1] - Excess-k representation means that the value is offset by adding 'k'
2362 : : * and then treated as unsigned, so the smallest representable value is stored
2363 : : * with all bits zero. This allows simple comparisons to work on the composite
2364 : : * value.
2365 : : */
2366 : : static Datum
2367 : 12679 : numeric_abbrev_convert_var(const NumericVar *var, NumericSortSupport *nss)
2368 : : {
2369 : 12679 : int ndigits = var->ndigits;
2370 : 12679 : int weight = var->weight;
2371 : : int64 result;
2372 : :
2373 [ + + - + ]: 12679 : if (ndigits == 0 || weight < -44)
2374 : : {
2375 : 34 : result = 0;
2376 : : }
2377 [ + + ]: 12645 : else if (weight > 83)
2378 : : {
2379 : 8 : result = PG_INT64_MAX;
2380 : : }
2381 : : else
2382 : : {
2383 : 12637 : result = ((int64) (weight + 44) << 56);
2384 : :
2385 [ - + + + ]: 12637 : switch (ndigits)
2386 : : {
2387 : 0 : default:
2388 : 0 : result |= ((int64) var->digits[3]);
2389 : : pg_fallthrough;
2390 : 4138 : case 3:
2391 : 4138 : result |= ((int64) var->digits[2]) << 14;
2392 : : pg_fallthrough;
2393 : 12221 : case 2:
2394 : 12221 : result |= ((int64) var->digits[1]) << 28;
2395 : : pg_fallthrough;
2396 : 12637 : case 1:
2397 : 12637 : result |= ((int64) var->digits[0]) << 42;
2398 : 12637 : break;
2399 : : }
2400 : : }
2401 : :
2402 : : /* the abbrev is negated relative to the original */
2403 [ + + ]: 12679 : if (var->sign == NUMERIC_POS)
2404 : 12615 : result = -result;
2405 : :
2406 [ + - ]: 12679 : if (nss->estimating)
2407 : 12679 : addHyperLogLog(&nss->abbr_card,
2408 : 12679 : (uint32) murmurhash64((uint64) result));
2409 : :
2410 : 12679 : return NumericAbbrevGetDatum(result);
2411 : : }
2412 : :
2413 : :
2414 : : /*
2415 : : * Ordinary (non-sortsupport) comparisons follow.
2416 : : */
2417 : :
2418 : : Datum
2419 : 485645 : numeric_cmp(PG_FUNCTION_ARGS)
2420 : : {
2421 : 485645 : Numeric num1 = PG_GETARG_NUMERIC(0);
2422 : 485645 : Numeric num2 = PG_GETARG_NUMERIC(1);
2423 : : int result;
2424 : :
2425 : 485645 : result = cmp_numerics(num1, num2);
2426 : :
2427 [ + + ]: 485645 : PG_FREE_IF_COPY(num1, 0);
2428 [ + + ]: 485645 : PG_FREE_IF_COPY(num2, 1);
2429 : :
2430 : 485645 : PG_RETURN_INT32(result);
2431 : : }
2432 : :
2433 : :
2434 : : Datum
2435 : 428509 : numeric_eq(PG_FUNCTION_ARGS)
2436 : : {
2437 : 428509 : Numeric num1 = PG_GETARG_NUMERIC(0);
2438 : 428509 : Numeric num2 = PG_GETARG_NUMERIC(1);
2439 : : bool result;
2440 : :
2441 : 428509 : result = cmp_numerics(num1, num2) == 0;
2442 : :
2443 [ + + ]: 428509 : PG_FREE_IF_COPY(num1, 0);
2444 [ + + ]: 428509 : PG_FREE_IF_COPY(num2, 1);
2445 : :
2446 : 428509 : PG_RETURN_BOOL(result);
2447 : : }
2448 : :
2449 : : Datum
2450 : 3584 : numeric_ne(PG_FUNCTION_ARGS)
2451 : : {
2452 : 3584 : Numeric num1 = PG_GETARG_NUMERIC(0);
2453 : 3584 : Numeric num2 = PG_GETARG_NUMERIC(1);
2454 : : bool result;
2455 : :
2456 : 3584 : result = cmp_numerics(num1, num2) != 0;
2457 : :
2458 [ + + ]: 3584 : PG_FREE_IF_COPY(num1, 0);
2459 [ + + ]: 3584 : PG_FREE_IF_COPY(num2, 1);
2460 : :
2461 : 3584 : PG_RETURN_BOOL(result);
2462 : : }
2463 : :
2464 : : Datum
2465 : 33618 : numeric_gt(PG_FUNCTION_ARGS)
2466 : : {
2467 : 33618 : Numeric num1 = PG_GETARG_NUMERIC(0);
2468 : 33618 : Numeric num2 = PG_GETARG_NUMERIC(1);
2469 : : bool result;
2470 : :
2471 : 33618 : result = cmp_numerics(num1, num2) > 0;
2472 : :
2473 [ + + ]: 33618 : PG_FREE_IF_COPY(num1, 0);
2474 [ + + ]: 33618 : PG_FREE_IF_COPY(num2, 1);
2475 : :
2476 : 33618 : PG_RETURN_BOOL(result);
2477 : : }
2478 : :
2479 : : Datum
2480 : 7949 : numeric_ge(PG_FUNCTION_ARGS)
2481 : : {
2482 : 7949 : Numeric num1 = PG_GETARG_NUMERIC(0);
2483 : 7949 : Numeric num2 = PG_GETARG_NUMERIC(1);
2484 : : bool result;
2485 : :
2486 : 7949 : result = cmp_numerics(num1, num2) >= 0;
2487 : :
2488 [ + + ]: 7949 : PG_FREE_IF_COPY(num1, 0);
2489 [ - + ]: 7949 : PG_FREE_IF_COPY(num2, 1);
2490 : :
2491 : 7949 : PG_RETURN_BOOL(result);
2492 : : }
2493 : :
2494 : : Datum
2495 : 198916 : numeric_lt(PG_FUNCTION_ARGS)
2496 : : {
2497 : 198916 : Numeric num1 = PG_GETARG_NUMERIC(0);
2498 : 198916 : Numeric num2 = PG_GETARG_NUMERIC(1);
2499 : : bool result;
2500 : :
2501 : 198916 : result = cmp_numerics(num1, num2) < 0;
2502 : :
2503 [ + + ]: 198916 : PG_FREE_IF_COPY(num1, 0);
2504 [ + + ]: 198916 : PG_FREE_IF_COPY(num2, 1);
2505 : :
2506 : 198916 : PG_RETURN_BOOL(result);
2507 : : }
2508 : :
2509 : : Datum
2510 : 9938 : numeric_le(PG_FUNCTION_ARGS)
2511 : : {
2512 : 9938 : Numeric num1 = PG_GETARG_NUMERIC(0);
2513 : 9938 : Numeric num2 = PG_GETARG_NUMERIC(1);
2514 : : bool result;
2515 : :
2516 : 9938 : result = cmp_numerics(num1, num2) <= 0;
2517 : :
2518 [ + + ]: 9938 : PG_FREE_IF_COPY(num1, 0);
2519 [ + + ]: 9938 : PG_FREE_IF_COPY(num2, 1);
2520 : :
2521 : 9938 : PG_RETURN_BOOL(result);
2522 : : }
2523 : :
2524 : : static int
2525 : 18398933 : cmp_numerics(Numeric num1, Numeric num2)
2526 : : {
2527 : : int result;
2528 : :
2529 : : /*
2530 : : * We consider all NANs to be equal and larger than any non-NAN (including
2531 : : * Infinity). This is somewhat arbitrary; the important thing is to have
2532 : : * a consistent sort order.
2533 : : */
2534 [ + + ]: 18398933 : if (NUMERIC_IS_SPECIAL(num1))
2535 : : {
2536 [ + + ]: 2261 : if (NUMERIC_IS_NAN(num1))
2537 : : {
2538 [ + + ]: 1172 : if (NUMERIC_IS_NAN(num2))
2539 : 558 : result = 0; /* NAN = NAN */
2540 : : else
2541 : 614 : result = 1; /* NAN > non-NAN */
2542 : : }
2543 [ + + ]: 1089 : else if (NUMERIC_IS_PINF(num1))
2544 : : {
2545 [ + + ]: 87 : if (NUMERIC_IS_NAN(num2))
2546 : 14 : result = -1; /* PINF < NAN */
2547 [ + + ]: 73 : else if (NUMERIC_IS_PINF(num2))
2548 : 4 : result = 0; /* PINF = PINF */
2549 : : else
2550 : 69 : result = 1; /* PINF > anything else */
2551 : : }
2552 : : else /* num1 must be NINF */
2553 : : {
2554 [ + + ]: 1002 : if (NUMERIC_IS_NINF(num2))
2555 : 4 : result = 0; /* NINF = NINF */
2556 : : else
2557 : 998 : result = -1; /* NINF < anything else */
2558 : : }
2559 : : }
2560 [ + + ]: 18396672 : else if (NUMERIC_IS_SPECIAL(num2))
2561 : : {
2562 [ + + ]: 7927 : if (NUMERIC_IS_NINF(num2))
2563 : 12 : result = 1; /* normal > NINF */
2564 : : else
2565 : 7915 : result = -1; /* normal < NAN or PINF */
2566 : : }
2567 : : else
2568 : : {
2569 [ + + + + ]: 36778114 : result = cmp_var_common(NUMERIC_DIGITS(num1), NUMERIC_NDIGITS(num1),
2570 [ + + - + : 18388943 : NUMERIC_WEIGHT(num1), NUMERIC_SIGN(num1),
+ + + + ]
2571 [ + + + + ]: 18388745 : NUMERIC_DIGITS(num2), NUMERIC_NDIGITS(num2),
2572 [ + + - + : 18389171 : NUMERIC_WEIGHT(num2), NUMERIC_SIGN(num2));
+ + + + ]
2573 : : }
2574 : :
2575 : 18398933 : return result;
2576 : : }
2577 : :
2578 : : /*
2579 : : * in_range support function for numeric.
2580 : : */
2581 : : Datum
2582 : 768 : in_range_numeric_numeric(PG_FUNCTION_ARGS)
2583 : : {
2584 : 768 : Numeric val = PG_GETARG_NUMERIC(0);
2585 : 768 : Numeric base = PG_GETARG_NUMERIC(1);
2586 : 768 : Numeric offset = PG_GETARG_NUMERIC(2);
2587 : 768 : bool sub = PG_GETARG_BOOL(3);
2588 : 768 : bool less = PG_GETARG_BOOL(4);
2589 : : bool result;
2590 : :
2591 : : /*
2592 : : * Reject negative (including -Inf) or NaN offset. Negative is per spec,
2593 : : * and NaN is because appropriate semantics for that seem non-obvious.
2594 : : */
2595 [ + + ]: 768 : if (NUMERIC_IS_NAN(offset) ||
2596 [ + - ]: 764 : NUMERIC_IS_NINF(offset) ||
2597 [ + + - + : 764 : NUMERIC_SIGN(offset) == NUMERIC_NEG)
+ - - + -
- ]
2598 [ + - ]: 4 : ereport(ERROR,
2599 : : (errcode(ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE),
2600 : : errmsg("invalid preceding or following size in window function")));
2601 : :
2602 : : /*
2603 : : * Deal with cases where val and/or base is NaN, following the rule that
2604 : : * NaN sorts after non-NaN (cf cmp_numerics). The offset cannot affect
2605 : : * the conclusion.
2606 : : */
2607 [ + + ]: 764 : if (NUMERIC_IS_NAN(val))
2608 : : {
2609 [ + + ]: 124 : if (NUMERIC_IS_NAN(base))
2610 : 40 : result = true; /* NAN = NAN */
2611 : : else
2612 : 84 : result = !less; /* NAN > non-NAN */
2613 : : }
2614 [ + + ]: 640 : else if (NUMERIC_IS_NAN(base))
2615 : : {
2616 : 84 : result = less; /* non-NAN < NAN */
2617 : : }
2618 : :
2619 : : /*
2620 : : * Deal with infinite offset (necessarily +Inf, at this point).
2621 : : */
2622 [ + + ]: 556 : else if (NUMERIC_IS_SPECIAL(offset))
2623 : : {
2624 : : Assert(NUMERIC_IS_PINF(offset));
2625 [ + + + + ]: 280 : if (sub ? NUMERIC_IS_PINF(base) : NUMERIC_IS_NINF(base))
2626 : : {
2627 : : /*
2628 : : * base +/- offset would produce NaN, so return true for any val
2629 : : * (see in_range_float8_float8() for reasoning).
2630 : : */
2631 : 116 : result = true;
2632 : : }
2633 [ + + ]: 164 : else if (sub)
2634 : : {
2635 : : /* base - offset must be -inf */
2636 [ + + ]: 100 : if (less)
2637 : 36 : result = NUMERIC_IS_NINF(val); /* only -inf is <= sum */
2638 : : else
2639 : 64 : result = true; /* any val is >= sum */
2640 : : }
2641 : : else
2642 : : {
2643 : : /* base + offset must be +inf */
2644 [ - + ]: 64 : if (less)
2645 : 0 : result = true; /* any val is <= sum */
2646 : : else
2647 : 64 : result = NUMERIC_IS_PINF(val); /* only +inf is >= sum */
2648 : : }
2649 : : }
2650 : :
2651 : : /*
2652 : : * Deal with cases where val and/or base is infinite. The offset, being
2653 : : * now known finite, cannot affect the conclusion.
2654 : : */
2655 [ + + ]: 276 : else if (NUMERIC_IS_SPECIAL(val))
2656 : : {
2657 [ + + ]: 52 : if (NUMERIC_IS_PINF(val))
2658 : : {
2659 [ + + ]: 24 : if (NUMERIC_IS_PINF(base))
2660 : 16 : result = true; /* PINF = PINF */
2661 : : else
2662 : 8 : result = !less; /* PINF > any other non-NAN */
2663 : : }
2664 : : else /* val must be NINF */
2665 : : {
2666 [ + + ]: 28 : if (NUMERIC_IS_NINF(base))
2667 : 20 : result = true; /* NINF = NINF */
2668 : : else
2669 : 8 : result = less; /* NINF < anything else */
2670 : : }
2671 : : }
2672 [ + + ]: 224 : else if (NUMERIC_IS_SPECIAL(base))
2673 : : {
2674 [ + + ]: 16 : if (NUMERIC_IS_NINF(base))
2675 : 8 : result = !less; /* normal > NINF */
2676 : : else
2677 : 8 : result = less; /* normal < PINF */
2678 : : }
2679 : : else
2680 : : {
2681 : : /*
2682 : : * Otherwise go ahead and compute base +/- offset. While it's
2683 : : * possible for this to overflow the numeric format, it's unlikely
2684 : : * enough that we don't take measures to prevent it.
2685 : : */
2686 : : NumericVar valv;
2687 : : NumericVar basev;
2688 : : NumericVar offsetv;
2689 : : NumericVar sum;
2690 : :
2691 : 208 : init_var_from_num(val, &valv);
2692 : 208 : init_var_from_num(base, &basev);
2693 : 208 : init_var_from_num(offset, &offsetv);
2694 : 208 : init_var(&sum);
2695 : :
2696 [ + + ]: 208 : if (sub)
2697 : 104 : sub_var(&basev, &offsetv, &sum);
2698 : : else
2699 : 104 : add_var(&basev, &offsetv, &sum);
2700 : :
2701 [ + + ]: 208 : if (less)
2702 : 104 : result = (cmp_var(&valv, &sum) <= 0);
2703 : : else
2704 : 104 : result = (cmp_var(&valv, &sum) >= 0);
2705 : :
2706 : 208 : free_var(&sum);
2707 : : }
2708 : :
2709 [ + - ]: 764 : PG_FREE_IF_COPY(val, 0);
2710 [ + - ]: 764 : PG_FREE_IF_COPY(base, 1);
2711 [ - + ]: 764 : PG_FREE_IF_COPY(offset, 2);
2712 : :
2713 : 764 : PG_RETURN_BOOL(result);
2714 : : }
2715 : :
2716 : : Datum
2717 : 405122 : hash_numeric(PG_FUNCTION_ARGS)
2718 : : {
2719 : 405122 : Numeric key = PG_GETARG_NUMERIC(0);
2720 : : uint32 digit_hash;
2721 : : uint32 result;
2722 : : int weight;
2723 : : int start_offset;
2724 : : int end_offset;
2725 : : int i;
2726 : : int hash_len;
2727 : : NumericDigit *digits;
2728 : :
2729 : : /* If it's NaN or infinity, don't try to hash the rest of the fields */
2730 [ - + ]: 405122 : if (NUMERIC_IS_SPECIAL(key))
2731 : 0 : PG_RETURN_UINT32(0);
2732 : :
2733 [ + - + + ]: 405122 : weight = NUMERIC_WEIGHT(key);
2734 : 405122 : start_offset = 0;
2735 : 405122 : end_offset = 0;
2736 : :
2737 : : /*
2738 : : * Omit any leading or trailing zeros from the input to the hash. The
2739 : : * numeric implementation *should* guarantee that leading and trailing
2740 : : * zeros are suppressed, but we're paranoid. Note that we measure the
2741 : : * starting and ending offsets in units of NumericDigits, not bytes.
2742 : : */
2743 [ + - ]: 405122 : digits = NUMERIC_DIGITS(key);
2744 [ + - + + ]: 405122 : for (i = 0; i < NUMERIC_NDIGITS(key); i++)
2745 : : {
2746 [ + - ]: 404029 : if (digits[i] != (NumericDigit) 0)
2747 : 404029 : break;
2748 : :
2749 : 0 : start_offset++;
2750 : :
2751 : : /*
2752 : : * The weight is effectively the # of digits before the decimal point,
2753 : : * so decrement it for each leading zero we skip.
2754 : : */
2755 : 0 : weight--;
2756 : : }
2757 : :
2758 : : /*
2759 : : * If there are no non-zero digits, then the value of the number is zero,
2760 : : * regardless of any other fields.
2761 : : */
2762 [ + - + + ]: 405122 : if (NUMERIC_NDIGITS(key) == start_offset)
2763 : 1093 : PG_RETURN_UINT32(-1);
2764 : :
2765 [ + - + - ]: 404029 : for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--)
2766 : : {
2767 [ + - ]: 404029 : if (digits[i] != (NumericDigit) 0)
2768 : 404029 : break;
2769 : :
2770 : 0 : end_offset++;
2771 : : }
2772 : :
2773 : : /* If we get here, there should be at least one non-zero digit */
2774 : : Assert(start_offset + end_offset < NUMERIC_NDIGITS(key));
2775 : :
2776 : : /*
2777 : : * Note that we don't hash on the Numeric's scale, since two numerics can
2778 : : * compare equal but have different scales. We also don't hash on the
2779 : : * sign, although we could: since a sign difference implies inequality,
2780 : : * this shouldn't affect correctness.
2781 : : */
2782 [ + - ]: 404029 : hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset;
2783 [ + - ]: 404029 : digit_hash = hash_bytes((unsigned char *) (NUMERIC_DIGITS(key)
2784 : 404029 : + start_offset),
2785 : : hash_len * sizeof(NumericDigit));
2786 : :
2787 : : /* Mix in the weight, via XOR */
2788 : 404029 : result = digit_hash ^ weight;
2789 : :
2790 : 404029 : PG_RETURN_UINT32(result);
2791 : : }
2792 : :
2793 : : /*
2794 : : * Returns 64-bit value by hashing a value to a 64-bit value, with a seed.
2795 : : * Otherwise, similar to hash_numeric.
2796 : : */
2797 : : Datum
2798 : 56 : hash_numeric_extended(PG_FUNCTION_ARGS)
2799 : : {
2800 : 56 : Numeric key = PG_GETARG_NUMERIC(0);
2801 : 56 : uint64 seed = PG_GETARG_INT64(1);
2802 : : uint64 digit_hash;
2803 : : uint64 result;
2804 : : int weight;
2805 : : int start_offset;
2806 : : int end_offset;
2807 : : int i;
2808 : : int hash_len;
2809 : : NumericDigit *digits;
2810 : :
2811 : : /* If it's NaN or infinity, don't try to hash the rest of the fields */
2812 [ - + ]: 56 : if (NUMERIC_IS_SPECIAL(key))
2813 : 0 : PG_RETURN_UINT64(seed);
2814 : :
2815 [ + - - + ]: 56 : weight = NUMERIC_WEIGHT(key);
2816 : 56 : start_offset = 0;
2817 : 56 : end_offset = 0;
2818 : :
2819 [ + - ]: 56 : digits = NUMERIC_DIGITS(key);
2820 [ + - + + ]: 56 : for (i = 0; i < NUMERIC_NDIGITS(key); i++)
2821 : : {
2822 [ + - ]: 48 : if (digits[i] != (NumericDigit) 0)
2823 : 48 : break;
2824 : :
2825 : 0 : start_offset++;
2826 : :
2827 : 0 : weight--;
2828 : : }
2829 : :
2830 [ + - + + ]: 56 : if (NUMERIC_NDIGITS(key) == start_offset)
2831 : 8 : PG_RETURN_UINT64(seed - 1);
2832 : :
2833 [ + - + - ]: 48 : for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--)
2834 : : {
2835 [ + - ]: 48 : if (digits[i] != (NumericDigit) 0)
2836 : 48 : break;
2837 : :
2838 : 0 : end_offset++;
2839 : : }
2840 : :
2841 : : Assert(start_offset + end_offset < NUMERIC_NDIGITS(key));
2842 : :
2843 [ + - ]: 48 : hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset;
2844 [ + - ]: 48 : digit_hash = hash_bytes_extended((unsigned char *) (NUMERIC_DIGITS(key)
2845 : 48 : + start_offset),
2846 : : hash_len * sizeof(NumericDigit),
2847 : : seed);
2848 : :
2849 : 48 : result = digit_hash ^ weight;
2850 : :
2851 : 48 : PG_RETURN_UINT64(result);
2852 : : }
2853 : :
2854 : :
2855 : : /* ----------------------------------------------------------------------
2856 : : *
2857 : : * Basic arithmetic functions
2858 : : *
2859 : : * ----------------------------------------------------------------------
2860 : : */
2861 : :
2862 : :
2863 : : /*
2864 : : * numeric_add() -
2865 : : *
2866 : : * Add two numerics
2867 : : */
2868 : : Datum
2869 : 168460 : numeric_add(PG_FUNCTION_ARGS)
2870 : : {
2871 : 168460 : Numeric num1 = PG_GETARG_NUMERIC(0);
2872 : 168460 : Numeric num2 = PG_GETARG_NUMERIC(1);
2873 : : Numeric res;
2874 : :
2875 : 168460 : res = numeric_add_safe(num1, num2, NULL);
2876 : :
2877 : 168460 : PG_RETURN_NUMERIC(res);
2878 : : }
2879 : :
2880 : : /*
2881 : : * numeric_add_safe() -
2882 : : *
2883 : : * Internal version of numeric_add() with support for soft error reporting.
2884 : : */
2885 : : Numeric
2886 : 169154 : numeric_add_safe(Numeric num1, Numeric num2, Node *escontext)
2887 : : {
2888 : : NumericVar arg1;
2889 : : NumericVar arg2;
2890 : : NumericVar result;
2891 : : Numeric res;
2892 : :
2893 : : /*
2894 : : * Handle NaN and infinities
2895 : : */
2896 [ + + + + ]: 169154 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
2897 : : {
2898 [ + + + + ]: 132 : if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2899 : 52 : return make_result(&const_nan);
2900 [ + + ]: 80 : if (NUMERIC_IS_PINF(num1))
2901 : : {
2902 [ + + ]: 24 : if (NUMERIC_IS_NINF(num2))
2903 : 4 : return make_result(&const_nan); /* Inf + -Inf */
2904 : : else
2905 : 20 : return make_result(&const_pinf);
2906 : : }
2907 [ + + ]: 56 : if (NUMERIC_IS_NINF(num1))
2908 : : {
2909 [ + + ]: 24 : if (NUMERIC_IS_PINF(num2))
2910 : 4 : return make_result(&const_nan); /* -Inf + Inf */
2911 : : else
2912 : 20 : return make_result(&const_ninf);
2913 : : }
2914 : : /* by here, num1 must be finite, so num2 is not */
2915 [ + + ]: 32 : if (NUMERIC_IS_PINF(num2))
2916 : 16 : return make_result(&const_pinf);
2917 : : Assert(NUMERIC_IS_NINF(num2));
2918 : 16 : return make_result(&const_ninf);
2919 : : }
2920 : :
2921 : : /*
2922 : : * Unpack the values, let add_var() compute the result and return it.
2923 : : */
2924 : 169022 : init_var_from_num(num1, &arg1);
2925 : 169022 : init_var_from_num(num2, &arg2);
2926 : :
2927 : 169022 : init_var(&result);
2928 : 169022 : add_var(&arg1, &arg2, &result);
2929 : :
2930 : 169022 : res = make_result_safe(&result, escontext);
2931 : :
2932 : 169022 : free_var(&result);
2933 : :
2934 : 169022 : return res;
2935 : : }
2936 : :
2937 : :
2938 : : /*
2939 : : * numeric_sub() -
2940 : : *
2941 : : * Subtract one numeric from another
2942 : : */
2943 : : Datum
2944 : 46362 : numeric_sub(PG_FUNCTION_ARGS)
2945 : : {
2946 : 46362 : Numeric num1 = PG_GETARG_NUMERIC(0);
2947 : 46362 : Numeric num2 = PG_GETARG_NUMERIC(1);
2948 : : Numeric res;
2949 : :
2950 : 46362 : res = numeric_sub_safe(num1, num2, NULL);
2951 : :
2952 : 46362 : PG_RETURN_NUMERIC(res);
2953 : : }
2954 : :
2955 : :
2956 : : /*
2957 : : * numeric_sub_safe() -
2958 : : *
2959 : : * Internal version of numeric_sub() with support for soft error reporting.
2960 : : */
2961 : : Numeric
2962 : 46466 : numeric_sub_safe(Numeric num1, Numeric num2, Node *escontext)
2963 : : {
2964 : : NumericVar arg1;
2965 : : NumericVar arg2;
2966 : : NumericVar result;
2967 : : Numeric res;
2968 : :
2969 : : /*
2970 : : * Handle NaN and infinities
2971 : : */
2972 [ + + + + ]: 46466 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
2973 : : {
2974 [ + + + + ]: 132 : if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2975 : 52 : return make_result(&const_nan);
2976 [ + + ]: 80 : if (NUMERIC_IS_PINF(num1))
2977 : : {
2978 [ + + ]: 24 : if (NUMERIC_IS_PINF(num2))
2979 : 4 : return make_result(&const_nan); /* Inf - Inf */
2980 : : else
2981 : 20 : return make_result(&const_pinf);
2982 : : }
2983 [ + + ]: 56 : if (NUMERIC_IS_NINF(num1))
2984 : : {
2985 [ + + ]: 24 : if (NUMERIC_IS_NINF(num2))
2986 : 4 : return make_result(&const_nan); /* -Inf - -Inf */
2987 : : else
2988 : 20 : return make_result(&const_ninf);
2989 : : }
2990 : : /* by here, num1 must be finite, so num2 is not */
2991 [ + + ]: 32 : if (NUMERIC_IS_PINF(num2))
2992 : 16 : return make_result(&const_ninf);
2993 : : Assert(NUMERIC_IS_NINF(num2));
2994 : 16 : return make_result(&const_pinf);
2995 : : }
2996 : :
2997 : : /*
2998 : : * Unpack the values, let sub_var() compute the result and return it.
2999 : : */
3000 : 46334 : init_var_from_num(num1, &arg1);
3001 : 46334 : init_var_from_num(num2, &arg2);
3002 : :
3003 : 46334 : init_var(&result);
3004 : 46334 : sub_var(&arg1, &arg2, &result);
3005 : :
3006 : 46334 : res = make_result_safe(&result, escontext);
3007 : :
3008 : 46334 : free_var(&result);
3009 : :
3010 : 46334 : return res;
3011 : : }
3012 : :
3013 : :
3014 : : /*
3015 : : * numeric_mul() -
3016 : : *
3017 : : * Calculate the product of two numerics
3018 : : */
3019 : : Datum
3020 : 326759 : numeric_mul(PG_FUNCTION_ARGS)
3021 : : {
3022 : 326759 : Numeric num1 = PG_GETARG_NUMERIC(0);
3023 : 326759 : Numeric num2 = PG_GETARG_NUMERIC(1);
3024 : : Numeric res;
3025 : :
3026 : 326759 : res = numeric_mul_safe(num1, num2, fcinfo->context);
3027 : :
3028 [ - + - - : 326759 : if (unlikely(SOFT_ERROR_OCCURRED(fcinfo->context)))
- + - - -
+ ]
3029 : 0 : PG_RETURN_NULL();
3030 : :
3031 : 326759 : PG_RETURN_NUMERIC(res);
3032 : : }
3033 : :
3034 : :
3035 : : /*
3036 : : * numeric_mul_safe() -
3037 : : *
3038 : : * Internal version of numeric_mul() with support for soft error reporting.
3039 : : */
3040 : : Numeric
3041 : 326791 : numeric_mul_safe(Numeric num1, Numeric num2, Node *escontext)
3042 : : {
3043 : : NumericVar arg1;
3044 : : NumericVar arg2;
3045 : : NumericVar result;
3046 : : Numeric res;
3047 : :
3048 : : /*
3049 : : * Handle NaN and infinities
3050 : : */
3051 [ + + + + ]: 326791 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3052 : : {
3053 [ + + + + ]: 132 : if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3054 : 52 : return make_result(&const_nan);
3055 [ + + ]: 80 : if (NUMERIC_IS_PINF(num1))
3056 : : {
3057 [ + + + - ]: 24 : switch (numeric_sign_internal(num2))
3058 : : {
3059 : 4 : case 0:
3060 : 4 : return make_result(&const_nan); /* Inf * 0 */
3061 : 12 : case 1:
3062 : 12 : return make_result(&const_pinf);
3063 : 8 : case -1:
3064 : 8 : return make_result(&const_ninf);
3065 : : }
3066 : : Assert(false);
3067 : : }
3068 [ + + ]: 56 : if (NUMERIC_IS_NINF(num1))
3069 : : {
3070 [ + + + - ]: 24 : switch (numeric_sign_internal(num2))
3071 : : {
3072 : 4 : case 0:
3073 : 4 : return make_result(&const_nan); /* -Inf * 0 */
3074 : 12 : case 1:
3075 : 12 : return make_result(&const_ninf);
3076 : 8 : case -1:
3077 : 8 : return make_result(&const_pinf);
3078 : : }
3079 : : Assert(false);
3080 : : }
3081 : : /* by here, num1 must be finite, so num2 is not */
3082 [ + + ]: 32 : if (NUMERIC_IS_PINF(num2))
3083 : : {
3084 [ + + + - ]: 16 : switch (numeric_sign_internal(num1))
3085 : : {
3086 : 4 : case 0:
3087 : 4 : return make_result(&const_nan); /* 0 * Inf */
3088 : 8 : case 1:
3089 : 8 : return make_result(&const_pinf);
3090 : 4 : case -1:
3091 : 4 : return make_result(&const_ninf);
3092 : : }
3093 : : Assert(false);
3094 : : }
3095 : : Assert(NUMERIC_IS_NINF(num2));
3096 [ + + + - ]: 16 : switch (numeric_sign_internal(num1))
3097 : : {
3098 : 4 : case 0:
3099 : 4 : return make_result(&const_nan); /* 0 * -Inf */
3100 : 8 : case 1:
3101 : 8 : return make_result(&const_ninf);
3102 : 4 : case -1:
3103 : 4 : return make_result(&const_pinf);
3104 : : }
3105 : : Assert(false);
3106 : : }
3107 : :
3108 : : /*
3109 : : * Unpack the values, let mul_var() compute the result and return it.
3110 : : * Unlike add_var() and sub_var(), mul_var() will round its result. In the
3111 : : * case of numeric_mul(), which is invoked for the * operator on numerics,
3112 : : * we request exact representation for the product (rscale = sum(dscale of
3113 : : * arg1, dscale of arg2)). If the exact result has more digits after the
3114 : : * decimal point than can be stored in a numeric, we round it. Rounding
3115 : : * after computing the exact result ensures that the final result is
3116 : : * correctly rounded (rounding in mul_var() using a truncated product
3117 : : * would not guarantee this).
3118 : : */
3119 : 326659 : init_var_from_num(num1, &arg1);
3120 : 326659 : init_var_from_num(num2, &arg2);
3121 : :
3122 : 326659 : init_var(&result);
3123 : 326659 : mul_var(&arg1, &arg2, &result, arg1.dscale + arg2.dscale);
3124 : :
3125 [ + + ]: 326659 : if (result.dscale > NUMERIC_DSCALE_MAX)
3126 : 5 : round_var(&result, NUMERIC_DSCALE_MAX);
3127 : :
3128 : 326659 : res = make_result_safe(&result, escontext);
3129 : :
3130 : 326659 : free_var(&result);
3131 : :
3132 : 326659 : return res;
3133 : : }
3134 : :
3135 : :
3136 : : /*
3137 : : * numeric_div() -
3138 : : *
3139 : : * Divide one numeric into another
3140 : : */
3141 : : Datum
3142 : 98473 : numeric_div(PG_FUNCTION_ARGS)
3143 : : {
3144 : 98473 : Numeric num1 = PG_GETARG_NUMERIC(0);
3145 : 98473 : Numeric num2 = PG_GETARG_NUMERIC(1);
3146 : : Numeric res;
3147 : :
3148 : 98473 : res = numeric_div_safe(num1, num2, NULL);
3149 : :
3150 : 98452 : PG_RETURN_NUMERIC(res);
3151 : : }
3152 : :
3153 : :
3154 : : /*
3155 : : * numeric_div_safe() -
3156 : : *
3157 : : * Internal version of numeric_div() with support for soft error reporting.
3158 : : */
3159 : : Numeric
3160 : 99034 : numeric_div_safe(Numeric num1, Numeric num2, Node *escontext)
3161 : : {
3162 : : NumericVar arg1;
3163 : : NumericVar arg2;
3164 : : NumericVar result;
3165 : : Numeric res;
3166 : : int rscale;
3167 : :
3168 : : /*
3169 : : * Handle NaN and infinities
3170 : : */
3171 [ + + + + ]: 99034 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3172 : : {
3173 [ + + + + ]: 133 : if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3174 : 53 : return make_result(&const_nan);
3175 [ + + ]: 80 : if (NUMERIC_IS_PINF(num1))
3176 : : {
3177 [ + + ]: 24 : if (NUMERIC_IS_SPECIAL(num2))
3178 : 8 : return make_result(&const_nan); /* Inf / [-]Inf */
3179 [ + + + - ]: 16 : switch (numeric_sign_internal(num2))
3180 : : {
3181 : 4 : case 0:
3182 : 4 : goto division_by_zero;
3183 : 8 : case 1:
3184 : 8 : return make_result(&const_pinf);
3185 : 4 : case -1:
3186 : 4 : return make_result(&const_ninf);
3187 : : }
3188 : : Assert(false);
3189 : : }
3190 [ + + ]: 56 : if (NUMERIC_IS_NINF(num1))
3191 : : {
3192 [ + + ]: 24 : if (NUMERIC_IS_SPECIAL(num2))
3193 : 8 : return make_result(&const_nan); /* -Inf / [-]Inf */
3194 [ + + + - ]: 16 : switch (numeric_sign_internal(num2))
3195 : : {
3196 : 4 : case 0:
3197 : 4 : goto division_by_zero;
3198 : 8 : case 1:
3199 : 8 : return make_result(&const_ninf);
3200 : 4 : case -1:
3201 : 4 : return make_result(&const_pinf);
3202 : : }
3203 : : Assert(false);
3204 : : }
3205 : : /* by here, num1 must be finite, so num2 is not */
3206 : :
3207 : : /*
3208 : : * POSIX would have us return zero or minus zero if num1 is zero, and
3209 : : * otherwise throw an underflow error. But the numeric type doesn't
3210 : : * really do underflow, so let's just return zero.
3211 : : */
3212 : 32 : return make_result(&const_zero);
3213 : : }
3214 : :
3215 : : /*
3216 : : * Unpack the arguments
3217 : : */
3218 : 98901 : init_var_from_num(num1, &arg1);
3219 : 98901 : init_var_from_num(num2, &arg2);
3220 : :
3221 : 98901 : init_var(&result);
3222 : :
3223 : : /*
3224 : : * Select scale for division result
3225 : : */
3226 : 98901 : rscale = select_div_scale(&arg1, &arg2);
3227 : :
3228 : : /* Check for division by zero */
3229 [ + + - + ]: 98901 : if (arg2.ndigits == 0 || arg2.digits[0] == 0)
3230 : 33 : goto division_by_zero;
3231 : :
3232 : : /*
3233 : : * Do the divide and return the result
3234 : : */
3235 : 98868 : div_var(&arg1, &arg2, &result, rscale, true, true);
3236 : :
3237 : 98868 : res = make_result_safe(&result, escontext);
3238 : :
3239 : 98868 : free_var(&result);
3240 : :
3241 : 98868 : return res;
3242 : :
3243 : 41 : division_by_zero:
3244 [ + + ]: 41 : ereturn(escontext, NULL,
3245 : : errcode(ERRCODE_DIVISION_BY_ZERO),
3246 : : errmsg("division by zero"));
3247 : : }
3248 : :
3249 : :
3250 : : /*
3251 : : * numeric_div_trunc() -
3252 : : *
3253 : : * Divide one numeric into another, truncating the result to an integer
3254 : : */
3255 : : Datum
3256 : 822 : numeric_div_trunc(PG_FUNCTION_ARGS)
3257 : : {
3258 : 822 : Numeric num1 = PG_GETARG_NUMERIC(0);
3259 : 822 : Numeric num2 = PG_GETARG_NUMERIC(1);
3260 : : NumericVar arg1;
3261 : : NumericVar arg2;
3262 : : NumericVar result;
3263 : : Numeric res;
3264 : :
3265 : : /*
3266 : : * Handle NaN and infinities
3267 : : */
3268 [ + + + + ]: 822 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3269 : : {
3270 [ + + + + ]: 133 : if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3271 : 53 : PG_RETURN_NUMERIC(make_result(&const_nan));
3272 [ + + ]: 80 : if (NUMERIC_IS_PINF(num1))
3273 : : {
3274 [ + + ]: 24 : if (NUMERIC_IS_SPECIAL(num2))
3275 : 8 : PG_RETURN_NUMERIC(make_result(&const_nan)); /* Inf / [-]Inf */
3276 [ + + + - ]: 16 : switch (numeric_sign_internal(num2))
3277 : : {
3278 : 4 : case 0:
3279 [ + - ]: 4 : ereport(ERROR,
3280 : : (errcode(ERRCODE_DIVISION_BY_ZERO),
3281 : : errmsg("division by zero")));
3282 : : break;
3283 : 8 : case 1:
3284 : 8 : PG_RETURN_NUMERIC(make_result(&const_pinf));
3285 : 4 : case -1:
3286 : 4 : PG_RETURN_NUMERIC(make_result(&const_ninf));
3287 : : }
3288 : : Assert(false);
3289 : : }
3290 [ + + ]: 56 : if (NUMERIC_IS_NINF(num1))
3291 : : {
3292 [ + + ]: 24 : if (NUMERIC_IS_SPECIAL(num2))
3293 : 8 : PG_RETURN_NUMERIC(make_result(&const_nan)); /* -Inf / [-]Inf */
3294 [ + + + - ]: 16 : switch (numeric_sign_internal(num2))
3295 : : {
3296 : 4 : case 0:
3297 [ + - ]: 4 : ereport(ERROR,
3298 : : (errcode(ERRCODE_DIVISION_BY_ZERO),
3299 : : errmsg("division by zero")));
3300 : : break;
3301 : 8 : case 1:
3302 : 8 : PG_RETURN_NUMERIC(make_result(&const_ninf));
3303 : 4 : case -1:
3304 : 4 : PG_RETURN_NUMERIC(make_result(&const_pinf));
3305 : : }
3306 : : Assert(false);
3307 : : }
3308 : : /* by here, num1 must be finite, so num2 is not */
3309 : :
3310 : : /*
3311 : : * POSIX would have us return zero or minus zero if num1 is zero, and
3312 : : * otherwise throw an underflow error. But the numeric type doesn't
3313 : : * really do underflow, so let's just return zero.
3314 : : */
3315 : 32 : PG_RETURN_NUMERIC(make_result(&const_zero));
3316 : : }
3317 : :
3318 : : /*
3319 : : * Unpack the arguments
3320 : : */
3321 : 689 : init_var_from_num(num1, &arg1);
3322 : 689 : init_var_from_num(num2, &arg2);
3323 : :
3324 : 689 : init_var(&result);
3325 : :
3326 : : /*
3327 : : * Do the divide and return the result
3328 : : */
3329 : 689 : div_var(&arg1, &arg2, &result, 0, false, true);
3330 : :
3331 : 685 : res = make_result(&result);
3332 : :
3333 : 685 : free_var(&result);
3334 : :
3335 : 685 : PG_RETURN_NUMERIC(res);
3336 : : }
3337 : :
3338 : :
3339 : : /*
3340 : : * numeric_mod() -
3341 : : *
3342 : : * Calculate the modulo of two numerics
3343 : : */
3344 : : Datum
3345 : 275242 : numeric_mod(PG_FUNCTION_ARGS)
3346 : : {
3347 : 275242 : Numeric num1 = PG_GETARG_NUMERIC(0);
3348 : 275242 : Numeric num2 = PG_GETARG_NUMERIC(1);
3349 : : Numeric res;
3350 : :
3351 : 275242 : res = numeric_mod_safe(num1, num2, NULL);
3352 : :
3353 : 275230 : PG_RETURN_NUMERIC(res);
3354 : : }
3355 : :
3356 : :
3357 : : /*
3358 : : * numeric_mod_safe() -
3359 : : *
3360 : : * Internal version of numeric_mod() with support for soft error reporting.
3361 : : */
3362 : : Numeric
3363 : 275250 : numeric_mod_safe(Numeric num1, Numeric num2, Node *escontext)
3364 : : {
3365 : : Numeric res;
3366 : : NumericVar arg1;
3367 : : NumericVar arg2;
3368 : : NumericVar result;
3369 : :
3370 : : /*
3371 : : * Handle NaN and infinities. We follow POSIX fmod() on this, except that
3372 : : * POSIX treats x-is-infinite and y-is-zero identically, raising EDOM and
3373 : : * returning NaN. We choose to throw error only for y-is-zero.
3374 : : */
3375 [ + + + + ]: 275250 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3376 : : {
3377 [ + + + + ]: 133 : if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3378 : 53 : return make_result(&const_nan);
3379 [ + + ]: 80 : if (NUMERIC_IS_INF(num1))
3380 : : {
3381 [ + + ]: 48 : if (numeric_sign_internal(num2) == 0)
3382 : 8 : goto division_by_zero;
3383 : :
3384 : : /* Inf % any nonzero = NaN */
3385 : 40 : return make_result(&const_nan);
3386 : : }
3387 : : /* num2 must be [-]Inf; result is num1 regardless of sign of num2 */
3388 : 32 : return duplicate_numeric(num1);
3389 : : }
3390 : :
3391 : 275117 : init_var_from_num(num1, &arg1);
3392 : 275117 : init_var_from_num(num2, &arg2);
3393 : :
3394 : 275117 : init_var(&result);
3395 : :
3396 : : /* Check for division by zero */
3397 [ + + - + ]: 275117 : if (arg2.ndigits == 0 || arg2.digits[0] == 0)
3398 : 8 : goto division_by_zero;
3399 : :
3400 : 275109 : mod_var(&arg1, &arg2, &result);
3401 : :
3402 : 275109 : res = make_result_safe(&result, escontext);
3403 : :
3404 : 275109 : free_var(&result);
3405 : :
3406 : 275109 : return res;
3407 : :
3408 : 16 : division_by_zero:
3409 [ + - ]: 16 : ereturn(escontext, NULL,
3410 : : errcode(ERRCODE_DIVISION_BY_ZERO),
3411 : : errmsg("division by zero"));
3412 : : }
3413 : :
3414 : :
3415 : : /*
3416 : : * numeric_inc() -
3417 : : *
3418 : : * Increment a number by one
3419 : : */
3420 : : Datum
3421 : 32 : numeric_inc(PG_FUNCTION_ARGS)
3422 : : {
3423 : 32 : Numeric num = PG_GETARG_NUMERIC(0);
3424 : : NumericVar arg;
3425 : : Numeric res;
3426 : :
3427 : : /*
3428 : : * Handle NaN and infinities
3429 : : */
3430 [ + + ]: 32 : if (NUMERIC_IS_SPECIAL(num))
3431 : 12 : PG_RETURN_NUMERIC(duplicate_numeric(num));
3432 : :
3433 : : /*
3434 : : * Compute the result and return it
3435 : : */
3436 : 20 : init_var_from_num(num, &arg);
3437 : :
3438 : 20 : add_var(&arg, &const_one, &arg);
3439 : :
3440 : 20 : res = make_result(&arg);
3441 : :
3442 : 20 : free_var(&arg);
3443 : :
3444 : 20 : PG_RETURN_NUMERIC(res);
3445 : : }
3446 : :
3447 : :
3448 : : /*
3449 : : * numeric_smaller() -
3450 : : *
3451 : : * Return the smaller of two numbers
3452 : : */
3453 : : Datum
3454 : 543 : numeric_smaller(PG_FUNCTION_ARGS)
3455 : : {
3456 : 543 : Numeric num1 = PG_GETARG_NUMERIC(0);
3457 : 543 : Numeric num2 = PG_GETARG_NUMERIC(1);
3458 : :
3459 : : /*
3460 : : * Use cmp_numerics so that this will agree with the comparison operators,
3461 : : * particularly as regards comparisons involving NaN.
3462 : : */
3463 [ + + ]: 543 : if (cmp_numerics(num1, num2) < 0)
3464 : 436 : PG_RETURN_NUMERIC(num1);
3465 : : else
3466 : 107 : PG_RETURN_NUMERIC(num2);
3467 : : }
3468 : :
3469 : :
3470 : : /*
3471 : : * numeric_larger() -
3472 : : *
3473 : : * Return the larger of two numbers
3474 : : */
3475 : : Datum
3476 : 12420 : numeric_larger(PG_FUNCTION_ARGS)
3477 : : {
3478 : 12420 : Numeric num1 = PG_GETARG_NUMERIC(0);
3479 : 12420 : Numeric num2 = PG_GETARG_NUMERIC(1);
3480 : :
3481 : : /*
3482 : : * Use cmp_numerics so that this will agree with the comparison operators,
3483 : : * particularly as regards comparisons involving NaN.
3484 : : */
3485 [ + + ]: 12420 : if (cmp_numerics(num1, num2) > 0)
3486 : 11949 : PG_RETURN_NUMERIC(num1);
3487 : : else
3488 : 471 : PG_RETURN_NUMERIC(num2);
3489 : : }
3490 : :
3491 : :
3492 : : /* ----------------------------------------------------------------------
3493 : : *
3494 : : * Advanced math functions
3495 : : *
3496 : : * ----------------------------------------------------------------------
3497 : : */
3498 : :
3499 : : /*
3500 : : * numeric_gcd() -
3501 : : *
3502 : : * Calculate the greatest common divisor of two numerics
3503 : : */
3504 : : Datum
3505 : 144 : numeric_gcd(PG_FUNCTION_ARGS)
3506 : : {
3507 : 144 : Numeric num1 = PG_GETARG_NUMERIC(0);
3508 : 144 : Numeric num2 = PG_GETARG_NUMERIC(1);
3509 : : NumericVar arg1;
3510 : : NumericVar arg2;
3511 : : NumericVar result;
3512 : : Numeric res;
3513 : :
3514 : : /*
3515 : : * Handle NaN and infinities: we consider the result to be NaN in all such
3516 : : * cases.
3517 : : */
3518 [ + + + + ]: 144 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3519 : 64 : PG_RETURN_NUMERIC(make_result(&const_nan));
3520 : :
3521 : : /*
3522 : : * Unpack the arguments
3523 : : */
3524 : 80 : init_var_from_num(num1, &arg1);
3525 : 80 : init_var_from_num(num2, &arg2);
3526 : :
3527 : 80 : init_var(&result);
3528 : :
3529 : : /*
3530 : : * Find the GCD and return the result
3531 : : */
3532 : 80 : gcd_var(&arg1, &arg2, &result);
3533 : :
3534 : 80 : res = make_result(&result);
3535 : :
3536 : 80 : free_var(&result);
3537 : :
3538 : 80 : PG_RETURN_NUMERIC(res);
3539 : : }
3540 : :
3541 : :
3542 : : /*
3543 : : * numeric_lcm() -
3544 : : *
3545 : : * Calculate the least common multiple of two numerics
3546 : : */
3547 : : Datum
3548 : 164 : numeric_lcm(PG_FUNCTION_ARGS)
3549 : : {
3550 : 164 : Numeric num1 = PG_GETARG_NUMERIC(0);
3551 : 164 : Numeric num2 = PG_GETARG_NUMERIC(1);
3552 : : NumericVar arg1;
3553 : : NumericVar arg2;
3554 : : NumericVar result;
3555 : : Numeric res;
3556 : :
3557 : : /*
3558 : : * Handle NaN and infinities: we consider the result to be NaN in all such
3559 : : * cases.
3560 : : */
3561 [ + + + + ]: 164 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3562 : 64 : PG_RETURN_NUMERIC(make_result(&const_nan));
3563 : :
3564 : : /*
3565 : : * Unpack the arguments
3566 : : */
3567 : 100 : init_var_from_num(num1, &arg1);
3568 : 100 : init_var_from_num(num2, &arg2);
3569 : :
3570 : 100 : init_var(&result);
3571 : :
3572 : : /*
3573 : : * Compute the result using lcm(x, y) = abs(x / gcd(x, y) * y), returning
3574 : : * zero if either input is zero.
3575 : : *
3576 : : * Note that the division is guaranteed to be exact, returning an integer
3577 : : * result, so the LCM is an integral multiple of both x and y. A display
3578 : : * scale of Min(x.dscale, y.dscale) would be sufficient to represent it,
3579 : : * but as with other numeric functions, we choose to return a result whose
3580 : : * display scale is no smaller than either input.
3581 : : */
3582 [ + + + + ]: 100 : if (arg1.ndigits == 0 || arg2.ndigits == 0)
3583 : 32 : set_var_from_var(&const_zero, &result);
3584 : : else
3585 : : {
3586 : 68 : gcd_var(&arg1, &arg2, &result);
3587 : 68 : div_var(&arg1, &result, &result, 0, false, true);
3588 : 68 : mul_var(&arg2, &result, &result, arg2.dscale);
3589 : 68 : result.sign = NUMERIC_POS;
3590 : : }
3591 : :
3592 : 100 : result.dscale = Max(arg1.dscale, arg2.dscale);
3593 : :
3594 : 100 : res = make_result(&result);
3595 : :
3596 : 96 : free_var(&result);
3597 : :
3598 : 96 : PG_RETURN_NUMERIC(res);
3599 : : }
3600 : :
3601 : :
3602 : : /*
3603 : : * numeric_fac()
3604 : : *
3605 : : * Compute factorial
3606 : : */
3607 : : Datum
3608 : 33 : numeric_fac(PG_FUNCTION_ARGS)
3609 : : {
3610 : 33 : int64 num = PG_GETARG_INT64(0);
3611 : : Numeric res;
3612 : : NumericVar fact;
3613 : : NumericVar result;
3614 : :
3615 [ + + ]: 33 : if (num < 0)
3616 [ + - ]: 4 : ereport(ERROR,
3617 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
3618 : : errmsg("factorial of a negative number is undefined")));
3619 [ + + ]: 29 : if (num <= 1)
3620 : : {
3621 : 5 : res = make_result(&const_one);
3622 : 5 : PG_RETURN_NUMERIC(res);
3623 : : }
3624 : : /* Fail immediately if the result would overflow */
3625 [ + + ]: 24 : if (num > 32177)
3626 [ + - ]: 4 : ereport(ERROR,
3627 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
3628 : : errmsg("value overflows numeric format")));
3629 : :
3630 : 20 : init_var(&fact);
3631 : 20 : init_var(&result);
3632 : :
3633 : 20 : int64_to_numericvar(num, &result);
3634 : :
3635 [ + + ]: 245 : for (num = num - 1; num > 1; num--)
3636 : : {
3637 : : /* this loop can take awhile, so allow it to be interrupted */
3638 [ - + ]: 225 : CHECK_FOR_INTERRUPTS();
3639 : :
3640 : 225 : int64_to_numericvar(num, &fact);
3641 : :
3642 : 225 : mul_var(&result, &fact, &result, 0);
3643 : : }
3644 : :
3645 : 20 : res = make_result(&result);
3646 : :
3647 : 20 : free_var(&fact);
3648 : 20 : free_var(&result);
3649 : :
3650 : 20 : PG_RETURN_NUMERIC(res);
3651 : : }
3652 : :
3653 : :
3654 : : /*
3655 : : * numeric_sqrt() -
3656 : : *
3657 : : * Compute the square root of a numeric.
3658 : : */
3659 : : Datum
3660 : 108 : numeric_sqrt(PG_FUNCTION_ARGS)
3661 : : {
3662 : 108 : Numeric num = PG_GETARG_NUMERIC(0);
3663 : : Numeric res;
3664 : : NumericVar arg;
3665 : : NumericVar result;
3666 : : int sweight;
3667 : : int rscale;
3668 : :
3669 : : /*
3670 : : * Handle NaN and infinities
3671 : : */
3672 [ + + ]: 108 : if (NUMERIC_IS_SPECIAL(num))
3673 : : {
3674 : : /* error should match that in sqrt_var() */
3675 [ + + ]: 12 : if (NUMERIC_IS_NINF(num))
3676 [ + - ]: 4 : ereport(ERROR,
3677 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
3678 : : errmsg("cannot take square root of a negative number")));
3679 : : /* For NAN or PINF, just duplicate the input */
3680 : 8 : PG_RETURN_NUMERIC(duplicate_numeric(num));
3681 : : }
3682 : :
3683 : : /*
3684 : : * Unpack the argument and determine the result scale. We choose a scale
3685 : : * to give at least NUMERIC_MIN_SIG_DIGITS significant digits; but in any
3686 : : * case not less than the input's dscale.
3687 : : */
3688 : 96 : init_var_from_num(num, &arg);
3689 : :
3690 : 96 : init_var(&result);
3691 : :
3692 : : /*
3693 : : * Assume the input was normalized, so arg.weight is accurate. The result
3694 : : * then has at least sweight = floor(arg.weight * DEC_DIGITS / 2 + 1)
3695 : : * digits before the decimal point. When DEC_DIGITS is even, we can save
3696 : : * a few cycles, since the division is exact and there is no need to round
3697 : : * towards negative infinity.
3698 : : */
3699 : : #if DEC_DIGITS == ((DEC_DIGITS / 2) * 2)
3700 : 96 : sweight = arg.weight * DEC_DIGITS / 2 + 1;
3701 : : #else
3702 : : if (arg.weight >= 0)
3703 : : sweight = arg.weight * DEC_DIGITS / 2 + 1;
3704 : : else
3705 : : sweight = 1 - (1 - arg.weight * DEC_DIGITS) / 2;
3706 : : #endif
3707 : :
3708 : 96 : rscale = NUMERIC_MIN_SIG_DIGITS - sweight;
3709 : 96 : rscale = Max(rscale, arg.dscale);
3710 : 96 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
3711 : 96 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
3712 : :
3713 : : /*
3714 : : * Let sqrt_var() do the calculation and return the result.
3715 : : */
3716 : 96 : sqrt_var(&arg, &result, rscale);
3717 : :
3718 : 92 : res = make_result(&result);
3719 : :
3720 : 92 : free_var(&result);
3721 : :
3722 : 92 : PG_RETURN_NUMERIC(res);
3723 : : }
3724 : :
3725 : :
3726 : : /*
3727 : : * numeric_exp() -
3728 : : *
3729 : : * Raise e to the power of x
3730 : : */
3731 : : Datum
3732 : 65 : numeric_exp(PG_FUNCTION_ARGS)
3733 : : {
3734 : 65 : Numeric num = PG_GETARG_NUMERIC(0);
3735 : : Numeric res;
3736 : : NumericVar arg;
3737 : : NumericVar result;
3738 : : int rscale;
3739 : : double val;
3740 : :
3741 : : /*
3742 : : * Handle NaN and infinities
3743 : : */
3744 [ + + ]: 65 : if (NUMERIC_IS_SPECIAL(num))
3745 : : {
3746 : : /* Per POSIX, exp(-Inf) is zero */
3747 [ + + ]: 15 : if (NUMERIC_IS_NINF(num))
3748 : 5 : PG_RETURN_NUMERIC(make_result(&const_zero));
3749 : : /* For NAN or PINF, just duplicate the input */
3750 : 10 : PG_RETURN_NUMERIC(duplicate_numeric(num));
3751 : : }
3752 : :
3753 : : /*
3754 : : * Unpack the argument and determine the result scale. We choose a scale
3755 : : * to give at least NUMERIC_MIN_SIG_DIGITS significant digits; but in any
3756 : : * case not less than the input's dscale.
3757 : : */
3758 : 50 : init_var_from_num(num, &arg);
3759 : :
3760 : 50 : init_var(&result);
3761 : :
3762 : : /* convert input to float8, ignoring overflow */
3763 : 50 : val = numericvar_to_double_no_overflow(&arg);
3764 : :
3765 : : /*
3766 : : * log10(result) = num * log10(e), so this is approximately the decimal
3767 : : * weight of the result:
3768 : : */
3769 : 50 : val *= 0.434294481903252;
3770 : :
3771 : : /* limit to something that won't cause integer overflow */
3772 [ + + ]: 50 : val = Max(val, -NUMERIC_MAX_RESULT_SCALE);
3773 [ + - ]: 50 : val = Min(val, NUMERIC_MAX_RESULT_SCALE);
3774 : :
3775 : 50 : rscale = NUMERIC_MIN_SIG_DIGITS - (int) val;
3776 : 50 : rscale = Max(rscale, arg.dscale);
3777 : 50 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
3778 : 50 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
3779 : :
3780 : : /*
3781 : : * Let exp_var() do the calculation and return the result.
3782 : : */
3783 : 50 : exp_var(&arg, &result, rscale);
3784 : :
3785 : 50 : res = make_result(&result);
3786 : :
3787 : 50 : free_var(&result);
3788 : :
3789 : 50 : PG_RETURN_NUMERIC(res);
3790 : : }
3791 : :
3792 : :
3793 : : /*
3794 : : * numeric_ln() -
3795 : : *
3796 : : * Compute the natural logarithm of x
3797 : : */
3798 : : Datum
3799 : 140 : numeric_ln(PG_FUNCTION_ARGS)
3800 : : {
3801 : 140 : Numeric num = PG_GETARG_NUMERIC(0);
3802 : : Numeric res;
3803 : : NumericVar arg;
3804 : : NumericVar result;
3805 : : int ln_dweight;
3806 : : int rscale;
3807 : :
3808 : : /*
3809 : : * Handle NaN and infinities
3810 : : */
3811 [ + + ]: 140 : if (NUMERIC_IS_SPECIAL(num))
3812 : : {
3813 [ + + ]: 12 : if (NUMERIC_IS_NINF(num))
3814 [ + - ]: 4 : ereport(ERROR,
3815 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
3816 : : errmsg("cannot take logarithm of a negative number")));
3817 : : /* For NAN or PINF, just duplicate the input */
3818 : 8 : PG_RETURN_NUMERIC(duplicate_numeric(num));
3819 : : }
3820 : :
3821 : 128 : init_var_from_num(num, &arg);
3822 : 128 : init_var(&result);
3823 : :
3824 : : /* Estimated dweight of logarithm */
3825 : 128 : ln_dweight = estimate_ln_dweight(&arg);
3826 : :
3827 : 128 : rscale = NUMERIC_MIN_SIG_DIGITS - ln_dweight;
3828 : 128 : rscale = Max(rscale, arg.dscale);
3829 : 128 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
3830 : 128 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
3831 : :
3832 : 128 : ln_var(&arg, &result, rscale);
3833 : :
3834 : 112 : res = make_result(&result);
3835 : :
3836 : 112 : free_var(&result);
3837 : :
3838 : 112 : PG_RETURN_NUMERIC(res);
3839 : : }
3840 : :
3841 : :
3842 : : /*
3843 : : * numeric_log() -
3844 : : *
3845 : : * Compute the logarithm of x in a given base
3846 : : */
3847 : : Datum
3848 : 249 : numeric_log(PG_FUNCTION_ARGS)
3849 : : {
3850 : 249 : Numeric num1 = PG_GETARG_NUMERIC(0);
3851 : 249 : Numeric num2 = PG_GETARG_NUMERIC(1);
3852 : : Numeric res;
3853 : : NumericVar arg1;
3854 : : NumericVar arg2;
3855 : : NumericVar result;
3856 : :
3857 : : /*
3858 : : * Handle NaN and infinities
3859 : : */
3860 [ + + + + ]: 249 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3861 : : {
3862 : : int sign1,
3863 : : sign2;
3864 : :
3865 [ + + + + ]: 93 : if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3866 : 36 : PG_RETURN_NUMERIC(make_result(&const_nan));
3867 : : /* fail on negative inputs including -Inf, as log_var would */
3868 : 57 : sign1 = numeric_sign_internal(num1);
3869 : 57 : sign2 = numeric_sign_internal(num2);
3870 [ + + + + ]: 57 : if (sign1 < 0 || sign2 < 0)
3871 [ + - ]: 16 : ereport(ERROR,
3872 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
3873 : : errmsg("cannot take logarithm of a negative number")));
3874 : : /* fail on zero inputs, as log_var would */
3875 [ + - + + ]: 41 : if (sign1 == 0 || sign2 == 0)
3876 [ + - ]: 4 : ereport(ERROR,
3877 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
3878 : : errmsg("cannot take logarithm of zero")));
3879 [ + + ]: 37 : if (NUMERIC_IS_PINF(num1))
3880 : : {
3881 : : /* log(Inf, Inf) reduces to Inf/Inf, so it's NaN */
3882 [ + + ]: 12 : if (NUMERIC_IS_PINF(num2))
3883 : 4 : PG_RETURN_NUMERIC(make_result(&const_nan));
3884 : : /* log(Inf, finite-positive) is zero (we don't throw underflow) */
3885 : 8 : PG_RETURN_NUMERIC(make_result(&const_zero));
3886 : : }
3887 : : Assert(NUMERIC_IS_PINF(num2));
3888 : :
3889 : : /*
3890 : : * For a finite-positive base, log(base, Inf) = Inf / ln(base), so the
3891 : : * sign depends on whether base is more or less than 1. If base = 1,
3892 : : * fall through and let log_var report the error.
3893 : : */
3894 : 25 : init_var_from_num(num1, &arg1);
3895 : 25 : sign1 = cmp_var(&arg1, &const_one);
3896 [ + + ]: 25 : if (sign1 < 0)
3897 : 5 : PG_RETURN_NUMERIC(make_result(&const_ninf));
3898 [ + + ]: 20 : if (sign1 > 0)
3899 : 16 : PG_RETURN_NUMERIC(make_result(&const_pinf));
3900 : : }
3901 : :
3902 : : /*
3903 : : * Initialize things
3904 : : */
3905 : 160 : init_var_from_num(num1, &arg1);
3906 : 160 : init_var_from_num(num2, &arg2);
3907 : 160 : init_var(&result);
3908 : :
3909 : : /*
3910 : : * Call log_var() to compute and return the result; note it handles scale
3911 : : * selection itself.
3912 : : */
3913 : 160 : log_var(&arg1, &arg2, &result);
3914 : :
3915 : 116 : res = make_result(&result);
3916 : :
3917 : 116 : free_var(&result);
3918 : :
3919 : 116 : PG_RETURN_NUMERIC(res);
3920 : : }
3921 : :
3922 : :
3923 : : /*
3924 : : * numeric_power() -
3925 : : *
3926 : : * Raise x to the power of y
3927 : : */
3928 : : Datum
3929 : 1149 : numeric_power(PG_FUNCTION_ARGS)
3930 : : {
3931 : 1149 : Numeric num1 = PG_GETARG_NUMERIC(0);
3932 : 1149 : Numeric num2 = PG_GETARG_NUMERIC(1);
3933 : : Numeric res;
3934 : : NumericVar arg1;
3935 : : NumericVar arg2;
3936 : : NumericVar result;
3937 : : int sign1,
3938 : : sign2;
3939 : :
3940 : : /*
3941 : : * Handle NaN and infinities
3942 : : */
3943 [ + + + + ]: 1149 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3944 : : {
3945 : : /*
3946 : : * We follow the POSIX spec for pow(3), which says that NaN ^ 0 = 1,
3947 : : * and 1 ^ NaN = 1, while all other cases with NaN inputs yield NaN
3948 : : * (with no error).
3949 : : */
3950 [ + + ]: 173 : if (NUMERIC_IS_NAN(num1))
3951 : : {
3952 [ + + ]: 39 : if (!NUMERIC_IS_SPECIAL(num2))
3953 : : {
3954 : 26 : init_var_from_num(num2, &arg2);
3955 [ + + ]: 26 : if (cmp_var(&arg2, &const_zero) == 0)
3956 : 9 : PG_RETURN_NUMERIC(make_result(&const_one));
3957 : : }
3958 : 30 : PG_RETURN_NUMERIC(make_result(&const_nan));
3959 : : }
3960 [ + + ]: 134 : if (NUMERIC_IS_NAN(num2))
3961 : : {
3962 [ + + ]: 30 : if (!NUMERIC_IS_SPECIAL(num1))
3963 : : {
3964 : 26 : init_var_from_num(num1, &arg1);
3965 [ + + ]: 26 : if (cmp_var(&arg1, &const_one) == 0)
3966 : 9 : PG_RETURN_NUMERIC(make_result(&const_one));
3967 : : }
3968 : 21 : PG_RETURN_NUMERIC(make_result(&const_nan));
3969 : : }
3970 : : /* At least one input is infinite, but error rules still apply */
3971 : 104 : sign1 = numeric_sign_internal(num1);
3972 : 104 : sign2 = numeric_sign_internal(num2);
3973 [ + + + + ]: 104 : if (sign1 == 0 && sign2 < 0)
3974 [ + - ]: 4 : ereport(ERROR,
3975 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
3976 : : errmsg("zero raised to a negative power is undefined")));
3977 [ + + + + ]: 100 : if (sign1 < 0 && !numeric_is_integral(num2))
3978 [ + - ]: 4 : ereport(ERROR,
3979 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
3980 : : errmsg("a negative number raised to a non-integer power yields a complex result")));
3981 : :
3982 : : /*
3983 : : * POSIX gives this series of rules for pow(3) with infinite inputs:
3984 : : *
3985 : : * For any value of y, if x is +1, 1.0 shall be returned.
3986 : : */
3987 [ + + ]: 96 : if (!NUMERIC_IS_SPECIAL(num1))
3988 : : {
3989 : 31 : init_var_from_num(num1, &arg1);
3990 [ + + ]: 31 : if (cmp_var(&arg1, &const_one) == 0)
3991 : 4 : PG_RETURN_NUMERIC(make_result(&const_one));
3992 : : }
3993 : :
3994 : : /*
3995 : : * For any value of x, if y is [-]0, 1.0 shall be returned.
3996 : : */
3997 [ + + ]: 92 : if (sign2 == 0)
3998 : 9 : PG_RETURN_NUMERIC(make_result(&const_one));
3999 : :
4000 : : /*
4001 : : * For any odd integer value of y > 0, if x is [-]0, [-]0 shall be
4002 : : * returned. For y > 0 and not an odd integer, if x is [-]0, +0 shall
4003 : : * be returned. (Since we don't deal in minus zero, we need not
4004 : : * distinguish these two cases.)
4005 : : */
4006 [ + + + - ]: 83 : if (sign1 == 0 && sign2 > 0)
4007 : 4 : PG_RETURN_NUMERIC(make_result(&const_zero));
4008 : :
4009 : : /*
4010 : : * If x is -1, and y is [-]Inf, 1.0 shall be returned.
4011 : : *
4012 : : * For |x| < 1, if y is -Inf, +Inf shall be returned.
4013 : : *
4014 : : * For |x| > 1, if y is -Inf, +0 shall be returned.
4015 : : *
4016 : : * For |x| < 1, if y is +Inf, +0 shall be returned.
4017 : : *
4018 : : * For |x| > 1, if y is +Inf, +Inf shall be returned.
4019 : : */
4020 [ + + ]: 79 : if (NUMERIC_IS_INF(num2))
4021 : : {
4022 : : bool abs_x_gt_one;
4023 : :
4024 [ + + ]: 42 : if (NUMERIC_IS_SPECIAL(num1))
4025 : 19 : abs_x_gt_one = true; /* x is either Inf or -Inf */
4026 : : else
4027 : : {
4028 : 23 : init_var_from_num(num1, &arg1);
4029 [ + + ]: 23 : if (cmp_var(&arg1, &const_minus_one) == 0)
4030 : 5 : PG_RETURN_NUMERIC(make_result(&const_one));
4031 : 18 : arg1.sign = NUMERIC_POS; /* now arg1 = abs(x) */
4032 : 18 : abs_x_gt_one = (cmp_var(&arg1, &const_one) > 0);
4033 : : }
4034 [ + + ]: 37 : if (abs_x_gt_one == (sign2 > 0))
4035 : 22 : PG_RETURN_NUMERIC(make_result(&const_pinf));
4036 : : else
4037 : 15 : PG_RETURN_NUMERIC(make_result(&const_zero));
4038 : : }
4039 : :
4040 : : /*
4041 : : * For y < 0, if x is +Inf, +0 shall be returned.
4042 : : *
4043 : : * For y > 0, if x is +Inf, +Inf shall be returned.
4044 : : */
4045 [ + + ]: 37 : if (NUMERIC_IS_PINF(num1))
4046 : : {
4047 [ + + ]: 17 : if (sign2 > 0)
4048 : 12 : PG_RETURN_NUMERIC(make_result(&const_pinf));
4049 : : else
4050 : 5 : PG_RETURN_NUMERIC(make_result(&const_zero));
4051 : : }
4052 : :
4053 : : Assert(NUMERIC_IS_NINF(num1));
4054 : :
4055 : : /*
4056 : : * For y an odd integer < 0, if x is -Inf, -0 shall be returned. For
4057 : : * y < 0 and not an odd integer, if x is -Inf, +0 shall be returned.
4058 : : * (Again, we need not distinguish these two cases.)
4059 : : */
4060 [ + + ]: 20 : if (sign2 < 0)
4061 : 10 : PG_RETURN_NUMERIC(make_result(&const_zero));
4062 : :
4063 : : /*
4064 : : * For y an odd integer > 0, if x is -Inf, -Inf shall be returned. For
4065 : : * y > 0 and not an odd integer, if x is -Inf, +Inf shall be returned.
4066 : : */
4067 : 10 : init_var_from_num(num2, &arg2);
4068 [ + - + - ]: 10 : if (arg2.ndigits > 0 && arg2.ndigits == arg2.weight + 1 &&
4069 [ + + ]: 10 : (arg2.digits[arg2.ndigits - 1] & 1))
4070 : 5 : PG_RETURN_NUMERIC(make_result(&const_ninf));
4071 : : else
4072 : 5 : PG_RETURN_NUMERIC(make_result(&const_pinf));
4073 : : }
4074 : :
4075 : : /*
4076 : : * The SQL spec requires that we emit a particular SQLSTATE error code for
4077 : : * certain error conditions. Specifically, we don't return a
4078 : : * divide-by-zero error code for 0 ^ -1. Raising a negative number to a
4079 : : * non-integer power must produce the same error code, but that case is
4080 : : * handled in power_var().
4081 : : */
4082 : 976 : sign1 = numeric_sign_internal(num1);
4083 : 976 : sign2 = numeric_sign_internal(num2);
4084 : :
4085 [ + + + + ]: 976 : if (sign1 == 0 && sign2 < 0)
4086 [ + - ]: 8 : ereport(ERROR,
4087 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
4088 : : errmsg("zero raised to a negative power is undefined")));
4089 : :
4090 : : /*
4091 : : * Initialize things
4092 : : */
4093 : 968 : init_var(&result);
4094 : 968 : init_var_from_num(num1, &arg1);
4095 : 968 : init_var_from_num(num2, &arg2);
4096 : :
4097 : : /*
4098 : : * Call power_var() to compute and return the result; note it handles
4099 : : * scale selection itself.
4100 : : */
4101 : 968 : power_var(&arg1, &arg2, &result);
4102 : :
4103 : 948 : res = make_result(&result);
4104 : :
4105 : 948 : free_var(&result);
4106 : :
4107 : 948 : PG_RETURN_NUMERIC(res);
4108 : : }
4109 : :
4110 : : /*
4111 : : * numeric_scale() -
4112 : : *
4113 : : * Returns the scale, i.e. the count of decimal digits in the fractional part
4114 : : */
4115 : : Datum
4116 : 81 : numeric_scale(PG_FUNCTION_ARGS)
4117 : : {
4118 : 81 : Numeric num = PG_GETARG_NUMERIC(0);
4119 : :
4120 [ + + ]: 81 : if (NUMERIC_IS_SPECIAL(num))
4121 : 14 : PG_RETURN_NULL();
4122 : :
4123 [ + - ]: 67 : PG_RETURN_INT32(NUMERIC_DSCALE(num));
4124 : : }
4125 : :
4126 : : /*
4127 : : * Calculate minimum scale for value.
4128 : : */
4129 : : static int
4130 : 267 : get_min_scale(NumericVar *var)
4131 : : {
4132 : : int min_scale;
4133 : : int last_digit_pos;
4134 : :
4135 : : /*
4136 : : * Ordinarily, the input value will be "stripped" so that the last
4137 : : * NumericDigit is nonzero. But we don't want to get into an infinite
4138 : : * loop if it isn't, so explicitly find the last nonzero digit.
4139 : : */
4140 : 267 : last_digit_pos = var->ndigits - 1;
4141 [ + + ]: 267 : while (last_digit_pos >= 0 &&
4142 [ - + ]: 243 : var->digits[last_digit_pos] == 0)
4143 : 0 : last_digit_pos--;
4144 : :
4145 [ + + ]: 267 : if (last_digit_pos >= 0)
4146 : : {
4147 : : /* compute min_scale assuming that last ndigit has no zeroes */
4148 : 243 : min_scale = (last_digit_pos - var->weight) * DEC_DIGITS;
4149 : :
4150 : : /*
4151 : : * We could get a negative result if there are no digits after the
4152 : : * decimal point. In this case the min_scale must be zero.
4153 : : */
4154 [ + + ]: 243 : if (min_scale > 0)
4155 : : {
4156 : : /*
4157 : : * Reduce min_scale if trailing digit(s) in last NumericDigit are
4158 : : * zero.
4159 : : */
4160 : 135 : NumericDigit last_digit = var->digits[last_digit_pos];
4161 : :
4162 [ + + ]: 365 : while (last_digit % 10 == 0)
4163 : : {
4164 : 230 : min_scale--;
4165 : 230 : last_digit /= 10;
4166 : : }
4167 : : }
4168 : : else
4169 : 108 : min_scale = 0;
4170 : : }
4171 : : else
4172 : 24 : min_scale = 0; /* result if input is zero */
4173 : :
4174 : 267 : return min_scale;
4175 : : }
4176 : :
4177 : : /*
4178 : : * Returns minimum scale required to represent supplied value without loss.
4179 : : */
4180 : : Datum
4181 : 60 : numeric_min_scale(PG_FUNCTION_ARGS)
4182 : : {
4183 : 60 : Numeric num = PG_GETARG_NUMERIC(0);
4184 : : NumericVar arg;
4185 : : int min_scale;
4186 : :
4187 [ + + ]: 60 : if (NUMERIC_IS_SPECIAL(num))
4188 : 10 : PG_RETURN_NULL();
4189 : :
4190 : 50 : init_var_from_num(num, &arg);
4191 : 50 : min_scale = get_min_scale(&arg);
4192 : 50 : free_var(&arg);
4193 : :
4194 : 50 : PG_RETURN_INT32(min_scale);
4195 : : }
4196 : :
4197 : : /*
4198 : : * Reduce scale of numeric value to represent supplied value without loss.
4199 : : */
4200 : : Datum
4201 : 227 : numeric_trim_scale(PG_FUNCTION_ARGS)
4202 : : {
4203 : 227 : Numeric num = PG_GETARG_NUMERIC(0);
4204 : : Numeric res;
4205 : : NumericVar result;
4206 : :
4207 [ + + ]: 227 : if (NUMERIC_IS_SPECIAL(num))
4208 : 10 : PG_RETURN_NUMERIC(duplicate_numeric(num));
4209 : :
4210 : 217 : init_var_from_num(num, &result);
4211 : 217 : result.dscale = get_min_scale(&result);
4212 : 217 : res = make_result(&result);
4213 : 217 : free_var(&result);
4214 : :
4215 : 217 : PG_RETURN_NUMERIC(res);
4216 : : }
4217 : :
4218 : : /*
4219 : : * Return a random numeric value in the range [rmin, rmax].
4220 : : */
4221 : : Numeric
4222 : 22308 : random_numeric(pg_prng_state *state, Numeric rmin, Numeric rmax)
4223 : : {
4224 : : NumericVar rmin_var;
4225 : : NumericVar rmax_var;
4226 : : NumericVar result;
4227 : : Numeric res;
4228 : :
4229 : : /* Range bounds must not be NaN/infinity */
4230 [ + + ]: 22308 : if (NUMERIC_IS_SPECIAL(rmin))
4231 : : {
4232 [ + + ]: 8 : if (NUMERIC_IS_NAN(rmin))
4233 [ + - ]: 4 : ereport(ERROR,
4234 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4235 : : errmsg("lower bound cannot be NaN"));
4236 : : else
4237 [ + - ]: 4 : ereport(ERROR,
4238 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4239 : : errmsg("lower bound cannot be infinity"));
4240 : : }
4241 [ + + ]: 22300 : if (NUMERIC_IS_SPECIAL(rmax))
4242 : : {
4243 [ + + ]: 8 : if (NUMERIC_IS_NAN(rmax))
4244 [ + - ]: 4 : ereport(ERROR,
4245 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4246 : : errmsg("upper bound cannot be NaN"));
4247 : : else
4248 [ + - ]: 4 : ereport(ERROR,
4249 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4250 : : errmsg("upper bound cannot be infinity"));
4251 : : }
4252 : :
4253 : : /* Return a random value in the range [rmin, rmax] */
4254 : 22292 : init_var_from_num(rmin, &rmin_var);
4255 : 22292 : init_var_from_num(rmax, &rmax_var);
4256 : :
4257 : 22292 : init_var(&result);
4258 : :
4259 : 22292 : random_var(state, &rmin_var, &rmax_var, &result);
4260 : :
4261 : 22288 : res = make_result(&result);
4262 : :
4263 : 22288 : free_var(&result);
4264 : :
4265 : 22288 : return res;
4266 : : }
4267 : :
4268 : :
4269 : : /* ----------------------------------------------------------------------
4270 : : *
4271 : : * Type conversion functions
4272 : : *
4273 : : * ----------------------------------------------------------------------
4274 : : */
4275 : :
4276 : : Numeric
4277 : 1246610 : int64_to_numeric(int64 val)
4278 : : {
4279 : : Numeric res;
4280 : : NumericVar result;
4281 : :
4282 : 1246610 : init_var(&result);
4283 : :
4284 : 1246610 : int64_to_numericvar(val, &result);
4285 : :
4286 : 1246610 : res = make_result(&result);
4287 : :
4288 : 1246610 : free_var(&result);
4289 : :
4290 : 1246610 : return res;
4291 : : }
4292 : :
4293 : : /*
4294 : : * Convert val1/(10**log10val2) to numeric. This is much faster than normal
4295 : : * numeric division.
4296 : : */
4297 : : Numeric
4298 : 15155 : int64_div_fast_to_numeric(int64 val1, int log10val2)
4299 : : {
4300 : : Numeric res;
4301 : : NumericVar result;
4302 : : int rscale;
4303 : : int w;
4304 : : int m;
4305 : :
4306 : 15155 : init_var(&result);
4307 : :
4308 : : /* result scale */
4309 : 15155 : rscale = log10val2 < 0 ? 0 : log10val2;
4310 : :
4311 : : /* how much to decrease the weight by */
4312 : 15155 : w = log10val2 / DEC_DIGITS;
4313 : : /* how much is left to divide by */
4314 : 15155 : m = log10val2 % DEC_DIGITS;
4315 [ - + ]: 15155 : if (m < 0)
4316 : : {
4317 : 0 : m += DEC_DIGITS;
4318 : 0 : w--;
4319 : : }
4320 : :
4321 : : /*
4322 : : * If there is anything left to divide by (10^m with 0 < m < DEC_DIGITS),
4323 : : * multiply the dividend by 10^(DEC_DIGITS - m), and shift the weight by
4324 : : * one more.
4325 : : */
4326 [ + - ]: 15155 : if (m > 0)
4327 : : {
4328 : : #if DEC_DIGITS == 4
4329 : : static const int pow10[] = {1, 10, 100, 1000};
4330 : : #elif DEC_DIGITS == 2
4331 : : static const int pow10[] = {1, 10};
4332 : : #elif DEC_DIGITS == 1
4333 : : static const int pow10[] = {1};
4334 : : #else
4335 : : #error unsupported NBASE
4336 : : #endif
4337 : 15155 : int64 factor = pow10[DEC_DIGITS - m];
4338 : : int64 new_val1;
4339 : :
4340 : : StaticAssertDecl(lengthof(pow10) == DEC_DIGITS, "mismatch with DEC_DIGITS");
4341 : :
4342 [ + + ]: 15155 : if (unlikely(pg_mul_s64_overflow(val1, factor, &new_val1)))
4343 : : {
4344 : : /* do the multiplication using 128-bit integers */
4345 : : INT128 tmp;
4346 : :
4347 : 9 : tmp = int64_to_int128(0);
4348 : 9 : int128_add_int64_mul_int64(&tmp, val1, factor);
4349 : :
4350 : 9 : int128_to_numericvar(tmp, &result);
4351 : : }
4352 : : else
4353 : 15146 : int64_to_numericvar(new_val1, &result);
4354 : :
4355 : 15155 : w++;
4356 : : }
4357 : : else
4358 : 0 : int64_to_numericvar(val1, &result);
4359 : :
4360 : 15155 : result.weight -= w;
4361 : 15155 : result.dscale = rscale;
4362 : :
4363 : 15155 : res = make_result(&result);
4364 : :
4365 : 15155 : free_var(&result);
4366 : :
4367 : 15155 : return res;
4368 : : }
4369 : :
4370 : : Datum
4371 : 1038019 : int4_numeric(PG_FUNCTION_ARGS)
4372 : : {
4373 : 1038019 : int32 val = PG_GETARG_INT32(0);
4374 : :
4375 : 1038019 : PG_RETURN_NUMERIC(int64_to_numeric(val));
4376 : : }
4377 : :
4378 : : /*
4379 : : * Internal version of numeric_int4() with support for soft error reporting.
4380 : : */
4381 : : int32
4382 : 4921 : numeric_int4_safe(Numeric num, Node *escontext)
4383 : : {
4384 : : NumericVar x;
4385 : : int32 result;
4386 : :
4387 [ + + ]: 4921 : if (NUMERIC_IS_SPECIAL(num))
4388 : : {
4389 [ + + ]: 12 : if (NUMERIC_IS_NAN(num))
4390 [ + - ]: 4 : ereturn(escontext, 0,
4391 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4392 : : errmsg("cannot convert NaN to %s", "integer")));
4393 : : else
4394 [ + - ]: 8 : ereturn(escontext, 0,
4395 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4396 : : errmsg("cannot convert infinity to %s", "integer")));
4397 : : }
4398 : :
4399 : : /* Convert to variable format, then convert to int4 */
4400 : 4909 : init_var_from_num(num, &x);
4401 : :
4402 [ + + ]: 4909 : if (!numericvar_to_int32(&x, &result))
4403 [ + + ]: 70 : ereturn(escontext, 0,
4404 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4405 : : errmsg("integer out of range")));
4406 : :
4407 : 4839 : return result;
4408 : : }
4409 : :
4410 : : Datum
4411 : 3778 : numeric_int4(PG_FUNCTION_ARGS)
4412 : : {
4413 : 3778 : Numeric num = PG_GETARG_NUMERIC(0);
4414 : : int32 result;
4415 : :
4416 : 3778 : result = numeric_int4_safe(num, fcinfo->context);
4417 : :
4418 [ - + - - : 3758 : if (unlikely(SOFT_ERROR_OCCURRED(fcinfo->context)))
- + - - -
+ ]
4419 : 0 : PG_RETURN_NULL();
4420 : :
4421 : 3758 : PG_RETURN_INT32(result);
4422 : : }
4423 : :
4424 : : /*
4425 : : * Given a NumericVar, convert it to an int32. If the NumericVar
4426 : : * exceeds the range of an int32, false is returned, otherwise true is returned.
4427 : : * The input NumericVar is *not* free'd.
4428 : : */
4429 : : static bool
4430 : 5410 : numericvar_to_int32(const NumericVar *var, int32 *result)
4431 : : {
4432 : : int64 val;
4433 : :
4434 [ + + ]: 5410 : if (!numericvar_to_int64(var, &val))
4435 : 4 : return false;
4436 : :
4437 [ + + + + ]: 5406 : if (unlikely(val < PG_INT32_MIN) || unlikely(val > PG_INT32_MAX))
4438 : 66 : return false;
4439 : :
4440 : : /* Down-convert to int4 */
4441 : 5340 : *result = (int32) val;
4442 : :
4443 : 5340 : return true;
4444 : : }
4445 : :
4446 : : Datum
4447 : 24588 : int8_numeric(PG_FUNCTION_ARGS)
4448 : : {
4449 : 24588 : int64 val = PG_GETARG_INT64(0);
4450 : :
4451 : 24588 : PG_RETURN_NUMERIC(int64_to_numeric(val));
4452 : : }
4453 : :
4454 : : /*
4455 : : * Internal version of numeric_int8() with support for soft error reporting.
4456 : : */
4457 : : int64
4458 : 387 : numeric_int8_safe(Numeric num, Node *escontext)
4459 : : {
4460 : : NumericVar x;
4461 : : int64 result;
4462 : :
4463 [ + + ]: 387 : if (NUMERIC_IS_SPECIAL(num))
4464 : : {
4465 [ + + ]: 12 : if (NUMERIC_IS_NAN(num))
4466 [ + - ]: 4 : ereturn(escontext, 0,
4467 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4468 : : errmsg("cannot convert NaN to %s", "bigint")));
4469 : : else
4470 [ + - ]: 8 : ereturn(escontext, 0,
4471 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4472 : : errmsg("cannot convert infinity to %s", "bigint")));
4473 : : }
4474 : :
4475 : : /* Convert to variable format, then convert to int8 */
4476 : 375 : init_var_from_num(num, &x);
4477 : :
4478 [ + + ]: 375 : if (!numericvar_to_int64(&x, &result))
4479 [ + + ]: 40 : ereturn(escontext, 0,
4480 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4481 : : errmsg("bigint out of range")));
4482 : :
4483 : 335 : return result;
4484 : : }
4485 : :
4486 : : Datum
4487 : 347 : numeric_int8(PG_FUNCTION_ARGS)
4488 : : {
4489 : 347 : Numeric num = PG_GETARG_NUMERIC(0);
4490 : : int64 result;
4491 : :
4492 : 347 : result = numeric_int8_safe(num, fcinfo->context);
4493 : :
4494 [ - + - - : 303 : if (unlikely(SOFT_ERROR_OCCURRED(fcinfo->context)))
- + - - -
+ ]
4495 : 0 : PG_RETURN_NULL();
4496 : :
4497 : 303 : PG_RETURN_INT64(result);
4498 : : }
4499 : :
4500 : :
4501 : : Datum
4502 : 5 : int2_numeric(PG_FUNCTION_ARGS)
4503 : : {
4504 : 5 : int16 val = PG_GETARG_INT16(0);
4505 : :
4506 : 5 : PG_RETURN_NUMERIC(int64_to_numeric(val));
4507 : : }
4508 : :
4509 : :
4510 : : Datum
4511 : 73 : numeric_int2(PG_FUNCTION_ARGS)
4512 : : {
4513 : 73 : Numeric num = PG_GETARG_NUMERIC(0);
4514 : : NumericVar x;
4515 : : int64 val;
4516 : : int16 result;
4517 : :
4518 [ + + ]: 73 : if (NUMERIC_IS_SPECIAL(num))
4519 : : {
4520 [ + + ]: 12 : if (NUMERIC_IS_NAN(num))
4521 [ + - ]: 4 : ereturn(fcinfo->context, (Datum) 0,
4522 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4523 : : errmsg("cannot convert NaN to %s", "smallint")));
4524 : : else
4525 [ + - ]: 8 : ereturn(fcinfo->context, (Datum) 0,
4526 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4527 : : errmsg("cannot convert infinity to %s", "smallint")));
4528 : : }
4529 : :
4530 : : /* Convert to variable format and thence to int8 */
4531 : 61 : init_var_from_num(num, &x);
4532 : :
4533 [ - + ]: 61 : if (!numericvar_to_int64(&x, &val))
4534 [ # # ]: 0 : ereturn(fcinfo->context, (Datum) 0,
4535 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4536 : : errmsg("smallint out of range")));
4537 : :
4538 [ + + + + ]: 61 : if (unlikely(val < PG_INT16_MIN) || unlikely(val > PG_INT16_MAX))
4539 [ + - ]: 8 : ereturn(fcinfo->context, (Datum) 0,
4540 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4541 : : errmsg("smallint out of range")));
4542 : :
4543 : : /* Down-convert to int2 */
4544 : 53 : result = (int16) val;
4545 : :
4546 : 53 : PG_RETURN_INT16(result);
4547 : : }
4548 : :
4549 : :
4550 : : Datum
4551 : 12798 : float8_numeric(PG_FUNCTION_ARGS)
4552 : : {
4553 : 12798 : float8 val = PG_GETARG_FLOAT8(0);
4554 : : Numeric res;
4555 : : NumericVar result;
4556 : : char buf[DBL_DIG + 100];
4557 : : const char *endptr;
4558 : :
4559 [ + + ]: 12798 : if (isnan(val))
4560 : 5 : PG_RETURN_NUMERIC(make_result(&const_nan));
4561 : :
4562 [ + + ]: 12793 : if (isinf(val))
4563 : : {
4564 [ + + ]: 10 : if (val < 0)
4565 : 5 : PG_RETURN_NUMERIC(make_result(&const_ninf));
4566 : : else
4567 : 5 : PG_RETURN_NUMERIC(make_result(&const_pinf));
4568 : : }
4569 : :
4570 : 12783 : snprintf(buf, sizeof(buf), "%.*g", DBL_DIG, val);
4571 : :
4572 : 12783 : init_var(&result);
4573 : :
4574 : : /* Assume we need not worry about leading/trailing spaces */
4575 [ - + ]: 12783 : if (!set_var_from_str(buf, buf, &result, &endptr, fcinfo->context))
4576 : 0 : PG_RETURN_NULL();
4577 : :
4578 : 12783 : res = make_result(&result);
4579 : :
4580 : 12783 : free_var(&result);
4581 : :
4582 : 12783 : PG_RETURN_NUMERIC(res);
4583 : : }
4584 : :
4585 : :
4586 : : Datum
4587 : 347671 : numeric_float8(PG_FUNCTION_ARGS)
4588 : : {
4589 : 347671 : Numeric num = PG_GETARG_NUMERIC(0);
4590 : : char *tmp;
4591 : : Datum result;
4592 : :
4593 [ + + ]: 347671 : if (NUMERIC_IS_SPECIAL(num))
4594 : : {
4595 [ + + ]: 56 : if (NUMERIC_IS_PINF(num))
4596 : 17 : PG_RETURN_FLOAT8(get_float8_infinity());
4597 [ + + ]: 39 : else if (NUMERIC_IS_NINF(num))
4598 : 17 : PG_RETURN_FLOAT8(-get_float8_infinity());
4599 : : else
4600 : 22 : PG_RETURN_FLOAT8(get_float8_nan());
4601 : : }
4602 : :
4603 : 347615 : tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
4604 : : NumericGetDatum(num)));
4605 [ - + ]: 347615 : if (!DirectInputFunctionCallSafe(float8in, tmp,
4606 : : InvalidOid, -1,
4607 : : (Node *) fcinfo->context,
4608 : : &result))
4609 : : {
4610 : 0 : pfree(tmp);
4611 : 0 : PG_RETURN_NULL();
4612 : : }
4613 : :
4614 : 347615 : PG_RETURN_DATUM(result);
4615 : : }
4616 : :
4617 : :
4618 : : /*
4619 : : * Convert numeric to float8; if out of range, return +/- HUGE_VAL
4620 : : *
4621 : : * (internal helper function, not directly callable from SQL)
4622 : : */
4623 : : Datum
4624 : 15 : numeric_float8_no_overflow(PG_FUNCTION_ARGS)
4625 : : {
4626 : 15 : Numeric num = PG_GETARG_NUMERIC(0);
4627 : : double val;
4628 : :
4629 [ - + ]: 15 : if (NUMERIC_IS_SPECIAL(num))
4630 : : {
4631 [ # # ]: 0 : if (NUMERIC_IS_PINF(num))
4632 : 0 : val = HUGE_VAL;
4633 [ # # ]: 0 : else if (NUMERIC_IS_NINF(num))
4634 : 0 : val = -HUGE_VAL;
4635 : : else
4636 : 0 : val = get_float8_nan();
4637 : : }
4638 : : else
4639 : : {
4640 : : NumericVar x;
4641 : :
4642 : 15 : init_var_from_num(num, &x);
4643 : 15 : val = numericvar_to_double_no_overflow(&x);
4644 : : }
4645 : :
4646 : 15 : PG_RETURN_FLOAT8(val);
4647 : : }
4648 : :
4649 : : Datum
4650 : 15121 : float4_numeric(PG_FUNCTION_ARGS)
4651 : : {
4652 : 15121 : float4 val = PG_GETARG_FLOAT4(0);
4653 : : Numeric res;
4654 : : NumericVar result;
4655 : : char buf[FLT_DIG + 100];
4656 : : const char *endptr;
4657 : :
4658 [ + + ]: 15121 : if (isnan(val))
4659 : 5 : PG_RETURN_NUMERIC(make_result(&const_nan));
4660 : :
4661 [ + + ]: 15116 : if (isinf(val))
4662 : : {
4663 [ + + ]: 10 : if (val < 0)
4664 : 5 : PG_RETURN_NUMERIC(make_result(&const_ninf));
4665 : : else
4666 : 5 : PG_RETURN_NUMERIC(make_result(&const_pinf));
4667 : : }
4668 : :
4669 : 15106 : snprintf(buf, sizeof(buf), "%.*g", FLT_DIG, val);
4670 : :
4671 : 15106 : init_var(&result);
4672 : :
4673 : : /* Assume we need not worry about leading/trailing spaces */
4674 [ - + ]: 15106 : if (!set_var_from_str(buf, buf, &result, &endptr, fcinfo->context))
4675 : 0 : PG_RETURN_NULL();
4676 : :
4677 : 15106 : res = make_result(&result);
4678 : :
4679 : 15106 : free_var(&result);
4680 : :
4681 : 15106 : PG_RETURN_NUMERIC(res);
4682 : : }
4683 : :
4684 : :
4685 : : Datum
4686 : 1748 : numeric_float4(PG_FUNCTION_ARGS)
4687 : : {
4688 : 1748 : Numeric num = PG_GETARG_NUMERIC(0);
4689 : : char *tmp;
4690 : : Datum result;
4691 : :
4692 [ + + ]: 1748 : if (NUMERIC_IS_SPECIAL(num))
4693 : : {
4694 [ + + ]: 56 : if (NUMERIC_IS_PINF(num))
4695 : 17 : PG_RETURN_FLOAT4(get_float4_infinity());
4696 [ + + ]: 39 : else if (NUMERIC_IS_NINF(num))
4697 : 17 : PG_RETURN_FLOAT4(-get_float4_infinity());
4698 : : else
4699 : 22 : PG_RETURN_FLOAT4(get_float4_nan());
4700 : : }
4701 : :
4702 : 1692 : tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
4703 : : NumericGetDatum(num)));
4704 : :
4705 [ - + ]: 1692 : if (!DirectInputFunctionCallSafe(float4in, tmp,
4706 : : InvalidOid, -1,
4707 : : (Node *) fcinfo->context,
4708 : : &result))
4709 : : {
4710 : 0 : pfree(tmp);
4711 : 0 : PG_RETURN_NULL();
4712 : : }
4713 : :
4714 : 1692 : pfree(tmp);
4715 : :
4716 : 1692 : PG_RETURN_DATUM(result);
4717 : : }
4718 : :
4719 : :
4720 : : Datum
4721 : 105 : numeric_pg_lsn(PG_FUNCTION_ARGS)
4722 : : {
4723 : 105 : Numeric num = PG_GETARG_NUMERIC(0);
4724 : : NumericVar x;
4725 : : XLogRecPtr result;
4726 : :
4727 [ + + ]: 105 : if (NUMERIC_IS_SPECIAL(num))
4728 : : {
4729 [ + - ]: 4 : if (NUMERIC_IS_NAN(num))
4730 [ + - ]: 4 : ereport(ERROR,
4731 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4732 : : errmsg("cannot convert NaN to %s", "pg_lsn")));
4733 : : else
4734 [ # # ]: 0 : ereport(ERROR,
4735 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4736 : : errmsg("cannot convert infinity to %s", "pg_lsn")));
4737 : : }
4738 : :
4739 : : /* Convert to variable format and thence to pg_lsn */
4740 : 101 : init_var_from_num(num, &x);
4741 : :
4742 [ + + ]: 101 : if (!numericvar_to_uint64(&x, (uint64 *) &result))
4743 [ + - ]: 16 : ereport(ERROR,
4744 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4745 : : errmsg("pg_lsn out of range")));
4746 : :
4747 : 85 : PG_RETURN_LSN(result);
4748 : : }
4749 : :
4750 : :
4751 : : /* ----------------------------------------------------------------------
4752 : : *
4753 : : * Aggregate functions
4754 : : *
4755 : : * The transition datatype for all these aggregates is declared as INTERNAL.
4756 : : * Actually, it's a pointer to a NumericAggState allocated in the aggregate
4757 : : * context. The digit buffers for the NumericVars will be there too.
4758 : : *
4759 : : * For integer inputs, some aggregates use special-purpose 64-bit or 128-bit
4760 : : * integer based transition datatypes to speed up calculations.
4761 : : *
4762 : : * ----------------------------------------------------------------------
4763 : : */
4764 : :
4765 : : typedef struct NumericAggState
4766 : : {
4767 : : bool calcSumX2; /* if true, calculate sumX2 */
4768 : : MemoryContext agg_context; /* context we're calculating in */
4769 : : int64 N; /* count of processed numbers */
4770 : : NumericSumAccum sumX; /* sum of processed numbers */
4771 : : NumericSumAccum sumX2; /* sum of squares of processed numbers */
4772 : : int maxScale; /* maximum scale seen so far */
4773 : : int64 maxScaleCount; /* number of values seen with maximum scale */
4774 : : /* These counts are *not* included in N! Use NA_TOTAL_COUNT() as needed */
4775 : : int64 NaNcount; /* count of NaN values */
4776 : : int64 pInfcount; /* count of +Inf values */
4777 : : int64 nInfcount; /* count of -Inf values */
4778 : : } NumericAggState;
4779 : :
4780 : : #define NA_TOTAL_COUNT(na) \
4781 : : ((na)->N + (na)->NaNcount + (na)->pInfcount + (na)->nInfcount)
4782 : :
4783 : : /*
4784 : : * Prepare state data for a numeric aggregate function that needs to compute
4785 : : * sum, count and optionally sum of squares of the input.
4786 : : */
4787 : : static NumericAggState *
4788 : 114080 : makeNumericAggState(FunctionCallInfo fcinfo, bool calcSumX2)
4789 : : {
4790 : : NumericAggState *state;
4791 : : MemoryContext agg_context;
4792 : : MemoryContext old_context;
4793 : :
4794 [ - + ]: 114080 : if (!AggCheckCallContext(fcinfo, &agg_context))
4795 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
4796 : :
4797 : 114080 : old_context = MemoryContextSwitchTo(agg_context);
4798 : :
4799 : 114080 : state = palloc0_object(NumericAggState);
4800 : 114080 : state->calcSumX2 = calcSumX2;
4801 : 114080 : state->agg_context = agg_context;
4802 : :
4803 : 114080 : MemoryContextSwitchTo(old_context);
4804 : :
4805 : 114080 : return state;
4806 : : }
4807 : :
4808 : : /*
4809 : : * Like makeNumericAggState(), but allocate the state in the current memory
4810 : : * context.
4811 : : */
4812 : : static NumericAggState *
4813 : 54 : makeNumericAggStateCurrentContext(bool calcSumX2)
4814 : : {
4815 : : NumericAggState *state;
4816 : :
4817 : 54 : state = palloc0_object(NumericAggState);
4818 : 54 : state->calcSumX2 = calcSumX2;
4819 : 54 : state->agg_context = CurrentMemoryContext;
4820 : :
4821 : 54 : return state;
4822 : : }
4823 : :
4824 : : /*
4825 : : * Accumulate a new input value for numeric aggregate functions.
4826 : : */
4827 : : static void
4828 : 1409012 : do_numeric_accum(NumericAggState *state, Numeric newval)
4829 : : {
4830 : : NumericVar X;
4831 : : NumericVar X2;
4832 : : MemoryContext old_context;
4833 : :
4834 : : /* Count NaN/infinity inputs separately from all else */
4835 [ + + ]: 1409012 : if (NUMERIC_IS_SPECIAL(newval))
4836 : : {
4837 [ + + ]: 108 : if (NUMERIC_IS_PINF(newval))
4838 : 48 : state->pInfcount++;
4839 [ + + ]: 60 : else if (NUMERIC_IS_NINF(newval))
4840 : 24 : state->nInfcount++;
4841 : : else
4842 : 36 : state->NaNcount++;
4843 : 108 : return;
4844 : : }
4845 : :
4846 : : /* load processed number in short-lived context */
4847 : 1408904 : init_var_from_num(newval, &X);
4848 : :
4849 : : /*
4850 : : * Track the highest input dscale that we've seen, to support inverse
4851 : : * transitions (see do_numeric_discard).
4852 : : */
4853 [ + + ]: 1408904 : if (X.dscale > state->maxScale)
4854 : : {
4855 : 104 : state->maxScale = X.dscale;
4856 : 104 : state->maxScaleCount = 1;
4857 : : }
4858 [ + + ]: 1408800 : else if (X.dscale == state->maxScale)
4859 : 1408776 : state->maxScaleCount++;
4860 : :
4861 : : /* if we need X^2, calculate that in short-lived context */
4862 [ + + ]: 1408904 : if (state->calcSumX2)
4863 : : {
4864 : 160488 : init_var(&X2);
4865 : 160488 : mul_var(&X, &X, &X2, X.dscale * 2);
4866 : : }
4867 : :
4868 : : /* The rest of this needs to work in the aggregate context */
4869 : 1408904 : old_context = MemoryContextSwitchTo(state->agg_context);
4870 : :
4871 : 1408904 : state->N++;
4872 : :
4873 : : /* Accumulate sums */
4874 : 1408904 : accum_sum_add(&(state->sumX), &X);
4875 : :
4876 [ + + ]: 1408904 : if (state->calcSumX2)
4877 : 160488 : accum_sum_add(&(state->sumX2), &X2);
4878 : :
4879 : 1408904 : MemoryContextSwitchTo(old_context);
4880 : : }
4881 : :
4882 : : /*
4883 : : * Attempt to remove an input value from the aggregated state.
4884 : : *
4885 : : * If the value cannot be removed then the function will return false; the
4886 : : * possible reasons for failing are described below.
4887 : : *
4888 : : * If we aggregate the values 1.01 and 2 then the result will be 3.01.
4889 : : * If we are then asked to un-aggregate the 1.01 then we must fail as we
4890 : : * won't be able to tell what the new aggregated value's dscale should be.
4891 : : * We don't want to return 2.00 (dscale = 2), since the sum's dscale would
4892 : : * have been zero if we'd really aggregated only 2.
4893 : : *
4894 : : * Note: alternatively, we could count the number of inputs with each possible
4895 : : * dscale (up to some sane limit). Not yet clear if it's worth the trouble.
4896 : : */
4897 : : static bool
4898 : 228 : do_numeric_discard(NumericAggState *state, Numeric newval)
4899 : : {
4900 : : NumericVar X;
4901 : : NumericVar X2;
4902 : : MemoryContext old_context;
4903 : :
4904 : : /* Count NaN/infinity inputs separately from all else */
4905 [ + + ]: 228 : if (NUMERIC_IS_SPECIAL(newval))
4906 : : {
4907 [ - + ]: 4 : if (NUMERIC_IS_PINF(newval))
4908 : 0 : state->pInfcount--;
4909 [ - + ]: 4 : else if (NUMERIC_IS_NINF(newval))
4910 : 0 : state->nInfcount--;
4911 : : else
4912 : 4 : state->NaNcount--;
4913 : 4 : return true;
4914 : : }
4915 : :
4916 : : /* load processed number in short-lived context */
4917 : 224 : init_var_from_num(newval, &X);
4918 : :
4919 : : /*
4920 : : * state->sumX's dscale is the maximum dscale of any of the inputs.
4921 : : * Removing the last input with that dscale would require us to recompute
4922 : : * the maximum dscale of the *remaining* inputs, which we cannot do unless
4923 : : * no more non-NaN inputs remain at all. So we report a failure instead,
4924 : : * and force the aggregation to be redone from scratch.
4925 : : */
4926 [ + - ]: 224 : if (X.dscale == state->maxScale)
4927 : : {
4928 [ + + + + ]: 224 : if (state->maxScaleCount > 1 || state->maxScale == 0)
4929 : : {
4930 : : /*
4931 : : * Some remaining inputs have same dscale, or dscale hasn't gotten
4932 : : * above zero anyway
4933 : : */
4934 : 212 : state->maxScaleCount--;
4935 : : }
4936 [ + + ]: 12 : else if (state->N == 1)
4937 : : {
4938 : : /* No remaining non-NaN inputs at all, so reset maxScale */
4939 : 8 : state->maxScale = 0;
4940 : 8 : state->maxScaleCount = 0;
4941 : : }
4942 : : else
4943 : : {
4944 : : /* Correct new maxScale is uncertain, must fail */
4945 : 4 : return false;
4946 : : }
4947 : : }
4948 : :
4949 : : /* if we need X^2, calculate that in short-lived context */
4950 [ + + ]: 220 : if (state->calcSumX2)
4951 : : {
4952 : 192 : init_var(&X2);
4953 : 192 : mul_var(&X, &X, &X2, X.dscale * 2);
4954 : : }
4955 : :
4956 : : /* The rest of this needs to work in the aggregate context */
4957 : 220 : old_context = MemoryContextSwitchTo(state->agg_context);
4958 : :
4959 [ + + ]: 220 : if (state->N-- > 1)
4960 : : {
4961 : : /* Negate X, to subtract it from the sum */
4962 [ + - ]: 208 : X.sign = (X.sign == NUMERIC_POS ? NUMERIC_NEG : NUMERIC_POS);
4963 : 208 : accum_sum_add(&(state->sumX), &X);
4964 : :
4965 [ + + ]: 208 : if (state->calcSumX2)
4966 : : {
4967 : : /* Negate X^2. X^2 is always positive */
4968 : 192 : X2.sign = NUMERIC_NEG;
4969 : 192 : accum_sum_add(&(state->sumX2), &X2);
4970 : : }
4971 : : }
4972 : : else
4973 : : {
4974 : : /* Zero the sums */
4975 : : Assert(state->N == 0);
4976 : :
4977 : 12 : accum_sum_reset(&state->sumX);
4978 [ - + ]: 12 : if (state->calcSumX2)
4979 : 0 : accum_sum_reset(&state->sumX2);
4980 : : }
4981 : :
4982 : 220 : MemoryContextSwitchTo(old_context);
4983 : :
4984 : 220 : return true;
4985 : : }
4986 : :
4987 : : /*
4988 : : * Generic transition function for numeric aggregates that require sumX2.
4989 : : */
4990 : : Datum
4991 : 428 : numeric_accum(PG_FUNCTION_ARGS)
4992 : : {
4993 : : NumericAggState *state;
4994 : :
4995 [ + + ]: 428 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4996 : :
4997 : : /* Create the state data on the first call */
4998 [ + + ]: 428 : if (state == NULL)
4999 : 116 : state = makeNumericAggState(fcinfo, true);
5000 : :
5001 [ + + ]: 428 : if (!PG_ARGISNULL(1))
5002 : 416 : do_numeric_accum(state, PG_GETARG_NUMERIC(1));
5003 : :
5004 : 428 : PG_RETURN_POINTER(state);
5005 : : }
5006 : :
5007 : : /*
5008 : : * Generic combine function for numeric aggregates which require sumX2
5009 : : */
5010 : : Datum
5011 : 23 : numeric_combine(PG_FUNCTION_ARGS)
5012 : : {
5013 : : NumericAggState *state1;
5014 : : NumericAggState *state2;
5015 : : MemoryContext agg_context;
5016 : : MemoryContext old_context;
5017 : :
5018 [ - + ]: 23 : if (!AggCheckCallContext(fcinfo, &agg_context))
5019 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5020 : :
5021 [ + + ]: 23 : state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5022 [ + - ]: 23 : state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
5023 : :
5024 [ - + ]: 23 : if (state2 == NULL)
5025 : : {
5026 : : /*
5027 : : * NULL state2 is easy, just return state1, which we know is already
5028 : : * in the agg_context
5029 : : */
5030 [ # # ]: 0 : if (state1 == NULL)
5031 : 0 : PG_RETURN_NULL();
5032 : 0 : PG_RETURN_POINTER(state1);
5033 : : }
5034 : :
5035 : : /* manually copy all fields from state2 to state1 */
5036 [ + + ]: 23 : if (state1 == NULL)
5037 : : {
5038 : 12 : old_context = MemoryContextSwitchTo(agg_context);
5039 : :
5040 : 12 : state1 = makeNumericAggStateCurrentContext(true);
5041 : 12 : state1->N = state2->N;
5042 : 12 : state1->NaNcount = state2->NaNcount;
5043 : 12 : state1->pInfcount = state2->pInfcount;
5044 : 12 : state1->nInfcount = state2->nInfcount;
5045 : 12 : state1->maxScale = state2->maxScale;
5046 : 12 : state1->maxScaleCount = state2->maxScaleCount;
5047 : :
5048 : 12 : accum_sum_copy(&state1->sumX, &state2->sumX);
5049 : 12 : accum_sum_copy(&state1->sumX2, &state2->sumX2);
5050 : :
5051 : 12 : MemoryContextSwitchTo(old_context);
5052 : :
5053 : 12 : PG_RETURN_POINTER(state1);
5054 : : }
5055 : :
5056 : 11 : state1->N += state2->N;
5057 : 11 : state1->NaNcount += state2->NaNcount;
5058 : 11 : state1->pInfcount += state2->pInfcount;
5059 : 11 : state1->nInfcount += state2->nInfcount;
5060 : :
5061 [ + - ]: 11 : if (state2->N > 0)
5062 : : {
5063 : : /*
5064 : : * These are currently only needed for moving aggregates, but let's do
5065 : : * the right thing anyway...
5066 : : */
5067 [ - + ]: 11 : if (state2->maxScale > state1->maxScale)
5068 : : {
5069 : 0 : state1->maxScale = state2->maxScale;
5070 : 0 : state1->maxScaleCount = state2->maxScaleCount;
5071 : : }
5072 [ + - ]: 11 : else if (state2->maxScale == state1->maxScale)
5073 : 11 : state1->maxScaleCount += state2->maxScaleCount;
5074 : :
5075 : : /* The rest of this needs to work in the aggregate context */
5076 : 11 : old_context = MemoryContextSwitchTo(agg_context);
5077 : :
5078 : : /* Accumulate sums */
5079 : 11 : accum_sum_combine(&state1->sumX, &state2->sumX);
5080 : 11 : accum_sum_combine(&state1->sumX2, &state2->sumX2);
5081 : :
5082 : 11 : MemoryContextSwitchTo(old_context);
5083 : : }
5084 : 11 : PG_RETURN_POINTER(state1);
5085 : : }
5086 : :
5087 : : /*
5088 : : * Generic transition function for numeric aggregates that don't require sumX2.
5089 : : */
5090 : : Datum
5091 : 1248516 : numeric_avg_accum(PG_FUNCTION_ARGS)
5092 : : {
5093 : : NumericAggState *state;
5094 : :
5095 [ + + ]: 1248516 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5096 : :
5097 : : /* Create the state data on the first call */
5098 [ + + ]: 1248516 : if (state == NULL)
5099 : 113925 : state = makeNumericAggState(fcinfo, false);
5100 : :
5101 [ + + ]: 1248516 : if (!PG_ARGISNULL(1))
5102 : 1248476 : do_numeric_accum(state, PG_GETARG_NUMERIC(1));
5103 : :
5104 : 1248516 : PG_RETURN_POINTER(state);
5105 : : }
5106 : :
5107 : : /*
5108 : : * Combine function for numeric aggregates which don't require sumX2
5109 : : */
5110 : : Datum
5111 : 15 : numeric_avg_combine(PG_FUNCTION_ARGS)
5112 : : {
5113 : : NumericAggState *state1;
5114 : : NumericAggState *state2;
5115 : : MemoryContext agg_context;
5116 : : MemoryContext old_context;
5117 : :
5118 [ - + ]: 15 : if (!AggCheckCallContext(fcinfo, &agg_context))
5119 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5120 : :
5121 [ + + ]: 15 : state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5122 [ + - ]: 15 : state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
5123 : :
5124 [ - + ]: 15 : if (state2 == NULL)
5125 : : {
5126 : : /*
5127 : : * NULL state2 is easy, just return state1, which we know is already
5128 : : * in the agg_context
5129 : : */
5130 [ # # ]: 0 : if (state1 == NULL)
5131 : 0 : PG_RETURN_NULL();
5132 : 0 : PG_RETURN_POINTER(state1);
5133 : : }
5134 : :
5135 : : /* manually copy all fields from state2 to state1 */
5136 [ + + ]: 15 : if (state1 == NULL)
5137 : : {
5138 : 4 : old_context = MemoryContextSwitchTo(agg_context);
5139 : :
5140 : 4 : state1 = makeNumericAggStateCurrentContext(false);
5141 : 4 : state1->N = state2->N;
5142 : 4 : state1->NaNcount = state2->NaNcount;
5143 : 4 : state1->pInfcount = state2->pInfcount;
5144 : 4 : state1->nInfcount = state2->nInfcount;
5145 : 4 : state1->maxScale = state2->maxScale;
5146 : 4 : state1->maxScaleCount = state2->maxScaleCount;
5147 : :
5148 : 4 : accum_sum_copy(&state1->sumX, &state2->sumX);
5149 : :
5150 : 4 : MemoryContextSwitchTo(old_context);
5151 : :
5152 : 4 : PG_RETURN_POINTER(state1);
5153 : : }
5154 : :
5155 : 11 : state1->N += state2->N;
5156 : 11 : state1->NaNcount += state2->NaNcount;
5157 : 11 : state1->pInfcount += state2->pInfcount;
5158 : 11 : state1->nInfcount += state2->nInfcount;
5159 : :
5160 [ + - ]: 11 : if (state2->N > 0)
5161 : : {
5162 : : /*
5163 : : * These are currently only needed for moving aggregates, but let's do
5164 : : * the right thing anyway...
5165 : : */
5166 [ - + ]: 11 : if (state2->maxScale > state1->maxScale)
5167 : : {
5168 : 0 : state1->maxScale = state2->maxScale;
5169 : 0 : state1->maxScaleCount = state2->maxScaleCount;
5170 : : }
5171 [ + - ]: 11 : else if (state2->maxScale == state1->maxScale)
5172 : 11 : state1->maxScaleCount += state2->maxScaleCount;
5173 : :
5174 : : /* The rest of this needs to work in the aggregate context */
5175 : 11 : old_context = MemoryContextSwitchTo(agg_context);
5176 : :
5177 : : /* Accumulate sums */
5178 : 11 : accum_sum_combine(&state1->sumX, &state2->sumX);
5179 : :
5180 : 11 : MemoryContextSwitchTo(old_context);
5181 : : }
5182 : 11 : PG_RETURN_POINTER(state1);
5183 : : }
5184 : :
5185 : : /*
5186 : : * numeric_avg_serialize
5187 : : * Serialize NumericAggState for numeric aggregates that don't require
5188 : : * sumX2.
5189 : : */
5190 : : Datum
5191 : 15 : numeric_avg_serialize(PG_FUNCTION_ARGS)
5192 : : {
5193 : : NumericAggState *state;
5194 : : StringInfoData buf;
5195 : : bytea *result;
5196 : : NumericVar tmp_var;
5197 : :
5198 : : /* Ensure we disallow calling when not in aggregate context */
5199 [ - + ]: 15 : if (!AggCheckCallContext(fcinfo, NULL))
5200 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5201 : :
5202 : 15 : state = (NumericAggState *) PG_GETARG_POINTER(0);
5203 : :
5204 : 15 : init_var(&tmp_var);
5205 : :
5206 : 15 : pq_begintypsend(&buf);
5207 : :
5208 : : /* N */
5209 : 15 : pq_sendint64(&buf, state->N);
5210 : :
5211 : : /* sumX */
5212 : 15 : accum_sum_final(&state->sumX, &tmp_var);
5213 : 15 : numericvar_serialize(&buf, &tmp_var);
5214 : :
5215 : : /* maxScale */
5216 : 15 : pq_sendint32(&buf, state->maxScale);
5217 : :
5218 : : /* maxScaleCount */
5219 : 15 : pq_sendint64(&buf, state->maxScaleCount);
5220 : :
5221 : : /* NaNcount */
5222 : 15 : pq_sendint64(&buf, state->NaNcount);
5223 : :
5224 : : /* pInfcount */
5225 : 15 : pq_sendint64(&buf, state->pInfcount);
5226 : :
5227 : : /* nInfcount */
5228 : 15 : pq_sendint64(&buf, state->nInfcount);
5229 : :
5230 : 15 : result = pq_endtypsend(&buf);
5231 : :
5232 : 15 : free_var(&tmp_var);
5233 : :
5234 : 15 : PG_RETURN_BYTEA_P(result);
5235 : : }
5236 : :
5237 : : /*
5238 : : * numeric_avg_deserialize
5239 : : * Deserialize bytea into NumericAggState for numeric aggregates that
5240 : : * don't require sumX2.
5241 : : */
5242 : : Datum
5243 : 15 : numeric_avg_deserialize(PG_FUNCTION_ARGS)
5244 : : {
5245 : : bytea *sstate;
5246 : : NumericAggState *result;
5247 : : StringInfoData buf;
5248 : : NumericVar tmp_var;
5249 : :
5250 [ - + ]: 15 : if (!AggCheckCallContext(fcinfo, NULL))
5251 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5252 : :
5253 : 15 : sstate = PG_GETARG_BYTEA_PP(0);
5254 : :
5255 : 15 : init_var(&tmp_var);
5256 : :
5257 : : /*
5258 : : * Initialize a StringInfo so that we can "receive" it using the standard
5259 : : * recv-function infrastructure.
5260 : : */
5261 : 15 : initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
5262 : 15 : VARSIZE_ANY_EXHDR(sstate));
5263 : :
5264 : 15 : result = makeNumericAggStateCurrentContext(false);
5265 : :
5266 : : /* N */
5267 : 15 : result->N = pq_getmsgint64(&buf);
5268 : :
5269 : : /* sumX */
5270 : 15 : numericvar_deserialize(&buf, &tmp_var);
5271 : 15 : accum_sum_add(&(result->sumX), &tmp_var);
5272 : :
5273 : : /* maxScale */
5274 : 15 : result->maxScale = pq_getmsgint(&buf, 4);
5275 : :
5276 : : /* maxScaleCount */
5277 : 15 : result->maxScaleCount = pq_getmsgint64(&buf);
5278 : :
5279 : : /* NaNcount */
5280 : 15 : result->NaNcount = pq_getmsgint64(&buf);
5281 : :
5282 : : /* pInfcount */
5283 : 15 : result->pInfcount = pq_getmsgint64(&buf);
5284 : :
5285 : : /* nInfcount */
5286 : 15 : result->nInfcount = pq_getmsgint64(&buf);
5287 : :
5288 : 15 : pq_getmsgend(&buf);
5289 : :
5290 : 15 : free_var(&tmp_var);
5291 : :
5292 : 15 : PG_RETURN_POINTER(result);
5293 : : }
5294 : :
5295 : : /*
5296 : : * numeric_serialize
5297 : : * Serialization function for NumericAggState for numeric aggregates that
5298 : : * require sumX2.
5299 : : */
5300 : : Datum
5301 : 23 : numeric_serialize(PG_FUNCTION_ARGS)
5302 : : {
5303 : : NumericAggState *state;
5304 : : StringInfoData buf;
5305 : : bytea *result;
5306 : : NumericVar tmp_var;
5307 : :
5308 : : /* Ensure we disallow calling when not in aggregate context */
5309 [ - + ]: 23 : if (!AggCheckCallContext(fcinfo, NULL))
5310 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5311 : :
5312 : 23 : state = (NumericAggState *) PG_GETARG_POINTER(0);
5313 : :
5314 : 23 : init_var(&tmp_var);
5315 : :
5316 : 23 : pq_begintypsend(&buf);
5317 : :
5318 : : /* N */
5319 : 23 : pq_sendint64(&buf, state->N);
5320 : :
5321 : : /* sumX */
5322 : 23 : accum_sum_final(&state->sumX, &tmp_var);
5323 : 23 : numericvar_serialize(&buf, &tmp_var);
5324 : :
5325 : : /* sumX2 */
5326 : 23 : accum_sum_final(&state->sumX2, &tmp_var);
5327 : 23 : numericvar_serialize(&buf, &tmp_var);
5328 : :
5329 : : /* maxScale */
5330 : 23 : pq_sendint32(&buf, state->maxScale);
5331 : :
5332 : : /* maxScaleCount */
5333 : 23 : pq_sendint64(&buf, state->maxScaleCount);
5334 : :
5335 : : /* NaNcount */
5336 : 23 : pq_sendint64(&buf, state->NaNcount);
5337 : :
5338 : : /* pInfcount */
5339 : 23 : pq_sendint64(&buf, state->pInfcount);
5340 : :
5341 : : /* nInfcount */
5342 : 23 : pq_sendint64(&buf, state->nInfcount);
5343 : :
5344 : 23 : result = pq_endtypsend(&buf);
5345 : :
5346 : 23 : free_var(&tmp_var);
5347 : :
5348 : 23 : PG_RETURN_BYTEA_P(result);
5349 : : }
5350 : :
5351 : : /*
5352 : : * numeric_deserialize
5353 : : * Deserialization function for NumericAggState for numeric aggregates that
5354 : : * require sumX2.
5355 : : */
5356 : : Datum
5357 : 23 : numeric_deserialize(PG_FUNCTION_ARGS)
5358 : : {
5359 : : bytea *sstate;
5360 : : NumericAggState *result;
5361 : : StringInfoData buf;
5362 : : NumericVar tmp_var;
5363 : :
5364 [ - + ]: 23 : if (!AggCheckCallContext(fcinfo, NULL))
5365 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5366 : :
5367 : 23 : sstate = PG_GETARG_BYTEA_PP(0);
5368 : :
5369 : 23 : init_var(&tmp_var);
5370 : :
5371 : : /*
5372 : : * Initialize a StringInfo so that we can "receive" it using the standard
5373 : : * recv-function infrastructure.
5374 : : */
5375 : 23 : initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
5376 : 23 : VARSIZE_ANY_EXHDR(sstate));
5377 : :
5378 : 23 : result = makeNumericAggStateCurrentContext(true);
5379 : :
5380 : : /* N */
5381 : 23 : result->N = pq_getmsgint64(&buf);
5382 : :
5383 : : /* sumX */
5384 : 23 : numericvar_deserialize(&buf, &tmp_var);
5385 : 23 : accum_sum_add(&(result->sumX), &tmp_var);
5386 : :
5387 : : /* sumX2 */
5388 : 23 : numericvar_deserialize(&buf, &tmp_var);
5389 : 23 : accum_sum_add(&(result->sumX2), &tmp_var);
5390 : :
5391 : : /* maxScale */
5392 : 23 : result->maxScale = pq_getmsgint(&buf, 4);
5393 : :
5394 : : /* maxScaleCount */
5395 : 23 : result->maxScaleCount = pq_getmsgint64(&buf);
5396 : :
5397 : : /* NaNcount */
5398 : 23 : result->NaNcount = pq_getmsgint64(&buf);
5399 : :
5400 : : /* pInfcount */
5401 : 23 : result->pInfcount = pq_getmsgint64(&buf);
5402 : :
5403 : : /* nInfcount */
5404 : 23 : result->nInfcount = pq_getmsgint64(&buf);
5405 : :
5406 : 23 : pq_getmsgend(&buf);
5407 : :
5408 : 23 : free_var(&tmp_var);
5409 : :
5410 : 23 : PG_RETURN_POINTER(result);
5411 : : }
5412 : :
5413 : : /*
5414 : : * Generic inverse transition function for numeric aggregates
5415 : : * (with or without requirement for X^2).
5416 : : */
5417 : : Datum
5418 : 152 : numeric_accum_inv(PG_FUNCTION_ARGS)
5419 : : {
5420 : : NumericAggState *state;
5421 : :
5422 [ + - ]: 152 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5423 : :
5424 : : /* Should not get here with no state */
5425 [ - + ]: 152 : if (state == NULL)
5426 [ # # ]: 0 : elog(ERROR, "numeric_accum_inv called with NULL state");
5427 : :
5428 [ + + ]: 152 : if (!PG_ARGISNULL(1))
5429 : : {
5430 : : /* If we fail to perform the inverse transition, return NULL */
5431 [ + + ]: 132 : if (!do_numeric_discard(state, PG_GETARG_NUMERIC(1)))
5432 : 4 : PG_RETURN_NULL();
5433 : : }
5434 : :
5435 : 148 : PG_RETURN_POINTER(state);
5436 : : }
5437 : :
5438 : :
5439 : : /*
5440 : : * Integer data types in general use Numeric accumulators to share code and
5441 : : * avoid risk of overflow. However for performance reasons optimized
5442 : : * special-purpose accumulator routines are used when possible:
5443 : : *
5444 : : * For 16-bit and 32-bit inputs, N and sum(X) fit into 64-bit, so 64-bit
5445 : : * accumulators are used for SUM and AVG of these data types.
5446 : : *
5447 : : * For 16-bit and 32-bit inputs, sum(X^2) fits into 128-bit, so 128-bit
5448 : : * accumulators are used for STDDEV_POP, STDDEV_SAMP, VAR_POP, and VAR_SAMP of
5449 : : * these data types.
5450 : : *
5451 : : * For 64-bit inputs, sum(X) fits into 128-bit, so a 128-bit accumulator is
5452 : : * used for SUM(int8) and AVG(int8).
5453 : : */
5454 : :
5455 : : typedef struct Int128AggState
5456 : : {
5457 : : bool calcSumX2; /* if true, calculate sumX2 */
5458 : : int64 N; /* count of processed numbers */
5459 : : INT128 sumX; /* sum of processed numbers */
5460 : : INT128 sumX2; /* sum of squares of processed numbers */
5461 : : } Int128AggState;
5462 : :
5463 : : /*
5464 : : * Prepare state data for a 128-bit aggregate function that needs to compute
5465 : : * sum, count and optionally sum of squares of the input.
5466 : : */
5467 : : static Int128AggState *
5468 : 622 : makeInt128AggState(FunctionCallInfo fcinfo, bool calcSumX2)
5469 : : {
5470 : : Int128AggState *state;
5471 : : MemoryContext agg_context;
5472 : : MemoryContext old_context;
5473 : :
5474 [ - + ]: 622 : if (!AggCheckCallContext(fcinfo, &agg_context))
5475 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5476 : :
5477 : 622 : old_context = MemoryContextSwitchTo(agg_context);
5478 : :
5479 : 622 : state = palloc0_object(Int128AggState);
5480 : 622 : state->calcSumX2 = calcSumX2;
5481 : :
5482 : 622 : MemoryContextSwitchTo(old_context);
5483 : :
5484 : 622 : return state;
5485 : : }
5486 : :
5487 : : /*
5488 : : * Like makeInt128AggState(), but allocate the state in the current memory
5489 : : * context.
5490 : : */
5491 : : static Int128AggState *
5492 : 35 : makeInt128AggStateCurrentContext(bool calcSumX2)
5493 : : {
5494 : : Int128AggState *state;
5495 : :
5496 : 35 : state = palloc0_object(Int128AggState);
5497 : 35 : state->calcSumX2 = calcSumX2;
5498 : :
5499 : 35 : return state;
5500 : : }
5501 : :
5502 : : /*
5503 : : * Accumulate a new input value for 128-bit aggregate functions.
5504 : : */
5505 : : static void
5506 : 370943 : do_int128_accum(Int128AggState *state, int64 newval)
5507 : : {
5508 [ + + ]: 370943 : if (state->calcSumX2)
5509 : 161240 : int128_add_int64_mul_int64(&state->sumX2, newval, newval);
5510 : :
5511 : 370943 : int128_add_int64(&state->sumX, newval);
5512 : 370943 : state->N++;
5513 : 370943 : }
5514 : :
5515 : : /*
5516 : : * Remove an input value from the aggregated state.
5517 : : */
5518 : : static void
5519 : 208 : do_int128_discard(Int128AggState *state, int64 newval)
5520 : : {
5521 [ + + ]: 208 : if (state->calcSumX2)
5522 : 192 : int128_sub_int64_mul_int64(&state->sumX2, newval, newval);
5523 : :
5524 : 208 : int128_sub_int64(&state->sumX, newval);
5525 : 208 : state->N--;
5526 : 208 : }
5527 : :
5528 : : Datum
5529 : 132 : int2_accum(PG_FUNCTION_ARGS)
5530 : : {
5531 : : Int128AggState *state;
5532 : :
5533 [ + + ]: 132 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5534 : :
5535 : : /* Create the state data on the first call */
5536 [ + + ]: 132 : if (state == NULL)
5537 : 24 : state = makeInt128AggState(fcinfo, true);
5538 : :
5539 [ + + ]: 132 : if (!PG_ARGISNULL(1))
5540 : 120 : do_int128_accum(state, PG_GETARG_INT16(1));
5541 : :
5542 : 132 : PG_RETURN_POINTER(state);
5543 : : }
5544 : :
5545 : : Datum
5546 : 161132 : int4_accum(PG_FUNCTION_ARGS)
5547 : : {
5548 : : Int128AggState *state;
5549 : :
5550 [ + + ]: 161132 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5551 : :
5552 : : /* Create the state data on the first call */
5553 [ + + ]: 161132 : if (state == NULL)
5554 : 49 : state = makeInt128AggState(fcinfo, true);
5555 : :
5556 [ + + ]: 161132 : if (!PG_ARGISNULL(1))
5557 : 161120 : do_int128_accum(state, PG_GETARG_INT32(1));
5558 : :
5559 : 161132 : PG_RETURN_POINTER(state);
5560 : : }
5561 : :
5562 : : Datum
5563 : 160132 : int8_accum(PG_FUNCTION_ARGS)
5564 : : {
5565 : : NumericAggState *state;
5566 : :
5567 [ + + ]: 160132 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5568 : :
5569 : : /* Create the state data on the first call */
5570 [ + + ]: 160132 : if (state == NULL)
5571 : 39 : state = makeNumericAggState(fcinfo, true);
5572 : :
5573 [ + + ]: 160132 : if (!PG_ARGISNULL(1))
5574 : 160120 : do_numeric_accum(state, int64_to_numeric(PG_GETARG_INT64(1)));
5575 : :
5576 : 160132 : PG_RETURN_POINTER(state);
5577 : : }
5578 : :
5579 : : /*
5580 : : * Combine function for Int128AggState for aggregates which require sumX2
5581 : : */
5582 : : Datum
5583 : 15 : numeric_poly_combine(PG_FUNCTION_ARGS)
5584 : : {
5585 : : Int128AggState *state1;
5586 : : Int128AggState *state2;
5587 : : MemoryContext agg_context;
5588 : : MemoryContext old_context;
5589 : :
5590 [ - + ]: 15 : if (!AggCheckCallContext(fcinfo, &agg_context))
5591 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5592 : :
5593 [ + + ]: 15 : state1 = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5594 [ + - ]: 15 : state2 = PG_ARGISNULL(1) ? NULL : (Int128AggState *) PG_GETARG_POINTER(1);
5595 : :
5596 [ - + ]: 15 : if (state2 == NULL)
5597 : : {
5598 : : /*
5599 : : * NULL state2 is easy, just return state1, which we know is already
5600 : : * in the agg_context
5601 : : */
5602 [ # # ]: 0 : if (state1 == NULL)
5603 : 0 : PG_RETURN_NULL();
5604 : 0 : PG_RETURN_POINTER(state1);
5605 : : }
5606 : :
5607 : : /* manually copy all fields from state2 to state1 */
5608 [ + + ]: 15 : if (state1 == NULL)
5609 : : {
5610 : 4 : old_context = MemoryContextSwitchTo(agg_context);
5611 : :
5612 : 4 : state1 = makeInt128AggState(fcinfo, true);
5613 : 4 : state1->N = state2->N;
5614 : 4 : state1->sumX = state2->sumX;
5615 : 4 : state1->sumX2 = state2->sumX2;
5616 : :
5617 : 4 : MemoryContextSwitchTo(old_context);
5618 : :
5619 : 4 : PG_RETURN_POINTER(state1);
5620 : : }
5621 : :
5622 [ + - ]: 11 : if (state2->N > 0)
5623 : : {
5624 : 11 : state1->N += state2->N;
5625 : 11 : int128_add_int128(&state1->sumX, state2->sumX);
5626 : 11 : int128_add_int128(&state1->sumX2, state2->sumX2);
5627 : : }
5628 : 11 : PG_RETURN_POINTER(state1);
5629 : : }
5630 : :
5631 : : /*
5632 : : * int128_serialize - serialize a 128-bit integer to binary format
5633 : : */
5634 : : static inline void
5635 : 50 : int128_serialize(StringInfo buf, INT128 val)
5636 : : {
5637 : 50 : pq_sendint64(buf, PG_INT128_HI_INT64(val));
5638 : 50 : pq_sendint64(buf, PG_INT128_LO_UINT64(val));
5639 : 50 : }
5640 : :
5641 : : /*
5642 : : * int128_deserialize - deserialize binary format to a 128-bit integer.
5643 : : */
5644 : : static inline INT128
5645 : 50 : int128_deserialize(StringInfo buf)
5646 : : {
5647 : 50 : int64 hi = pq_getmsgint64(buf);
5648 : 50 : uint64 lo = pq_getmsgint64(buf);
5649 : :
5650 : 50 : return make_int128(hi, lo);
5651 : : }
5652 : :
5653 : : /*
5654 : : * numeric_poly_serialize
5655 : : * Serialize Int128AggState into bytea for aggregate functions which
5656 : : * require sumX2.
5657 : : */
5658 : : Datum
5659 : 15 : numeric_poly_serialize(PG_FUNCTION_ARGS)
5660 : : {
5661 : : Int128AggState *state;
5662 : : StringInfoData buf;
5663 : : bytea *result;
5664 : :
5665 : : /* Ensure we disallow calling when not in aggregate context */
5666 [ - + ]: 15 : if (!AggCheckCallContext(fcinfo, NULL))
5667 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5668 : :
5669 : 15 : state = (Int128AggState *) PG_GETARG_POINTER(0);
5670 : :
5671 : 15 : pq_begintypsend(&buf);
5672 : :
5673 : : /* N */
5674 : 15 : pq_sendint64(&buf, state->N);
5675 : :
5676 : : /* sumX */
5677 : 15 : int128_serialize(&buf, state->sumX);
5678 : :
5679 : : /* sumX2 */
5680 : 15 : int128_serialize(&buf, state->sumX2);
5681 : :
5682 : 15 : result = pq_endtypsend(&buf);
5683 : :
5684 : 15 : PG_RETURN_BYTEA_P(result);
5685 : : }
5686 : :
5687 : : /*
5688 : : * numeric_poly_deserialize
5689 : : * Deserialize Int128AggState from bytea for aggregate functions which
5690 : : * require sumX2.
5691 : : */
5692 : : Datum
5693 : 15 : numeric_poly_deserialize(PG_FUNCTION_ARGS)
5694 : : {
5695 : : bytea *sstate;
5696 : : Int128AggState *result;
5697 : : StringInfoData buf;
5698 : :
5699 [ - + ]: 15 : if (!AggCheckCallContext(fcinfo, NULL))
5700 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5701 : :
5702 : 15 : sstate = PG_GETARG_BYTEA_PP(0);
5703 : :
5704 : : /*
5705 : : * Initialize a StringInfo so that we can "receive" it using the standard
5706 : : * recv-function infrastructure.
5707 : : */
5708 : 15 : initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
5709 : 15 : VARSIZE_ANY_EXHDR(sstate));
5710 : :
5711 : 15 : result = makeInt128AggStateCurrentContext(true);
5712 : :
5713 : : /* N */
5714 : 15 : result->N = pq_getmsgint64(&buf);
5715 : :
5716 : : /* sumX */
5717 : 15 : result->sumX = int128_deserialize(&buf);
5718 : :
5719 : : /* sumX2 */
5720 : 15 : result->sumX2 = int128_deserialize(&buf);
5721 : :
5722 : 15 : pq_getmsgend(&buf);
5723 : :
5724 : 15 : PG_RETURN_POINTER(result);
5725 : : }
5726 : :
5727 : : /*
5728 : : * Transition function for int8 input when we don't need sumX2.
5729 : : */
5730 : : Datum
5731 : 212407 : int8_avg_accum(PG_FUNCTION_ARGS)
5732 : : {
5733 : : Int128AggState *state;
5734 : :
5735 [ + + ]: 212407 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5736 : :
5737 : : /* Create the state data on the first call */
5738 [ + + ]: 212407 : if (state == NULL)
5739 : 537 : state = makeInt128AggState(fcinfo, false);
5740 : :
5741 [ + + ]: 212407 : if (!PG_ARGISNULL(1))
5742 : 209703 : do_int128_accum(state, PG_GETARG_INT64(1));
5743 : :
5744 : 212407 : PG_RETURN_POINTER(state);
5745 : : }
5746 : :
5747 : : /*
5748 : : * Combine function for Int128AggState for aggregates which don't require
5749 : : * sumX2
5750 : : */
5751 : : Datum
5752 : 20 : int8_avg_combine(PG_FUNCTION_ARGS)
5753 : : {
5754 : : Int128AggState *state1;
5755 : : Int128AggState *state2;
5756 : : MemoryContext agg_context;
5757 : : MemoryContext old_context;
5758 : :
5759 [ - + ]: 20 : if (!AggCheckCallContext(fcinfo, &agg_context))
5760 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5761 : :
5762 [ + + ]: 20 : state1 = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5763 [ + - ]: 20 : state2 = PG_ARGISNULL(1) ? NULL : (Int128AggState *) PG_GETARG_POINTER(1);
5764 : :
5765 [ - + ]: 20 : if (state2 == NULL)
5766 : : {
5767 : : /*
5768 : : * NULL state2 is easy, just return state1, which we know is already
5769 : : * in the agg_context
5770 : : */
5771 [ # # ]: 0 : if (state1 == NULL)
5772 : 0 : PG_RETURN_NULL();
5773 : 0 : PG_RETURN_POINTER(state1);
5774 : : }
5775 : :
5776 : : /* manually copy all fields from state2 to state1 */
5777 [ + + ]: 20 : if (state1 == NULL)
5778 : : {
5779 : 8 : old_context = MemoryContextSwitchTo(agg_context);
5780 : :
5781 : 8 : state1 = makeInt128AggState(fcinfo, false);
5782 : 8 : state1->N = state2->N;
5783 : 8 : state1->sumX = state2->sumX;
5784 : :
5785 : 8 : MemoryContextSwitchTo(old_context);
5786 : :
5787 : 8 : PG_RETURN_POINTER(state1);
5788 : : }
5789 : :
5790 [ + - ]: 12 : if (state2->N > 0)
5791 : : {
5792 : 12 : state1->N += state2->N;
5793 : 12 : int128_add_int128(&state1->sumX, state2->sumX);
5794 : : }
5795 : 12 : PG_RETURN_POINTER(state1);
5796 : : }
5797 : :
5798 : : /*
5799 : : * int8_avg_serialize
5800 : : * Serialize Int128AggState into bytea for aggregate functions which
5801 : : * don't require sumX2.
5802 : : */
5803 : : Datum
5804 : 20 : int8_avg_serialize(PG_FUNCTION_ARGS)
5805 : : {
5806 : : Int128AggState *state;
5807 : : StringInfoData buf;
5808 : : bytea *result;
5809 : :
5810 : : /* Ensure we disallow calling when not in aggregate context */
5811 [ - + ]: 20 : if (!AggCheckCallContext(fcinfo, NULL))
5812 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5813 : :
5814 : 20 : state = (Int128AggState *) PG_GETARG_POINTER(0);
5815 : :
5816 : 20 : pq_begintypsend(&buf);
5817 : :
5818 : : /* N */
5819 : 20 : pq_sendint64(&buf, state->N);
5820 : :
5821 : : /* sumX */
5822 : 20 : int128_serialize(&buf, state->sumX);
5823 : :
5824 : 20 : result = pq_endtypsend(&buf);
5825 : :
5826 : 20 : PG_RETURN_BYTEA_P(result);
5827 : : }
5828 : :
5829 : : /*
5830 : : * int8_avg_deserialize
5831 : : * Deserialize Int128AggState from bytea for aggregate functions which
5832 : : * don't require sumX2.
5833 : : */
5834 : : Datum
5835 : 20 : int8_avg_deserialize(PG_FUNCTION_ARGS)
5836 : : {
5837 : : bytea *sstate;
5838 : : Int128AggState *result;
5839 : : StringInfoData buf;
5840 : :
5841 [ - + ]: 20 : if (!AggCheckCallContext(fcinfo, NULL))
5842 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5843 : :
5844 : 20 : sstate = PG_GETARG_BYTEA_PP(0);
5845 : :
5846 : : /*
5847 : : * Initialize a StringInfo so that we can "receive" it using the standard
5848 : : * recv-function infrastructure.
5849 : : */
5850 : 20 : initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
5851 : 20 : VARSIZE_ANY_EXHDR(sstate));
5852 : :
5853 : 20 : result = makeInt128AggStateCurrentContext(false);
5854 : :
5855 : : /* N */
5856 : 20 : result->N = pq_getmsgint64(&buf);
5857 : :
5858 : : /* sumX */
5859 : 20 : result->sumX = int128_deserialize(&buf);
5860 : :
5861 : 20 : pq_getmsgend(&buf);
5862 : :
5863 : 20 : PG_RETURN_POINTER(result);
5864 : : }
5865 : :
5866 : : /*
5867 : : * Inverse transition functions to go with the above.
5868 : : */
5869 : :
5870 : : Datum
5871 : 108 : int2_accum_inv(PG_FUNCTION_ARGS)
5872 : : {
5873 : : Int128AggState *state;
5874 : :
5875 [ + - ]: 108 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5876 : :
5877 : : /* Should not get here with no state */
5878 [ - + ]: 108 : if (state == NULL)
5879 [ # # ]: 0 : elog(ERROR, "int2_accum_inv called with NULL state");
5880 : :
5881 [ + + ]: 108 : if (!PG_ARGISNULL(1))
5882 : 96 : do_int128_discard(state, PG_GETARG_INT16(1));
5883 : :
5884 : 108 : PG_RETURN_POINTER(state);
5885 : : }
5886 : :
5887 : : Datum
5888 : 108 : int4_accum_inv(PG_FUNCTION_ARGS)
5889 : : {
5890 : : Int128AggState *state;
5891 : :
5892 [ + - ]: 108 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5893 : :
5894 : : /* Should not get here with no state */
5895 [ - + ]: 108 : if (state == NULL)
5896 [ # # ]: 0 : elog(ERROR, "int4_accum_inv called with NULL state");
5897 : :
5898 [ + + ]: 108 : if (!PG_ARGISNULL(1))
5899 : 96 : do_int128_discard(state, PG_GETARG_INT32(1));
5900 : :
5901 : 108 : PG_RETURN_POINTER(state);
5902 : : }
5903 : :
5904 : : Datum
5905 : 108 : int8_accum_inv(PG_FUNCTION_ARGS)
5906 : : {
5907 : : NumericAggState *state;
5908 : :
5909 [ + - ]: 108 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5910 : :
5911 : : /* Should not get here with no state */
5912 [ - + ]: 108 : if (state == NULL)
5913 [ # # ]: 0 : elog(ERROR, "int8_accum_inv called with NULL state");
5914 : :
5915 [ + + ]: 108 : if (!PG_ARGISNULL(1))
5916 : : {
5917 : : /* Should never fail, all inputs have dscale 0 */
5918 [ - + ]: 96 : if (!do_numeric_discard(state, int64_to_numeric(PG_GETARG_INT64(1))))
5919 [ # # ]: 0 : elog(ERROR, "do_numeric_discard failed unexpectedly");
5920 : : }
5921 : :
5922 : 108 : PG_RETURN_POINTER(state);
5923 : : }
5924 : :
5925 : : Datum
5926 : 24 : int8_avg_accum_inv(PG_FUNCTION_ARGS)
5927 : : {
5928 : : Int128AggState *state;
5929 : :
5930 [ + - ]: 24 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5931 : :
5932 : : /* Should not get here with no state */
5933 [ - + ]: 24 : if (state == NULL)
5934 [ # # ]: 0 : elog(ERROR, "int8_avg_accum_inv called with NULL state");
5935 : :
5936 [ + + ]: 24 : if (!PG_ARGISNULL(1))
5937 : 16 : do_int128_discard(state, PG_GETARG_INT64(1));
5938 : :
5939 : 24 : PG_RETURN_POINTER(state);
5940 : : }
5941 : :
5942 : : Datum
5943 : 681 : numeric_poly_sum(PG_FUNCTION_ARGS)
5944 : : {
5945 : : Int128AggState *state;
5946 : : Numeric res;
5947 : : NumericVar result;
5948 : :
5949 [ + + ]: 681 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5950 : :
5951 : : /* If there were no non-null inputs, return NULL */
5952 [ + + + + ]: 681 : if (state == NULL || state->N == 0)
5953 : 16 : PG_RETURN_NULL();
5954 : :
5955 : 665 : init_var(&result);
5956 : :
5957 : 665 : int128_to_numericvar(state->sumX, &result);
5958 : :
5959 : 665 : res = make_result(&result);
5960 : :
5961 : 665 : free_var(&result);
5962 : :
5963 : 665 : PG_RETURN_NUMERIC(res);
5964 : : }
5965 : :
5966 : : Datum
5967 : 24 : numeric_poly_avg(PG_FUNCTION_ARGS)
5968 : : {
5969 : : Int128AggState *state;
5970 : : NumericVar result;
5971 : : Datum countd,
5972 : : sumd;
5973 : :
5974 [ + - ]: 24 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5975 : :
5976 : : /* If there were no non-null inputs, return NULL */
5977 [ + - + + ]: 24 : if (state == NULL || state->N == 0)
5978 : 12 : PG_RETURN_NULL();
5979 : :
5980 : 12 : init_var(&result);
5981 : :
5982 : 12 : int128_to_numericvar(state->sumX, &result);
5983 : :
5984 : 12 : countd = NumericGetDatum(int64_to_numeric(state->N));
5985 : 12 : sumd = NumericGetDatum(make_result(&result));
5986 : :
5987 : 12 : free_var(&result);
5988 : :
5989 : 12 : PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumd, countd));
5990 : : }
5991 : :
5992 : : Datum
5993 : 52 : numeric_avg(PG_FUNCTION_ARGS)
5994 : : {
5995 : : NumericAggState *state;
5996 : : Datum N_datum;
5997 : : Datum sumX_datum;
5998 : : NumericVar sumX_var;
5999 : :
6000 [ + - ]: 52 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6001 : :
6002 : : /* If there were no non-null inputs, return NULL */
6003 [ + - + + ]: 52 : if (state == NULL || NA_TOTAL_COUNT(state) == 0)
6004 : 12 : PG_RETURN_NULL();
6005 : :
6006 [ + + ]: 40 : if (state->NaNcount > 0) /* there was at least one NaN input */
6007 : 4 : PG_RETURN_NUMERIC(make_result(&const_nan));
6008 : :
6009 : : /* adding plus and minus infinities gives NaN */
6010 [ + + + + ]: 36 : if (state->pInfcount > 0 && state->nInfcount > 0)
6011 : 4 : PG_RETURN_NUMERIC(make_result(&const_nan));
6012 [ + + ]: 32 : if (state->pInfcount > 0)
6013 : 12 : PG_RETURN_NUMERIC(make_result(&const_pinf));
6014 [ + + ]: 20 : if (state->nInfcount > 0)
6015 : 4 : PG_RETURN_NUMERIC(make_result(&const_ninf));
6016 : :
6017 : 16 : N_datum = NumericGetDatum(int64_to_numeric(state->N));
6018 : :
6019 : 16 : init_var(&sumX_var);
6020 : 16 : accum_sum_final(&state->sumX, &sumX_var);
6021 : 16 : sumX_datum = NumericGetDatum(make_result(&sumX_var));
6022 : 16 : free_var(&sumX_var);
6023 : :
6024 : 16 : PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumX_datum, N_datum));
6025 : : }
6026 : :
6027 : : Datum
6028 : 113926 : numeric_sum(PG_FUNCTION_ARGS)
6029 : : {
6030 : : NumericAggState *state;
6031 : : NumericVar sumX_var;
6032 : : Numeric result;
6033 : :
6034 [ + - ]: 113926 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6035 : :
6036 : : /* If there were no non-null inputs, return NULL */
6037 [ + - + + ]: 113926 : if (state == NULL || NA_TOTAL_COUNT(state) == 0)
6038 : 12 : PG_RETURN_NULL();
6039 : :
6040 [ + + ]: 113914 : if (state->NaNcount > 0) /* there was at least one NaN input */
6041 : 12 : PG_RETURN_NUMERIC(make_result(&const_nan));
6042 : :
6043 : : /* adding plus and minus infinities gives NaN */
6044 [ + + + + ]: 113902 : if (state->pInfcount > 0 && state->nInfcount > 0)
6045 : 4 : PG_RETURN_NUMERIC(make_result(&const_nan));
6046 [ + + ]: 113898 : if (state->pInfcount > 0)
6047 : 12 : PG_RETURN_NUMERIC(make_result(&const_pinf));
6048 [ + + ]: 113886 : if (state->nInfcount > 0)
6049 : 4 : PG_RETURN_NUMERIC(make_result(&const_ninf));
6050 : :
6051 : 113882 : init_var(&sumX_var);
6052 : 113882 : accum_sum_final(&state->sumX, &sumX_var);
6053 : 113882 : result = make_result(&sumX_var);
6054 : 113882 : free_var(&sumX_var);
6055 : :
6056 : 113882 : PG_RETURN_NUMERIC(result);
6057 : : }
6058 : :
6059 : : /*
6060 : : * Workhorse routine for the standard deviance and variance
6061 : : * aggregates. 'state' is aggregate's transition state.
6062 : : * 'variance' specifies whether we should calculate the
6063 : : * variance or the standard deviation. 'sample' indicates whether the
6064 : : * caller is interested in the sample or the population
6065 : : * variance/stddev.
6066 : : *
6067 : : * If appropriate variance statistic is undefined for the input,
6068 : : * *is_null is set to true and NULL is returned.
6069 : : */
6070 : : static Numeric
6071 : 654 : numeric_stddev_internal(NumericAggState *state,
6072 : : bool variance, bool sample,
6073 : : bool *is_null)
6074 : : {
6075 : : Numeric res;
6076 : : NumericVar vN,
6077 : : vsumX,
6078 : : vsumX2,
6079 : : vNminus1;
6080 : : int64 totCount;
6081 : : int rscale;
6082 : :
6083 : : /*
6084 : : * Sample stddev and variance are undefined when N <= 1; population stddev
6085 : : * is undefined when N == 0. Return NULL in either case (note that NaNs
6086 : : * and infinities count as normal inputs for this purpose).
6087 : : */
6088 [ + - - + ]: 654 : if (state == NULL || (totCount = NA_TOTAL_COUNT(state)) == 0)
6089 : : {
6090 : 0 : *is_null = true;
6091 : 0 : return NULL;
6092 : : }
6093 : :
6094 [ + + + + ]: 654 : if (sample && totCount <= 1)
6095 : : {
6096 : 88 : *is_null = true;
6097 : 88 : return NULL;
6098 : : }
6099 : :
6100 : 566 : *is_null = false;
6101 : :
6102 : : /*
6103 : : * Deal with NaN and infinity cases. By analogy to the behavior of the
6104 : : * float8 functions, any infinity input produces NaN output.
6105 : : */
6106 [ + + + + : 566 : if (state->NaNcount > 0 || state->pInfcount > 0 || state->nInfcount > 0)
+ + ]
6107 : 36 : return make_result(&const_nan);
6108 : :
6109 : : /* OK, normal calculation applies */
6110 : 530 : init_var(&vN);
6111 : 530 : init_var(&vsumX);
6112 : 530 : init_var(&vsumX2);
6113 : :
6114 : 530 : int64_to_numericvar(state->N, &vN);
6115 : 530 : accum_sum_final(&(state->sumX), &vsumX);
6116 : 530 : accum_sum_final(&(state->sumX2), &vsumX2);
6117 : :
6118 : 530 : init_var(&vNminus1);
6119 : 530 : sub_var(&vN, &const_one, &vNminus1);
6120 : :
6121 : : /* compute rscale for mul_var calls */
6122 : 530 : rscale = vsumX.dscale * 2;
6123 : :
6124 : 530 : mul_var(&vsumX, &vsumX, &vsumX, rscale); /* vsumX = sumX * sumX */
6125 : 530 : mul_var(&vN, &vsumX2, &vsumX2, rscale); /* vsumX2 = N * sumX2 */
6126 : 530 : sub_var(&vsumX2, &vsumX, &vsumX2); /* N * sumX2 - sumX * sumX */
6127 : :
6128 [ + + ]: 530 : if (cmp_var(&vsumX2, &const_zero) <= 0)
6129 : : {
6130 : : /* Watch out for roundoff error producing a negative numerator */
6131 : 50 : res = make_result(&const_zero);
6132 : : }
6133 : : else
6134 : : {
6135 [ + + ]: 480 : if (sample)
6136 : 328 : mul_var(&vN, &vNminus1, &vNminus1, 0); /* N * (N - 1) */
6137 : : else
6138 : 152 : mul_var(&vN, &vN, &vNminus1, 0); /* N * N */
6139 : 480 : rscale = select_div_scale(&vsumX2, &vNminus1);
6140 : 480 : div_var(&vsumX2, &vNminus1, &vsumX, rscale, true, true); /* variance */
6141 [ + + ]: 480 : if (!variance)
6142 : 252 : sqrt_var(&vsumX, &vsumX, rscale); /* stddev */
6143 : :
6144 : 480 : res = make_result(&vsumX);
6145 : : }
6146 : :
6147 : 530 : free_var(&vNminus1);
6148 : 530 : free_var(&vsumX);
6149 : 530 : free_var(&vsumX2);
6150 : :
6151 : 530 : return res;
6152 : : }
6153 : :
6154 : : Datum
6155 : 120 : numeric_var_samp(PG_FUNCTION_ARGS)
6156 : : {
6157 : : NumericAggState *state;
6158 : : Numeric res;
6159 : : bool is_null;
6160 : :
6161 [ + - ]: 120 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6162 : :
6163 : 120 : res = numeric_stddev_internal(state, true, true, &is_null);
6164 : :
6165 [ + + ]: 120 : if (is_null)
6166 : 28 : PG_RETURN_NULL();
6167 : : else
6168 : 92 : PG_RETURN_NUMERIC(res);
6169 : : }
6170 : :
6171 : : Datum
6172 : 116 : numeric_stddev_samp(PG_FUNCTION_ARGS)
6173 : : {
6174 : : NumericAggState *state;
6175 : : Numeric res;
6176 : : bool is_null;
6177 : :
6178 [ + - ]: 116 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6179 : :
6180 : 116 : res = numeric_stddev_internal(state, false, true, &is_null);
6181 : :
6182 [ + + ]: 116 : if (is_null)
6183 : 28 : PG_RETURN_NULL();
6184 : : else
6185 : 88 : PG_RETURN_NUMERIC(res);
6186 : : }
6187 : :
6188 : : Datum
6189 : 76 : numeric_var_pop(PG_FUNCTION_ARGS)
6190 : : {
6191 : : NumericAggState *state;
6192 : : Numeric res;
6193 : : bool is_null;
6194 : :
6195 [ + - ]: 76 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6196 : :
6197 : 76 : res = numeric_stddev_internal(state, true, false, &is_null);
6198 : :
6199 [ - + ]: 76 : if (is_null)
6200 : 0 : PG_RETURN_NULL();
6201 : : else
6202 : 76 : PG_RETURN_NUMERIC(res);
6203 : : }
6204 : :
6205 : : Datum
6206 : 64 : numeric_stddev_pop(PG_FUNCTION_ARGS)
6207 : : {
6208 : : NumericAggState *state;
6209 : : Numeric res;
6210 : : bool is_null;
6211 : :
6212 [ + - ]: 64 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6213 : :
6214 : 64 : res = numeric_stddev_internal(state, false, false, &is_null);
6215 : :
6216 [ - + ]: 64 : if (is_null)
6217 : 0 : PG_RETURN_NULL();
6218 : : else
6219 : 64 : PG_RETURN_NUMERIC(res);
6220 : : }
6221 : :
6222 : : static Numeric
6223 : 278 : numeric_poly_stddev_internal(Int128AggState *state,
6224 : : bool variance, bool sample,
6225 : : bool *is_null)
6226 : : {
6227 : : NumericAggState numstate;
6228 : : Numeric res;
6229 : :
6230 : : /* Initialize an empty agg state */
6231 : 278 : memset(&numstate, 0, sizeof(NumericAggState));
6232 : :
6233 [ + - ]: 278 : if (state)
6234 : : {
6235 : : NumericVar tmp_var;
6236 : :
6237 : 278 : numstate.N = state->N;
6238 : :
6239 : 278 : init_var(&tmp_var);
6240 : :
6241 : 278 : int128_to_numericvar(state->sumX, &tmp_var);
6242 : 278 : accum_sum_add(&numstate.sumX, &tmp_var);
6243 : :
6244 : 278 : int128_to_numericvar(state->sumX2, &tmp_var);
6245 : 278 : accum_sum_add(&numstate.sumX2, &tmp_var);
6246 : :
6247 : 278 : free_var(&tmp_var);
6248 : : }
6249 : :
6250 : 278 : res = numeric_stddev_internal(&numstate, variance, sample, is_null);
6251 : :
6252 [ + - ]: 278 : if (numstate.sumX.ndigits > 0)
6253 : : {
6254 : 278 : pfree(numstate.sumX.pos_digits);
6255 : 278 : pfree(numstate.sumX.neg_digits);
6256 : : }
6257 [ + - ]: 278 : if (numstate.sumX2.ndigits > 0)
6258 : : {
6259 : 278 : pfree(numstate.sumX2.pos_digits);
6260 : 278 : pfree(numstate.sumX2.neg_digits);
6261 : : }
6262 : :
6263 : 278 : return res;
6264 : : }
6265 : :
6266 : : Datum
6267 : 84 : numeric_poly_var_samp(PG_FUNCTION_ARGS)
6268 : : {
6269 : : Int128AggState *state;
6270 : : Numeric res;
6271 : : bool is_null;
6272 : :
6273 [ + - ]: 84 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
6274 : :
6275 : 84 : res = numeric_poly_stddev_internal(state, true, true, &is_null);
6276 : :
6277 [ + + ]: 84 : if (is_null)
6278 : 16 : PG_RETURN_NULL();
6279 : : else
6280 : 68 : PG_RETURN_NUMERIC(res);
6281 : : }
6282 : :
6283 : : Datum
6284 : 106 : numeric_poly_stddev_samp(PG_FUNCTION_ARGS)
6285 : : {
6286 : : Int128AggState *state;
6287 : : Numeric res;
6288 : : bool is_null;
6289 : :
6290 [ + - ]: 106 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
6291 : :
6292 : 106 : res = numeric_poly_stddev_internal(state, false, true, &is_null);
6293 : :
6294 [ + + ]: 106 : if (is_null)
6295 : 16 : PG_RETURN_NULL();
6296 : : else
6297 : 90 : PG_RETURN_NUMERIC(res);
6298 : : }
6299 : :
6300 : : Datum
6301 : 40 : numeric_poly_var_pop(PG_FUNCTION_ARGS)
6302 : : {
6303 : : Int128AggState *state;
6304 : : Numeric res;
6305 : : bool is_null;
6306 : :
6307 [ + - ]: 40 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
6308 : :
6309 : 40 : res = numeric_poly_stddev_internal(state, true, false, &is_null);
6310 : :
6311 [ - + ]: 40 : if (is_null)
6312 : 0 : PG_RETURN_NULL();
6313 : : else
6314 : 40 : PG_RETURN_NUMERIC(res);
6315 : : }
6316 : :
6317 : : Datum
6318 : 48 : numeric_poly_stddev_pop(PG_FUNCTION_ARGS)
6319 : : {
6320 : : Int128AggState *state;
6321 : : Numeric res;
6322 : : bool is_null;
6323 : :
6324 [ + - ]: 48 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
6325 : :
6326 : 48 : res = numeric_poly_stddev_internal(state, false, false, &is_null);
6327 : :
6328 [ - + ]: 48 : if (is_null)
6329 : 0 : PG_RETURN_NULL();
6330 : : else
6331 : 48 : PG_RETURN_NUMERIC(res);
6332 : : }
6333 : :
6334 : : /*
6335 : : * SUM transition functions for integer datatypes.
6336 : : *
6337 : : * To avoid overflow, we use accumulators wider than the input datatype.
6338 : : * A Numeric accumulator is needed for int8 input; for int4 and int2
6339 : : * inputs, we use int8 accumulators which should be sufficient for practical
6340 : : * purposes. (The latter two therefore don't really belong in this file,
6341 : : * but we keep them here anyway.)
6342 : : *
6343 : : * Because SQL defines the SUM() of no values to be NULL, not zero,
6344 : : * the initial condition of the transition data value needs to be NULL. This
6345 : : * means we can't rely on ExecAgg to automatically insert the first non-null
6346 : : * data value into the transition data: it doesn't know how to do the type
6347 : : * conversion. The upshot is that these routines have to be marked non-strict
6348 : : * and handle substitution of the first non-null input themselves.
6349 : : *
6350 : : * Note: these functions are used only in plain aggregation mode.
6351 : : * In moving-aggregate mode, we use intX_avg_accum and intX_avg_accum_inv.
6352 : : */
6353 : :
6354 : : Datum
6355 : 16 : int2_sum(PG_FUNCTION_ARGS)
6356 : : {
6357 : : int64 oldsum;
6358 : : int64 newval;
6359 : :
6360 [ - + ]: 16 : if (PG_ARGISNULL(1))
6361 : : {
6362 : : /* NULL value being aggregated, so return state unchanged */
6363 : 0 : PG_RETURN_ARG(0);
6364 : : }
6365 : :
6366 [ + + ]: 16 : if (PG_ARGISNULL(0))
6367 : : {
6368 : : /* This is the first non-null input. */
6369 : 4 : PG_RETURN_INT64((int64) PG_GETARG_INT16(1));
6370 : : }
6371 : :
6372 : 12 : oldsum = PG_GETARG_INT64(0);
6373 : :
6374 : : /* OK to do the addition. */
6375 [ - + ]: 12 : if (unlikely(pg_add_s64_overflow(oldsum, (int64) PG_GETARG_INT16(1),
6376 : : &newval)))
6377 [ # # ]: 0 : ereport(ERROR,
6378 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
6379 : : errmsg("bigint out of range")));
6380 : :
6381 : 12 : PG_RETURN_INT64(newval);
6382 : : }
6383 : :
6384 : : Datum
6385 : 3412740 : int4_sum(PG_FUNCTION_ARGS)
6386 : : {
6387 : : int64 oldsum;
6388 : : int64 newval;
6389 : :
6390 [ + + ]: 3412740 : if (PG_ARGISNULL(1))
6391 : : {
6392 : : /* NULL value being aggregated, so return state unchanged */
6393 : 21260 : PG_RETURN_ARG(0);
6394 : : }
6395 : :
6396 [ + + ]: 3391480 : if (PG_ARGISNULL(0))
6397 : : {
6398 : : /* This is the first non-null input. */
6399 : 128636 : PG_RETURN_INT64((int64) PG_GETARG_INT32(1));
6400 : : }
6401 : :
6402 : 3262844 : oldsum = PG_GETARG_INT64(0);
6403 : :
6404 : : /* OK to do the addition. */
6405 [ - + ]: 3262844 : if (unlikely(pg_add_s64_overflow(oldsum, (int64) PG_GETARG_INT32(1),
6406 : : &newval)))
6407 [ # # ]: 0 : ereport(ERROR,
6408 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
6409 : : errmsg("bigint out of range")));
6410 : :
6411 : 3262844 : PG_RETURN_INT64(newval);
6412 : : }
6413 : :
6414 : : /*
6415 : : * Note: this function is obsolete, it's no longer used for SUM(int8).
6416 : : */
6417 : : Datum
6418 : 0 : int8_sum(PG_FUNCTION_ARGS)
6419 : : {
6420 : : Numeric oldsum;
6421 : :
6422 [ # # ]: 0 : if (PG_ARGISNULL(0))
6423 : : {
6424 : : /* No non-null input seen so far... */
6425 [ # # ]: 0 : if (PG_ARGISNULL(1))
6426 : 0 : PG_RETURN_NULL(); /* still no non-null */
6427 : : /* This is the first non-null input. */
6428 : 0 : PG_RETURN_NUMERIC(int64_to_numeric(PG_GETARG_INT64(1)));
6429 : : }
6430 : :
6431 : 0 : oldsum = PG_GETARG_NUMERIC(0);
6432 : :
6433 : : /* Leave sum unchanged if new input is null. */
6434 [ # # ]: 0 : if (PG_ARGISNULL(1))
6435 : 0 : PG_RETURN_NUMERIC(oldsum);
6436 : :
6437 : : /* OK to do the addition. */
6438 : 0 : PG_RETURN_DATUM(DirectFunctionCall2(numeric_add,
6439 : : NumericGetDatum(oldsum),
6440 : : NumericGetDatum(int64_to_numeric(PG_GETARG_INT64(1)))));
6441 : : }
6442 : :
6443 : :
6444 : : /*
6445 : : * Routines for avg(int2) and avg(int4). The transition datatype
6446 : : * is a two-element int8 array, holding count and sum.
6447 : : *
6448 : : * These functions are also used for sum(int2) and sum(int4) when
6449 : : * operating in moving-aggregate mode, since for correct inverse transitions
6450 : : * we need to count the inputs.
6451 : : */
6452 : :
6453 : : typedef struct Int8TransTypeData
6454 : : {
6455 : : int64 count;
6456 : : int64 sum;
6457 : : } Int8TransTypeData;
6458 : :
6459 : : Datum
6460 : 28 : int2_avg_accum(PG_FUNCTION_ARGS)
6461 : : {
6462 : : ArrayType *transarray;
6463 : 28 : int16 newval = PG_GETARG_INT16(1);
6464 : : Int8TransTypeData *transdata;
6465 : : int64 newsum;
6466 : :
6467 : : /*
6468 : : * If we're invoked as an aggregate, we can cheat and modify our first
6469 : : * parameter in-place to reduce palloc overhead. Otherwise we need to make
6470 : : * a copy of it before scribbling on it.
6471 : : */
6472 [ + - ]: 28 : if (AggCheckCallContext(fcinfo, NULL))
6473 : 28 : transarray = PG_GETARG_ARRAYTYPE_P(0);
6474 : : else
6475 : 0 : transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6476 : :
6477 [ + - - + ]: 56 : if (ARR_HASNULL(transarray) ||
6478 : 28 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6479 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6480 : :
6481 [ - + ]: 28 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6482 : :
6483 [ - + ]: 28 : if (unlikely(pg_add_s64_overflow(transdata->sum, (int64) newval, &newsum)))
6484 [ # # ]: 0 : ereport(ERROR,
6485 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
6486 : : errmsg("bigint out of range")));
6487 : :
6488 : 28 : transdata->count++;
6489 : 28 : transdata->sum = newsum;
6490 : :
6491 : 28 : PG_RETURN_ARRAYTYPE_P(transarray);
6492 : : }
6493 : :
6494 : : Datum
6495 : 1744070 : int4_avg_accum(PG_FUNCTION_ARGS)
6496 : : {
6497 : : ArrayType *transarray;
6498 : 1744070 : int32 newval = PG_GETARG_INT32(1);
6499 : : Int8TransTypeData *transdata;
6500 : : int64 newsum;
6501 : :
6502 : : /*
6503 : : * If we're invoked as an aggregate, we can cheat and modify our first
6504 : : * parameter in-place to reduce palloc overhead. Otherwise we need to make
6505 : : * a copy of it before scribbling on it.
6506 : : */
6507 [ + - ]: 1744070 : if (AggCheckCallContext(fcinfo, NULL))
6508 : 1744070 : transarray = PG_GETARG_ARRAYTYPE_P(0);
6509 : : else
6510 : 0 : transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6511 : :
6512 [ + - - + ]: 3488140 : if (ARR_HASNULL(transarray) ||
6513 : 1744070 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6514 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6515 : :
6516 [ - + ]: 1744070 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6517 : :
6518 [ - + ]: 1744070 : if (unlikely(pg_add_s64_overflow(transdata->sum, (int64) newval, &newsum)))
6519 [ # # ]: 0 : ereport(ERROR,
6520 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
6521 : : errmsg("bigint out of range")));
6522 : :
6523 : 1744070 : transdata->count++;
6524 : 1744070 : transdata->sum = newsum;
6525 : :
6526 : 1744070 : PG_RETURN_ARRAYTYPE_P(transarray);
6527 : : }
6528 : :
6529 : : Datum
6530 : 6641 : int4_avg_combine(PG_FUNCTION_ARGS)
6531 : : {
6532 : : ArrayType *transarray1;
6533 : : ArrayType *transarray2;
6534 : : Int8TransTypeData *state1;
6535 : : Int8TransTypeData *state2;
6536 : : int64 newsum;
6537 : :
6538 [ - + ]: 6641 : if (!AggCheckCallContext(fcinfo, NULL))
6539 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
6540 : :
6541 : 6641 : transarray1 = PG_GETARG_ARRAYTYPE_P(0);
6542 : 6641 : transarray2 = PG_GETARG_ARRAYTYPE_P(1);
6543 : :
6544 [ + - - + ]: 13282 : if (ARR_HASNULL(transarray1) ||
6545 : 6641 : ARR_SIZE(transarray1) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6546 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6547 : :
6548 [ + - - + ]: 13282 : if (ARR_HASNULL(transarray2) ||
6549 : 6641 : ARR_SIZE(transarray2) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6550 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6551 : :
6552 [ - + ]: 6641 : state1 = (Int8TransTypeData *) ARR_DATA_PTR(transarray1);
6553 [ - + ]: 6641 : state2 = (Int8TransTypeData *) ARR_DATA_PTR(transarray2);
6554 : :
6555 [ - + ]: 6641 : if (unlikely(pg_add_s64_overflow(state1->sum, state2->sum, &newsum)))
6556 [ # # ]: 0 : ereport(ERROR,
6557 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
6558 : : errmsg("bigint out of range")));
6559 : :
6560 : 6641 : state1->count += state2->count;
6561 : 6641 : state1->sum = newsum;
6562 : :
6563 : 6641 : PG_RETURN_ARRAYTYPE_P(transarray1);
6564 : : }
6565 : :
6566 : : Datum
6567 : 8 : int2_avg_accum_inv(PG_FUNCTION_ARGS)
6568 : : {
6569 : : ArrayType *transarray;
6570 : 8 : int16 newval = PG_GETARG_INT16(1);
6571 : : Int8TransTypeData *transdata;
6572 : :
6573 : : /*
6574 : : * If we're invoked as an aggregate, we can cheat and modify our first
6575 : : * parameter in-place to reduce palloc overhead. Otherwise we need to make
6576 : : * a copy of it before scribbling on it.
6577 : : */
6578 [ + - ]: 8 : if (AggCheckCallContext(fcinfo, NULL))
6579 : 8 : transarray = PG_GETARG_ARRAYTYPE_P(0);
6580 : : else
6581 : 0 : transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6582 : :
6583 [ + - - + ]: 16 : if (ARR_HASNULL(transarray) ||
6584 : 8 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6585 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6586 : :
6587 [ - + ]: 8 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6588 : 8 : transdata->count--;
6589 : 8 : transdata->sum -= newval;
6590 : :
6591 : 8 : PG_RETURN_ARRAYTYPE_P(transarray);
6592 : : }
6593 : :
6594 : : Datum
6595 : 1000 : int4_avg_accum_inv(PG_FUNCTION_ARGS)
6596 : : {
6597 : : ArrayType *transarray;
6598 : 1000 : int32 newval = PG_GETARG_INT32(1);
6599 : : Int8TransTypeData *transdata;
6600 : :
6601 : : /*
6602 : : * If we're invoked as an aggregate, we can cheat and modify our first
6603 : : * parameter in-place to reduce palloc overhead. Otherwise we need to make
6604 : : * a copy of it before scribbling on it.
6605 : : */
6606 [ + - ]: 1000 : if (AggCheckCallContext(fcinfo, NULL))
6607 : 1000 : transarray = PG_GETARG_ARRAYTYPE_P(0);
6608 : : else
6609 : 0 : transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6610 : :
6611 [ + - - + ]: 2000 : if (ARR_HASNULL(transarray) ||
6612 : 1000 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6613 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6614 : :
6615 [ - + ]: 1000 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6616 : 1000 : transdata->count--;
6617 : 1000 : transdata->sum -= newval;
6618 : :
6619 : 1000 : PG_RETURN_ARRAYTYPE_P(transarray);
6620 : : }
6621 : :
6622 : : Datum
6623 : 6817 : int8_avg(PG_FUNCTION_ARGS)
6624 : : {
6625 : 6817 : ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
6626 : : Int8TransTypeData *transdata;
6627 : : Datum countd,
6628 : : sumd;
6629 : :
6630 [ + - - + ]: 13634 : if (ARR_HASNULL(transarray) ||
6631 : 6817 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6632 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6633 [ - + ]: 6817 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6634 : :
6635 : : /* SQL defines AVG of no values to be NULL */
6636 [ + + ]: 6817 : if (transdata->count == 0)
6637 : 73 : PG_RETURN_NULL();
6638 : :
6639 : 6744 : countd = NumericGetDatum(int64_to_numeric(transdata->count));
6640 : 6744 : sumd = NumericGetDatum(int64_to_numeric(transdata->sum));
6641 : :
6642 : 6744 : PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumd, countd));
6643 : : }
6644 : :
6645 : : /*
6646 : : * SUM(int2) and SUM(int4) both return int8, so we can use this
6647 : : * final function for both.
6648 : : */
6649 : : Datum
6650 : 2716 : int2int4_sum(PG_FUNCTION_ARGS)
6651 : : {
6652 : 2716 : ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
6653 : : Int8TransTypeData *transdata;
6654 : :
6655 [ + - - + ]: 5432 : if (ARR_HASNULL(transarray) ||
6656 : 2716 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6657 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6658 [ - + ]: 2716 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6659 : :
6660 : : /* SQL defines SUM of no values to be NULL */
6661 [ + + ]: 2716 : if (transdata->count == 0)
6662 : 404 : PG_RETURN_NULL();
6663 : :
6664 : 2312 : PG_RETURN_DATUM(Int64GetDatumFast(transdata->sum));
6665 : : }
6666 : :
6667 : :
6668 : : /* ----------------------------------------------------------------------
6669 : : *
6670 : : * Debug support
6671 : : *
6672 : : * ----------------------------------------------------------------------
6673 : : */
6674 : :
6675 : : #ifdef NUMERIC_DEBUG
6676 : :
6677 : : /*
6678 : : * dump_numeric() - Dump a value in the db storage format for debugging
6679 : : */
6680 : : static void
6681 : : dump_numeric(const char *str, Numeric num)
6682 : : {
6683 : : NumericDigit *digits = NUMERIC_DIGITS(num);
6684 : : int ndigits;
6685 : : int i;
6686 : :
6687 : : ndigits = NUMERIC_NDIGITS(num);
6688 : :
6689 : : printf("%s: NUMERIC w=%d d=%d ", str,
6690 : : NUMERIC_WEIGHT(num), NUMERIC_DSCALE(num));
6691 : : switch (NUMERIC_SIGN(num))
6692 : : {
6693 : : case NUMERIC_POS:
6694 : : printf("POS");
6695 : : break;
6696 : : case NUMERIC_NEG:
6697 : : printf("NEG");
6698 : : break;
6699 : : case NUMERIC_NAN:
6700 : : printf("NaN");
6701 : : break;
6702 : : case NUMERIC_PINF:
6703 : : printf("Infinity");
6704 : : break;
6705 : : case NUMERIC_NINF:
6706 : : printf("-Infinity");
6707 : : break;
6708 : : default:
6709 : : printf("SIGN=0x%x", NUMERIC_SIGN(num));
6710 : : break;
6711 : : }
6712 : :
6713 : : for (i = 0; i < ndigits; i++)
6714 : : printf(" %0*d", DEC_DIGITS, digits[i]);
6715 : : printf("\n");
6716 : : }
6717 : :
6718 : :
6719 : : /*
6720 : : * dump_var() - Dump a value in the variable format for debugging
6721 : : */
6722 : : static void
6723 : : dump_var(const char *str, NumericVar *var)
6724 : : {
6725 : : int i;
6726 : :
6727 : : printf("%s: VAR w=%d d=%d ", str, var->weight, var->dscale);
6728 : : switch (var->sign)
6729 : : {
6730 : : case NUMERIC_POS:
6731 : : printf("POS");
6732 : : break;
6733 : : case NUMERIC_NEG:
6734 : : printf("NEG");
6735 : : break;
6736 : : case NUMERIC_NAN:
6737 : : printf("NaN");
6738 : : break;
6739 : : case NUMERIC_PINF:
6740 : : printf("Infinity");
6741 : : break;
6742 : : case NUMERIC_NINF:
6743 : : printf("-Infinity");
6744 : : break;
6745 : : default:
6746 : : printf("SIGN=0x%x", var->sign);
6747 : : break;
6748 : : }
6749 : :
6750 : : for (i = 0; i < var->ndigits; i++)
6751 : : printf(" %0*d", DEC_DIGITS, var->digits[i]);
6752 : :
6753 : : printf("\n");
6754 : : }
6755 : : #endif /* NUMERIC_DEBUG */
6756 : :
6757 : :
6758 : : /* ----------------------------------------------------------------------
6759 : : *
6760 : : * Local functions follow
6761 : : *
6762 : : * In general, these do not support "special" (NaN or infinity) inputs;
6763 : : * callers should handle those possibilities first.
6764 : : * (There are one or two exceptions, noted in their header comments.)
6765 : : *
6766 : : * ----------------------------------------------------------------------
6767 : : */
6768 : :
6769 : :
6770 : : /*
6771 : : * alloc_var() -
6772 : : *
6773 : : * Allocate a digit buffer of ndigits digits (plus a spare digit for rounding)
6774 : : */
6775 : : static void
6776 : 1456894 : alloc_var(NumericVar *var, int ndigits)
6777 : : {
6778 [ + + ]: 1456894 : digitbuf_free(var->buf);
6779 : 1456894 : var->buf = digitbuf_alloc(ndigits + 1);
6780 : 1456894 : var->buf[0] = 0; /* spare digit for rounding */
6781 : 1456894 : var->digits = var->buf + 1;
6782 : 1456894 : var->ndigits = ndigits;
6783 : 1456894 : }
6784 : :
6785 : :
6786 : : /*
6787 : : * free_var() -
6788 : : *
6789 : : * Return the digit buffer of a variable to the free pool
6790 : : */
6791 : : static void
6792 : 2793226 : free_var(NumericVar *var)
6793 : : {
6794 [ + + ]: 2793226 : digitbuf_free(var->buf);
6795 : 2793226 : var->buf = NULL;
6796 : 2793226 : var->digits = NULL;
6797 : 2793226 : var->sign = NUMERIC_NAN;
6798 : 2793226 : }
6799 : :
6800 : :
6801 : : /*
6802 : : * zero_var() -
6803 : : *
6804 : : * Set a variable to ZERO.
6805 : : * Note: its dscale is not touched.
6806 : : */
6807 : : static void
6808 : 37759 : zero_var(NumericVar *var)
6809 : : {
6810 [ + + ]: 37759 : digitbuf_free(var->buf);
6811 : 37759 : var->buf = NULL;
6812 : 37759 : var->digits = NULL;
6813 : 37759 : var->ndigits = 0;
6814 : 37759 : var->weight = 0; /* by convention; doesn't really matter */
6815 : 37759 : var->sign = NUMERIC_POS; /* anything but NAN... */
6816 : 37759 : }
6817 : :
6818 : :
6819 : : /*
6820 : : * set_var_from_str()
6821 : : *
6822 : : * Parse a string and put the number into a variable
6823 : : *
6824 : : * This function does not handle leading or trailing spaces. It returns
6825 : : * the end+1 position parsed into *endptr, so that caller can check for
6826 : : * trailing spaces/garbage if deemed necessary.
6827 : : *
6828 : : * cp is the place to actually start parsing; str is what to use in error
6829 : : * reports. (Typically cp would be the same except advanced over spaces.)
6830 : : *
6831 : : * Returns true on success, false on failure (if escontext points to an
6832 : : * ErrorSaveContext; otherwise errors are thrown).
6833 : : */
6834 : : static bool
6835 : 129426 : set_var_from_str(const char *str, const char *cp,
6836 : : NumericVar *dest, const char **endptr,
6837 : : Node *escontext)
6838 : : {
6839 : 129426 : bool have_dp = false;
6840 : : int i;
6841 : : unsigned char *decdigits;
6842 : 129426 : int sign = NUMERIC_POS;
6843 : 129426 : int dweight = -1;
6844 : : int ddigits;
6845 : 129426 : int dscale = 0;
6846 : : int weight;
6847 : : int ndigits;
6848 : : int offset;
6849 : : NumericDigit *digits;
6850 : :
6851 : : /*
6852 : : * We first parse the string to extract decimal digits and determine the
6853 : : * correct decimal weight. Then convert to NBASE representation.
6854 : : */
6855 [ - + + ]: 129426 : switch (*cp)
6856 : : {
6857 : 0 : case '+':
6858 : 0 : sign = NUMERIC_POS;
6859 : 0 : cp++;
6860 : 0 : break;
6861 : :
6862 : 183 : case '-':
6863 : 183 : sign = NUMERIC_NEG;
6864 : 183 : cp++;
6865 : 183 : break;
6866 : : }
6867 : :
6868 [ + + ]: 129426 : if (*cp == '.')
6869 : : {
6870 : 253 : have_dp = true;
6871 : 253 : cp++;
6872 : : }
6873 : :
6874 [ - + ]: 129426 : if (!isdigit((unsigned char) *cp))
6875 : 0 : goto invalid_syntax;
6876 : :
6877 : 129426 : decdigits = (unsigned char *) palloc(strlen(cp) + DEC_DIGITS * 2);
6878 : :
6879 : : /* leading padding for digit alignment later */
6880 : 129426 : memset(decdigits, 0, DEC_DIGITS);
6881 : 129426 : i = DEC_DIGITS;
6882 : :
6883 [ + + ]: 546678 : while (*cp)
6884 : : {
6885 [ + + ]: 418334 : if (isdigit((unsigned char) *cp))
6886 : : {
6887 : 405180 : decdigits[i++] = *cp++ - '0';
6888 [ + + ]: 405180 : if (!have_dp)
6889 : 343260 : dweight++;
6890 : : else
6891 : 61920 : dscale++;
6892 : : }
6893 [ + + ]: 13154 : else if (*cp == '.')
6894 : : {
6895 [ - + ]: 11964 : if (have_dp)
6896 : 0 : goto invalid_syntax;
6897 : 11964 : have_dp = true;
6898 : 11964 : cp++;
6899 : : /* decimal point must not be followed by underscore */
6900 [ + + ]: 11964 : if (*cp == '_')
6901 : 4 : goto invalid_syntax;
6902 : : }
6903 [ + + ]: 1190 : else if (*cp == '_')
6904 : : {
6905 : : /* underscore must be followed by more digits */
6906 : 124 : cp++;
6907 [ + + ]: 124 : if (!isdigit((unsigned char) *cp))
6908 : 12 : goto invalid_syntax;
6909 : : }
6910 : : else
6911 : 1066 : break;
6912 : : }
6913 : :
6914 : 129410 : ddigits = i - DEC_DIGITS;
6915 : : /* trailing padding for digit alignment later */
6916 : 129410 : memset(decdigits + i, 0, DEC_DIGITS - 1);
6917 : :
6918 : : /* Handle exponent, if any */
6919 [ + + + + ]: 129410 : if (*cp == 'e' || *cp == 'E')
6920 : : {
6921 : 1034 : int64 exponent = 0;
6922 : 1034 : bool neg = false;
6923 : :
6924 : : /*
6925 : : * At this point, dweight and dscale can't be more than about
6926 : : * INT_MAX/2 due to the MaxAllocSize limit on string length, so
6927 : : * constraining the exponent similarly should be enough to prevent
6928 : : * integer overflow in this function. If the value is too large to
6929 : : * fit in storage format, make_result() will complain about it later;
6930 : : * for consistency use the same ereport errcode/text as make_result().
6931 : : */
6932 : :
6933 : : /* exponent sign */
6934 : 1034 : cp++;
6935 [ + + ]: 1034 : if (*cp == '+')
6936 : 102 : cp++;
6937 [ + + ]: 932 : else if (*cp == '-')
6938 : : {
6939 : 456 : neg = true;
6940 : 456 : cp++;
6941 : : }
6942 : :
6943 : : /* exponent digits */
6944 [ + + ]: 1034 : if (!isdigit((unsigned char) *cp))
6945 : 4 : goto invalid_syntax;
6946 : :
6947 [ + + ]: 3593 : while (*cp)
6948 : : {
6949 [ + + ]: 2575 : if (isdigit((unsigned char) *cp))
6950 : : {
6951 : 2547 : exponent = exponent * 10 + (*cp++ - '0');
6952 [ + + ]: 2547 : if (exponent > PG_INT32_MAX / 2)
6953 : 4 : goto out_of_range;
6954 : : }
6955 [ + - ]: 28 : else if (*cp == '_')
6956 : : {
6957 : : /* underscore must be followed by more digits */
6958 : 28 : cp++;
6959 [ + + ]: 28 : if (!isdigit((unsigned char) *cp))
6960 : 8 : goto invalid_syntax;
6961 : : }
6962 : : else
6963 : 0 : break;
6964 : : }
6965 : :
6966 [ + + ]: 1018 : if (neg)
6967 : 456 : exponent = -exponent;
6968 : :
6969 : 1018 : dweight += (int) exponent;
6970 : 1018 : dscale -= (int) exponent;
6971 [ + + ]: 1018 : if (dscale < 0)
6972 : 426 : dscale = 0;
6973 : : }
6974 : :
6975 : : /*
6976 : : * Okay, convert pure-decimal representation to base NBASE. First we need
6977 : : * to determine the converted weight and ndigits. offset is the number of
6978 : : * decimal zeroes to insert before the first given digit to have a
6979 : : * correctly aligned first NBASE digit.
6980 : : */
6981 [ + + ]: 129394 : if (dweight >= 0)
6982 : 128753 : weight = (dweight + 1 + DEC_DIGITS - 1) / DEC_DIGITS - 1;
6983 : : else
6984 : 641 : weight = -((-dweight - 1) / DEC_DIGITS + 1);
6985 : 129394 : offset = (weight + 1) * DEC_DIGITS - (dweight + 1);
6986 : 129394 : ndigits = (ddigits + offset + DEC_DIGITS - 1) / DEC_DIGITS;
6987 : :
6988 : 129394 : alloc_var(dest, ndigits);
6989 : 129394 : dest->sign = sign;
6990 : 129394 : dest->weight = weight;
6991 : 129394 : dest->dscale = dscale;
6992 : :
6993 : 129394 : i = DEC_DIGITS - offset;
6994 : 129394 : digits = dest->digits;
6995 : :
6996 [ + + ]: 307245 : while (ndigits-- > 0)
6997 : : {
6998 : : #if DEC_DIGITS == 4
6999 : 177851 : *digits++ = ((decdigits[i] * 10 + decdigits[i + 1]) * 10 +
7000 : 177851 : decdigits[i + 2]) * 10 + decdigits[i + 3];
7001 : : #elif DEC_DIGITS == 2
7002 : : *digits++ = decdigits[i] * 10 + decdigits[i + 1];
7003 : : #elif DEC_DIGITS == 1
7004 : : *digits++ = decdigits[i];
7005 : : #else
7006 : : #error unsupported NBASE
7007 : : #endif
7008 : 177851 : i += DEC_DIGITS;
7009 : : }
7010 : :
7011 : 129394 : pfree(decdigits);
7012 : :
7013 : : /* Strip any leading/trailing zeroes, and normalize weight if zero */
7014 : 129394 : strip_var(dest);
7015 : :
7016 : : /* Return end+1 position for caller */
7017 : 129394 : *endptr = cp;
7018 : :
7019 : 129394 : return true;
7020 : :
7021 : 4 : out_of_range:
7022 [ + - ]: 4 : ereturn(escontext, false,
7023 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7024 : : errmsg("value overflows numeric format")));
7025 : :
7026 : 28 : invalid_syntax:
7027 [ + - ]: 28 : ereturn(escontext, false,
7028 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
7029 : : errmsg("invalid input syntax for type %s: \"%s\"",
7030 : : "numeric", str)));
7031 : : }
7032 : :
7033 : :
7034 : : /*
7035 : : * Return the numeric value of a single hex digit.
7036 : : */
7037 : : static inline int
7038 : 472 : xdigit_value(char dig)
7039 : : {
7040 [ + - + + ]: 596 : return dig >= '0' && dig <= '9' ? dig - '0' :
7041 [ + + + - ]: 196 : dig >= 'a' && dig <= 'f' ? dig - 'a' + 10 :
7042 [ + - + - ]: 72 : dig >= 'A' && dig <= 'F' ? dig - 'A' + 10 : -1;
7043 : : }
7044 : :
7045 : : /*
7046 : : * set_var_from_non_decimal_integer_str()
7047 : : *
7048 : : * Parse a string containing a non-decimal integer
7049 : : *
7050 : : * This function does not handle leading or trailing spaces. It returns
7051 : : * the end+1 position parsed into *endptr, so that caller can check for
7052 : : * trailing spaces/garbage if deemed necessary.
7053 : : *
7054 : : * cp is the place to actually start parsing; str is what to use in error
7055 : : * reports. The number's sign and base prefix indicator (e.g., "0x") are
7056 : : * assumed to have already been parsed, so cp should point to the number's
7057 : : * first digit in the base specified.
7058 : : *
7059 : : * base is expected to be 2, 8 or 16.
7060 : : *
7061 : : * Returns true on success, false on failure (if escontext points to an
7062 : : * ErrorSaveContext; otherwise errors are thrown).
7063 : : */
7064 : : static bool
7065 : 104 : set_var_from_non_decimal_integer_str(const char *str, const char *cp, int sign,
7066 : : int base, NumericVar *dest,
7067 : : const char **endptr, Node *escontext)
7068 : : {
7069 : 104 : const char *firstdigit = cp;
7070 : : int64 tmp;
7071 : : int64 mul;
7072 : : NumericVar tmp_var;
7073 : :
7074 : 104 : init_var(&tmp_var);
7075 : :
7076 : 104 : zero_var(dest);
7077 : :
7078 : : /*
7079 : : * Process input digits in groups that fit in int64. Here "tmp" is the
7080 : : * value of the digits in the group, and "mul" is base^n, where n is the
7081 : : * number of digits in the group. Thus tmp < mul, and we must start a new
7082 : : * group when mul * base threatens to overflow PG_INT64_MAX.
7083 : : */
7084 : 104 : tmp = 0;
7085 : 104 : mul = 1;
7086 : :
7087 [ + + ]: 104 : if (base == 16)
7088 : : {
7089 [ + + ]: 552 : while (*cp)
7090 : : {
7091 [ + + ]: 532 : if (isxdigit((unsigned char) *cp))
7092 : : {
7093 [ + + ]: 472 : if (mul > PG_INT64_MAX / 16)
7094 : : {
7095 : : /* Add the contribution from this group of digits */
7096 : 20 : int64_to_numericvar(mul, &tmp_var);
7097 : 20 : mul_var(dest, &tmp_var, dest, 0);
7098 : 20 : int64_to_numericvar(tmp, &tmp_var);
7099 : 20 : add_var(dest, &tmp_var, dest);
7100 : :
7101 : : /* Result will overflow if weight overflows int16 */
7102 [ - + ]: 20 : if (dest->weight > NUMERIC_WEIGHT_MAX)
7103 : 0 : goto out_of_range;
7104 : :
7105 : : /* Begin a new group */
7106 : 20 : tmp = 0;
7107 : 20 : mul = 1;
7108 : : }
7109 : :
7110 : 472 : tmp = tmp * 16 + xdigit_value(*cp++);
7111 : 472 : mul = mul * 16;
7112 : : }
7113 [ + + ]: 60 : else if (*cp == '_')
7114 : : {
7115 : : /* Underscore must be followed by more digits */
7116 : 44 : cp++;
7117 [ + + ]: 44 : if (!isxdigit((unsigned char) *cp))
7118 : 12 : goto invalid_syntax;
7119 : : }
7120 : : else
7121 : 16 : break;
7122 : : }
7123 : : }
7124 [ + + ]: 56 : else if (base == 8)
7125 : : {
7126 [ + + ]: 424 : while (*cp)
7127 : : {
7128 [ + + + + ]: 404 : if (*cp >= '0' && *cp <= '7')
7129 : : {
7130 [ + + ]: 372 : if (mul > PG_INT64_MAX / 8)
7131 : : {
7132 : : /* Add the contribution from this group of digits */
7133 : 12 : int64_to_numericvar(mul, &tmp_var);
7134 : 12 : mul_var(dest, &tmp_var, dest, 0);
7135 : 12 : int64_to_numericvar(tmp, &tmp_var);
7136 : 12 : add_var(dest, &tmp_var, dest);
7137 : :
7138 : : /* Result will overflow if weight overflows int16 */
7139 [ - + ]: 12 : if (dest->weight > NUMERIC_WEIGHT_MAX)
7140 : 0 : goto out_of_range;
7141 : :
7142 : : /* Begin a new group */
7143 : 12 : tmp = 0;
7144 : 12 : mul = 1;
7145 : : }
7146 : :
7147 : 372 : tmp = tmp * 8 + (*cp++ - '0');
7148 : 372 : mul = mul * 8;
7149 : : }
7150 [ + + ]: 32 : else if (*cp == '_')
7151 : : {
7152 : : /* Underscore must be followed by more digits */
7153 : 24 : cp++;
7154 [ + - - + ]: 24 : if (*cp < '0' || *cp > '7')
7155 : 0 : goto invalid_syntax;
7156 : : }
7157 : : else
7158 : 8 : break;
7159 : : }
7160 : : }
7161 [ + - ]: 28 : else if (base == 2)
7162 : : {
7163 [ + + ]: 1040 : while (*cp)
7164 : : {
7165 [ + + + + ]: 1020 : if (*cp >= '0' && *cp <= '1')
7166 : : {
7167 [ + + ]: 944 : if (mul > PG_INT64_MAX / 2)
7168 : : {
7169 : : /* Add the contribution from this group of digits */
7170 : 12 : int64_to_numericvar(mul, &tmp_var);
7171 : 12 : mul_var(dest, &tmp_var, dest, 0);
7172 : 12 : int64_to_numericvar(tmp, &tmp_var);
7173 : 12 : add_var(dest, &tmp_var, dest);
7174 : :
7175 : : /* Result will overflow if weight overflows int16 */
7176 [ - + ]: 12 : if (dest->weight > NUMERIC_WEIGHT_MAX)
7177 : 0 : goto out_of_range;
7178 : :
7179 : : /* Begin a new group */
7180 : 12 : tmp = 0;
7181 : 12 : mul = 1;
7182 : : }
7183 : :
7184 : 944 : tmp = tmp * 2 + (*cp++ - '0');
7185 : 944 : mul = mul * 2;
7186 : : }
7187 [ + + ]: 76 : else if (*cp == '_')
7188 : : {
7189 : : /* Underscore must be followed by more digits */
7190 : 68 : cp++;
7191 [ + - - + ]: 68 : if (*cp < '0' || *cp > '1')
7192 : 0 : goto invalid_syntax;
7193 : : }
7194 : : else
7195 : 8 : break;
7196 : : }
7197 : : }
7198 : : else
7199 : : /* Should never happen; treat as invalid input */
7200 : 0 : goto invalid_syntax;
7201 : :
7202 : : /* Check that we got at least one digit */
7203 [ - + ]: 92 : if (unlikely(cp == firstdigit))
7204 : 0 : goto invalid_syntax;
7205 : :
7206 : : /* Add the contribution from the final group of digits */
7207 : 92 : int64_to_numericvar(mul, &tmp_var);
7208 : 92 : mul_var(dest, &tmp_var, dest, 0);
7209 : 92 : int64_to_numericvar(tmp, &tmp_var);
7210 : 92 : add_var(dest, &tmp_var, dest);
7211 : :
7212 [ - + ]: 92 : if (dest->weight > NUMERIC_WEIGHT_MAX)
7213 : 0 : goto out_of_range;
7214 : :
7215 : 92 : dest->sign = sign;
7216 : :
7217 : 92 : free_var(&tmp_var);
7218 : :
7219 : : /* Return end+1 position for caller */
7220 : 92 : *endptr = cp;
7221 : :
7222 : 92 : return true;
7223 : :
7224 : 0 : out_of_range:
7225 [ # # ]: 0 : ereturn(escontext, false,
7226 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7227 : : errmsg("value overflows numeric format")));
7228 : :
7229 : 12 : invalid_syntax:
7230 [ + - ]: 12 : ereturn(escontext, false,
7231 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
7232 : : errmsg("invalid input syntax for type %s: \"%s\"",
7233 : : "numeric", str)));
7234 : : }
7235 : :
7236 : :
7237 : : /*
7238 : : * set_var_from_num() -
7239 : : *
7240 : : * Convert the packed db format into a variable
7241 : : */
7242 : : static void
7243 : 8831 : set_var_from_num(Numeric num, NumericVar *dest)
7244 : : {
7245 : : int ndigits;
7246 : :
7247 [ + + ]: 8831 : ndigits = NUMERIC_NDIGITS(num);
7248 : :
7249 : 8831 : alloc_var(dest, ndigits);
7250 : :
7251 [ + + + + ]: 8831 : dest->weight = NUMERIC_WEIGHT(num);
7252 [ + + - + ]: 8831 : dest->sign = NUMERIC_SIGN(num);
7253 [ + + ]: 8831 : dest->dscale = NUMERIC_DSCALE(num);
7254 : :
7255 [ + + ]: 8831 : memcpy(dest->digits, NUMERIC_DIGITS(num), ndigits * sizeof(NumericDigit));
7256 : 8831 : }
7257 : :
7258 : :
7259 : : /*
7260 : : * init_var_from_num() -
7261 : : *
7262 : : * Initialize a variable from packed db format. The digits array is not
7263 : : * copied, which saves some cycles when the resulting var is not modified.
7264 : : * Also, there's no need to call free_var(), as long as you don't assign any
7265 : : * other value to it (with set_var_* functions, or by using the var as the
7266 : : * destination of a function like add_var())
7267 : : *
7268 : : * CAUTION: Do not modify the digits buffer of a var initialized with this
7269 : : * function, e.g by calling round_var() or trunc_var(), as the changes will
7270 : : * propagate to the original Numeric! It's OK to use it as the destination
7271 : : * argument of one of the calculational functions, though.
7272 : : */
7273 : : static void
7274 : 3870812 : init_var_from_num(Numeric num, NumericVar *dest)
7275 : : {
7276 [ + + ]: 3870812 : dest->ndigits = NUMERIC_NDIGITS(num);
7277 [ + + + + ]: 3870812 : dest->weight = NUMERIC_WEIGHT(num);
7278 [ + + + + ]: 3870812 : dest->sign = NUMERIC_SIGN(num);
7279 [ + + ]: 3870812 : dest->dscale = NUMERIC_DSCALE(num);
7280 [ + + ]: 3870812 : dest->digits = NUMERIC_DIGITS(num);
7281 : 3870812 : dest->buf = NULL; /* digits array is not palloc'd */
7282 : 3870812 : }
7283 : :
7284 : :
7285 : : /*
7286 : : * set_var_from_var() -
7287 : : *
7288 : : * Copy one variable into another
7289 : : */
7290 : : static void
7291 : 24546 : set_var_from_var(const NumericVar *value, NumericVar *dest)
7292 : : {
7293 : : NumericDigit *newbuf;
7294 : :
7295 : 24546 : newbuf = digitbuf_alloc(value->ndigits + 1);
7296 : 24546 : newbuf[0] = 0; /* spare digit for rounding */
7297 [ + + ]: 24546 : if (value->ndigits > 0) /* else value->digits might be null */
7298 : 23874 : memcpy(newbuf + 1, value->digits,
7299 : 23874 : value->ndigits * sizeof(NumericDigit));
7300 : :
7301 [ + + ]: 24546 : digitbuf_free(dest->buf);
7302 : :
7303 : 24546 : memmove(dest, value, sizeof(NumericVar));
7304 : 24546 : dest->buf = newbuf;
7305 : 24546 : dest->digits = newbuf + 1;
7306 : 24546 : }
7307 : :
7308 : :
7309 : : /*
7310 : : * get_str_from_var() -
7311 : : *
7312 : : * Convert a var to text representation (guts of numeric_out).
7313 : : * The var is displayed to the number of digits indicated by its dscale.
7314 : : * Returns a palloc'd string.
7315 : : */
7316 : : static char *
7317 : 560484 : get_str_from_var(const NumericVar *var)
7318 : : {
7319 : : int dscale;
7320 : : char *str;
7321 : : char *cp;
7322 : : char *endcp;
7323 : : int i;
7324 : : int d;
7325 : : NumericDigit dig;
7326 : :
7327 : : #if DEC_DIGITS > 1
7328 : : NumericDigit d1;
7329 : : #endif
7330 : :
7331 : 560484 : dscale = var->dscale;
7332 : :
7333 : : /*
7334 : : * Allocate space for the result.
7335 : : *
7336 : : * i is set to the # of decimal digits before decimal point. dscale is the
7337 : : * # of decimal digits we will print after decimal point. We may generate
7338 : : * as many as DEC_DIGITS-1 excess digits at the end, and in addition we
7339 : : * need room for sign, decimal point, null terminator.
7340 : : */
7341 : 560484 : i = (var->weight + 1) * DEC_DIGITS;
7342 [ + + ]: 560484 : if (i <= 0)
7343 : 72493 : i = 1;
7344 : :
7345 : 560484 : str = palloc(i + dscale + DEC_DIGITS + 2);
7346 : 560484 : cp = str;
7347 : :
7348 : : /*
7349 : : * Output a dash for negative values
7350 : : */
7351 [ + + ]: 560484 : if (var->sign == NUMERIC_NEG)
7352 : 4413 : *cp++ = '-';
7353 : :
7354 : : /*
7355 : : * Output all digits before the decimal point
7356 : : */
7357 [ + + ]: 560484 : if (var->weight < 0)
7358 : : {
7359 : 72493 : d = var->weight + 1;
7360 : 72493 : *cp++ = '0';
7361 : : }
7362 : : else
7363 : : {
7364 [ + + ]: 1037998 : for (d = 0; d <= var->weight; d++)
7365 : : {
7366 [ + + ]: 550007 : dig = (d < var->ndigits) ? var->digits[d] : 0;
7367 : : /* In the first digit, suppress extra leading decimal zeroes */
7368 : : #if DEC_DIGITS == 4
7369 : : {
7370 : 550007 : bool putit = (d > 0);
7371 : :
7372 : 550007 : d1 = dig / 1000;
7373 : 550007 : dig -= d1 * 1000;
7374 : 550007 : putit |= (d1 > 0);
7375 [ + + ]: 550007 : if (putit)
7376 : 102575 : *cp++ = d1 + '0';
7377 : 550007 : d1 = dig / 100;
7378 : 550007 : dig -= d1 * 100;
7379 : 550007 : putit |= (d1 > 0);
7380 [ + + ]: 550007 : if (putit)
7381 : 375298 : *cp++ = d1 + '0';
7382 : 550007 : d1 = dig / 10;
7383 : 550007 : dig -= d1 * 10;
7384 : 550007 : putit |= (d1 > 0);
7385 [ + + ]: 550007 : if (putit)
7386 : 458821 : *cp++ = d1 + '0';
7387 : 550007 : *cp++ = dig + '0';
7388 : : }
7389 : : #elif DEC_DIGITS == 2
7390 : : d1 = dig / 10;
7391 : : dig -= d1 * 10;
7392 : : if (d1 > 0 || d > 0)
7393 : : *cp++ = d1 + '0';
7394 : : *cp++ = dig + '0';
7395 : : #elif DEC_DIGITS == 1
7396 : : *cp++ = dig + '0';
7397 : : #else
7398 : : #error unsupported NBASE
7399 : : #endif
7400 : : }
7401 : : }
7402 : :
7403 : : /*
7404 : : * If requested, output a decimal point and all the digits that follow it.
7405 : : * We initially put out a multiple of DEC_DIGITS digits, then truncate if
7406 : : * needed.
7407 : : */
7408 [ + + ]: 560484 : if (dscale > 0)
7409 : : {
7410 : 409258 : *cp++ = '.';
7411 : 409258 : endcp = cp + dscale;
7412 [ + + ]: 1150068 : for (i = 0; i < dscale; d++, i += DEC_DIGITS)
7413 : : {
7414 [ + + + + ]: 740810 : dig = (d >= 0 && d < var->ndigits) ? var->digits[d] : 0;
7415 : : #if DEC_DIGITS == 4
7416 : 740810 : d1 = dig / 1000;
7417 : 740810 : dig -= d1 * 1000;
7418 : 740810 : *cp++ = d1 + '0';
7419 : 740810 : d1 = dig / 100;
7420 : 740810 : dig -= d1 * 100;
7421 : 740810 : *cp++ = d1 + '0';
7422 : 740810 : d1 = dig / 10;
7423 : 740810 : dig -= d1 * 10;
7424 : 740810 : *cp++ = d1 + '0';
7425 : 740810 : *cp++ = dig + '0';
7426 : : #elif DEC_DIGITS == 2
7427 : : d1 = dig / 10;
7428 : : dig -= d1 * 10;
7429 : : *cp++ = d1 + '0';
7430 : : *cp++ = dig + '0';
7431 : : #elif DEC_DIGITS == 1
7432 : : *cp++ = dig + '0';
7433 : : #else
7434 : : #error unsupported NBASE
7435 : : #endif
7436 : : }
7437 : 409258 : cp = endcp;
7438 : : }
7439 : :
7440 : : /*
7441 : : * terminate the string and return it
7442 : : */
7443 : 560484 : *cp = '\0';
7444 : 560484 : return str;
7445 : : }
7446 : :
7447 : : /*
7448 : : * get_str_from_var_sci() -
7449 : : *
7450 : : * Convert a var to a normalised scientific notation text representation.
7451 : : * This function does the heavy lifting for numeric_out_sci().
7452 : : *
7453 : : * This notation has the general form a * 10^b, where a is known as the
7454 : : * "significand" and b is known as the "exponent".
7455 : : *
7456 : : * Because we can't do superscript in ASCII (and because we want to copy
7457 : : * printf's behaviour) we display the exponent using E notation, with a
7458 : : * minimum of two exponent digits.
7459 : : *
7460 : : * For example, the value 1234 could be output as 1.2e+03.
7461 : : *
7462 : : * We assume that the exponent can fit into an int32.
7463 : : *
7464 : : * rscale is the number of decimal digits desired after the decimal point in
7465 : : * the output, negative values will be treated as meaning zero.
7466 : : *
7467 : : * Returns a palloc'd string.
7468 : : */
7469 : : static char *
7470 : 152 : get_str_from_var_sci(const NumericVar *var, int rscale)
7471 : : {
7472 : : int32 exponent;
7473 : : NumericVar tmp_var;
7474 : : size_t len;
7475 : : char *str;
7476 : : char *sig_out;
7477 : :
7478 [ - + ]: 152 : if (rscale < 0)
7479 : 0 : rscale = 0;
7480 : :
7481 : : /*
7482 : : * Determine the exponent of this number in normalised form.
7483 : : *
7484 : : * This is the exponent required to represent the number with only one
7485 : : * significant digit before the decimal place.
7486 : : */
7487 [ + + ]: 152 : if (var->ndigits > 0)
7488 : : {
7489 : 140 : exponent = (var->weight + 1) * DEC_DIGITS;
7490 : :
7491 : : /*
7492 : : * Compensate for leading decimal zeroes in the first numeric digit by
7493 : : * decrementing the exponent.
7494 : : */
7495 : 140 : exponent -= DEC_DIGITS - (int) log10(var->digits[0]);
7496 : : }
7497 : : else
7498 : : {
7499 : : /*
7500 : : * If var has no digits, then it must be zero.
7501 : : *
7502 : : * Zero doesn't technically have a meaningful exponent in normalised
7503 : : * notation, but we just display the exponent as zero for consistency
7504 : : * of output.
7505 : : */
7506 : 12 : exponent = 0;
7507 : : }
7508 : :
7509 : : /*
7510 : : * Divide var by 10^exponent to get the significand, rounding to rscale
7511 : : * decimal digits in the process.
7512 : : */
7513 : 152 : init_var(&tmp_var);
7514 : :
7515 : 152 : power_ten_int(exponent, &tmp_var);
7516 : 152 : div_var(var, &tmp_var, &tmp_var, rscale, true, true);
7517 : 152 : sig_out = get_str_from_var(&tmp_var);
7518 : :
7519 : 152 : free_var(&tmp_var);
7520 : :
7521 : : /*
7522 : : * Allocate space for the result.
7523 : : *
7524 : : * In addition to the significand, we need room for the exponent
7525 : : * decoration ("e"), the sign of the exponent, up to 10 digits for the
7526 : : * exponent itself, and of course the null terminator.
7527 : : */
7528 : 152 : len = strlen(sig_out) + 13;
7529 : 152 : str = palloc(len);
7530 : 152 : snprintf(str, len, "%se%+03d", sig_out, exponent);
7531 : :
7532 : 152 : pfree(sig_out);
7533 : :
7534 : 152 : return str;
7535 : : }
7536 : :
7537 : :
7538 : : /*
7539 : : * numericvar_serialize - serialize NumericVar to binary format
7540 : : *
7541 : : * At variable level, no checks are performed on the weight or dscale, allowing
7542 : : * us to pass around intermediate values with higher precision than supported
7543 : : * by the numeric type. Note: this is incompatible with numeric_send/recv(),
7544 : : * which use 16-bit integers for these fields.
7545 : : */
7546 : : static void
7547 : 61 : numericvar_serialize(StringInfo buf, const NumericVar *var)
7548 : : {
7549 : : int i;
7550 : :
7551 : 61 : pq_sendint32(buf, var->ndigits);
7552 : 61 : pq_sendint32(buf, var->weight);
7553 : 61 : pq_sendint32(buf, var->sign);
7554 : 61 : pq_sendint32(buf, var->dscale);
7555 [ + + ]: 425164 : for (i = 0; i < var->ndigits; i++)
7556 : 425103 : pq_sendint16(buf, var->digits[i]);
7557 : 61 : }
7558 : :
7559 : : /*
7560 : : * numericvar_deserialize - deserialize binary format to NumericVar
7561 : : */
7562 : : static void
7563 : 61 : numericvar_deserialize(StringInfo buf, NumericVar *var)
7564 : : {
7565 : : int len,
7566 : : i;
7567 : :
7568 : 61 : len = pq_getmsgint(buf, sizeof(int32));
7569 : :
7570 : 61 : alloc_var(var, len); /* sets var->ndigits */
7571 : :
7572 : 61 : var->weight = pq_getmsgint(buf, sizeof(int32));
7573 : 61 : var->sign = pq_getmsgint(buf, sizeof(int32));
7574 : 61 : var->dscale = pq_getmsgint(buf, sizeof(int32));
7575 [ + + ]: 425164 : for (i = 0; i < len; i++)
7576 : 425103 : var->digits[i] = pq_getmsgint(buf, sizeof(int16));
7577 : 61 : }
7578 : :
7579 : :
7580 : : /*
7581 : : * duplicate_numeric() - copy a packed-format Numeric
7582 : : *
7583 : : * This will handle NaN and Infinity cases.
7584 : : */
7585 : : static Numeric
7586 : 18826 : duplicate_numeric(Numeric num)
7587 : : {
7588 : : Numeric res;
7589 : :
7590 : 18826 : res = (Numeric) palloc(VARSIZE(num));
7591 : 18826 : memcpy(res, num, VARSIZE(num));
7592 : 18826 : return res;
7593 : : }
7594 : :
7595 : : /*
7596 : : * make_result_safe() -
7597 : : *
7598 : : * Create the packed db numeric format in palloc()'d memory from
7599 : : * a variable. This will handle NaN and Infinity cases.
7600 : : */
7601 : : static Numeric
7602 : 2538719 : make_result_safe(const NumericVar *var, Node *escontext)
7603 : : {
7604 : : Numeric result;
7605 : 2538719 : NumericDigit *digits = var->digits;
7606 : 2538719 : int weight = var->weight;
7607 : 2538719 : int sign = var->sign;
7608 : : int n;
7609 : : Size len;
7610 : :
7611 [ + + ]: 2538719 : if ((sign & NUMERIC_SIGN_MASK) == NUMERIC_SPECIAL)
7612 : : {
7613 : : /*
7614 : : * Verify valid special value. This could be just an Assert, perhaps,
7615 : : * but it seems worthwhile to expend a few cycles to ensure that we
7616 : : * never write any nonzero reserved bits to disk.
7617 : : */
7618 [ + + + + : 2221 : if (!(sign == NUMERIC_NAN ||
- + ]
7619 : : sign == NUMERIC_PINF ||
7620 : : sign == NUMERIC_NINF))
7621 [ # # ]: 0 : elog(ERROR, "invalid numeric sign value 0x%x", sign);
7622 : :
7623 : 2221 : result = (Numeric) palloc(NUMERIC_HDRSZ_SHORT);
7624 : :
7625 : 2221 : SET_VARSIZE(result, NUMERIC_HDRSZ_SHORT);
7626 : 2221 : result->choice.n_header = sign;
7627 : : /* the header word is all we need */
7628 : :
7629 : : dump_numeric("make_result()", result);
7630 : 2221 : return result;
7631 : : }
7632 : :
7633 : 2536498 : n = var->ndigits;
7634 : :
7635 : : /* truncate leading zeroes */
7636 [ + + + + ]: 2536528 : while (n > 0 && *digits == 0)
7637 : : {
7638 : 30 : digits++;
7639 : 30 : weight--;
7640 : 30 : n--;
7641 : : }
7642 : : /* truncate trailing zeroes */
7643 [ + + + + ]: 2588625 : while (n > 0 && digits[n - 1] == 0)
7644 : 52127 : n--;
7645 : :
7646 : : /* If zero result, force to weight=0 and positive sign */
7647 [ + + ]: 2536498 : if (n == 0)
7648 : : {
7649 : 82335 : weight = 0;
7650 : 82335 : sign = NUMERIC_POS;
7651 : : }
7652 : :
7653 : : /* Build the result */
7654 [ + + + + : 2536498 : if (NUMERIC_CAN_BE_SHORT(var->dscale, weight))
+ - ]
7655 : : {
7656 : 2534564 : len = NUMERIC_HDRSZ_SHORT + n * sizeof(NumericDigit);
7657 : 2534564 : result = (Numeric) palloc(len);
7658 : 2534564 : SET_VARSIZE(result, len);
7659 : 2534564 : result->choice.n_short.n_header =
7660 : : (sign == NUMERIC_NEG ? (NUMERIC_SHORT | NUMERIC_SHORT_SIGN_MASK)
7661 : : : NUMERIC_SHORT)
7662 [ + + ]: 2534564 : | (var->dscale << NUMERIC_SHORT_DSCALE_SHIFT)
7663 : 2534564 : | (weight < 0 ? NUMERIC_SHORT_WEIGHT_SIGN_MASK : 0)
7664 : 2534564 : | (weight & NUMERIC_SHORT_WEIGHT_MASK);
7665 : : }
7666 : : else
7667 : : {
7668 : 1934 : len = NUMERIC_HDRSZ + n * sizeof(NumericDigit);
7669 : 1934 : result = (Numeric) palloc(len);
7670 : 1934 : SET_VARSIZE(result, len);
7671 : 1934 : result->choice.n_long.n_sign_dscale =
7672 : 1934 : sign | (var->dscale & NUMERIC_DSCALE_MASK);
7673 : 1934 : result->choice.n_long.n_weight = weight;
7674 : : }
7675 : :
7676 : : Assert(NUMERIC_NDIGITS(result) == n);
7677 [ + + ]: 2536498 : if (n > 0)
7678 [ + + ]: 2454163 : memcpy(NUMERIC_DIGITS(result), digits, n * sizeof(NumericDigit));
7679 : :
7680 : : /* Check for overflow of int16 fields */
7681 [ + + + + : 2536498 : if (NUMERIC_WEIGHT(result) != weight ||
+ + ]
7682 [ + + - + ]: 2536478 : NUMERIC_DSCALE(result) != var->dscale)
7683 [ + + ]: 20 : ereturn(escontext, NULL,
7684 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7685 : : errmsg("value overflows numeric format")));
7686 : :
7687 : : dump_numeric("make_result()", result);
7688 : 2536478 : return result;
7689 : : }
7690 : :
7691 : :
7692 : : /*
7693 : : * make_result() -
7694 : : *
7695 : : * An interface to make_result_safe() without "escontext" argument.
7696 : : */
7697 : : static Numeric
7698 : 1518162 : make_result(const NumericVar *var)
7699 : : {
7700 : 1518162 : return make_result_safe(var, NULL);
7701 : : }
7702 : :
7703 : :
7704 : : /*
7705 : : * apply_typmod() -
7706 : : *
7707 : : * Do bounds checking and rounding according to the specified typmod.
7708 : : * Note that this is only applied to normal finite values.
7709 : : *
7710 : : * Returns true on success, false on failure (if escontext points to an
7711 : : * ErrorSaveContext; otherwise errors are thrown).
7712 : : */
7713 : : static bool
7714 : 104680 : apply_typmod(NumericVar *var, int32 typmod, Node *escontext)
7715 : : {
7716 : : int precision;
7717 : : int scale;
7718 : : int maxdigits;
7719 : : int ddigits;
7720 : : int i;
7721 : :
7722 : : /* Do nothing if we have an invalid typmod */
7723 [ + + ]: 104680 : if (!is_valid_numeric_typmod(typmod))
7724 : 85164 : return true;
7725 : :
7726 : 19516 : precision = numeric_typmod_precision(typmod);
7727 : 19516 : scale = numeric_typmod_scale(typmod);
7728 : 19516 : maxdigits = precision - scale;
7729 : :
7730 : : /* Round to target scale (and set var->dscale) */
7731 : 19516 : round_var(var, scale);
7732 : :
7733 : : /* but don't allow var->dscale to be negative */
7734 [ + + ]: 19516 : if (var->dscale < 0)
7735 : 100 : var->dscale = 0;
7736 : :
7737 : : /*
7738 : : * Check for overflow - note we can't do this before rounding, because
7739 : : * rounding could raise the weight. Also note that the var's weight could
7740 : : * be inflated by leading zeroes, which will be stripped before storage
7741 : : * but perhaps might not have been yet. In any case, we must recognize a
7742 : : * true zero, whose weight doesn't mean anything.
7743 : : */
7744 : 19516 : ddigits = (var->weight + 1) * DEC_DIGITS;
7745 [ + + ]: 19516 : if (ddigits > maxdigits)
7746 : : {
7747 : : /* Determine true weight; and check for all-zero result */
7748 [ + + ]: 4297 : for (i = 0; i < var->ndigits; i++)
7749 : : {
7750 : 4286 : NumericDigit dig = var->digits[i];
7751 : :
7752 [ + - ]: 4286 : if (dig)
7753 : : {
7754 : : /* Adjust for any high-order decimal zero digits */
7755 : : #if DEC_DIGITS == 4
7756 [ + + ]: 4286 : if (dig < 10)
7757 : 206 : ddigits -= 3;
7758 [ + + ]: 4080 : else if (dig < 100)
7759 : 428 : ddigits -= 2;
7760 [ + + ]: 3652 : else if (dig < 1000)
7761 : 3640 : ddigits -= 1;
7762 : : #elif DEC_DIGITS == 2
7763 : : if (dig < 10)
7764 : : ddigits -= 1;
7765 : : #elif DEC_DIGITS == 1
7766 : : /* no adjustment */
7767 : : #else
7768 : : #error unsupported NBASE
7769 : : #endif
7770 [ + + ]: 4286 : if (ddigits > maxdigits)
7771 [ + + + + : 64 : ereturn(escontext, false,
+ + ]
7772 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7773 : : errmsg("numeric field overflow"),
7774 : : errdetail("A field with precision %d, scale %d must round to an absolute value less than %s%d.",
7775 : : precision, scale,
7776 : : /* Display 10^0 as 1 */
7777 : : maxdigits ? "10^" : "",
7778 : : maxdigits ? maxdigits : 1
7779 : : )));
7780 : 4222 : break;
7781 : : }
7782 : 0 : ddigits -= DEC_DIGITS;
7783 : : }
7784 : : }
7785 : :
7786 : 19452 : return true;
7787 : : }
7788 : :
7789 : : /*
7790 : : * apply_typmod_special() -
7791 : : *
7792 : : * Do bounds checking according to the specified typmod, for an Inf or NaN.
7793 : : * For convenience of most callers, the value is presented in packed form.
7794 : : *
7795 : : * Returns true on success, false on failure (if escontext points to an
7796 : : * ErrorSaveContext; otherwise errors are thrown).
7797 : : */
7798 : : static bool
7799 : 1308 : apply_typmod_special(Numeric num, int32 typmod, Node *escontext)
7800 : : {
7801 : : int precision;
7802 : : int scale;
7803 : :
7804 : : Assert(NUMERIC_IS_SPECIAL(num)); /* caller error if not */
7805 : :
7806 : : /*
7807 : : * NaN is allowed regardless of the typmod; that's rather dubious perhaps,
7808 : : * but it's a longstanding behavior. Inf is rejected if we have any
7809 : : * typmod restriction, since an infinity shouldn't be claimed to fit in
7810 : : * any finite number of digits.
7811 : : */
7812 [ + + ]: 1308 : if (NUMERIC_IS_NAN(num))
7813 : 557 : return true;
7814 : :
7815 : : /* Do nothing if we have a default typmod (-1) */
7816 [ + + ]: 751 : if (!is_valid_numeric_typmod(typmod))
7817 : 739 : return true;
7818 : :
7819 : 12 : precision = numeric_typmod_precision(typmod);
7820 : 12 : scale = numeric_typmod_scale(typmod);
7821 : :
7822 [ + - ]: 12 : ereturn(escontext, false,
7823 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7824 : : errmsg("numeric field overflow"),
7825 : : errdetail("A field with precision %d, scale %d cannot hold an infinite value.",
7826 : : precision, scale)));
7827 : : }
7828 : :
7829 : :
7830 : : /*
7831 : : * Convert numeric to int8, rounding if needed.
7832 : : *
7833 : : * If overflow, return false (no error is raised). Return true if okay.
7834 : : */
7835 : : static bool
7836 : 6724 : numericvar_to_int64(const NumericVar *var, int64 *result)
7837 : : {
7838 : : NumericDigit *digits;
7839 : : int ndigits;
7840 : : int weight;
7841 : : int i;
7842 : : int64 val;
7843 : : bool neg;
7844 : : NumericVar rounded;
7845 : :
7846 : : /* Round to nearest integer */
7847 : 6724 : init_var(&rounded);
7848 : 6724 : set_var_from_var(var, &rounded);
7849 : 6724 : round_var(&rounded, 0);
7850 : :
7851 : : /* Check for zero input */
7852 : 6724 : strip_var(&rounded);
7853 : 6724 : ndigits = rounded.ndigits;
7854 [ + + ]: 6724 : if (ndigits == 0)
7855 : : {
7856 : 348 : *result = 0;
7857 : 348 : free_var(&rounded);
7858 : 348 : return true;
7859 : : }
7860 : :
7861 : : /*
7862 : : * For input like 10000000000, we must treat stripped digits as real. So
7863 : : * the loop assumes there are weight+1 digits before the decimal point.
7864 : : */
7865 : 6376 : weight = rounded.weight;
7866 : : Assert(weight >= 0 && ndigits <= weight + 1);
7867 : :
7868 : : /*
7869 : : * Construct the result. To avoid issues with converting a value
7870 : : * corresponding to INT64_MIN (which can't be represented as a positive 64
7871 : : * bit two's complement integer), accumulate value as a negative number.
7872 : : */
7873 : 6376 : digits = rounded.digits;
7874 : 6376 : neg = (rounded.sign == NUMERIC_NEG);
7875 : 6376 : val = -digits[0];
7876 [ + + ]: 8911 : for (i = 1; i <= weight; i++)
7877 : : {
7878 [ + + ]: 2568 : if (unlikely(pg_mul_s64_overflow(val, NBASE, &val)))
7879 : : {
7880 : 21 : free_var(&rounded);
7881 : 21 : return false;
7882 : : }
7883 : :
7884 [ + + ]: 2547 : if (i < ndigits)
7885 : : {
7886 [ + + ]: 2343 : if (unlikely(pg_sub_s64_overflow(val, digits[i], &val)))
7887 : : {
7888 : 12 : free_var(&rounded);
7889 : 12 : return false;
7890 : : }
7891 : : }
7892 : : }
7893 : :
7894 : 6343 : free_var(&rounded);
7895 : :
7896 [ + + ]: 6343 : if (!neg)
7897 : : {
7898 [ + + ]: 5793 : if (unlikely(pg_neg_s64_overflow(val, &val)))
7899 : 16 : return false;
7900 : : }
7901 : 6327 : *result = val;
7902 : :
7903 : 6327 : return true;
7904 : : }
7905 : :
7906 : : /*
7907 : : * Convert int8 value to numeric.
7908 : : */
7909 : : static void
7910 : 1263308 : int64_to_numericvar(int64 val, NumericVar *var)
7911 : : {
7912 : : uint64 uval,
7913 : : newuval;
7914 : : NumericDigit *ptr;
7915 : : int ndigits;
7916 : :
7917 : : /* int64 can require at most 19 decimal digits; add one for safety */
7918 : 1263308 : alloc_var(var, 20 / DEC_DIGITS);
7919 [ + + ]: 1263308 : if (val < 0)
7920 : : {
7921 : 1263 : var->sign = NUMERIC_NEG;
7922 : 1263 : uval = pg_abs_s64(val);
7923 : : }
7924 : : else
7925 : : {
7926 : 1262045 : var->sign = NUMERIC_POS;
7927 : 1262045 : uval = val;
7928 : : }
7929 : 1263308 : var->dscale = 0;
7930 [ + + ]: 1263308 : if (val == 0)
7931 : : {
7932 : 19365 : var->ndigits = 0;
7933 : 19365 : var->weight = 0;
7934 : 19365 : return;
7935 : : }
7936 : 1243943 : ptr = var->digits + var->ndigits;
7937 : 1243943 : ndigits = 0;
7938 : : do
7939 : : {
7940 : 1441535 : ptr--;
7941 : 1441535 : ndigits++;
7942 : 1441535 : newuval = uval / NBASE;
7943 : 1441535 : *ptr = uval - newuval * NBASE;
7944 : 1441535 : uval = newuval;
7945 [ + + ]: 1441535 : } while (uval);
7946 : 1243943 : var->digits = ptr;
7947 : 1243943 : var->ndigits = ndigits;
7948 : 1243943 : var->weight = ndigits - 1;
7949 : : }
7950 : :
7951 : : /*
7952 : : * Convert numeric to uint64, rounding if needed.
7953 : : *
7954 : : * If overflow, return false (no error is raised). Return true if okay.
7955 : : */
7956 : : static bool
7957 : 101 : numericvar_to_uint64(const NumericVar *var, uint64 *result)
7958 : : {
7959 : : NumericDigit *digits;
7960 : : int ndigits;
7961 : : int weight;
7962 : : int i;
7963 : : uint64 val;
7964 : : NumericVar rounded;
7965 : :
7966 : : /* Round to nearest integer */
7967 : 101 : init_var(&rounded);
7968 : 101 : set_var_from_var(var, &rounded);
7969 : 101 : round_var(&rounded, 0);
7970 : :
7971 : : /* Check for zero input */
7972 : 101 : strip_var(&rounded);
7973 : 101 : ndigits = rounded.ndigits;
7974 [ + + ]: 101 : if (ndigits == 0)
7975 : : {
7976 : 15 : *result = 0;
7977 : 15 : free_var(&rounded);
7978 : 15 : return true;
7979 : : }
7980 : :
7981 : : /* Check for negative input */
7982 [ + + ]: 86 : if (rounded.sign == NUMERIC_NEG)
7983 : : {
7984 : 8 : free_var(&rounded);
7985 : 8 : return false;
7986 : : }
7987 : :
7988 : : /*
7989 : : * For input like 10000000000, we must treat stripped digits as real. So
7990 : : * the loop assumes there are weight+1 digits before the decimal point.
7991 : : */
7992 : 78 : weight = rounded.weight;
7993 : : Assert(weight >= 0 && ndigits <= weight + 1);
7994 : :
7995 : : /* Construct the result */
7996 : 78 : digits = rounded.digits;
7997 : 78 : val = digits[0];
7998 [ + + ]: 220 : for (i = 1; i <= weight; i++)
7999 : : {
8000 [ - + ]: 150 : if (unlikely(pg_mul_u64_overflow(val, NBASE, &val)))
8001 : : {
8002 : 0 : free_var(&rounded);
8003 : 0 : return false;
8004 : : }
8005 : :
8006 [ + - ]: 150 : if (i < ndigits)
8007 : : {
8008 [ + + ]: 150 : if (unlikely(pg_add_u64_overflow(val, digits[i], &val)))
8009 : : {
8010 : 8 : free_var(&rounded);
8011 : 8 : return false;
8012 : : }
8013 : : }
8014 : : }
8015 : :
8016 : 70 : free_var(&rounded);
8017 : :
8018 : 70 : *result = val;
8019 : :
8020 : 70 : return true;
8021 : : }
8022 : :
8023 : : /*
8024 : : * Convert 128 bit integer to numeric.
8025 : : */
8026 : : static void
8027 : 6242 : int128_to_numericvar(INT128 val, NumericVar *var)
8028 : : {
8029 : : int sign;
8030 : : NumericDigit *ptr;
8031 : : int ndigits;
8032 : : int32 dig;
8033 : :
8034 : : /* int128 can require at most 39 decimal digits; add one for safety */
8035 : 6242 : alloc_var(var, 40 / DEC_DIGITS);
8036 : 6242 : sign = int128_sign(val);
8037 : 6242 : var->sign = sign < 0 ? NUMERIC_NEG : NUMERIC_POS;
8038 : 6242 : var->dscale = 0;
8039 [ + + ]: 6242 : if (sign == 0)
8040 : : {
8041 : 136 : var->ndigits = 0;
8042 : 136 : var->weight = 0;
8043 : 136 : return;
8044 : : }
8045 : 6106 : ptr = var->digits + var->ndigits;
8046 : 6106 : ndigits = 0;
8047 : : do
8048 : : {
8049 : 32812 : ptr--;
8050 : 32812 : ndigits++;
8051 : 32812 : int128_div_mod_int32(&val, NBASE, &dig);
8052 : 32812 : *ptr = (NumericDigit) abs(dig);
8053 [ + + ]: 32812 : } while (!int128_is_zero(val));
8054 : 6106 : var->digits = ptr;
8055 : 6106 : var->ndigits = ndigits;
8056 : 6106 : var->weight = ndigits - 1;
8057 : : }
8058 : :
8059 : : /*
8060 : : * Convert a NumericVar to float8; if out of range, return +/- HUGE_VAL
8061 : : */
8062 : : static double
8063 : 358 : numericvar_to_double_no_overflow(const NumericVar *var)
8064 : : {
8065 : : char *tmp;
8066 : : double val;
8067 : : char *endptr;
8068 : :
8069 : 358 : tmp = get_str_from_var(var);
8070 : :
8071 : : /* unlike float8in, we ignore ERANGE from strtod */
8072 : 358 : val = strtod(tmp, &endptr);
8073 [ - + ]: 358 : if (*endptr != '\0')
8074 : : {
8075 : : /* shouldn't happen ... */
8076 [ # # ]: 0 : ereport(ERROR,
8077 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
8078 : : errmsg("invalid input syntax for type %s: \"%s\"",
8079 : : "double precision", tmp)));
8080 : : }
8081 : :
8082 : 358 : pfree(tmp);
8083 : :
8084 : 358 : return val;
8085 : : }
8086 : :
8087 : :
8088 : : /*
8089 : : * cmp_var() -
8090 : : *
8091 : : * Compare two values on variable level. We assume zeroes have been
8092 : : * truncated to no digits.
8093 : : */
8094 : : static int
8095 : 114524 : cmp_var(const NumericVar *var1, const NumericVar *var2)
8096 : : {
8097 : 229048 : return cmp_var_common(var1->digits, var1->ndigits,
8098 : 114524 : var1->weight, var1->sign,
8099 : 114524 : var2->digits, var2->ndigits,
8100 : 114524 : var2->weight, var2->sign);
8101 : : }
8102 : :
8103 : : /*
8104 : : * cmp_var_common() -
8105 : : *
8106 : : * Main routine of cmp_var(). This function can be used by both
8107 : : * NumericVar and Numeric.
8108 : : */
8109 : : static int
8110 : 18503269 : cmp_var_common(const NumericDigit *var1digits, int var1ndigits,
8111 : : int var1weight, int var1sign,
8112 : : const NumericDigit *var2digits, int var2ndigits,
8113 : : int var2weight, int var2sign)
8114 : : {
8115 [ + + ]: 18503269 : if (var1ndigits == 0)
8116 : : {
8117 [ + + ]: 423526 : if (var2ndigits == 0)
8118 : 334334 : return 0;
8119 [ + + ]: 89192 : if (var2sign == NUMERIC_NEG)
8120 : 450 : return 1;
8121 : 88742 : return -1;
8122 : : }
8123 [ + + ]: 18079743 : if (var2ndigits == 0)
8124 : : {
8125 [ + + ]: 69873 : if (var1sign == NUMERIC_POS)
8126 : 64108 : return 1;
8127 : 5765 : return -1;
8128 : : }
8129 : :
8130 [ + + ]: 18009870 : if (var1sign == NUMERIC_POS)
8131 : : {
8132 [ + + ]: 17961126 : if (var2sign == NUMERIC_NEG)
8133 : 15557 : return 1;
8134 : 17945569 : return cmp_abs_common(var1digits, var1ndigits, var1weight,
8135 : : var2digits, var2ndigits, var2weight);
8136 : : }
8137 : :
8138 [ + + ]: 48744 : if (var2sign == NUMERIC_POS)
8139 : 13811 : return -1;
8140 : :
8141 : 34933 : return cmp_abs_common(var2digits, var2ndigits, var2weight,
8142 : : var1digits, var1ndigits, var1weight);
8143 : : }
8144 : :
8145 : :
8146 : : /*
8147 : : * add_var() -
8148 : : *
8149 : : * Full version of add functionality on variable level (handling signs).
8150 : : * result might point to one of the operands too without danger.
8151 : : */
8152 : : static void
8153 : 414380 : add_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
8154 : : {
8155 : : /*
8156 : : * Decide on the signs of the two variables what to do
8157 : : */
8158 [ + + ]: 414380 : if (var1->sign == NUMERIC_POS)
8159 : : {
8160 [ + + ]: 413125 : if (var2->sign == NUMERIC_POS)
8161 : : {
8162 : : /*
8163 : : * Both are positive result = +(ABS(var1) + ABS(var2))
8164 : : */
8165 : 279530 : add_abs(var1, var2, result);
8166 : 279530 : result->sign = NUMERIC_POS;
8167 : : }
8168 : : else
8169 : : {
8170 : : /*
8171 : : * var1 is positive, var2 is negative Must compare absolute values
8172 : : */
8173 [ + + + - ]: 133595 : switch (cmp_abs(var1, var2))
8174 : : {
8175 : 129 : case 0:
8176 : : /* ----------
8177 : : * ABS(var1) == ABS(var2)
8178 : : * result = ZERO
8179 : : * ----------
8180 : : */
8181 : 129 : zero_var(result);
8182 : 129 : result->dscale = Max(var1->dscale, var2->dscale);
8183 : 129 : break;
8184 : :
8185 : 124235 : case 1:
8186 : : /* ----------
8187 : : * ABS(var1) > ABS(var2)
8188 : : * result = +(ABS(var1) - ABS(var2))
8189 : : * ----------
8190 : : */
8191 : 124235 : sub_abs(var1, var2, result);
8192 : 124235 : result->sign = NUMERIC_POS;
8193 : 124235 : break;
8194 : :
8195 : 9231 : case -1:
8196 : : /* ----------
8197 : : * ABS(var1) < ABS(var2)
8198 : : * result = -(ABS(var2) - ABS(var1))
8199 : : * ----------
8200 : : */
8201 : 9231 : sub_abs(var2, var1, result);
8202 : 9231 : result->sign = NUMERIC_NEG;
8203 : 9231 : break;
8204 : : }
8205 : : }
8206 : : }
8207 : : else
8208 : : {
8209 [ + + ]: 1255 : if (var2->sign == NUMERIC_POS)
8210 : : {
8211 : : /* ----------
8212 : : * var1 is negative, var2 is positive
8213 : : * Must compare absolute values
8214 : : * ----------
8215 : : */
8216 [ + + + - ]: 318 : switch (cmp_abs(var1, var2))
8217 : : {
8218 : 20 : case 0:
8219 : : /* ----------
8220 : : * ABS(var1) == ABS(var2)
8221 : : * result = ZERO
8222 : : * ----------
8223 : : */
8224 : 20 : zero_var(result);
8225 : 20 : result->dscale = Max(var1->dscale, var2->dscale);
8226 : 20 : break;
8227 : :
8228 : 197 : case 1:
8229 : : /* ----------
8230 : : * ABS(var1) > ABS(var2)
8231 : : * result = -(ABS(var1) - ABS(var2))
8232 : : * ----------
8233 : : */
8234 : 197 : sub_abs(var1, var2, result);
8235 : 197 : result->sign = NUMERIC_NEG;
8236 : 197 : break;
8237 : :
8238 : 101 : case -1:
8239 : : /* ----------
8240 : : * ABS(var1) < ABS(var2)
8241 : : * result = +(ABS(var2) - ABS(var1))
8242 : : * ----------
8243 : : */
8244 : 101 : sub_abs(var2, var1, result);
8245 : 101 : result->sign = NUMERIC_POS;
8246 : 101 : break;
8247 : : }
8248 : : }
8249 : : else
8250 : : {
8251 : : /* ----------
8252 : : * Both are negative
8253 : : * result = -(ABS(var1) + ABS(var2))
8254 : : * ----------
8255 : : */
8256 : 937 : add_abs(var1, var2, result);
8257 : 937 : result->sign = NUMERIC_NEG;
8258 : : }
8259 : : }
8260 : 414380 : }
8261 : :
8262 : :
8263 : : /*
8264 : : * sub_var() -
8265 : : *
8266 : : * Full version of sub functionality on variable level (handling signs).
8267 : : * result might point to one of the operands too without danger.
8268 : : */
8269 : : static void
8270 : 351307 : sub_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
8271 : : {
8272 : : /*
8273 : : * Decide on the signs of the two variables what to do
8274 : : */
8275 [ + + ]: 351307 : if (var1->sign == NUMERIC_POS)
8276 : : {
8277 [ + + ]: 350698 : if (var2->sign == NUMERIC_NEG)
8278 : : {
8279 : : /* ----------
8280 : : * var1 is positive, var2 is negative
8281 : : * result = +(ABS(var1) + ABS(var2))
8282 : : * ----------
8283 : : */
8284 : 18921 : add_abs(var1, var2, result);
8285 : 18921 : result->sign = NUMERIC_POS;
8286 : : }
8287 : : else
8288 : : {
8289 : : /* ----------
8290 : : * Both are positive
8291 : : * Must compare absolute values
8292 : : * ----------
8293 : : */
8294 [ + + + - ]: 331777 : switch (cmp_abs(var1, var2))
8295 : : {
8296 : 29370 : case 0:
8297 : : /* ----------
8298 : : * ABS(var1) == ABS(var2)
8299 : : * result = ZERO
8300 : : * ----------
8301 : : */
8302 : 29370 : zero_var(result);
8303 : 29370 : result->dscale = Max(var1->dscale, var2->dscale);
8304 : 29370 : break;
8305 : :
8306 : 295066 : case 1:
8307 : : /* ----------
8308 : : * ABS(var1) > ABS(var2)
8309 : : * result = +(ABS(var1) - ABS(var2))
8310 : : * ----------
8311 : : */
8312 : 295066 : sub_abs(var1, var2, result);
8313 : 295066 : result->sign = NUMERIC_POS;
8314 : 295066 : break;
8315 : :
8316 : 7341 : case -1:
8317 : : /* ----------
8318 : : * ABS(var1) < ABS(var2)
8319 : : * result = -(ABS(var2) - ABS(var1))
8320 : : * ----------
8321 : : */
8322 : 7341 : sub_abs(var2, var1, result);
8323 : 7341 : result->sign = NUMERIC_NEG;
8324 : 7341 : break;
8325 : : }
8326 : : }
8327 : : }
8328 : : else
8329 : : {
8330 [ + + ]: 609 : if (var2->sign == NUMERIC_NEG)
8331 : : {
8332 : : /* ----------
8333 : : * Both are negative
8334 : : * Must compare absolute values
8335 : : * ----------
8336 : : */
8337 [ + + + - ]: 304 : switch (cmp_abs(var1, var2))
8338 : : {
8339 : 110 : case 0:
8340 : : /* ----------
8341 : : * ABS(var1) == ABS(var2)
8342 : : * result = ZERO
8343 : : * ----------
8344 : : */
8345 : 110 : zero_var(result);
8346 : 110 : result->dscale = Max(var1->dscale, var2->dscale);
8347 : 110 : break;
8348 : :
8349 : 162 : case 1:
8350 : : /* ----------
8351 : : * ABS(var1) > ABS(var2)
8352 : : * result = -(ABS(var1) - ABS(var2))
8353 : : * ----------
8354 : : */
8355 : 162 : sub_abs(var1, var2, result);
8356 : 162 : result->sign = NUMERIC_NEG;
8357 : 162 : break;
8358 : :
8359 : 32 : case -1:
8360 : : /* ----------
8361 : : * ABS(var1) < ABS(var2)
8362 : : * result = +(ABS(var2) - ABS(var1))
8363 : : * ----------
8364 : : */
8365 : 32 : sub_abs(var2, var1, result);
8366 : 32 : result->sign = NUMERIC_POS;
8367 : 32 : break;
8368 : : }
8369 : : }
8370 : : else
8371 : : {
8372 : : /* ----------
8373 : : * var1 is negative, var2 is positive
8374 : : * result = -(ABS(var1) + ABS(var2))
8375 : : * ----------
8376 : : */
8377 : 305 : add_abs(var1, var2, result);
8378 : 305 : result->sign = NUMERIC_NEG;
8379 : : }
8380 : : }
8381 : 351307 : }
8382 : :
8383 : :
8384 : : /*
8385 : : * mul_var() -
8386 : : *
8387 : : * Multiplication on variable level. Product of var1 * var2 is stored
8388 : : * in result. Result is rounded to no more than rscale fractional digits.
8389 : : */
8390 : : static void
8391 : 795537 : mul_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result,
8392 : : int rscale)
8393 : : {
8394 : : int res_ndigits;
8395 : : int res_ndigitpairs;
8396 : : int res_sign;
8397 : : int res_weight;
8398 : : int pair_offset;
8399 : : int maxdigits;
8400 : : int maxdigitpairs;
8401 : : uint64 *dig,
8402 : : *dig_i1_off;
8403 : : uint64 maxdig;
8404 : : uint64 carry;
8405 : : uint64 newdig;
8406 : : int var1ndigits;
8407 : : int var2ndigits;
8408 : : int var1ndigitpairs;
8409 : : int var2ndigitpairs;
8410 : : NumericDigit *var1digits;
8411 : : NumericDigit *var2digits;
8412 : : uint32 var1digitpair;
8413 : : uint32 *var2digitpairs;
8414 : : NumericDigit *res_digits;
8415 : : int i,
8416 : : i1,
8417 : : i2,
8418 : : i2limit;
8419 : :
8420 : : /*
8421 : : * Arrange for var1 to be the shorter of the two numbers. This improves
8422 : : * performance because the inner multiplication loop is much simpler than
8423 : : * the outer loop, so it's better to have a smaller number of iterations
8424 : : * of the outer loop. This also reduces the number of times that the
8425 : : * accumulator array needs to be normalized.
8426 : : */
8427 [ + + ]: 795537 : if (var1->ndigits > var2->ndigits)
8428 : : {
8429 : 10402 : const NumericVar *tmp = var1;
8430 : :
8431 : 10402 : var1 = var2;
8432 : 10402 : var2 = tmp;
8433 : : }
8434 : :
8435 : : /* copy these values into local vars for speed in inner loop */
8436 : 795537 : var1ndigits = var1->ndigits;
8437 : 795537 : var2ndigits = var2->ndigits;
8438 : 795537 : var1digits = var1->digits;
8439 : 795537 : var2digits = var2->digits;
8440 : :
8441 [ + + ]: 795537 : if (var1ndigits == 0)
8442 : : {
8443 : : /* one or both inputs is zero; so is result */
8444 : 1947 : zero_var(result);
8445 : 1947 : result->dscale = rscale;
8446 : 1947 : return;
8447 : : }
8448 : :
8449 : : /*
8450 : : * If var1 has 1-6 digits and the exact result was requested, delegate to
8451 : : * mul_var_short() which uses a faster direct multiplication algorithm.
8452 : : */
8453 [ + + + + ]: 793590 : if (var1ndigits <= 6 && rscale == var1->dscale + var2->dscale)
8454 : : {
8455 : 772973 : mul_var_short(var1, var2, result);
8456 : 772973 : return;
8457 : : }
8458 : :
8459 : : /* Determine result sign */
8460 [ + + ]: 20617 : if (var1->sign == var2->sign)
8461 : 19338 : res_sign = NUMERIC_POS;
8462 : : else
8463 : 1279 : res_sign = NUMERIC_NEG;
8464 : :
8465 : : /*
8466 : : * Determine the number of result digits to compute and the (maximum
8467 : : * possible) result weight. If the exact result would have more than
8468 : : * rscale fractional digits, truncate the computation with
8469 : : * MUL_GUARD_DIGITS guard digits, i.e., ignore input digits that would
8470 : : * only contribute to the right of that. (This will give the exact
8471 : : * rounded-to-rscale answer unless carries out of the ignored positions
8472 : : * would have propagated through more than MUL_GUARD_DIGITS digits.)
8473 : : *
8474 : : * Note: an exact computation could not produce more than var1ndigits +
8475 : : * var2ndigits digits, but we allocate at least one extra output digit in
8476 : : * case rscale-driven rounding produces a carry out of the highest exact
8477 : : * digit.
8478 : : *
8479 : : * The computation itself is done using base-NBASE^2 arithmetic, so we
8480 : : * actually process the input digits in pairs, producing a base-NBASE^2
8481 : : * intermediate result. This significantly improves performance, since
8482 : : * schoolbook multiplication is O(N^2) in the number of input digits, and
8483 : : * working in base NBASE^2 effectively halves "N".
8484 : : *
8485 : : * Note: in a truncated computation, we must compute at least one extra
8486 : : * output digit to ensure that all the guard digits are fully computed.
8487 : : */
8488 : : /* digit pairs in each input */
8489 : 20617 : var1ndigitpairs = (var1ndigits + 1) / 2;
8490 : 20617 : var2ndigitpairs = (var2ndigits + 1) / 2;
8491 : :
8492 : : /* digits in exact result */
8493 : 20617 : res_ndigits = var1ndigits + var2ndigits;
8494 : :
8495 : : /* digit pairs in exact result with at least one extra output digit */
8496 : 20617 : res_ndigitpairs = res_ndigits / 2 + 1;
8497 : :
8498 : : /* pair offset to align result to end of dig[] */
8499 : 20617 : pair_offset = res_ndigitpairs - var1ndigitpairs - var2ndigitpairs + 1;
8500 : :
8501 : : /* maximum possible result weight (odd-length inputs shifted up below) */
8502 : 20617 : res_weight = var1->weight + var2->weight + 1 + 2 * res_ndigitpairs -
8503 : 20617 : res_ndigits - (var1ndigits & 1) - (var2ndigits & 1);
8504 : :
8505 : : /* rscale-based truncation with at least one extra output digit */
8506 : 20617 : maxdigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS +
8507 : : MUL_GUARD_DIGITS;
8508 : 20617 : maxdigitpairs = maxdigits / 2 + 1;
8509 : :
8510 : 20617 : res_ndigitpairs = Min(res_ndigitpairs, maxdigitpairs);
8511 : 20617 : res_ndigits = 2 * res_ndigitpairs;
8512 : :
8513 : : /*
8514 : : * In the computation below, digit pair i1 of var1 and digit pair i2 of
8515 : : * var2 are multiplied and added to digit i1+i2+pair_offset of dig[]. Thus
8516 : : * input digit pairs with index >= res_ndigitpairs - pair_offset don't
8517 : : * contribute to the result, and can be ignored.
8518 : : */
8519 [ + + ]: 20617 : if (res_ndigitpairs <= pair_offset)
8520 : : {
8521 : : /* All input digits will be ignored; so result is zero */
8522 : 10 : zero_var(result);
8523 : 10 : result->dscale = rscale;
8524 : 10 : return;
8525 : : }
8526 : 20607 : var1ndigitpairs = Min(var1ndigitpairs, res_ndigitpairs - pair_offset);
8527 : 20607 : var2ndigitpairs = Min(var2ndigitpairs, res_ndigitpairs - pair_offset);
8528 : :
8529 : : /*
8530 : : * We do the arithmetic in an array "dig[]" of unsigned 64-bit integers.
8531 : : * Since PG_UINT64_MAX is much larger than NBASE^4, this gives us a lot of
8532 : : * headroom to avoid normalizing carries immediately.
8533 : : *
8534 : : * maxdig tracks the maximum possible value of any dig[] entry; when this
8535 : : * threatens to exceed PG_UINT64_MAX, we take the time to propagate
8536 : : * carries. Furthermore, we need to ensure that overflow doesn't occur
8537 : : * during the carry propagation passes either. The carry values could be
8538 : : * as much as PG_UINT64_MAX / NBASE^2, so really we must normalize when
8539 : : * digits threaten to exceed PG_UINT64_MAX - PG_UINT64_MAX / NBASE^2.
8540 : : *
8541 : : * To avoid overflow in maxdig itself, it actually represents the maximum
8542 : : * possible value divided by NBASE^2-1, i.e., at the top of the loop it is
8543 : : * known that no dig[] entry exceeds maxdig * (NBASE^2-1).
8544 : : *
8545 : : * The conversion of var1 to base NBASE^2 is done on the fly, as each new
8546 : : * digit is required. The digits of var2 are converted upfront, and
8547 : : * stored at the end of dig[]. To avoid loss of precision, the input
8548 : : * digits are aligned with the start of digit pair array, effectively
8549 : : * shifting them up (multiplying by NBASE) if the inputs have an odd
8550 : : * number of NBASE digits.
8551 : : */
8552 : 20607 : dig = (uint64 *) palloc(res_ndigitpairs * sizeof(uint64) +
8553 : : var2ndigitpairs * sizeof(uint32));
8554 : :
8555 : : /* convert var2 to base NBASE^2, shifting up if its length is odd */
8556 : 20607 : var2digitpairs = (uint32 *) (dig + res_ndigitpairs);
8557 : :
8558 [ + + ]: 1048193 : for (i2 = 0; i2 < var2ndigitpairs - 1; i2++)
8559 : 1027586 : var2digitpairs[i2] = var2digits[2 * i2] * NBASE + var2digits[2 * i2 + 1];
8560 : :
8561 [ + + ]: 20607 : if (2 * i2 + 1 < var2ndigits)
8562 : 14623 : var2digitpairs[i2] = var2digits[2 * i2] * NBASE + var2digits[2 * i2 + 1];
8563 : : else
8564 : 5984 : var2digitpairs[i2] = var2digits[2 * i2] * NBASE;
8565 : :
8566 : : /*
8567 : : * Start by multiplying var2 by the least significant contributing digit
8568 : : * pair from var1, storing the results at the end of dig[], and filling
8569 : : * the leading digits with zeros.
8570 : : *
8571 : : * The loop here is the same as the inner loop below, except that we set
8572 : : * the results in dig[], rather than adding to them. This is the
8573 : : * performance bottleneck for multiplication, so we want to keep it simple
8574 : : * enough so that it can be auto-vectorized. Accordingly, process the
8575 : : * digits left-to-right even though schoolbook multiplication would
8576 : : * suggest right-to-left. Since we aren't propagating carries in this
8577 : : * loop, the order does not matter.
8578 : : */
8579 : 20607 : i1 = var1ndigitpairs - 1;
8580 [ + + ]: 20607 : if (2 * i1 + 1 < var1ndigits)
8581 : 9155 : var1digitpair = var1digits[2 * i1] * NBASE + var1digits[2 * i1 + 1];
8582 : : else
8583 : 11452 : var1digitpair = var1digits[2 * i1] * NBASE;
8584 : 20607 : maxdig = var1digitpair;
8585 : :
8586 : 20607 : i2limit = Min(var2ndigitpairs, res_ndigitpairs - i1 - pair_offset);
8587 : 20607 : dig_i1_off = &dig[i1 + pair_offset];
8588 : :
8589 : 20607 : memset(dig, 0, (i1 + pair_offset) * sizeof(uint64));
8590 [ + + ]: 930395 : for (i2 = 0; i2 < i2limit; i2++)
8591 : 909788 : dig_i1_off[i2] = (uint64) var1digitpair * var2digitpairs[i2];
8592 : :
8593 : : /*
8594 : : * Next, multiply var2 by the remaining digit pairs from var1, adding the
8595 : : * results to dig[] at the appropriate offsets, and normalizing whenever
8596 : : * there is a risk of any dig[] entry overflowing.
8597 : : */
8598 [ + + ]: 1012280 : for (i1 = i1 - 1; i1 >= 0; i1--)
8599 : : {
8600 : 991673 : var1digitpair = var1digits[2 * i1] * NBASE + var1digits[2 * i1 + 1];
8601 [ + + ]: 991673 : if (var1digitpair == 0)
8602 : 786344 : continue;
8603 : :
8604 : : /* Time to normalize? */
8605 : 205329 : maxdig += var1digitpair;
8606 [ + + ]: 205329 : if (maxdig > (PG_UINT64_MAX - PG_UINT64_MAX / NBASE_SQR) / (NBASE_SQR - 1))
8607 : : {
8608 : : /* Yes, do it (to base NBASE^2) */
8609 : 21 : carry = 0;
8610 [ + + ]: 84074 : for (i = res_ndigitpairs - 1; i >= 0; i--)
8611 : : {
8612 : 84053 : newdig = dig[i] + carry;
8613 [ + + ]: 84053 : if (newdig >= NBASE_SQR)
8614 : : {
8615 : 80719 : carry = newdig / NBASE_SQR;
8616 : 80719 : newdig -= carry * NBASE_SQR;
8617 : : }
8618 : : else
8619 : 3334 : carry = 0;
8620 : 84053 : dig[i] = newdig;
8621 : : }
8622 : : Assert(carry == 0);
8623 : : /* Reset maxdig to indicate new worst-case */
8624 : 21 : maxdig = 1 + var1digitpair;
8625 : : }
8626 : :
8627 : : /* Multiply and add */
8628 : 205329 : i2limit = Min(var2ndigitpairs, res_ndigitpairs - i1 - pair_offset);
8629 : 205329 : dig_i1_off = &dig[i1 + pair_offset];
8630 : :
8631 [ + + ]: 87004803 : for (i2 = 0; i2 < i2limit; i2++)
8632 : 86799474 : dig_i1_off[i2] += (uint64) var1digitpair * var2digitpairs[i2];
8633 : : }
8634 : :
8635 : : /*
8636 : : * Now we do a final carry propagation pass to normalize back to base
8637 : : * NBASE^2, and construct the base-NBASE result digits. Note that this is
8638 : : * still done at full precision w/guard digits.
8639 : : */
8640 : 20607 : alloc_var(result, res_ndigits);
8641 : 20607 : res_digits = result->digits;
8642 : 20607 : carry = 0;
8643 [ + + ]: 1946024 : for (i = res_ndigitpairs - 1; i >= 0; i--)
8644 : : {
8645 : 1925417 : newdig = dig[i] + carry;
8646 [ + + ]: 1925417 : if (newdig >= NBASE_SQR)
8647 : : {
8648 : 289944 : carry = newdig / NBASE_SQR;
8649 : 289944 : newdig -= carry * NBASE_SQR;
8650 : : }
8651 : : else
8652 : 1635473 : carry = 0;
8653 : 1925417 : res_digits[2 * i + 1] = (NumericDigit) ((uint32) newdig % NBASE);
8654 : 1925417 : res_digits[2 * i] = (NumericDigit) ((uint32) newdig / NBASE);
8655 : : }
8656 : : Assert(carry == 0);
8657 : :
8658 : 20607 : pfree(dig);
8659 : :
8660 : : /*
8661 : : * Finally, round the result to the requested precision.
8662 : : */
8663 : 20607 : result->weight = res_weight;
8664 : 20607 : result->sign = res_sign;
8665 : :
8666 : : /* Round to target rscale (and set result->dscale) */
8667 : 20607 : round_var(result, rscale);
8668 : :
8669 : : /* Strip leading and trailing zeroes */
8670 : 20607 : strip_var(result);
8671 : : }
8672 : :
8673 : :
8674 : : /*
8675 : : * mul_var_short() -
8676 : : *
8677 : : * Special-case multiplication function used when var1 has 1-6 digits, var2
8678 : : * has at least as many digits as var1, and the exact product var1 * var2 is
8679 : : * requested.
8680 : : */
8681 : : static void
8682 : 772973 : mul_var_short(const NumericVar *var1, const NumericVar *var2,
8683 : : NumericVar *result)
8684 : : {
8685 : 772973 : int var1ndigits = var1->ndigits;
8686 : 772973 : int var2ndigits = var2->ndigits;
8687 : 772973 : NumericDigit *var1digits = var1->digits;
8688 : 772973 : NumericDigit *var2digits = var2->digits;
8689 : : int res_sign;
8690 : : int res_weight;
8691 : : int res_ndigits;
8692 : : NumericDigit *res_buf;
8693 : : NumericDigit *res_digits;
8694 : 772973 : uint32 carry = 0;
8695 : : uint32 term;
8696 : :
8697 : : /* Check preconditions */
8698 : : Assert(var1ndigits >= 1);
8699 : : Assert(var1ndigits <= 6);
8700 : : Assert(var2ndigits >= var1ndigits);
8701 : :
8702 : : /*
8703 : : * Determine the result sign, weight, and number of digits to calculate.
8704 : : * The weight figured here is correct if the product has no leading zero
8705 : : * digits; otherwise strip_var() will fix things up. Note that, unlike
8706 : : * mul_var(), we do not need to allocate an extra output digit, because we
8707 : : * are not rounding here.
8708 : : */
8709 [ + + ]: 772973 : if (var1->sign == var2->sign)
8710 : 772166 : res_sign = NUMERIC_POS;
8711 : : else
8712 : 807 : res_sign = NUMERIC_NEG;
8713 : 772973 : res_weight = var1->weight + var2->weight + 1;
8714 : 772973 : res_ndigits = var1ndigits + var2ndigits;
8715 : :
8716 : : /* Allocate result digit array */
8717 : 772973 : res_buf = digitbuf_alloc(res_ndigits + 1);
8718 : 772973 : res_buf[0] = 0; /* spare digit for later rounding */
8719 : 772973 : res_digits = res_buf + 1;
8720 : :
8721 : : /*
8722 : : * Compute the result digits in reverse, in one pass, propagating the
8723 : : * carry up as we go. The i'th result digit consists of the sum of the
8724 : : * products var1digits[i1] * var2digits[i2] for which i = i1 + i2 + 1.
8725 : : */
8726 : : #define PRODSUM1(v1,i1,v2,i2) ((v1)[(i1)] * (v2)[(i2)])
8727 : : #define PRODSUM2(v1,i1,v2,i2) (PRODSUM1(v1,i1,v2,i2) + (v1)[(i1)+1] * (v2)[(i2)-1])
8728 : : #define PRODSUM3(v1,i1,v2,i2) (PRODSUM2(v1,i1,v2,i2) + (v1)[(i1)+2] * (v2)[(i2)-2])
8729 : : #define PRODSUM4(v1,i1,v2,i2) (PRODSUM3(v1,i1,v2,i2) + (v1)[(i1)+3] * (v2)[(i2)-3])
8730 : : #define PRODSUM5(v1,i1,v2,i2) (PRODSUM4(v1,i1,v2,i2) + (v1)[(i1)+4] * (v2)[(i2)-4])
8731 : : #define PRODSUM6(v1,i1,v2,i2) (PRODSUM5(v1,i1,v2,i2) + (v1)[(i1)+5] * (v2)[(i2)-5])
8732 : :
8733 [ + + + + : 772973 : switch (var1ndigits)
+ + - ]
8734 : : {
8735 : 768868 : case 1:
8736 : : /* ---------
8737 : : * 1-digit case:
8738 : : * var1ndigits = 1
8739 : : * var2ndigits >= 1
8740 : : * res_ndigits = var2ndigits + 1
8741 : : * ----------
8742 : : */
8743 [ + + ]: 2406338 : for (int i = var2ndigits - 1; i >= 0; i--)
8744 : : {
8745 : 1637470 : term = PRODSUM1(var1digits, 0, var2digits, i) + carry;
8746 : 1637470 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8747 : 1637470 : carry = term / NBASE;
8748 : : }
8749 : 768868 : res_digits[0] = (NumericDigit) carry;
8750 : 768868 : break;
8751 : :
8752 : 519 : case 2:
8753 : : /* ---------
8754 : : * 2-digit case:
8755 : : * var1ndigits = 2
8756 : : * var2ndigits >= 2
8757 : : * res_ndigits = var2ndigits + 2
8758 : : * ----------
8759 : : */
8760 : : /* last result digit and carry */
8761 : 519 : term = PRODSUM1(var1digits, 1, var2digits, var2ndigits - 1);
8762 : 519 : res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
8763 : 519 : carry = term / NBASE;
8764 : :
8765 : : /* remaining digits, except for the first two */
8766 [ + + ]: 1573 : for (int i = var2ndigits - 1; i >= 1; i--)
8767 : : {
8768 : 1054 : term = PRODSUM2(var1digits, 0, var2digits, i) + carry;
8769 : 1054 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8770 : 1054 : carry = term / NBASE;
8771 : : }
8772 : 519 : break;
8773 : :
8774 : 146 : case 3:
8775 : : /* ---------
8776 : : * 3-digit case:
8777 : : * var1ndigits = 3
8778 : : * var2ndigits >= 3
8779 : : * res_ndigits = var2ndigits + 3
8780 : : * ----------
8781 : : */
8782 : : /* last two result digits */
8783 : 146 : term = PRODSUM1(var1digits, 2, var2digits, var2ndigits - 1);
8784 : 146 : res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
8785 : 146 : carry = term / NBASE;
8786 : :
8787 : 146 : term = PRODSUM2(var1digits, 1, var2digits, var2ndigits - 1) + carry;
8788 : 146 : res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
8789 : 146 : carry = term / NBASE;
8790 : :
8791 : : /* remaining digits, except for the first three */
8792 [ + + ]: 387 : for (int i = var2ndigits - 1; i >= 2; i--)
8793 : : {
8794 : 241 : term = PRODSUM3(var1digits, 0, var2digits, i) + carry;
8795 : 241 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8796 : 241 : carry = term / NBASE;
8797 : : }
8798 : 146 : break;
8799 : :
8800 : 2848 : case 4:
8801 : : /* ---------
8802 : : * 4-digit case:
8803 : : * var1ndigits = 4
8804 : : * var2ndigits >= 4
8805 : : * res_ndigits = var2ndigits + 4
8806 : : * ----------
8807 : : */
8808 : : /* last three result digits */
8809 : 2848 : term = PRODSUM1(var1digits, 3, var2digits, var2ndigits - 1);
8810 : 2848 : res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
8811 : 2848 : carry = term / NBASE;
8812 : :
8813 : 2848 : term = PRODSUM2(var1digits, 2, var2digits, var2ndigits - 1) + carry;
8814 : 2848 : res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
8815 : 2848 : carry = term / NBASE;
8816 : :
8817 : 2848 : term = PRODSUM3(var1digits, 1, var2digits, var2ndigits - 1) + carry;
8818 : 2848 : res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
8819 : 2848 : carry = term / NBASE;
8820 : :
8821 : : /* remaining digits, except for the first four */
8822 [ + + ]: 7938 : for (int i = var2ndigits - 1; i >= 3; i--)
8823 : : {
8824 : 5090 : term = PRODSUM4(var1digits, 0, var2digits, i) + carry;
8825 : 5090 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8826 : 5090 : carry = term / NBASE;
8827 : : }
8828 : 2848 : break;
8829 : :
8830 : 91 : case 5:
8831 : : /* ---------
8832 : : * 5-digit case:
8833 : : * var1ndigits = 5
8834 : : * var2ndigits >= 5
8835 : : * res_ndigits = var2ndigits + 5
8836 : : * ----------
8837 : : */
8838 : : /* last four result digits */
8839 : 91 : term = PRODSUM1(var1digits, 4, var2digits, var2ndigits - 1);
8840 : 91 : res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
8841 : 91 : carry = term / NBASE;
8842 : :
8843 : 91 : term = PRODSUM2(var1digits, 3, var2digits, var2ndigits - 1) + carry;
8844 : 91 : res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
8845 : 91 : carry = term / NBASE;
8846 : :
8847 : 91 : term = PRODSUM3(var1digits, 2, var2digits, var2ndigits - 1) + carry;
8848 : 91 : res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
8849 : 91 : carry = term / NBASE;
8850 : :
8851 : 91 : term = PRODSUM4(var1digits, 1, var2digits, var2ndigits - 1) + carry;
8852 : 91 : res_digits[res_ndigits - 4] = (NumericDigit) (term % NBASE);
8853 : 91 : carry = term / NBASE;
8854 : :
8855 : : /* remaining digits, except for the first five */
8856 [ + + ]: 242 : for (int i = var2ndigits - 1; i >= 4; i--)
8857 : : {
8858 : 151 : term = PRODSUM5(var1digits, 0, var2digits, i) + carry;
8859 : 151 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8860 : 151 : carry = term / NBASE;
8861 : : }
8862 : 91 : break;
8863 : :
8864 : 501 : case 6:
8865 : : /* ---------
8866 : : * 6-digit case:
8867 : : * var1ndigits = 6
8868 : : * var2ndigits >= 6
8869 : : * res_ndigits = var2ndigits + 6
8870 : : * ----------
8871 : : */
8872 : : /* last five result digits */
8873 : 501 : term = PRODSUM1(var1digits, 5, var2digits, var2ndigits - 1);
8874 : 501 : res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
8875 : 501 : carry = term / NBASE;
8876 : :
8877 : 501 : term = PRODSUM2(var1digits, 4, var2digits, var2ndigits - 1) + carry;
8878 : 501 : res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
8879 : 501 : carry = term / NBASE;
8880 : :
8881 : 501 : term = PRODSUM3(var1digits, 3, var2digits, var2ndigits - 1) + carry;
8882 : 501 : res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
8883 : 501 : carry = term / NBASE;
8884 : :
8885 : 501 : term = PRODSUM4(var1digits, 2, var2digits, var2ndigits - 1) + carry;
8886 : 501 : res_digits[res_ndigits - 4] = (NumericDigit) (term % NBASE);
8887 : 501 : carry = term / NBASE;
8888 : :
8889 : 501 : term = PRODSUM5(var1digits, 1, var2digits, var2ndigits - 1) + carry;
8890 : 501 : res_digits[res_ndigits - 5] = (NumericDigit) (term % NBASE);
8891 : 501 : carry = term / NBASE;
8892 : :
8893 : : /* remaining digits, except for the first six */
8894 [ + + ]: 1400 : for (int i = var2ndigits - 1; i >= 5; i--)
8895 : : {
8896 : 899 : term = PRODSUM6(var1digits, 0, var2digits, i) + carry;
8897 : 899 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8898 : 899 : carry = term / NBASE;
8899 : : }
8900 : 501 : break;
8901 : : }
8902 : :
8903 : : /*
8904 : : * Finally, for var1ndigits > 1, compute the remaining var1ndigits most
8905 : : * significant result digits.
8906 : : */
8907 [ + + + + : 772973 : switch (var1ndigits)
+ + ]
8908 : : {
8909 : 501 : case 6:
8910 : 501 : term = PRODSUM5(var1digits, 0, var2digits, 4) + carry;
8911 : 501 : res_digits[5] = (NumericDigit) (term % NBASE);
8912 : 501 : carry = term / NBASE;
8913 : : pg_fallthrough;
8914 : 592 : case 5:
8915 : 592 : term = PRODSUM4(var1digits, 0, var2digits, 3) + carry;
8916 : 592 : res_digits[4] = (NumericDigit) (term % NBASE);
8917 : 592 : carry = term / NBASE;
8918 : : pg_fallthrough;
8919 : 3440 : case 4:
8920 : 3440 : term = PRODSUM3(var1digits, 0, var2digits, 2) + carry;
8921 : 3440 : res_digits[3] = (NumericDigit) (term % NBASE);
8922 : 3440 : carry = term / NBASE;
8923 : : pg_fallthrough;
8924 : 3586 : case 3:
8925 : 3586 : term = PRODSUM2(var1digits, 0, var2digits, 1) + carry;
8926 : 3586 : res_digits[2] = (NumericDigit) (term % NBASE);
8927 : 3586 : carry = term / NBASE;
8928 : : pg_fallthrough;
8929 : 4105 : case 2:
8930 : 4105 : term = PRODSUM1(var1digits, 0, var2digits, 0) + carry;
8931 : 4105 : res_digits[1] = (NumericDigit) (term % NBASE);
8932 : 4105 : res_digits[0] = (NumericDigit) (term / NBASE);
8933 : 4105 : break;
8934 : : }
8935 : :
8936 : : /* Store the product in result */
8937 [ + + ]: 772973 : digitbuf_free(result->buf);
8938 : 772973 : result->ndigits = res_ndigits;
8939 : 772973 : result->buf = res_buf;
8940 : 772973 : result->digits = res_digits;
8941 : 772973 : result->weight = res_weight;
8942 : 772973 : result->sign = res_sign;
8943 : 772973 : result->dscale = var1->dscale + var2->dscale;
8944 : :
8945 : : /* Strip leading and trailing zeroes */
8946 : 772973 : strip_var(result);
8947 : 772973 : }
8948 : :
8949 : :
8950 : : /*
8951 : : * div_var() -
8952 : : *
8953 : : * Compute the quotient var1 / var2 to rscale fractional digits.
8954 : : *
8955 : : * If "round" is true, the result is rounded at the rscale'th digit; if
8956 : : * false, it is truncated (towards zero) at that digit.
8957 : : *
8958 : : * If "exact" is true, the exact result is computed to the specified rscale;
8959 : : * if false, successive quotient digits are approximated up to rscale plus
8960 : : * DIV_GUARD_DIGITS extra digits, ignoring all contributions from digits to
8961 : : * the right of that, before rounding or truncating to the specified rscale.
8962 : : * This can be significantly faster, and usually gives the same result as the
8963 : : * exact computation, but it may occasionally be off by one in the final
8964 : : * digit, if contributions from the ignored digits would have propagated
8965 : : * through the guard digits. This is good enough for the transcendental
8966 : : * functions, where small errors are acceptable.
8967 : : */
8968 : : static void
8969 : 380392 : div_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result,
8970 : : int rscale, bool round, bool exact)
8971 : : {
8972 : 380392 : int var1ndigits = var1->ndigits;
8973 : 380392 : int var2ndigits = var2->ndigits;
8974 : : int res_sign;
8975 : : int res_weight;
8976 : : int res_ndigits;
8977 : : int var1ndigitpairs;
8978 : : int var2ndigitpairs;
8979 : : int res_ndigitpairs;
8980 : : int div_ndigitpairs;
8981 : : int64 *dividend;
8982 : : int32 *divisor;
8983 : : double fdivisor,
8984 : : fdivisorinverse,
8985 : : fdividend,
8986 : : fquotient;
8987 : : int64 maxdiv;
8988 : : int qi;
8989 : : int32 qdigit;
8990 : : int64 carry;
8991 : : int64 newdig;
8992 : : int64 *remainder;
8993 : : NumericDigit *res_digits;
8994 : : int i;
8995 : :
8996 : : /*
8997 : : * First of all division by zero check; we must not be handed an
8998 : : * unnormalized divisor.
8999 : : */
9000 [ + + - + ]: 380392 : if (var2ndigits == 0 || var2->digits[0] == 0)
9001 [ + - ]: 4 : ereport(ERROR,
9002 : : (errcode(ERRCODE_DIVISION_BY_ZERO),
9003 : : errmsg("division by zero")));
9004 : :
9005 : : /*
9006 : : * If the divisor has just one or two digits, delegate to div_var_int(),
9007 : : * which uses fast short division.
9008 : : *
9009 : : * Similarly, on platforms with 128-bit integer support, delegate to
9010 : : * div_var_int64() for divisors with three or four digits.
9011 : : */
9012 [ + + ]: 380388 : if (var2ndigits <= 2)
9013 : : {
9014 : : int idivisor;
9015 : : int idivisor_weight;
9016 : :
9017 : 376060 : idivisor = var2->digits[0];
9018 : 376060 : idivisor_weight = var2->weight;
9019 [ + + ]: 376060 : if (var2ndigits == 2)
9020 : : {
9021 : 2271 : idivisor = idivisor * NBASE + var2->digits[1];
9022 : 2271 : idivisor_weight--;
9023 : : }
9024 [ + + ]: 376060 : if (var2->sign == NUMERIC_NEG)
9025 : 440 : idivisor = -idivisor;
9026 : :
9027 : 376060 : div_var_int(var1, idivisor, idivisor_weight, result, rscale, round);
9028 : 376060 : return;
9029 : : }
9030 : : #ifdef HAVE_INT128
9031 [ + + ]: 4328 : if (var2ndigits <= 4)
9032 : : {
9033 : : int64 idivisor;
9034 : : int idivisor_weight;
9035 : :
9036 : 360 : idivisor = var2->digits[0];
9037 : 360 : idivisor_weight = var2->weight;
9038 [ + + ]: 1340 : for (i = 1; i < var2ndigits; i++)
9039 : : {
9040 : 980 : idivisor = idivisor * NBASE + var2->digits[i];
9041 : 980 : idivisor_weight--;
9042 : : }
9043 [ + + ]: 360 : if (var2->sign == NUMERIC_NEG)
9044 : 80 : idivisor = -idivisor;
9045 : :
9046 : 360 : div_var_int64(var1, idivisor, idivisor_weight, result, rscale, round);
9047 : 360 : return;
9048 : : }
9049 : : #endif
9050 : :
9051 : : /*
9052 : : * Otherwise, perform full long division.
9053 : : */
9054 : :
9055 : : /* Result zero check */
9056 [ + + ]: 3968 : if (var1ndigits == 0)
9057 : : {
9058 : 24 : zero_var(result);
9059 : 24 : result->dscale = rscale;
9060 : 24 : return;
9061 : : }
9062 : :
9063 : : /*
9064 : : * The approximate computation can be significantly faster than the exact
9065 : : * one, since the working dividend is var2ndigitpairs base-NBASE^2 digits
9066 : : * shorter below. However, that comes with the tradeoff of computing
9067 : : * DIV_GUARD_DIGITS extra base-NBASE result digits. Ignoring all other
9068 : : * overheads, that suggests that, in theory, the approximate computation
9069 : : * will only be faster than the exact one when var2ndigits is greater than
9070 : : * 2 * (DIV_GUARD_DIGITS + 1), independent of the size of var1.
9071 : : *
9072 : : * Thus, we're better off doing an exact computation when var2 is shorter
9073 : : * than this. Empirically, it has been found that the exact threshold is
9074 : : * a little higher, due to other overheads in the outer division loop.
9075 : : */
9076 [ + + ]: 3944 : if (var2ndigits <= 2 * (DIV_GUARD_DIGITS + 2))
9077 : 2688 : exact = true;
9078 : :
9079 : : /*
9080 : : * Determine the result sign, weight and number of digits to calculate.
9081 : : * The weight figured here is correct if the emitted quotient has no
9082 : : * leading zero digits; otherwise strip_var() will fix things up.
9083 : : */
9084 [ + + ]: 3944 : if (var1->sign == var2->sign)
9085 : 3842 : res_sign = NUMERIC_POS;
9086 : : else
9087 : 102 : res_sign = NUMERIC_NEG;
9088 : 3944 : res_weight = var1->weight - var2->weight + 1;
9089 : : /* The number of accurate result digits we need to produce: */
9090 : 3944 : res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
9091 : : /* ... but always at least 1 */
9092 : 3944 : res_ndigits = Max(res_ndigits, 1);
9093 : : /* If rounding needed, figure one more digit to ensure correct result */
9094 [ + + ]: 3944 : if (round)
9095 : 654 : res_ndigits++;
9096 : : /* Add guard digits for roundoff error when producing approx result */
9097 [ + + ]: 3944 : if (!exact)
9098 : 1246 : res_ndigits += DIV_GUARD_DIGITS;
9099 : :
9100 : : /*
9101 : : * The computation itself is done using base-NBASE^2 arithmetic, so we
9102 : : * actually process the input digits in pairs, producing a base-NBASE^2
9103 : : * intermediate result. This significantly improves performance, since
9104 : : * the computation is O(N^2) in the number of input digits, and working in
9105 : : * base NBASE^2 effectively halves "N".
9106 : : */
9107 : 3944 : var1ndigitpairs = (var1ndigits + 1) / 2;
9108 : 3944 : var2ndigitpairs = (var2ndigits + 1) / 2;
9109 : 3944 : res_ndigitpairs = (res_ndigits + 1) / 2;
9110 : 3944 : res_ndigits = 2 * res_ndigitpairs;
9111 : :
9112 : : /*
9113 : : * We do the arithmetic in an array "dividend[]" of signed 64-bit
9114 : : * integers. Since PG_INT64_MAX is much larger than NBASE^4, this gives
9115 : : * us a lot of headroom to avoid normalizing carries immediately.
9116 : : *
9117 : : * When performing an exact computation, the working dividend requires
9118 : : * res_ndigitpairs + var2ndigitpairs digits. If var1 is larger than that,
9119 : : * the extra digits do not contribute to the result, and are ignored.
9120 : : *
9121 : : * When performing an approximate computation, the working dividend only
9122 : : * requires res_ndigitpairs digits (which includes the extra guard
9123 : : * digits). All input digits beyond that are ignored.
9124 : : */
9125 [ + + ]: 3944 : if (exact)
9126 : : {
9127 : 2698 : div_ndigitpairs = res_ndigitpairs + var2ndigitpairs;
9128 : 2698 : var1ndigitpairs = Min(var1ndigitpairs, div_ndigitpairs);
9129 : : }
9130 : : else
9131 : : {
9132 : 1246 : div_ndigitpairs = res_ndigitpairs;
9133 : 1246 : var1ndigitpairs = Min(var1ndigitpairs, div_ndigitpairs);
9134 : 1246 : var2ndigitpairs = Min(var2ndigitpairs, div_ndigitpairs);
9135 : : }
9136 : :
9137 : : /*
9138 : : * Allocate room for the working dividend (div_ndigitpairs 64-bit digits)
9139 : : * plus the divisor (var2ndigitpairs 32-bit base-NBASE^2 digits).
9140 : : *
9141 : : * For convenience, we allocate one extra dividend digit, which is set to
9142 : : * zero and not counted in div_ndigitpairs, so that the main loop below
9143 : : * can safely read and write the (qi+1)'th digit in the approximate case.
9144 : : */
9145 : 3944 : dividend = (int64 *) palloc((div_ndigitpairs + 1) * sizeof(int64) +
9146 : : var2ndigitpairs * sizeof(int32));
9147 : 3944 : divisor = (int32 *) (dividend + div_ndigitpairs + 1);
9148 : :
9149 : : /* load var1 into dividend[0 .. var1ndigitpairs-1], zeroing the rest */
9150 [ + + ]: 37052 : for (i = 0; i < var1ndigitpairs - 1; i++)
9151 : 33108 : dividend[i] = var1->digits[2 * i] * NBASE + var1->digits[2 * i + 1];
9152 : :
9153 [ + + ]: 3944 : if (2 * i + 1 < var1ndigits)
9154 : 2317 : dividend[i] = var1->digits[2 * i] * NBASE + var1->digits[2 * i + 1];
9155 : : else
9156 : 1627 : dividend[i] = var1->digits[2 * i] * NBASE;
9157 : :
9158 : 3944 : memset(dividend + i + 1, 0, (div_ndigitpairs - i) * sizeof(int64));
9159 : :
9160 : : /* load var2 into divisor[0 .. var2ndigitpairs-1] */
9161 [ + + ]: 29344 : for (i = 0; i < var2ndigitpairs - 1; i++)
9162 : 25400 : divisor[i] = var2->digits[2 * i] * NBASE + var2->digits[2 * i + 1];
9163 : :
9164 [ + + ]: 3944 : if (2 * i + 1 < var2ndigits)
9165 : 2118 : divisor[i] = var2->digits[2 * i] * NBASE + var2->digits[2 * i + 1];
9166 : : else
9167 : 1826 : divisor[i] = var2->digits[2 * i] * NBASE;
9168 : :
9169 : : /*
9170 : : * We estimate each quotient digit using floating-point arithmetic, taking
9171 : : * the first 2 base-NBASE^2 digits of the (current) dividend and divisor.
9172 : : * This must be float to avoid overflow.
9173 : : *
9174 : : * Since the floating-point dividend and divisor use 4 base-NBASE input
9175 : : * digits, they include roughly 40-53 bits of information from their
9176 : : * respective inputs (assuming NBASE is 10000), which fits well in IEEE
9177 : : * double-precision variables. The relative error in the floating-point
9178 : : * quotient digit will then be less than around 2/NBASE^3, so the
9179 : : * estimated base-NBASE^2 quotient digit will typically be correct, and
9180 : : * should not be off by more than one from the correct value.
9181 : : */
9182 : 3944 : fdivisor = (double) divisor[0] * NBASE_SQR;
9183 [ + - ]: 3944 : if (var2ndigitpairs > 1)
9184 : 3944 : fdivisor += (double) divisor[1];
9185 : 3944 : fdivisorinverse = 1.0 / fdivisor;
9186 : :
9187 : : /*
9188 : : * maxdiv tracks the maximum possible absolute value of any dividend[]
9189 : : * entry; when this threatens to exceed PG_INT64_MAX, we take the time to
9190 : : * propagate carries. Furthermore, we need to ensure that overflow
9191 : : * doesn't occur during the carry propagation passes either. The carry
9192 : : * values may have an absolute value as high as PG_INT64_MAX/NBASE^2 + 1,
9193 : : * so really we must normalize when digits threaten to exceed PG_INT64_MAX
9194 : : * - PG_INT64_MAX/NBASE^2 - 1.
9195 : : *
9196 : : * To avoid overflow in maxdiv itself, it represents the max absolute
9197 : : * value divided by NBASE^2-1, i.e., at the top of the loop it is known
9198 : : * that no dividend[] entry has an absolute value exceeding maxdiv *
9199 : : * (NBASE^2-1).
9200 : : *
9201 : : * Actually, though, that holds good only for dividend[] entries after
9202 : : * dividend[qi]; the adjustment done at the bottom of the loop may cause
9203 : : * dividend[qi + 1] to exceed the maxdiv limit, so that dividend[qi] in
9204 : : * the next iteration is beyond the limit. This does not cause problems,
9205 : : * as explained below.
9206 : : */
9207 : 3944 : maxdiv = 1;
9208 : :
9209 : : /*
9210 : : * Outer loop computes next quotient digit, which goes in dividend[qi].
9211 : : */
9212 [ + + ]: 36356 : for (qi = 0; qi < res_ndigitpairs; qi++)
9213 : : {
9214 : : /* Approximate the current dividend value */
9215 : 32412 : fdividend = (double) dividend[qi] * NBASE_SQR;
9216 : 32412 : fdividend += (double) dividend[qi + 1];
9217 : :
9218 : : /* Compute the (approximate) quotient digit */
9219 : 32412 : fquotient = fdividend * fdivisorinverse;
9220 [ + + ]: 32412 : qdigit = (fquotient >= 0.0) ? ((int32) fquotient) :
9221 : 5 : (((int32) fquotient) - 1); /* truncate towards -infinity */
9222 : :
9223 [ + + ]: 32412 : if (qdigit != 0)
9224 : : {
9225 : : /* Do we need to normalize now? */
9226 : 29799 : maxdiv += i64abs(qdigit);
9227 [ + + ]: 29799 : if (maxdiv > (PG_INT64_MAX - PG_INT64_MAX / NBASE_SQR - 1) / (NBASE_SQR - 1))
9228 : : {
9229 : : /*
9230 : : * Yes, do it. Note that if var2ndigitpairs is much smaller
9231 : : * than div_ndigitpairs, we can save a significant amount of
9232 : : * effort here by noting that we only need to normalise those
9233 : : * dividend[] entries touched where prior iterations
9234 : : * subtracted multiples of the divisor.
9235 : : */
9236 : 5 : carry = 0;
9237 [ + + ]: 5625 : for (i = Min(qi + var2ndigitpairs - 2, div_ndigitpairs - 1); i > qi; i--)
9238 : : {
9239 : 5620 : newdig = dividend[i] + carry;
9240 [ + - ]: 5620 : if (newdig < 0)
9241 : : {
9242 : 5620 : carry = -((-newdig - 1) / NBASE_SQR) - 1;
9243 : 5620 : newdig -= carry * NBASE_SQR;
9244 : : }
9245 [ # # ]: 0 : else if (newdig >= NBASE_SQR)
9246 : : {
9247 : 0 : carry = newdig / NBASE_SQR;
9248 : 0 : newdig -= carry * NBASE_SQR;
9249 : : }
9250 : : else
9251 : 0 : carry = 0;
9252 : 5620 : dividend[i] = newdig;
9253 : : }
9254 : 5 : dividend[qi] += carry;
9255 : :
9256 : : /*
9257 : : * All the dividend[] digits except possibly dividend[qi] are
9258 : : * now in the range 0..NBASE^2-1. We do not need to consider
9259 : : * dividend[qi] in the maxdiv value anymore, so we can reset
9260 : : * maxdiv to 1.
9261 : : */
9262 : 5 : maxdiv = 1;
9263 : :
9264 : : /*
9265 : : * Recompute the quotient digit since new info may have
9266 : : * propagated into the top two dividend digits.
9267 : : */
9268 : 5 : fdividend = (double) dividend[qi] * NBASE_SQR;
9269 : 5 : fdividend += (double) dividend[qi + 1];
9270 : 5 : fquotient = fdividend * fdivisorinverse;
9271 [ + - ]: 5 : qdigit = (fquotient >= 0.0) ? ((int32) fquotient) :
9272 : 0 : (((int32) fquotient) - 1); /* truncate towards -infinity */
9273 : :
9274 : 5 : maxdiv += i64abs(qdigit);
9275 : : }
9276 : :
9277 : : /*
9278 : : * Subtract off the appropriate multiple of the divisor.
9279 : : *
9280 : : * The digits beyond dividend[qi] cannot overflow, because we know
9281 : : * they will fall within the maxdiv limit. As for dividend[qi]
9282 : : * itself, note that qdigit is approximately trunc(dividend[qi] /
9283 : : * divisor[0]), which would make the new value simply dividend[qi]
9284 : : * mod divisor[0]. The lower-order terms in qdigit can change
9285 : : * this result by not more than about twice PG_INT64_MAX/NBASE^2,
9286 : : * so overflow is impossible.
9287 : : *
9288 : : * This inner loop is the performance bottleneck for division, so
9289 : : * code it in the same way as the inner loop of mul_var() so that
9290 : : * it can be auto-vectorized.
9291 : : */
9292 [ + - ]: 29799 : if (qdigit != 0)
9293 : : {
9294 : 29799 : int istop = Min(var2ndigitpairs, div_ndigitpairs - qi);
9295 : 29799 : int64 *dividend_qi = ÷nd[qi];
9296 : :
9297 [ + + ]: 6518569 : for (i = 0; i < istop; i++)
9298 : 6488770 : dividend_qi[i] -= (int64) qdigit * divisor[i];
9299 : : }
9300 : : }
9301 : :
9302 : : /*
9303 : : * The dividend digit we are about to replace might still be nonzero.
9304 : : * Fold it into the next digit position.
9305 : : *
9306 : : * There is no risk of overflow here, although proving that requires
9307 : : * some care. Much as with the argument for dividend[qi] not
9308 : : * overflowing, if we consider the first two terms in the numerator
9309 : : * and denominator of qdigit, we can see that the final value of
9310 : : * dividend[qi + 1] will be approximately a remainder mod
9311 : : * (divisor[0]*NBASE^2 + divisor[1]). Accounting for the lower-order
9312 : : * terms is a bit complicated but ends up adding not much more than
9313 : : * PG_INT64_MAX/NBASE^2 to the possible range. Thus, dividend[qi + 1]
9314 : : * cannot overflow here, and in its role as dividend[qi] in the next
9315 : : * loop iteration, it can't be large enough to cause overflow in the
9316 : : * carry propagation step (if any), either.
9317 : : *
9318 : : * But having said that: dividend[qi] can be more than
9319 : : * PG_INT64_MAX/NBASE^2, as noted above, which means that the product
9320 : : * dividend[qi] * NBASE^2 *can* overflow. When that happens, adding
9321 : : * it to dividend[qi + 1] will always cause a canceling overflow so
9322 : : * that the end result is correct. We could avoid the intermediate
9323 : : * overflow by doing the multiplication and addition using unsigned
9324 : : * int64 arithmetic, which is modulo 2^64, but so far there appears no
9325 : : * need.
9326 : : */
9327 : 32412 : dividend[qi + 1] += dividend[qi] * NBASE_SQR;
9328 : :
9329 : 32412 : dividend[qi] = qdigit;
9330 : : }
9331 : :
9332 : : /*
9333 : : * If an exact result was requested, use the remainder to correct the
9334 : : * approximate quotient. The remainder is in dividend[], immediately
9335 : : * after the quotient digits. Note, however, that although the remainder
9336 : : * starts at dividend[qi = res_ndigitpairs], the first digit is the result
9337 : : * of folding two remainder digits into one above, and the remainder
9338 : : * currently only occupies var2ndigitpairs - 1 digits (the last digit of
9339 : : * the working dividend was untouched by the computation above). Thus we
9340 : : * expand the remainder down by one base-NBASE^2 digit when we normalize
9341 : : * it, so that it completely fills the last var2ndigitpairs digits of the
9342 : : * dividend array.
9343 : : */
9344 [ + + ]: 3944 : if (exact)
9345 : : {
9346 : : /* Normalize the remainder, expanding it down by one digit */
9347 : 2698 : remainder = ÷nd[qi];
9348 : 2698 : carry = 0;
9349 [ + + ]: 15438 : for (i = var2ndigitpairs - 2; i >= 0; i--)
9350 : : {
9351 : 12740 : newdig = remainder[i] + carry;
9352 [ + + ]: 12740 : if (newdig < 0)
9353 : : {
9354 : 10012 : carry = -((-newdig - 1) / NBASE_SQR) - 1;
9355 : 10012 : newdig -= carry * NBASE_SQR;
9356 : : }
9357 [ + + ]: 2728 : else if (newdig >= NBASE_SQR)
9358 : : {
9359 : 2672 : carry = newdig / NBASE_SQR;
9360 : 2672 : newdig -= carry * NBASE_SQR;
9361 : : }
9362 : : else
9363 : 56 : carry = 0;
9364 : 12740 : remainder[i + 1] = newdig;
9365 : : }
9366 : 2698 : remainder[0] = carry;
9367 : :
9368 [ + + ]: 2698 : if (remainder[0] < 0)
9369 : : {
9370 : : /*
9371 : : * The remainder is negative, so the approximate quotient is too
9372 : : * large. Correct by reducing the quotient by one and adding the
9373 : : * divisor to the remainder until the remainder is positive. We
9374 : : * expect the quotient to be off by at most one, which has been
9375 : : * borne out in all testing, but not conclusively proven, so we
9376 : : * allow for larger corrections, just in case.
9377 : : */
9378 : : do
9379 : : {
9380 : : /* Add the divisor to the remainder */
9381 : 5 : carry = 0;
9382 [ + + ]: 65 : for (i = var2ndigitpairs - 1; i > 0; i--)
9383 : : {
9384 : 60 : newdig = remainder[i] + divisor[i] + carry;
9385 [ - + ]: 60 : if (newdig >= NBASE_SQR)
9386 : : {
9387 : 0 : remainder[i] = newdig - NBASE_SQR;
9388 : 0 : carry = 1;
9389 : : }
9390 : : else
9391 : : {
9392 : 60 : remainder[i] = newdig;
9393 : 60 : carry = 0;
9394 : : }
9395 : : }
9396 : 5 : remainder[0] += divisor[0] + carry;
9397 : :
9398 : : /* Subtract 1 from the quotient (propagating carries later) */
9399 : 5 : dividend[qi - 1]--;
9400 : :
9401 [ - + ]: 5 : } while (remainder[0] < 0);
9402 : : }
9403 : : else
9404 : : {
9405 : : /*
9406 : : * The remainder is nonnegative. If it's greater than or equal to
9407 : : * the divisor, then the approximate quotient is too small and
9408 : : * must be corrected. As above, we don't expect to have to apply
9409 : : * more than one correction, but allow for it just in case.
9410 : : */
9411 : : while (true)
9412 : 5 : {
9413 : 2698 : bool less = false;
9414 : :
9415 : : /* Is remainder < divisor? */
9416 [ + + ]: 2713 : for (i = 0; i < var2ndigitpairs; i++)
9417 : : {
9418 [ + + ]: 2708 : if (remainder[i] < divisor[i])
9419 : : {
9420 : 2693 : less = true;
9421 : 2693 : break;
9422 : : }
9423 [ - + ]: 15 : if (remainder[i] > divisor[i])
9424 : 0 : break; /* remainder > divisor */
9425 : : }
9426 [ + + ]: 2698 : if (less)
9427 : 2693 : break; /* quotient is correct */
9428 : :
9429 : : /* Subtract the divisor from the remainder */
9430 : 5 : carry = 0;
9431 [ + + ]: 15 : for (i = var2ndigitpairs - 1; i > 0; i--)
9432 : : {
9433 : 10 : newdig = remainder[i] - divisor[i] + carry;
9434 [ - + ]: 10 : if (newdig < 0)
9435 : : {
9436 : 0 : remainder[i] = newdig + NBASE_SQR;
9437 : 0 : carry = -1;
9438 : : }
9439 : : else
9440 : : {
9441 : 10 : remainder[i] = newdig;
9442 : 10 : carry = 0;
9443 : : }
9444 : : }
9445 : 5 : remainder[0] = remainder[0] - divisor[0] + carry;
9446 : :
9447 : : /* Add 1 to the quotient (propagating carries later) */
9448 : 5 : dividend[qi - 1]++;
9449 : : }
9450 : : }
9451 : : }
9452 : :
9453 : : /*
9454 : : * Because the quotient digits were estimates that might have been off by
9455 : : * one (and we didn't bother propagating carries when adjusting the
9456 : : * quotient above), some quotient digits might be out of range, so do a
9457 : : * final carry propagation pass to normalize back to base NBASE^2, and
9458 : : * construct the base-NBASE result digits. Note that this is still done
9459 : : * at full precision w/guard digits.
9460 : : */
9461 : 3944 : alloc_var(result, res_ndigits);
9462 : 3944 : res_digits = result->digits;
9463 : 3944 : carry = 0;
9464 [ + + ]: 36356 : for (i = res_ndigitpairs - 1; i >= 0; i--)
9465 : : {
9466 : 32412 : newdig = dividend[i] + carry;
9467 [ + + ]: 32412 : if (newdig < 0)
9468 : : {
9469 : 5 : carry = -((-newdig - 1) / NBASE_SQR) - 1;
9470 : 5 : newdig -= carry * NBASE_SQR;
9471 : : }
9472 [ - + ]: 32407 : else if (newdig >= NBASE_SQR)
9473 : : {
9474 : 0 : carry = newdig / NBASE_SQR;
9475 : 0 : newdig -= carry * NBASE_SQR;
9476 : : }
9477 : : else
9478 : 32407 : carry = 0;
9479 : 32412 : res_digits[2 * i + 1] = (NumericDigit) ((uint32) newdig % NBASE);
9480 : 32412 : res_digits[2 * i] = (NumericDigit) ((uint32) newdig / NBASE);
9481 : : }
9482 : : Assert(carry == 0);
9483 : :
9484 : 3944 : pfree(dividend);
9485 : :
9486 : : /*
9487 : : * Finally, round or truncate the result to the requested precision.
9488 : : */
9489 : 3944 : result->weight = res_weight;
9490 : 3944 : result->sign = res_sign;
9491 : :
9492 : : /* Round or truncate to target rscale (and set result->dscale) */
9493 [ + + ]: 3944 : if (round)
9494 : 654 : round_var(result, rscale);
9495 : : else
9496 : 3290 : trunc_var(result, rscale);
9497 : :
9498 : : /* Strip leading and trailing zeroes */
9499 : 3944 : strip_var(result);
9500 : : }
9501 : :
9502 : :
9503 : : /*
9504 : : * div_var_int() -
9505 : : *
9506 : : * Divide a numeric variable by a 32-bit integer with the specified weight.
9507 : : * The quotient var / (ival * NBASE^ival_weight) is stored in result.
9508 : : */
9509 : : static void
9510 : 389770 : div_var_int(const NumericVar *var, int ival, int ival_weight,
9511 : : NumericVar *result, int rscale, bool round)
9512 : : {
9513 : 389770 : NumericDigit *var_digits = var->digits;
9514 : 389770 : int var_ndigits = var->ndigits;
9515 : : int res_sign;
9516 : : int res_weight;
9517 : : int res_ndigits;
9518 : : NumericDigit *res_buf;
9519 : : NumericDigit *res_digits;
9520 : : uint32 divisor;
9521 : : int i;
9522 : :
9523 : : /* Guard against division by zero */
9524 [ - + ]: 389770 : if (ival == 0)
9525 [ # # ]: 0 : ereport(ERROR,
9526 : : errcode(ERRCODE_DIVISION_BY_ZERO),
9527 : : errmsg("division by zero"));
9528 : :
9529 : : /* Result zero check */
9530 [ + + ]: 389770 : if (var_ndigits == 0)
9531 : : {
9532 : 1575 : zero_var(result);
9533 : 1575 : result->dscale = rscale;
9534 : 1575 : return;
9535 : : }
9536 : :
9537 : : /*
9538 : : * Determine the result sign, weight and number of digits to calculate.
9539 : : * The weight figured here is correct if the emitted quotient has no
9540 : : * leading zero digits; otherwise strip_var() will fix things up.
9541 : : */
9542 [ + + ]: 388195 : if (var->sign == NUMERIC_POS)
9543 [ + + ]: 385951 : res_sign = ival > 0 ? NUMERIC_POS : NUMERIC_NEG;
9544 : : else
9545 [ + + ]: 2244 : res_sign = ival > 0 ? NUMERIC_NEG : NUMERIC_POS;
9546 : 388195 : res_weight = var->weight - ival_weight;
9547 : : /* The number of accurate result digits we need to produce: */
9548 : 388195 : res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
9549 : : /* ... but always at least 1 */
9550 : 388195 : res_ndigits = Max(res_ndigits, 1);
9551 : : /* If rounding needed, figure one more digit to ensure correct result */
9552 [ + + ]: 388195 : if (round)
9553 : 111658 : res_ndigits++;
9554 : :
9555 : 388195 : res_buf = digitbuf_alloc(res_ndigits + 1);
9556 : 388195 : res_buf[0] = 0; /* spare digit for later rounding */
9557 : 388195 : res_digits = res_buf + 1;
9558 : :
9559 : : /*
9560 : : * Now compute the quotient digits. This is the short division algorithm
9561 : : * described in Knuth volume 2, section 4.3.1 exercise 16, except that we
9562 : : * allow the divisor to exceed the internal base.
9563 : : *
9564 : : * In this algorithm, the carry from one digit to the next is at most
9565 : : * divisor - 1. Therefore, while processing the next digit, carry may
9566 : : * become as large as divisor * NBASE - 1, and so it requires a 64-bit
9567 : : * integer if this exceeds UINT_MAX.
9568 : : */
9569 : 388195 : divisor = abs(ival);
9570 : :
9571 [ + + ]: 388195 : if (divisor <= UINT_MAX / NBASE)
9572 : : {
9573 : : /* carry cannot overflow 32 bits */
9574 : 386335 : uint32 carry = 0;
9575 : :
9576 [ + + ]: 1914004 : for (i = 0; i < res_ndigits; i++)
9577 : : {
9578 [ + + ]: 1527669 : carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
9579 : 1527669 : res_digits[i] = (NumericDigit) (carry / divisor);
9580 : 1527669 : carry = carry % divisor;
9581 : : }
9582 : : }
9583 : : else
9584 : : {
9585 : : /* carry may exceed 32 bits */
9586 : 1860 : uint64 carry = 0;
9587 : :
9588 [ + + ]: 6029 : for (i = 0; i < res_ndigits; i++)
9589 : : {
9590 [ + + ]: 4169 : carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
9591 : 4169 : res_digits[i] = (NumericDigit) (carry / divisor);
9592 : 4169 : carry = carry % divisor;
9593 : : }
9594 : : }
9595 : :
9596 : : /* Store the quotient in result */
9597 [ + + ]: 388195 : digitbuf_free(result->buf);
9598 : 388195 : result->ndigits = res_ndigits;
9599 : 388195 : result->buf = res_buf;
9600 : 388195 : result->digits = res_digits;
9601 : 388195 : result->weight = res_weight;
9602 : 388195 : result->sign = res_sign;
9603 : :
9604 : : /* Round or truncate to target rscale (and set result->dscale) */
9605 [ + + ]: 388195 : if (round)
9606 : 111658 : round_var(result, rscale);
9607 : : else
9608 : 276537 : trunc_var(result, rscale);
9609 : :
9610 : : /* Strip leading/trailing zeroes */
9611 : 388195 : strip_var(result);
9612 : : }
9613 : :
9614 : :
9615 : : #ifdef HAVE_INT128
9616 : : /*
9617 : : * div_var_int64() -
9618 : : *
9619 : : * Divide a numeric variable by a 64-bit integer with the specified weight.
9620 : : * The quotient var / (ival * NBASE^ival_weight) is stored in result.
9621 : : *
9622 : : * This duplicates the logic in div_var_int(), so any changes made there
9623 : : * should be made here too.
9624 : : */
9625 : : static void
9626 : 360 : div_var_int64(const NumericVar *var, int64 ival, int ival_weight,
9627 : : NumericVar *result, int rscale, bool round)
9628 : : {
9629 : 360 : NumericDigit *var_digits = var->digits;
9630 : 360 : int var_ndigits = var->ndigits;
9631 : : int res_sign;
9632 : : int res_weight;
9633 : : int res_ndigits;
9634 : : NumericDigit *res_buf;
9635 : : NumericDigit *res_digits;
9636 : : uint64 divisor;
9637 : : int i;
9638 : :
9639 : : /* Guard against division by zero */
9640 [ - + ]: 360 : if (ival == 0)
9641 [ # # ]: 0 : ereport(ERROR,
9642 : : errcode(ERRCODE_DIVISION_BY_ZERO),
9643 : : errmsg("division by zero"));
9644 : :
9645 : : /* Result zero check */
9646 [ + + ]: 360 : if (var_ndigits == 0)
9647 : : {
9648 : 64 : zero_var(result);
9649 : 64 : result->dscale = rscale;
9650 : 64 : return;
9651 : : }
9652 : :
9653 : : /*
9654 : : * Determine the result sign, weight and number of digits to calculate.
9655 : : * The weight figured here is correct if the emitted quotient has no
9656 : : * leading zero digits; otherwise strip_var() will fix things up.
9657 : : */
9658 [ + + ]: 296 : if (var->sign == NUMERIC_POS)
9659 [ + + ]: 175 : res_sign = ival > 0 ? NUMERIC_POS : NUMERIC_NEG;
9660 : : else
9661 [ + + ]: 121 : res_sign = ival > 0 ? NUMERIC_NEG : NUMERIC_POS;
9662 : 296 : res_weight = var->weight - ival_weight;
9663 : : /* The number of accurate result digits we need to produce: */
9664 : 296 : res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
9665 : : /* ... but always at least 1 */
9666 : 296 : res_ndigits = Max(res_ndigits, 1);
9667 : : /* If rounding needed, figure one more digit to ensure correct result */
9668 [ + + ]: 296 : if (round)
9669 : 291 : res_ndigits++;
9670 : :
9671 : 296 : res_buf = digitbuf_alloc(res_ndigits + 1);
9672 : 296 : res_buf[0] = 0; /* spare digit for later rounding */
9673 : 296 : res_digits = res_buf + 1;
9674 : :
9675 : : /*
9676 : : * Now compute the quotient digits. This is the short division algorithm
9677 : : * described in Knuth volume 2, section 4.3.1 exercise 16, except that we
9678 : : * allow the divisor to exceed the internal base.
9679 : : *
9680 : : * In this algorithm, the carry from one digit to the next is at most
9681 : : * divisor - 1. Therefore, while processing the next digit, carry may
9682 : : * become as large as divisor * NBASE - 1, and so it requires a 128-bit
9683 : : * integer if this exceeds PG_UINT64_MAX.
9684 : : */
9685 : 296 : divisor = i64abs(ival);
9686 : :
9687 [ + + ]: 296 : if (divisor <= PG_UINT64_MAX / NBASE)
9688 : : {
9689 : : /* carry cannot overflow 64 bits */
9690 : 232 : uint64 carry = 0;
9691 : :
9692 [ + + ]: 2361 : for (i = 0; i < res_ndigits; i++)
9693 : : {
9694 [ + + ]: 2129 : carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
9695 : 2129 : res_digits[i] = (NumericDigit) (carry / divisor);
9696 : 2129 : carry = carry % divisor;
9697 : : }
9698 : : }
9699 : : else
9700 : : {
9701 : : /* carry may exceed 64 bits */
9702 : 64 : uint128 carry = 0;
9703 : :
9704 [ + + ]: 688 : for (i = 0; i < res_ndigits; i++)
9705 : : {
9706 [ + + ]: 624 : carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
9707 : 624 : res_digits[i] = (NumericDigit) (carry / divisor);
9708 : 624 : carry = carry % divisor;
9709 : : }
9710 : : }
9711 : :
9712 : : /* Store the quotient in result */
9713 [ + + ]: 296 : digitbuf_free(result->buf);
9714 : 296 : result->ndigits = res_ndigits;
9715 : 296 : result->buf = res_buf;
9716 : 296 : result->digits = res_digits;
9717 : 296 : result->weight = res_weight;
9718 : 296 : result->sign = res_sign;
9719 : :
9720 : : /* Round or truncate to target rscale (and set result->dscale) */
9721 [ + + ]: 296 : if (round)
9722 : 291 : round_var(result, rscale);
9723 : : else
9724 : 5 : trunc_var(result, rscale);
9725 : :
9726 : : /* Strip leading/trailing zeroes */
9727 : 296 : strip_var(result);
9728 : : }
9729 : : #endif
9730 : :
9731 : :
9732 : : /*
9733 : : * Default scale selection for division
9734 : : *
9735 : : * Returns the appropriate result scale for the division result.
9736 : : */
9737 : : static int
9738 : 99381 : select_div_scale(const NumericVar *var1, const NumericVar *var2)
9739 : : {
9740 : : int weight1,
9741 : : weight2,
9742 : : qweight,
9743 : : i;
9744 : : NumericDigit firstdigit1,
9745 : : firstdigit2;
9746 : : int rscale;
9747 : :
9748 : : /*
9749 : : * The result scale of a division isn't specified in any SQL standard. For
9750 : : * PostgreSQL we select a result scale that will give at least
9751 : : * NUMERIC_MIN_SIG_DIGITS significant digits, so that numeric gives a
9752 : : * result no less accurate than float8; but use a scale not less than
9753 : : * either input's display scale.
9754 : : */
9755 : :
9756 : : /* Get the actual (normalized) weight and first digit of each input */
9757 : :
9758 : 99381 : weight1 = 0; /* values to use if var1 is zero */
9759 : 99381 : firstdigit1 = 0;
9760 [ + + ]: 99381 : for (i = 0; i < var1->ndigits; i++)
9761 : : {
9762 : 98248 : firstdigit1 = var1->digits[i];
9763 [ + - ]: 98248 : if (firstdigit1 != 0)
9764 : : {
9765 : 98248 : weight1 = var1->weight - i;
9766 : 98248 : break;
9767 : : }
9768 : : }
9769 : :
9770 : 99381 : weight2 = 0; /* values to use if var2 is zero */
9771 : 99381 : firstdigit2 = 0;
9772 [ + + ]: 99381 : for (i = 0; i < var2->ndigits; i++)
9773 : : {
9774 : 99348 : firstdigit2 = var2->digits[i];
9775 [ + - ]: 99348 : if (firstdigit2 != 0)
9776 : : {
9777 : 99348 : weight2 = var2->weight - i;
9778 : 99348 : break;
9779 : : }
9780 : : }
9781 : :
9782 : : /*
9783 : : * Estimate weight of quotient. If the two first digits are equal, we
9784 : : * can't be sure, but assume that var1 is less than var2.
9785 : : */
9786 : 99381 : qweight = weight1 - weight2;
9787 [ + + ]: 99381 : if (firstdigit1 <= firstdigit2)
9788 : 88560 : qweight--;
9789 : :
9790 : : /* Select result scale */
9791 : 99381 : rscale = NUMERIC_MIN_SIG_DIGITS - qweight * DEC_DIGITS;
9792 : 99381 : rscale = Max(rscale, var1->dscale);
9793 : 99381 : rscale = Max(rscale, var2->dscale);
9794 : 99381 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
9795 : 99381 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
9796 : :
9797 : 99381 : return rscale;
9798 : : }
9799 : :
9800 : :
9801 : : /*
9802 : : * mod_var() -
9803 : : *
9804 : : * Calculate the modulo of two numerics at variable level
9805 : : */
9806 : : static void
9807 : 275501 : mod_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
9808 : : {
9809 : : NumericVar tmp;
9810 : :
9811 : 275501 : init_var(&tmp);
9812 : :
9813 : : /* ---------
9814 : : * We do this using the equation
9815 : : * mod(x,y) = x - trunc(x/y)*y
9816 : : * div_var can be persuaded to give us trunc(x/y) directly.
9817 : : * ----------
9818 : : */
9819 : 275501 : div_var(var1, var2, &tmp, 0, false, true);
9820 : :
9821 : 275501 : mul_var(var2, &tmp, &tmp, var2->dscale);
9822 : :
9823 : 275501 : sub_var(var1, &tmp, result);
9824 : :
9825 : 275501 : free_var(&tmp);
9826 : 275501 : }
9827 : :
9828 : :
9829 : : /*
9830 : : * div_mod_var() -
9831 : : *
9832 : : * Calculate the truncated integer quotient and numeric remainder of two
9833 : : * numeric variables. The remainder is precise to var2's dscale.
9834 : : */
9835 : : static void
9836 : 3275 : div_mod_var(const NumericVar *var1, const NumericVar *var2,
9837 : : NumericVar *quot, NumericVar *rem)
9838 : : {
9839 : : NumericVar q;
9840 : : NumericVar r;
9841 : :
9842 : 3275 : init_var(&q);
9843 : 3275 : init_var(&r);
9844 : :
9845 : : /*
9846 : : * Use div_var() with exact = false to get an initial estimate for the
9847 : : * integer quotient (truncated towards zero). This might be slightly
9848 : : * inaccurate, but we correct it below.
9849 : : */
9850 : 3275 : div_var(var1, var2, &q, 0, false, false);
9851 : :
9852 : : /* Compute initial estimate of remainder using the quotient estimate. */
9853 : 3275 : mul_var(var2, &q, &r, var2->dscale);
9854 : 3275 : sub_var(var1, &r, &r);
9855 : :
9856 : : /*
9857 : : * Adjust the results if necessary --- the remainder should have the same
9858 : : * sign as var1, and its absolute value should be less than the absolute
9859 : : * value of var2.
9860 : : */
9861 [ + - - + ]: 3275 : while (r.ndigits != 0 && r.sign != var1->sign)
9862 : : {
9863 : : /* The absolute value of the quotient is too large */
9864 [ # # ]: 0 : if (var1->sign == var2->sign)
9865 : : {
9866 : 0 : sub_var(&q, &const_one, &q);
9867 : 0 : add_var(&r, var2, &r);
9868 : : }
9869 : : else
9870 : : {
9871 : 0 : add_var(&q, &const_one, &q);
9872 : 0 : sub_var(&r, var2, &r);
9873 : : }
9874 : : }
9875 : :
9876 [ - + ]: 3275 : while (cmp_abs(&r, var2) >= 0)
9877 : : {
9878 : : /* The absolute value of the quotient is too small */
9879 [ # # ]: 0 : if (var1->sign == var2->sign)
9880 : : {
9881 : 0 : add_var(&q, &const_one, &q);
9882 : 0 : sub_var(&r, var2, &r);
9883 : : }
9884 : : else
9885 : : {
9886 : 0 : sub_var(&q, &const_one, &q);
9887 : 0 : add_var(&r, var2, &r);
9888 : : }
9889 : : }
9890 : :
9891 : 3275 : set_var_from_var(&q, quot);
9892 : 3275 : set_var_from_var(&r, rem);
9893 : :
9894 : 3275 : free_var(&q);
9895 : 3275 : free_var(&r);
9896 : 3275 : }
9897 : :
9898 : :
9899 : : /*
9900 : : * ceil_var() -
9901 : : *
9902 : : * Return the smallest integer greater than or equal to the argument
9903 : : * on variable level
9904 : : */
9905 : : static void
9906 : 136 : ceil_var(const NumericVar *var, NumericVar *result)
9907 : : {
9908 : : NumericVar tmp;
9909 : :
9910 : 136 : init_var(&tmp);
9911 : 136 : set_var_from_var(var, &tmp);
9912 : :
9913 : 136 : trunc_var(&tmp, 0);
9914 : :
9915 [ + + + + ]: 136 : if (var->sign == NUMERIC_POS && cmp_var(var, &tmp) != 0)
9916 : 40 : add_var(&tmp, &const_one, &tmp);
9917 : :
9918 : 136 : set_var_from_var(&tmp, result);
9919 : 136 : free_var(&tmp);
9920 : 136 : }
9921 : :
9922 : :
9923 : : /*
9924 : : * floor_var() -
9925 : : *
9926 : : * Return the largest integer equal to or less than the argument
9927 : : * on variable level
9928 : : */
9929 : : static void
9930 : 72 : floor_var(const NumericVar *var, NumericVar *result)
9931 : : {
9932 : : NumericVar tmp;
9933 : :
9934 : 72 : init_var(&tmp);
9935 : 72 : set_var_from_var(var, &tmp);
9936 : :
9937 : 72 : trunc_var(&tmp, 0);
9938 : :
9939 [ + + + + ]: 72 : if (var->sign == NUMERIC_NEG && cmp_var(var, &tmp) != 0)
9940 : 20 : sub_var(&tmp, &const_one, &tmp);
9941 : :
9942 : 72 : set_var_from_var(&tmp, result);
9943 : 72 : free_var(&tmp);
9944 : 72 : }
9945 : :
9946 : :
9947 : : /*
9948 : : * gcd_var() -
9949 : : *
9950 : : * Calculate the greatest common divisor of two numerics at variable level
9951 : : */
9952 : : static void
9953 : 148 : gcd_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
9954 : : {
9955 : : int res_dscale;
9956 : : int cmp;
9957 : : NumericVar tmp_arg;
9958 : : NumericVar mod;
9959 : :
9960 : 148 : res_dscale = Max(var1->dscale, var2->dscale);
9961 : :
9962 : : /*
9963 : : * Arrange for var1 to be the number with the greater absolute value.
9964 : : *
9965 : : * This would happen automatically in the loop below, but avoids an
9966 : : * expensive modulo operation.
9967 : : */
9968 : 148 : cmp = cmp_abs(var1, var2);
9969 [ + + ]: 148 : if (cmp < 0)
9970 : : {
9971 : 56 : const NumericVar *tmp = var1;
9972 : :
9973 : 56 : var1 = var2;
9974 : 56 : var2 = tmp;
9975 : : }
9976 : :
9977 : : /*
9978 : : * Also avoid the taking the modulo if the inputs have the same absolute
9979 : : * value, or if the smaller input is zero.
9980 : : */
9981 [ + + + + ]: 148 : if (cmp == 0 || var2->ndigits == 0)
9982 : : {
9983 : 48 : set_var_from_var(var1, result);
9984 : 48 : result->sign = NUMERIC_POS;
9985 : 48 : result->dscale = res_dscale;
9986 : 48 : return;
9987 : : }
9988 : :
9989 : 100 : init_var(&tmp_arg);
9990 : 100 : init_var(&mod);
9991 : :
9992 : : /* Use the Euclidean algorithm to find the GCD */
9993 : 100 : set_var_from_var(var1, &tmp_arg);
9994 : 100 : set_var_from_var(var2, result);
9995 : :
9996 : : for (;;)
9997 : : {
9998 : : /* this loop can take a while, so allow it to be interrupted */
9999 [ - + ]: 392 : CHECK_FOR_INTERRUPTS();
10000 : :
10001 : 392 : mod_var(&tmp_arg, result, &mod);
10002 [ + + ]: 392 : if (mod.ndigits == 0)
10003 : 100 : break;
10004 : 292 : set_var_from_var(result, &tmp_arg);
10005 : 292 : set_var_from_var(&mod, result);
10006 : : }
10007 : 100 : result->sign = NUMERIC_POS;
10008 : 100 : result->dscale = res_dscale;
10009 : :
10010 : 100 : free_var(&tmp_arg);
10011 : 100 : free_var(&mod);
10012 : : }
10013 : :
10014 : :
10015 : : /*
10016 : : * sqrt_var() -
10017 : : *
10018 : : * Compute the square root of x using the Karatsuba Square Root algorithm.
10019 : : * NOTE: we allow rscale < 0 here, implying rounding before the decimal
10020 : : * point.
10021 : : */
10022 : : static void
10023 : 3028 : sqrt_var(const NumericVar *arg, NumericVar *result, int rscale)
10024 : : {
10025 : : int stat;
10026 : : int res_weight;
10027 : : int res_ndigits;
10028 : : int src_ndigits;
10029 : : int step;
10030 : : int ndigits[32];
10031 : : int blen;
10032 : : int64 arg_int64;
10033 : : int src_idx;
10034 : : int64 s_int64;
10035 : : int64 r_int64;
10036 : : NumericVar s_var;
10037 : : NumericVar r_var;
10038 : : NumericVar a0_var;
10039 : : NumericVar a1_var;
10040 : : NumericVar q_var;
10041 : : NumericVar u_var;
10042 : :
10043 : 3028 : stat = cmp_var(arg, &const_zero);
10044 [ + + ]: 3028 : if (stat == 0)
10045 : : {
10046 : 12 : zero_var(result);
10047 : 12 : result->dscale = rscale;
10048 : 12 : return;
10049 : : }
10050 : :
10051 : : /*
10052 : : * SQL2003 defines sqrt() in terms of power, so we need to emit the right
10053 : : * SQLSTATE error code if the operand is negative.
10054 : : */
10055 [ + + ]: 3016 : if (stat < 0)
10056 [ + - ]: 4 : ereport(ERROR,
10057 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
10058 : : errmsg("cannot take square root of a negative number")));
10059 : :
10060 : 3012 : init_var(&s_var);
10061 : 3012 : init_var(&r_var);
10062 : 3012 : init_var(&a0_var);
10063 : 3012 : init_var(&a1_var);
10064 : 3012 : init_var(&q_var);
10065 : 3012 : init_var(&u_var);
10066 : :
10067 : : /*
10068 : : * The result weight is half the input weight, rounded towards minus
10069 : : * infinity --- res_weight = floor(arg->weight / 2).
10070 : : */
10071 [ + + ]: 3012 : if (arg->weight >= 0)
10072 : 2741 : res_weight = arg->weight / 2;
10073 : : else
10074 : 271 : res_weight = -((-arg->weight - 1) / 2 + 1);
10075 : :
10076 : : /*
10077 : : * Number of NBASE digits to compute. To ensure correct rounding, compute
10078 : : * at least 1 extra decimal digit. We explicitly allow rscale to be
10079 : : * negative here, but must always compute at least 1 NBASE digit. Thus
10080 : : * res_ndigits = res_weight + 1 + ceil((rscale + 1) / DEC_DIGITS) or 1.
10081 : : */
10082 [ + - ]: 3012 : if (rscale + 1 >= 0)
10083 : 3012 : res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS) / DEC_DIGITS;
10084 : : else
10085 : 0 : res_ndigits = res_weight + 1 - (-rscale - 1) / DEC_DIGITS;
10086 : 3012 : res_ndigits = Max(res_ndigits, 1);
10087 : :
10088 : : /*
10089 : : * Number of source NBASE digits logically required to produce a result
10090 : : * with this precision --- every digit before the decimal point, plus 2
10091 : : * for each result digit after the decimal point (or minus 2 for each
10092 : : * result digit we round before the decimal point).
10093 : : */
10094 : 3012 : src_ndigits = arg->weight + 1 + (res_ndigits - res_weight - 1) * 2;
10095 : 3012 : src_ndigits = Max(src_ndigits, 1);
10096 : :
10097 : : /* ----------
10098 : : * From this point on, we treat the input and the result as integers and
10099 : : * compute the integer square root and remainder using the Karatsuba
10100 : : * Square Root algorithm, which may be written recursively as follows:
10101 : : *
10102 : : * SqrtRem(n = a3*b^3 + a2*b^2 + a1*b + a0):
10103 : : * [ for some base b, and coefficients a0,a1,a2,a3 chosen so that
10104 : : * 0 <= a0,a1,a2 < b and a3 >= b/4 ]
10105 : : * Let (s,r) = SqrtRem(a3*b + a2)
10106 : : * Let (q,u) = DivRem(r*b + a1, 2*s)
10107 : : * Let s = s*b + q
10108 : : * Let r = u*b + a0 - q^2
10109 : : * If r < 0 Then
10110 : : * Let r = r + s
10111 : : * Let s = s - 1
10112 : : * Let r = r + s
10113 : : * Return (s,r)
10114 : : *
10115 : : * See "Karatsuba Square Root", Paul Zimmermann, INRIA Research Report
10116 : : * RR-3805, November 1999. At the time of writing this was available
10117 : : * on the net at <https://hal.inria.fr/inria-00072854>.
10118 : : *
10119 : : * The way to read the assumption "n = a3*b^3 + a2*b^2 + a1*b + a0" is
10120 : : * "choose a base b such that n requires at least four base-b digits to
10121 : : * express; then those digits are a3,a2,a1,a0, with a3 possibly larger
10122 : : * than b". For optimal performance, b should have approximately a
10123 : : * quarter the number of digits in the input, so that the outer square
10124 : : * root computes roughly twice as many digits as the inner one. For
10125 : : * simplicity, we choose b = NBASE^blen, an integer power of NBASE.
10126 : : *
10127 : : * We implement the algorithm iteratively rather than recursively, to
10128 : : * allow the working variables to be reused. With this approach, each
10129 : : * digit of the input is read precisely once --- src_idx tracks the number
10130 : : * of input digits used so far.
10131 : : *
10132 : : * The array ndigits[] holds the number of NBASE digits of the input that
10133 : : * will have been used at the end of each iteration, which roughly doubles
10134 : : * each time. Note that the array elements are stored in reverse order,
10135 : : * so if the final iteration requires src_ndigits = 37 input digits, the
10136 : : * array will contain [37,19,11,7,5,3], and we would start by computing
10137 : : * the square root of the 3 most significant NBASE digits.
10138 : : *
10139 : : * In each iteration, we choose blen to be the largest integer for which
10140 : : * the input number has a3 >= b/4, when written in the form above. In
10141 : : * general, this means blen = src_ndigits / 4 (truncated), but if
10142 : : * src_ndigits is a multiple of 4, that might lead to the coefficient a3
10143 : : * being less than b/4 (if the first input digit is less than NBASE/4), in
10144 : : * which case we choose blen = src_ndigits / 4 - 1. The number of digits
10145 : : * in the inner square root is then src_ndigits - 2*blen. So, for
10146 : : * example, if we have src_ndigits = 26 initially, the array ndigits[]
10147 : : * will be either [26,14,8,4] or [26,14,8,6,4], depending on the size of
10148 : : * the first input digit.
10149 : : *
10150 : : * Additionally, we can put an upper bound on the number of steps required
10151 : : * as follows --- suppose that the number of source digits is an n-bit
10152 : : * number in the range [2^(n-1), 2^n-1], then blen will be in the range
10153 : : * [2^(n-3)-1, 2^(n-2)-1] and the number of digits in the inner square
10154 : : * root will be in the range [2^(n-2), 2^(n-1)+1]. In the next step, blen
10155 : : * will be in the range [2^(n-4)-1, 2^(n-3)] and the number of digits in
10156 : : * the next inner square root will be in the range [2^(n-3), 2^(n-2)+1].
10157 : : * This pattern repeats, and in the worst case the array ndigits[] will
10158 : : * contain [2^n-1, 2^(n-1)+1, 2^(n-2)+1, ... 9, 5, 3], and the computation
10159 : : * will require n steps. Therefore, since all digit array sizes are
10160 : : * signed 32-bit integers, the number of steps required is guaranteed to
10161 : : * be less than 32.
10162 : : * ----------
10163 : : */
10164 : 3012 : step = 0;
10165 [ + + ]: 14431 : while ((ndigits[step] = src_ndigits) > 4)
10166 : : {
10167 : : /* Choose b so that a3 >= b/4, as described above */
10168 : 11419 : blen = src_ndigits / 4;
10169 [ + + + + ]: 11419 : if (blen * 4 == src_ndigits && arg->digits[0] < NBASE / 4)
10170 : 259 : blen--;
10171 : :
10172 : : /* Number of digits in the next step (inner square root) */
10173 : 11419 : src_ndigits -= 2 * blen;
10174 : 11419 : step++;
10175 : : }
10176 : :
10177 : : /*
10178 : : * First iteration (innermost square root and remainder):
10179 : : *
10180 : : * Here src_ndigits <= 4, and the input fits in an int64. Its square root
10181 : : * has at most 9 decimal digits, so estimate it using double precision
10182 : : * arithmetic, which will in fact almost certainly return the correct
10183 : : * result with no further correction required.
10184 : : */
10185 : 3012 : arg_int64 = arg->digits[0];
10186 [ + + ]: 9635 : for (src_idx = 1; src_idx < src_ndigits; src_idx++)
10187 : : {
10188 : 6623 : arg_int64 *= NBASE;
10189 [ + + ]: 6623 : if (src_idx < arg->ndigits)
10190 : 5611 : arg_int64 += arg->digits[src_idx];
10191 : : }
10192 : :
10193 : 3012 : s_int64 = (int64) sqrt((double) arg_int64);
10194 : 3012 : r_int64 = arg_int64 - s_int64 * s_int64;
10195 : :
10196 : : /*
10197 : : * Use Newton's method to correct the result, if necessary.
10198 : : *
10199 : : * This uses integer division with truncation to compute the truncated
10200 : : * integer square root by iterating using the formula x -> (x + n/x) / 2.
10201 : : * This is known to converge to isqrt(n), unless n+1 is a perfect square.
10202 : : * If n+1 is a perfect square, the sequence will oscillate between the two
10203 : : * values isqrt(n) and isqrt(n)+1, so we can be assured of convergence by
10204 : : * checking the remainder.
10205 : : */
10206 [ - + - + ]: 3012 : while (r_int64 < 0 || r_int64 > 2 * s_int64)
10207 : : {
10208 : 0 : s_int64 = (s_int64 + arg_int64 / s_int64) / 2;
10209 : 0 : r_int64 = arg_int64 - s_int64 * s_int64;
10210 : : }
10211 : :
10212 : : /*
10213 : : * Iterations with src_ndigits <= 8:
10214 : : *
10215 : : * The next 1 or 2 iterations compute larger (outer) square roots with
10216 : : * src_ndigits <= 8, so the result still fits in an int64 (even though the
10217 : : * input no longer does) and we can continue to compute using int64
10218 : : * variables to avoid more expensive numeric computations.
10219 : : *
10220 : : * It is fairly easy to see that there is no risk of the intermediate
10221 : : * values below overflowing 64-bit integers. In the worst case, the
10222 : : * previous iteration will have computed a 3-digit square root (of a
10223 : : * 6-digit input less than NBASE^6 / 4), so at the start of this
10224 : : * iteration, s will be less than NBASE^3 / 2 = 10^12 / 2, and r will be
10225 : : * less than 10^12. In this case, blen will be 1, so numer will be less
10226 : : * than 10^17, and denom will be less than 10^12 (and hence u will also be
10227 : : * less than 10^12). Finally, since q^2 = u*b + a0 - r, we can also be
10228 : : * sure that q^2 < 10^17. Therefore all these quantities fit comfortably
10229 : : * in 64-bit integers.
10230 : : */
10231 : 3012 : step--;
10232 [ + - + + ]: 7612 : while (step >= 0 && (src_ndigits = ndigits[step]) <= 8)
10233 : : {
10234 : : int b;
10235 : : int a0;
10236 : : int a1;
10237 : : int i;
10238 : : int64 numer;
10239 : : int64 denom;
10240 : : int64 q;
10241 : : int64 u;
10242 : :
10243 : 4600 : blen = (src_ndigits - src_idx) / 2;
10244 : :
10245 : : /* Extract a1 and a0, and compute b */
10246 : 4600 : a0 = 0;
10247 : 4600 : a1 = 0;
10248 : 4600 : b = 1;
10249 : :
10250 [ + + ]: 9319 : for (i = 0; i < blen; i++, src_idx++)
10251 : : {
10252 : 4719 : b *= NBASE;
10253 : 4719 : a1 *= NBASE;
10254 [ + + ]: 4719 : if (src_idx < arg->ndigits)
10255 : 3500 : a1 += arg->digits[src_idx];
10256 : : }
10257 : :
10258 [ + + ]: 9319 : for (i = 0; i < blen; i++, src_idx++)
10259 : : {
10260 : 4719 : a0 *= NBASE;
10261 [ + + ]: 4719 : if (src_idx < arg->ndigits)
10262 : 3388 : a0 += arg->digits[src_idx];
10263 : : }
10264 : :
10265 : : /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
10266 : 4600 : numer = r_int64 * b + a1;
10267 : 4600 : denom = 2 * s_int64;
10268 : 4600 : q = numer / denom;
10269 : 4600 : u = numer - q * denom;
10270 : :
10271 : : /* Compute s = s*b + q and r = u*b + a0 - q^2 */
10272 : 4600 : s_int64 = s_int64 * b + q;
10273 : 4600 : r_int64 = u * b + a0 - q * q;
10274 : :
10275 [ + + ]: 4600 : if (r_int64 < 0)
10276 : : {
10277 : : /* s is too large by 1; set r += s, s--, r += s */
10278 : 161 : r_int64 += s_int64;
10279 : 161 : s_int64--;
10280 : 161 : r_int64 += s_int64;
10281 : : }
10282 : :
10283 : : Assert(src_idx == src_ndigits); /* All input digits consumed */
10284 : 4600 : step--;
10285 : : }
10286 : :
10287 : : /*
10288 : : * On platforms with 128-bit integer support, we can further delay the
10289 : : * need to use numeric variables.
10290 : : */
10291 : : #ifdef HAVE_INT128
10292 [ + - ]: 3012 : if (step >= 0)
10293 : : {
10294 : : int128 s_int128;
10295 : : int128 r_int128;
10296 : :
10297 : 3012 : s_int128 = s_int64;
10298 : 3012 : r_int128 = r_int64;
10299 : :
10300 : : /*
10301 : : * Iterations with src_ndigits <= 16:
10302 : : *
10303 : : * The result fits in an int128 (even though the input doesn't) so we
10304 : : * use int128 variables to avoid more expensive numeric computations.
10305 : : */
10306 [ + + + + ]: 6556 : while (step >= 0 && (src_ndigits = ndigits[step]) <= 16)
10307 : : {
10308 : : int64 b;
10309 : : int64 a0;
10310 : : int64 a1;
10311 : : int64 i;
10312 : : int128 numer;
10313 : : int128 denom;
10314 : : int128 q;
10315 : : int128 u;
10316 : :
10317 : 3544 : blen = (src_ndigits - src_idx) / 2;
10318 : :
10319 : : /* Extract a1 and a0, and compute b */
10320 : 3544 : a0 = 0;
10321 : 3544 : a1 = 0;
10322 : 3544 : b = 1;
10323 : :
10324 [ + + ]: 11736 : for (i = 0; i < blen; i++, src_idx++)
10325 : : {
10326 : 8192 : b *= NBASE;
10327 : 8192 : a1 *= NBASE;
10328 [ + + ]: 8192 : if (src_idx < arg->ndigits)
10329 : 4915 : a1 += arg->digits[src_idx];
10330 : : }
10331 : :
10332 [ + + ]: 11736 : for (i = 0; i < blen; i++, src_idx++)
10333 : : {
10334 : 8192 : a0 *= NBASE;
10335 [ + + ]: 8192 : if (src_idx < arg->ndigits)
10336 : 3407 : a0 += arg->digits[src_idx];
10337 : : }
10338 : :
10339 : : /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
10340 : 3544 : numer = r_int128 * b + a1;
10341 : 3544 : denom = 2 * s_int128;
10342 : 3544 : q = numer / denom;
10343 : 3544 : u = numer - q * denom;
10344 : :
10345 : : /* Compute s = s*b + q and r = u*b + a0 - q^2 */
10346 : 3544 : s_int128 = s_int128 * b + q;
10347 : 3544 : r_int128 = u * b + a0 - q * q;
10348 : :
10349 [ + + ]: 3544 : if (r_int128 < 0)
10350 : : {
10351 : : /* s is too large by 1; set r += s, s--, r += s */
10352 : 146 : r_int128 += s_int128;
10353 : 146 : s_int128--;
10354 : 146 : r_int128 += s_int128;
10355 : : }
10356 : :
10357 : : Assert(src_idx == src_ndigits); /* All input digits consumed */
10358 : 3544 : step--;
10359 : : }
10360 : :
10361 : : /*
10362 : : * All remaining iterations require numeric variables. Convert the
10363 : : * integer values to NumericVar and continue. Note that in the final
10364 : : * iteration we don't need the remainder, so we can save a few cycles
10365 : : * there by not fully computing it.
10366 : : */
10367 : 3012 : int128_to_numericvar(s_int128, &s_var);
10368 [ + + ]: 3012 : if (step >= 0)
10369 : 1988 : int128_to_numericvar(r_int128, &r_var);
10370 : : }
10371 : : else
10372 : : {
10373 : 0 : int64_to_numericvar(s_int64, &s_var);
10374 : : /* step < 0, so we certainly don't need r */
10375 : : }
10376 : : #else /* !HAVE_INT128 */
10377 : : int64_to_numericvar(s_int64, &s_var);
10378 : : if (step >= 0)
10379 : : int64_to_numericvar(r_int64, &r_var);
10380 : : #endif /* HAVE_INT128 */
10381 : :
10382 : : /*
10383 : : * The remaining iterations with src_ndigits > 8 (or 16, if have int128)
10384 : : * use numeric variables.
10385 : : */
10386 [ + + ]: 6287 : while (step >= 0)
10387 : : {
10388 : : int tmp_len;
10389 : :
10390 : 3275 : src_ndigits = ndigits[step];
10391 : 3275 : blen = (src_ndigits - src_idx) / 2;
10392 : :
10393 : : /* Extract a1 and a0 */
10394 [ + + ]: 3275 : if (src_idx < arg->ndigits)
10395 : : {
10396 : 1088 : tmp_len = Min(blen, arg->ndigits - src_idx);
10397 : 1088 : alloc_var(&a1_var, tmp_len);
10398 : 1088 : memcpy(a1_var.digits, arg->digits + src_idx,
10399 : : tmp_len * sizeof(NumericDigit));
10400 : 1088 : a1_var.weight = blen - 1;
10401 : 1088 : a1_var.sign = NUMERIC_POS;
10402 : 1088 : a1_var.dscale = 0;
10403 : 1088 : strip_var(&a1_var);
10404 : : }
10405 : : else
10406 : : {
10407 : 2187 : zero_var(&a1_var);
10408 : 2187 : a1_var.dscale = 0;
10409 : : }
10410 : 3275 : src_idx += blen;
10411 : :
10412 [ + + ]: 3275 : if (src_idx < arg->ndigits)
10413 : : {
10414 : 1088 : tmp_len = Min(blen, arg->ndigits - src_idx);
10415 : 1088 : alloc_var(&a0_var, tmp_len);
10416 : 1088 : memcpy(a0_var.digits, arg->digits + src_idx,
10417 : : tmp_len * sizeof(NumericDigit));
10418 : 1088 : a0_var.weight = blen - 1;
10419 : 1088 : a0_var.sign = NUMERIC_POS;
10420 : 1088 : a0_var.dscale = 0;
10421 : 1088 : strip_var(&a0_var);
10422 : : }
10423 : : else
10424 : : {
10425 : 2187 : zero_var(&a0_var);
10426 : 2187 : a0_var.dscale = 0;
10427 : : }
10428 : 3275 : src_idx += blen;
10429 : :
10430 : : /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
10431 : 3275 : set_var_from_var(&r_var, &q_var);
10432 : 3275 : q_var.weight += blen;
10433 : 3275 : add_var(&q_var, &a1_var, &q_var);
10434 : 3275 : add_var(&s_var, &s_var, &u_var);
10435 : 3275 : div_mod_var(&q_var, &u_var, &q_var, &u_var);
10436 : :
10437 : : /* Compute s = s*b + q */
10438 : 3275 : s_var.weight += blen;
10439 : 3275 : add_var(&s_var, &q_var, &s_var);
10440 : :
10441 : : /*
10442 : : * Compute r = u*b + a0 - q^2.
10443 : : *
10444 : : * In the final iteration, we don't actually need r; we just need to
10445 : : * know whether it is negative, so that we know whether to adjust s.
10446 : : * So instead of the final subtraction we can just compare.
10447 : : */
10448 : 3275 : u_var.weight += blen;
10449 : 3275 : add_var(&u_var, &a0_var, &u_var);
10450 : 3275 : mul_var(&q_var, &q_var, &q_var, 0);
10451 : :
10452 [ + + ]: 3275 : if (step > 0)
10453 : : {
10454 : : /* Need r for later iterations */
10455 : 1287 : sub_var(&u_var, &q_var, &r_var);
10456 [ + + ]: 1287 : if (r_var.sign == NUMERIC_NEG)
10457 : : {
10458 : : /* s is too large by 1; set r += s, s--, r += s */
10459 : 85 : add_var(&r_var, &s_var, &r_var);
10460 : 85 : sub_var(&s_var, &const_one, &s_var);
10461 : 85 : add_var(&r_var, &s_var, &r_var);
10462 : : }
10463 : : }
10464 : : else
10465 : : {
10466 : : /* Don't need r anymore, except to test if s is too large by 1 */
10467 [ + + ]: 1988 : if (cmp_var(&u_var, &q_var) < 0)
10468 : 27 : sub_var(&s_var, &const_one, &s_var);
10469 : : }
10470 : :
10471 : : Assert(src_idx == src_ndigits); /* All input digits consumed */
10472 : 3275 : step--;
10473 : : }
10474 : :
10475 : : /*
10476 : : * Construct the final result, rounding it to the requested precision.
10477 : : */
10478 : 3012 : set_var_from_var(&s_var, result);
10479 : 3012 : result->weight = res_weight;
10480 : 3012 : result->sign = NUMERIC_POS;
10481 : :
10482 : : /* Round to target rscale (and set result->dscale) */
10483 : 3012 : round_var(result, rscale);
10484 : :
10485 : : /* Strip leading and trailing zeroes */
10486 : 3012 : strip_var(result);
10487 : :
10488 : 3012 : free_var(&s_var);
10489 : 3012 : free_var(&r_var);
10490 : 3012 : free_var(&a0_var);
10491 : 3012 : free_var(&a1_var);
10492 : 3012 : free_var(&q_var);
10493 : 3012 : free_var(&u_var);
10494 : : }
10495 : :
10496 : :
10497 : : /*
10498 : : * exp_var() -
10499 : : *
10500 : : * Raise e to the power of x, computed to rscale fractional digits
10501 : : */
10502 : : static void
10503 : 139 : exp_var(const NumericVar *arg, NumericVar *result, int rscale)
10504 : : {
10505 : : NumericVar x;
10506 : : NumericVar elem;
10507 : : int ni;
10508 : : double val;
10509 : : int dweight;
10510 : : int ndiv2;
10511 : : int sig_digits;
10512 : : int local_rscale;
10513 : :
10514 : 139 : init_var(&x);
10515 : 139 : init_var(&elem);
10516 : :
10517 : 139 : set_var_from_var(arg, &x);
10518 : :
10519 : : /*
10520 : : * Estimate the dweight of the result using floating point arithmetic, so
10521 : : * that we can choose an appropriate local rscale for the calculation.
10522 : : */
10523 : 139 : val = numericvar_to_double_no_overflow(&x);
10524 : :
10525 : : /* Guard against overflow/underflow */
10526 : : /* If you change this limit, see also power_var()'s limit */
10527 [ + + ]: 139 : if (fabs(val) >= NUMERIC_MAX_RESULT_SCALE * 3)
10528 : : {
10529 [ - + ]: 5 : if (val > 0)
10530 [ # # ]: 0 : ereport(ERROR,
10531 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
10532 : : errmsg("value overflows numeric format")));
10533 : 5 : zero_var(result);
10534 : 5 : result->dscale = rscale;
10535 : 5 : return;
10536 : : }
10537 : :
10538 : : /* decimal weight = log10(e^x) = x * log10(e) */
10539 : 134 : dweight = (int) (val * 0.434294481903252);
10540 : :
10541 : : /*
10542 : : * Reduce x to the range -0.01 <= x <= 0.01 (approximately) by dividing by
10543 : : * 2^ndiv2, to improve the convergence rate of the Taylor series.
10544 : : *
10545 : : * Note that the overflow check above ensures that fabs(x) < 6000, which
10546 : : * means that ndiv2 <= 20 here.
10547 : : */
10548 [ + + ]: 134 : if (fabs(val) > 0.01)
10549 : : {
10550 : 110 : ndiv2 = 1;
10551 : 110 : val /= 2;
10552 : :
10553 [ + + ]: 1402 : while (fabs(val) > 0.01)
10554 : : {
10555 : 1292 : ndiv2++;
10556 : 1292 : val /= 2;
10557 : : }
10558 : :
10559 : 110 : local_rscale = x.dscale + ndiv2;
10560 : 110 : div_var_int(&x, 1 << ndiv2, 0, &x, local_rscale, true);
10561 : : }
10562 : : else
10563 : 24 : ndiv2 = 0;
10564 : :
10565 : : /*
10566 : : * Set the scale for the Taylor series expansion. The final result has
10567 : : * (dweight + rscale + 1) significant digits. In addition, we have to
10568 : : * raise the Taylor series result to the power 2^ndiv2, which introduces
10569 : : * an error of up to around log10(2^ndiv2) digits, so work with this many
10570 : : * extra digits of precision (plus a few more for good measure).
10571 : : */
10572 : 134 : sig_digits = 1 + dweight + rscale + (int) (ndiv2 * 0.301029995663981);
10573 : 134 : sig_digits = Max(sig_digits, 0) + 8;
10574 : :
10575 : 134 : local_rscale = sig_digits - 1;
10576 : :
10577 : : /*
10578 : : * Use the Taylor series
10579 : : *
10580 : : * exp(x) = 1 + x + x^2/2! + x^3/3! + ...
10581 : : *
10582 : : * Given the limited range of x, this should converge reasonably quickly.
10583 : : * We run the series until the terms fall below the local_rscale limit.
10584 : : */
10585 : 134 : add_var(&const_one, &x, result);
10586 : :
10587 : 134 : mul_var(&x, &x, &elem, local_rscale);
10588 : 134 : ni = 2;
10589 : 134 : div_var_int(&elem, ni, 0, &elem, local_rscale, true);
10590 : :
10591 [ + + ]: 3639 : while (elem.ndigits != 0)
10592 : : {
10593 : 3505 : add_var(result, &elem, result);
10594 : :
10595 : 3505 : mul_var(&elem, &x, &elem, local_rscale);
10596 : 3505 : ni++;
10597 : 3505 : div_var_int(&elem, ni, 0, &elem, local_rscale, true);
10598 : : }
10599 : :
10600 : : /*
10601 : : * Compensate for the argument range reduction. Since the weight of the
10602 : : * result doubles with each multiplication, we can reduce the local rscale
10603 : : * as we proceed.
10604 : : */
10605 [ + + ]: 1536 : while (ndiv2-- > 0)
10606 : : {
10607 : 1402 : local_rscale = sig_digits - result->weight * 2 * DEC_DIGITS;
10608 : 1402 : local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
10609 : 1402 : mul_var(result, result, result, local_rscale);
10610 : : }
10611 : :
10612 : : /* Round to requested rscale */
10613 : 134 : round_var(result, rscale);
10614 : :
10615 : 134 : free_var(&x);
10616 : 134 : free_var(&elem);
10617 : : }
10618 : :
10619 : :
10620 : : /*
10621 : : * Estimate the dweight of the most significant decimal digit of the natural
10622 : : * logarithm of a number.
10623 : : *
10624 : : * Essentially, we're approximating log10(abs(ln(var))). This is used to
10625 : : * determine the appropriate rscale when computing natural logarithms.
10626 : : *
10627 : : * Note: many callers call this before range-checking the input. Therefore,
10628 : : * we must be robust against values that are invalid to apply ln() to.
10629 : : * We don't wish to throw an error here, so just return zero in such cases.
10630 : : */
10631 : : static int
10632 : 526 : estimate_ln_dweight(const NumericVar *var)
10633 : : {
10634 : : int ln_dweight;
10635 : :
10636 : : /* Caller should fail on ln(negative), but for the moment return zero */
10637 [ + + ]: 526 : if (var->sign != NUMERIC_POS)
10638 : 28 : return 0;
10639 : :
10640 [ + + + + ]: 937 : if (cmp_var(var, &const_zero_point_nine) >= 0 &&
10641 : 439 : cmp_var(var, &const_one_point_one) <= 0)
10642 : 66 : {
10643 : : /*
10644 : : * 0.9 <= var <= 1.1
10645 : : *
10646 : : * ln(var) has a negative weight (possibly very large). To get a
10647 : : * reasonably accurate result, estimate it using ln(1+x) ~= x.
10648 : : */
10649 : : NumericVar x;
10650 : :
10651 : 66 : init_var(&x);
10652 : 66 : sub_var(var, &const_one, &x);
10653 : :
10654 [ + + ]: 66 : if (x.ndigits > 0)
10655 : : {
10656 : : /* Use weight of most significant decimal digit of x */
10657 : 35 : ln_dweight = x.weight * DEC_DIGITS + (int) log10(x.digits[0]);
10658 : : }
10659 : : else
10660 : : {
10661 : : /* x = 0. Since ln(1) = 0 exactly, we don't need extra digits */
10662 : 31 : ln_dweight = 0;
10663 : : }
10664 : :
10665 : 66 : free_var(&x);
10666 : : }
10667 : : else
10668 : : {
10669 : : /*
10670 : : * Estimate the logarithm using the first couple of digits from the
10671 : : * input number. This will give an accurate result whenever the input
10672 : : * is not too close to 1.
10673 : : */
10674 [ + + ]: 432 : if (var->ndigits > 0)
10675 : : {
10676 : : int digits;
10677 : : int dweight;
10678 : : double ln_var;
10679 : :
10680 : 404 : digits = var->digits[0];
10681 : 404 : dweight = var->weight * DEC_DIGITS;
10682 : :
10683 [ + + ]: 404 : if (var->ndigits > 1)
10684 : : {
10685 : 246 : digits = digits * NBASE + var->digits[1];
10686 : 246 : dweight -= DEC_DIGITS;
10687 : : }
10688 : :
10689 : : /*----------
10690 : : * We have var ~= digits * 10^dweight
10691 : : * so ln(var) ~= ln(digits) + dweight * ln(10)
10692 : : *----------
10693 : : */
10694 : 404 : ln_var = log((double) digits) + dweight * 2.302585092994046;
10695 : 404 : ln_dweight = (int) log10(fabs(ln_var));
10696 : : }
10697 : : else
10698 : : {
10699 : : /* Caller should fail on ln(0), but for the moment return zero */
10700 : 28 : ln_dweight = 0;
10701 : : }
10702 : : }
10703 : :
10704 : 498 : return ln_dweight;
10705 : : }
10706 : :
10707 : :
10708 : : /*
10709 : : * ln_var() -
10710 : : *
10711 : : * Compute the natural log of x
10712 : : */
10713 : : static void
10714 : 599 : ln_var(const NumericVar *arg, NumericVar *result, int rscale)
10715 : : {
10716 : : NumericVar x;
10717 : : NumericVar xx;
10718 : : int ni;
10719 : : NumericVar elem;
10720 : : NumericVar fact;
10721 : : int nsqrt;
10722 : : int local_rscale;
10723 : : int cmp;
10724 : :
10725 : 599 : cmp = cmp_var(arg, &const_zero);
10726 [ + + ]: 599 : if (cmp == 0)
10727 [ + - ]: 28 : ereport(ERROR,
10728 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
10729 : : errmsg("cannot take logarithm of zero")));
10730 [ + + ]: 571 : else if (cmp < 0)
10731 [ + - ]: 24 : ereport(ERROR,
10732 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
10733 : : errmsg("cannot take logarithm of a negative number")));
10734 : :
10735 : 547 : init_var(&x);
10736 : 547 : init_var(&xx);
10737 : 547 : init_var(&elem);
10738 : 547 : init_var(&fact);
10739 : :
10740 : 547 : set_var_from_var(arg, &x);
10741 : 547 : set_var_from_var(&const_two, &fact);
10742 : :
10743 : : /*
10744 : : * Reduce input into range 0.9 < x < 1.1 with repeated sqrt() operations.
10745 : : *
10746 : : * The final logarithm will have up to around rscale+6 significant digits.
10747 : : * Each sqrt() will roughly halve the weight of x, so adjust the local
10748 : : * rscale as we work so that we keep this many significant digits at each
10749 : : * step (plus a few more for good measure).
10750 : : *
10751 : : * Note that we allow local_rscale < 0 during this input reduction
10752 : : * process, which implies rounding before the decimal point. sqrt_var()
10753 : : * explicitly supports this, and it significantly reduces the work
10754 : : * required to reduce very large inputs to the required range. Once the
10755 : : * input reduction is complete, x.weight will be 0 and its display scale
10756 : : * will be non-negative again.
10757 : : */
10758 : 547 : nsqrt = 0;
10759 [ + + ]: 818 : while (cmp_var(&x, &const_zero_point_nine) <= 0)
10760 : : {
10761 : 271 : local_rscale = rscale - x.weight * DEC_DIGITS / 2 + 8;
10762 : 271 : sqrt_var(&x, &x, local_rscale);
10763 : 271 : mul_var(&fact, &const_two, &fact, 0);
10764 : 271 : nsqrt++;
10765 : : }
10766 [ + + ]: 2956 : while (cmp_var(&x, &const_one_point_one) >= 0)
10767 : : {
10768 : 2409 : local_rscale = rscale - x.weight * DEC_DIGITS / 2 + 8;
10769 : 2409 : sqrt_var(&x, &x, local_rscale);
10770 : 2409 : mul_var(&fact, &const_two, &fact, 0);
10771 : 2409 : nsqrt++;
10772 : : }
10773 : :
10774 : : /*
10775 : : * We use the Taylor series for 0.5 * ln((1+z)/(1-z)),
10776 : : *
10777 : : * z + z^3/3 + z^5/5 + ...
10778 : : *
10779 : : * where z = (x-1)/(x+1) is in the range (approximately) -0.053 .. 0.048
10780 : : * due to the above range-reduction of x.
10781 : : *
10782 : : * The convergence of this is not as fast as one would like, but is
10783 : : * tolerable given that z is small.
10784 : : *
10785 : : * The Taylor series result will be multiplied by 2^(nsqrt+1), which has a
10786 : : * decimal weight of (nsqrt+1) * log10(2), so work with this many extra
10787 : : * digits of precision (plus a few more for good measure).
10788 : : */
10789 : 547 : local_rscale = rscale + (int) ((nsqrt + 1) * 0.301029995663981) + 8;
10790 : :
10791 : 547 : sub_var(&x, &const_one, result);
10792 : 547 : add_var(&x, &const_one, &elem);
10793 : 547 : div_var(result, &elem, result, local_rscale, true, false);
10794 : 547 : set_var_from_var(result, &xx);
10795 : 547 : mul_var(result, result, &x, local_rscale);
10796 : :
10797 : 547 : ni = 1;
10798 : :
10799 : : for (;;)
10800 : : {
10801 : 9961 : ni += 2;
10802 : 9961 : mul_var(&xx, &x, &xx, local_rscale);
10803 : 9961 : div_var_int(&xx, ni, 0, &elem, local_rscale, true);
10804 : :
10805 [ + + ]: 9961 : if (elem.ndigits == 0)
10806 : 547 : break;
10807 : :
10808 : 9414 : add_var(result, &elem, result);
10809 : :
10810 [ - + ]: 9414 : if (elem.weight < (result->weight - local_rscale * 2 / DEC_DIGITS))
10811 : 0 : break;
10812 : : }
10813 : :
10814 : : /* Compensate for argument range reduction, round to requested rscale */
10815 : 547 : mul_var(result, &fact, result, rscale);
10816 : :
10817 : 547 : free_var(&x);
10818 : 547 : free_var(&xx);
10819 : 547 : free_var(&elem);
10820 : 547 : free_var(&fact);
10821 : 547 : }
10822 : :
10823 : :
10824 : : /*
10825 : : * log_var() -
10826 : : *
10827 : : * Compute the logarithm of num in a given base.
10828 : : *
10829 : : * Note: this routine chooses dscale of the result.
10830 : : */
10831 : : static void
10832 : 160 : log_var(const NumericVar *base, const NumericVar *num, NumericVar *result)
10833 : : {
10834 : : NumericVar ln_base;
10835 : : NumericVar ln_num;
10836 : : int ln_base_dweight;
10837 : : int ln_num_dweight;
10838 : : int result_dweight;
10839 : : int rscale;
10840 : : int ln_base_rscale;
10841 : : int ln_num_rscale;
10842 : :
10843 : : /*
10844 : : * ln_var will throw a suitable error for most invalid-input cases, but we
10845 : : * need a special case for base == 1, else we'd report "division by zero"
10846 : : * which is a bit confusing.
10847 : : */
10848 [ + + ]: 160 : if (cmp_var(base, &const_one) == 0)
10849 [ + - ]: 8 : ereport(ERROR,
10850 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
10851 : : errmsg("cannot take logarithm using base one")));
10852 : :
10853 : 152 : init_var(&ln_base);
10854 : 152 : init_var(&ln_num);
10855 : :
10856 : : /* Estimated dweights of ln(base), ln(num) and the final result */
10857 : 152 : ln_base_dweight = estimate_ln_dweight(base);
10858 : 152 : ln_num_dweight = estimate_ln_dweight(num);
10859 : 152 : result_dweight = ln_num_dweight - ln_base_dweight;
10860 : :
10861 : : /*
10862 : : * Select the scale of the result so that it will have at least
10863 : : * NUMERIC_MIN_SIG_DIGITS significant digits and is not less than either
10864 : : * input's display scale.
10865 : : */
10866 : 152 : rscale = NUMERIC_MIN_SIG_DIGITS - result_dweight;
10867 : 152 : rscale = Max(rscale, base->dscale);
10868 : 152 : rscale = Max(rscale, num->dscale);
10869 : 152 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
10870 : 152 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
10871 : :
10872 : : /*
10873 : : * Set the scales for ln(base) and ln(num) so that they each have more
10874 : : * significant digits than the final result.
10875 : : */
10876 : 152 : ln_base_rscale = rscale + result_dweight - ln_base_dweight + 8;
10877 : 152 : ln_base_rscale = Max(ln_base_rscale, NUMERIC_MIN_DISPLAY_SCALE);
10878 : :
10879 : 152 : ln_num_rscale = rscale + result_dweight - ln_num_dweight + 8;
10880 : 152 : ln_num_rscale = Max(ln_num_rscale, NUMERIC_MIN_DISPLAY_SCALE);
10881 : :
10882 : : /* Form natural logarithms */
10883 : 152 : ln_var(base, &ln_base, ln_base_rscale);
10884 : 136 : ln_var(num, &ln_num, ln_num_rscale);
10885 : :
10886 : : /* Divide and round to the required scale */
10887 : 116 : div_var(&ln_num, &ln_base, result, rscale, true, false);
10888 : :
10889 : 116 : free_var(&ln_num);
10890 : 116 : free_var(&ln_base);
10891 : 116 : }
10892 : :
10893 : :
10894 : : /*
10895 : : * power_var() -
10896 : : *
10897 : : * Raise base to the power of exp
10898 : : *
10899 : : * Note: this routine chooses dscale of the result.
10900 : : */
10901 : : static void
10902 : 968 : power_var(const NumericVar *base, const NumericVar *exp, NumericVar *result)
10903 : : {
10904 : : int res_sign;
10905 : : NumericVar abs_base;
10906 : : NumericVar ln_base;
10907 : : NumericVar ln_num;
10908 : : int ln_dweight;
10909 : : int rscale;
10910 : : int sig_digits;
10911 : : int local_rscale;
10912 : : double val;
10913 : :
10914 : : /* If exp can be represented as an integer, use power_var_int */
10915 [ + + + + ]: 968 : if (exp->ndigits == 0 || exp->ndigits <= exp->weight + 1)
10916 : : {
10917 : : /* exact integer, but does it fit in int? */
10918 : : int64 expval64;
10919 : :
10920 [ + + ]: 878 : if (numericvar_to_int64(exp, &expval64))
10921 : : {
10922 [ + - + + ]: 873 : if (expval64 >= PG_INT32_MIN && expval64 <= PG_INT32_MAX)
10923 : : {
10924 : : /* Okay, use power_var_int */
10925 : 848 : power_var_int(base, (int) expval64, exp->dscale, result);
10926 : 840 : return;
10927 : : }
10928 : : }
10929 : : }
10930 : :
10931 : : /*
10932 : : * This avoids log(0) for cases of 0 raised to a non-integer. 0 ^ 0 is
10933 : : * handled by power_var_int().
10934 : : */
10935 [ + + ]: 120 : if (cmp_var(base, &const_zero) == 0)
10936 : : {
10937 : 14 : set_var_from_var(&const_zero, result);
10938 : 14 : result->dscale = NUMERIC_MIN_SIG_DIGITS; /* no need to round */
10939 : 14 : return;
10940 : : }
10941 : :
10942 : 106 : init_var(&abs_base);
10943 : 106 : init_var(&ln_base);
10944 : 106 : init_var(&ln_num);
10945 : :
10946 : : /*
10947 : : * If base is negative, insist that exp be an integer. The result is then
10948 : : * positive if exp is even and negative if exp is odd.
10949 : : */
10950 [ + + ]: 106 : if (base->sign == NUMERIC_NEG)
10951 : : {
10952 : : /*
10953 : : * Check that exp is an integer. This error code is defined by the
10954 : : * SQL standard, and matches other errors in numeric_power().
10955 : : */
10956 [ + - + + ]: 27 : if (exp->ndigits > 0 && exp->ndigits > exp->weight + 1)
10957 [ + - ]: 12 : ereport(ERROR,
10958 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
10959 : : errmsg("a negative number raised to a non-integer power yields a complex result")));
10960 : :
10961 : : /* Test if exp is odd or even */
10962 [ + - + + ]: 15 : if (exp->ndigits > 0 && exp->ndigits == exp->weight + 1 &&
10963 [ + + ]: 10 : (exp->digits[exp->ndigits - 1] & 1))
10964 : 5 : res_sign = NUMERIC_NEG;
10965 : : else
10966 : 10 : res_sign = NUMERIC_POS;
10967 : :
10968 : : /* Then work with abs(base) below */
10969 : 15 : set_var_from_var(base, &abs_base);
10970 : 15 : abs_base.sign = NUMERIC_POS;
10971 : 15 : base = &abs_base;
10972 : : }
10973 : : else
10974 : 79 : res_sign = NUMERIC_POS;
10975 : :
10976 : : /*----------
10977 : : * Decide on the scale for the ln() calculation. For this we need an
10978 : : * estimate of the weight of the result, which we obtain by doing an
10979 : : * initial low-precision calculation of exp * ln(base).
10980 : : *
10981 : : * We want result = e ^ (exp * ln(base))
10982 : : * so result dweight = log10(result) = exp * ln(base) * log10(e)
10983 : : *
10984 : : * We also perform a crude overflow test here so that we can exit early if
10985 : : * the full-precision result is sure to overflow, and to guard against
10986 : : * integer overflow when determining the scale for the real calculation.
10987 : : * exp_var() supports inputs up to NUMERIC_MAX_RESULT_SCALE * 3, so the
10988 : : * result will overflow if exp * ln(base) >= NUMERIC_MAX_RESULT_SCALE * 3.
10989 : : * Since the values here are only approximations, we apply a small fuzz
10990 : : * factor to this overflow test and let exp_var() determine the exact
10991 : : * overflow threshold so that it is consistent for all inputs.
10992 : : *----------
10993 : : */
10994 : 94 : ln_dweight = estimate_ln_dweight(base);
10995 : :
10996 : : /*
10997 : : * Set the scale for the low-precision calculation, computing ln(base) to
10998 : : * around 8 significant digits. Note that ln_dweight may be as small as
10999 : : * -NUMERIC_DSCALE_MAX, so the scale may exceed NUMERIC_MAX_DISPLAY_SCALE
11000 : : * here.
11001 : : */
11002 : 94 : local_rscale = 8 - ln_dweight;
11003 : 94 : local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11004 : :
11005 : 94 : ln_var(base, &ln_base, local_rscale);
11006 : :
11007 : 94 : mul_var(&ln_base, exp, &ln_num, local_rscale);
11008 : :
11009 : 94 : val = numericvar_to_double_no_overflow(&ln_num);
11010 : :
11011 : : /* initial overflow/underflow test with fuzz factor */
11012 [ + + ]: 94 : if (fabs(val) > NUMERIC_MAX_RESULT_SCALE * 3.01)
11013 : : {
11014 [ - + ]: 5 : if (val > 0)
11015 [ # # ]: 0 : ereport(ERROR,
11016 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
11017 : : errmsg("value overflows numeric format")));
11018 : 5 : zero_var(result);
11019 : 5 : result->dscale = NUMERIC_MAX_DISPLAY_SCALE;
11020 : 5 : return;
11021 : : }
11022 : :
11023 : 89 : val *= 0.434294481903252; /* approximate decimal result weight */
11024 : :
11025 : : /* choose the result scale */
11026 : 89 : rscale = NUMERIC_MIN_SIG_DIGITS - (int) val;
11027 : 89 : rscale = Max(rscale, base->dscale);
11028 : 89 : rscale = Max(rscale, exp->dscale);
11029 : 89 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
11030 : 89 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
11031 : :
11032 : : /* significant digits required in the result */
11033 : 89 : sig_digits = rscale + (int) val;
11034 : 89 : sig_digits = Max(sig_digits, 0);
11035 : :
11036 : : /* set the scale for the real exp * ln(base) calculation */
11037 : 89 : local_rscale = sig_digits - ln_dweight + 8;
11038 : 89 : local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11039 : :
11040 : : /* and do the real calculation */
11041 : :
11042 : 89 : ln_var(base, &ln_base, local_rscale);
11043 : :
11044 : 89 : mul_var(&ln_base, exp, &ln_num, local_rscale);
11045 : :
11046 : 89 : exp_var(&ln_num, result, rscale);
11047 : :
11048 [ + + + - ]: 89 : if (res_sign == NUMERIC_NEG && result->ndigits > 0)
11049 : 5 : result->sign = NUMERIC_NEG;
11050 : :
11051 : 89 : free_var(&ln_num);
11052 : 89 : free_var(&ln_base);
11053 : 89 : free_var(&abs_base);
11054 : : }
11055 : :
11056 : : /*
11057 : : * power_var_int() -
11058 : : *
11059 : : * Raise base to the power of exp, where exp is an integer.
11060 : : *
11061 : : * Note: this routine chooses dscale of the result.
11062 : : */
11063 : : static void
11064 : 848 : power_var_int(const NumericVar *base, int exp, int exp_dscale,
11065 : : NumericVar *result)
11066 : : {
11067 : : double f;
11068 : : int p;
11069 : : int i;
11070 : : int rscale;
11071 : : int sig_digits;
11072 : : unsigned int mask;
11073 : : bool neg;
11074 : : NumericVar base_prod;
11075 : : int local_rscale;
11076 : :
11077 : : /*
11078 : : * Choose the result scale. For this we need an estimate of the decimal
11079 : : * weight of the result, which we obtain by approximating using double
11080 : : * precision arithmetic.
11081 : : *
11082 : : * We also perform crude overflow/underflow tests here so that we can exit
11083 : : * early if the result is sure to overflow/underflow, and to guard against
11084 : : * integer overflow when choosing the result scale.
11085 : : */
11086 [ + + ]: 848 : if (base->ndigits != 0)
11087 : : {
11088 : : /*----------
11089 : : * Choose f (double) and p (int) such that base ~= f * 10^p.
11090 : : * Then log10(result) = log10(base^exp) ~= exp * (log10(f) + p).
11091 : : *----------
11092 : : */
11093 : 826 : f = base->digits[0];
11094 : 826 : p = base->weight * DEC_DIGITS;
11095 : :
11096 [ + + + - ]: 891 : for (i = 1; i < base->ndigits && i * DEC_DIGITS < 16; i++)
11097 : : {
11098 : 65 : f = f * NBASE + base->digits[i];
11099 : 65 : p -= DEC_DIGITS;
11100 : : }
11101 : :
11102 : 826 : f = exp * (log10(f) + p); /* approximate decimal result weight */
11103 : : }
11104 : : else
11105 : 22 : f = 0; /* result is 0 or 1 (weight 0), or error */
11106 : :
11107 : : /* overflow/underflow tests with fuzz factors */
11108 [ + + ]: 848 : if (f > (NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS)
11109 [ + - ]: 8 : ereport(ERROR,
11110 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
11111 : : errmsg("value overflows numeric format")));
11112 [ + + ]: 840 : if (f + 1 < -NUMERIC_MAX_DISPLAY_SCALE)
11113 : : {
11114 : 10 : zero_var(result);
11115 : 10 : result->dscale = NUMERIC_MAX_DISPLAY_SCALE;
11116 : 151 : return;
11117 : : }
11118 : :
11119 : : /*
11120 : : * Choose the result scale in the same way as power_var(), so it has at
11121 : : * least NUMERIC_MIN_SIG_DIGITS significant digits and is not less than
11122 : : * either input's display scale.
11123 : : */
11124 : 830 : rscale = NUMERIC_MIN_SIG_DIGITS - (int) f;
11125 : 830 : rscale = Max(rscale, base->dscale);
11126 : 830 : rscale = Max(rscale, exp_dscale);
11127 : 830 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
11128 : 830 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
11129 : :
11130 : : /* Handle some common special cases, as well as corner cases */
11131 [ + + + + : 830 : switch (exp)
+ ]
11132 : : {
11133 : 52 : case 0:
11134 : :
11135 : : /*
11136 : : * While 0 ^ 0 can be either 1 or indeterminate (error), we treat
11137 : : * it as 1 because most programming languages do this. SQL:2003
11138 : : * also requires a return value of 1.
11139 : : * https://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_zero_power
11140 : : */
11141 : 52 : set_var_from_var(&const_one, result);
11142 : 52 : result->dscale = rscale; /* no need to round */
11143 : 52 : return;
11144 : 32 : case 1:
11145 : 32 : set_var_from_var(base, result);
11146 : 32 : round_var(result, rscale);
11147 : 32 : return;
11148 : 21 : case -1:
11149 : 21 : div_var(&const_one, base, result, rscale, true, true);
11150 : 21 : return;
11151 : 36 : case 2:
11152 : 36 : mul_var(base, base, result, rscale);
11153 : 36 : return;
11154 : 689 : default:
11155 : 689 : break;
11156 : : }
11157 : :
11158 : : /* Handle the special case where the base is zero */
11159 [ - + ]: 689 : if (base->ndigits == 0)
11160 : : {
11161 [ # # ]: 0 : if (exp < 0)
11162 [ # # ]: 0 : ereport(ERROR,
11163 : : (errcode(ERRCODE_DIVISION_BY_ZERO),
11164 : : errmsg("division by zero")));
11165 : 0 : zero_var(result);
11166 : 0 : result->dscale = rscale;
11167 : 0 : return;
11168 : : }
11169 : :
11170 : : /*
11171 : : * The general case repeatedly multiplies base according to the bit
11172 : : * pattern of exp.
11173 : : *
11174 : : * The local rscale used for each multiplication is varied to keep a fixed
11175 : : * number of significant digits, sufficient to give the required result
11176 : : * scale.
11177 : : */
11178 : :
11179 : : /*
11180 : : * Approximate number of significant digits in the result. Note that the
11181 : : * underflow test above, together with the choice of rscale, ensures that
11182 : : * this approximation is necessarily > 0.
11183 : : */
11184 : 689 : sig_digits = 1 + rscale + (int) f;
11185 : :
11186 : : /*
11187 : : * The multiplications to produce the result may introduce an error of up
11188 : : * to around log10(abs(exp)) digits, so work with this many extra digits
11189 : : * of precision (plus a few more for good measure).
11190 : : */
11191 : 689 : sig_digits += (int) log(fabs((double) exp)) + 8;
11192 : :
11193 : : /*
11194 : : * Now we can proceed with the multiplications.
11195 : : */
11196 : 689 : neg = (exp < 0);
11197 : 689 : mask = pg_abs_s32(exp);
11198 : :
11199 : 689 : init_var(&base_prod);
11200 : 689 : set_var_from_var(base, &base_prod);
11201 : :
11202 [ + + ]: 689 : if (mask & 1)
11203 : 343 : set_var_from_var(base, result);
11204 : : else
11205 : 346 : set_var_from_var(&const_one, result);
11206 : :
11207 [ + + ]: 3618 : while ((mask >>= 1) > 0)
11208 : : {
11209 : : /*
11210 : : * Do the multiplications using rscales large enough to hold the
11211 : : * results to the required number of significant digits, but don't
11212 : : * waste time by exceeding the scales of the numbers themselves.
11213 : : */
11214 : 2929 : local_rscale = sig_digits - 2 * base_prod.weight * DEC_DIGITS;
11215 : 2929 : local_rscale = Min(local_rscale, 2 * base_prod.dscale);
11216 : 2929 : local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11217 : :
11218 : 2929 : mul_var(&base_prod, &base_prod, &base_prod, local_rscale);
11219 : :
11220 [ + + ]: 2929 : if (mask & 1)
11221 : : {
11222 : 1932 : local_rscale = sig_digits -
11223 : 1932 : (base_prod.weight + result->weight) * DEC_DIGITS;
11224 : 1932 : local_rscale = Min(local_rscale,
11225 : : base_prod.dscale + result->dscale);
11226 : 1932 : local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11227 : :
11228 : 1932 : mul_var(&base_prod, result, result, local_rscale);
11229 : : }
11230 : :
11231 : : /*
11232 : : * When abs(base) > 1, the number of digits to the left of the decimal
11233 : : * point in base_prod doubles at each iteration, so if exp is large we
11234 : : * could easily spend large amounts of time and memory space doing the
11235 : : * multiplications. But once the weight exceeds what will fit in
11236 : : * int16, the final result is guaranteed to overflow (or underflow, if
11237 : : * exp < 0), so we can give up before wasting too many cycles.
11238 : : */
11239 [ + - ]: 2929 : if (base_prod.weight > NUMERIC_WEIGHT_MAX ||
11240 [ - + ]: 2929 : result->weight > NUMERIC_WEIGHT_MAX)
11241 : : {
11242 : : /* overflow, unless neg, in which case result should be 0 */
11243 [ # # ]: 0 : if (!neg)
11244 [ # # ]: 0 : ereport(ERROR,
11245 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
11246 : : errmsg("value overflows numeric format")));
11247 : 0 : zero_var(result);
11248 : 0 : neg = false;
11249 : 0 : break;
11250 : : }
11251 : : }
11252 : :
11253 : 689 : free_var(&base_prod);
11254 : :
11255 : : /* Compensate for input sign, and round to requested rscale */
11256 [ + + ]: 689 : if (neg)
11257 : 328 : div_var(&const_one, result, result, rscale, true, false);
11258 : : else
11259 : 361 : round_var(result, rscale);
11260 : : }
11261 : :
11262 : : /*
11263 : : * power_ten_int() -
11264 : : *
11265 : : * Raise ten to the power of exp, where exp is an integer. Note that unlike
11266 : : * power_var_int(), this does no overflow/underflow checking or rounding.
11267 : : */
11268 : : static void
11269 : 152 : power_ten_int(int exp, NumericVar *result)
11270 : : {
11271 : : /* Construct the result directly, starting from 10^0 = 1 */
11272 : 152 : set_var_from_var(&const_one, result);
11273 : :
11274 : : /* Scale needed to represent the result exactly */
11275 [ + + ]: 152 : result->dscale = exp < 0 ? -exp : 0;
11276 : :
11277 : : /* Base-NBASE weight of result and remaining exponent */
11278 [ + + ]: 152 : if (exp >= 0)
11279 : 108 : result->weight = exp / DEC_DIGITS;
11280 : : else
11281 : 44 : result->weight = (exp + 1) / DEC_DIGITS - 1;
11282 : :
11283 : 152 : exp -= result->weight * DEC_DIGITS;
11284 : :
11285 : : /* Final adjustment of the result's single NBASE digit */
11286 [ + + ]: 396 : while (exp-- > 0)
11287 : 244 : result->digits[0] *= 10;
11288 : 152 : }
11289 : :
11290 : : /*
11291 : : * random_var() - return a random value in the range [rmin, rmax].
11292 : : */
11293 : : static void
11294 : 22292 : random_var(pg_prng_state *state, const NumericVar *rmin,
11295 : : const NumericVar *rmax, NumericVar *result)
11296 : : {
11297 : : int rscale;
11298 : : NumericVar rlen;
11299 : : int res_ndigits;
11300 : : int n;
11301 : : int pow10;
11302 : : int i;
11303 : : uint64 rlen64;
11304 : : int rlen64_ndigits;
11305 : :
11306 : 22292 : rscale = Max(rmin->dscale, rmax->dscale);
11307 : :
11308 : : /* Compute rlen = rmax - rmin and check the range bounds */
11309 : 22292 : init_var(&rlen);
11310 : 22292 : sub_var(rmax, rmin, &rlen);
11311 : :
11312 [ + + ]: 22292 : if (rlen.sign == NUMERIC_NEG)
11313 [ + - ]: 4 : ereport(ERROR,
11314 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
11315 : : errmsg("lower bound must be less than or equal to upper bound"));
11316 : :
11317 : : /* Special case for an empty range */
11318 [ + + ]: 22288 : if (rlen.ndigits == 0)
11319 : : {
11320 : 8 : set_var_from_var(rmin, result);
11321 : 8 : result->dscale = rscale;
11322 : 8 : free_var(&rlen);
11323 : 8 : return;
11324 : : }
11325 : :
11326 : : /*
11327 : : * Otherwise, select a random value in the range [0, rlen = rmax - rmin],
11328 : : * and shift it to the required range by adding rmin.
11329 : : */
11330 : :
11331 : : /* Required result digits */
11332 : 22280 : res_ndigits = rlen.weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
11333 : :
11334 : : /*
11335 : : * To get the required rscale, the final result digit must be a multiple
11336 : : * of pow10 = 10^n, where n = (-rscale) mod DEC_DIGITS.
11337 : : */
11338 : 22280 : n = ((rscale + DEC_DIGITS - 1) / DEC_DIGITS) * DEC_DIGITS - rscale;
11339 : 22280 : pow10 = 1;
11340 [ + + ]: 58600 : for (i = 0; i < n; i++)
11341 : 36320 : pow10 *= 10;
11342 : :
11343 : : /*
11344 : : * To choose a random value uniformly from the range [0, rlen], we choose
11345 : : * from the slightly larger range [0, rlen2], where rlen2 is formed from
11346 : : * rlen by copying the first 4 NBASE digits, and setting all remaining
11347 : : * decimal digits to "9".
11348 : : *
11349 : : * Without loss of generality, we can ignore the weight of rlen2 and treat
11350 : : * it as a pure integer for the purposes of this discussion. The process
11351 : : * above gives rlen2 + 1 = rlen64 * 10^N, for some integer N, where rlen64
11352 : : * is a 64-bit integer formed from the first 4 NBASE digits copied from
11353 : : * rlen. Since this trivially factors into smaller pieces that fit in
11354 : : * 64-bit integers, the task of choosing a random value uniformly from the
11355 : : * rlen2 + 1 possible values in [0, rlen2] is much simpler.
11356 : : *
11357 : : * If the random value selected is too large, it is rejected, and we try
11358 : : * again until we get a result <= rlen, ensuring that the overall result
11359 : : * is uniform (no particular value is any more likely than any other).
11360 : : *
11361 : : * Since rlen64 holds 4 NBASE digits from rlen, it contains at least
11362 : : * DEC_DIGITS * 3 + 1 decimal digits (i.e., at least 13 decimal digits,
11363 : : * when DEC_DIGITS is 4). Therefore the probability of needing to reject
11364 : : * the value chosen and retry is less than 1e-13.
11365 : : */
11366 : 22280 : rlen64 = (uint64) rlen.digits[0];
11367 : 22280 : rlen64_ndigits = 1;
11368 [ + + + + ]: 50808 : while (rlen64_ndigits < res_ndigits && rlen64_ndigits < 4)
11369 : : {
11370 : 28528 : rlen64 *= NBASE;
11371 [ + + ]: 28528 : if (rlen64_ndigits < rlen.ndigits)
11372 : 4408 : rlen64 += rlen.digits[rlen64_ndigits];
11373 : 28528 : rlen64_ndigits++;
11374 : : }
11375 : :
11376 : : /* Loop until we get a result <= rlen */
11377 : : do
11378 : : {
11379 : : NumericDigit *res_digits;
11380 : : uint64 rand;
11381 : : int whole_ndigits;
11382 : :
11383 : 22280 : alloc_var(result, res_ndigits);
11384 : 22280 : result->sign = NUMERIC_POS;
11385 : 22280 : result->weight = rlen.weight;
11386 : 22280 : result->dscale = rscale;
11387 : 22280 : res_digits = result->digits;
11388 : :
11389 : : /*
11390 : : * Set the first rlen64_ndigits using a random value in [0, rlen64].
11391 : : *
11392 : : * If this is the whole result, and rscale is not a multiple of
11393 : : * DEC_DIGITS (pow10 from above is not 1), then we need this to be a
11394 : : * multiple of pow10.
11395 : : */
11396 [ + + + + ]: 22280 : if (rlen64_ndigits == res_ndigits && pow10 != 1)
11397 : 14088 : rand = pg_prng_uint64_range(state, 0, rlen64 / pow10) * pow10;
11398 : : else
11399 : 8192 : rand = pg_prng_uint64_range(state, 0, rlen64);
11400 : :
11401 [ + + ]: 73088 : for (i = rlen64_ndigits - 1; i >= 0; i--)
11402 : : {
11403 : 50808 : res_digits[i] = (NumericDigit) (rand % NBASE);
11404 : 50808 : rand = rand / NBASE;
11405 : : }
11406 : :
11407 : : /*
11408 : : * Set the remaining digits to random values in range [0, NBASE),
11409 : : * noting that the last digit needs to be a multiple of pow10.
11410 : : */
11411 : 22280 : whole_ndigits = res_ndigits;
11412 [ + + ]: 22280 : if (pow10 != 1)
11413 : 22140 : whole_ndigits--;
11414 : :
11415 : : /* Set whole digits in groups of 4 for best performance */
11416 : 22280 : i = rlen64_ndigits;
11417 [ + + ]: 22320 : while (i < whole_ndigits - 3)
11418 : : {
11419 : 40 : rand = pg_prng_uint64_range(state, 0,
11420 : : (uint64) NBASE * NBASE * NBASE * NBASE - 1);
11421 : 40 : res_digits[i++] = (NumericDigit) (rand % NBASE);
11422 : 40 : rand = rand / NBASE;
11423 : 40 : res_digits[i++] = (NumericDigit) (rand % NBASE);
11424 : 40 : rand = rand / NBASE;
11425 : 40 : res_digits[i++] = (NumericDigit) (rand % NBASE);
11426 : 40 : rand = rand / NBASE;
11427 : 40 : res_digits[i++] = (NumericDigit) rand;
11428 : : }
11429 : :
11430 : : /* Remaining whole digits */
11431 [ + + ]: 22420 : while (i < whole_ndigits)
11432 : : {
11433 : 140 : rand = pg_prng_uint64_range(state, 0, NBASE - 1);
11434 : 140 : res_digits[i++] = (NumericDigit) rand;
11435 : : }
11436 : :
11437 : : /* Final partial digit (multiple of pow10) */
11438 [ + + ]: 22280 : if (i < res_ndigits)
11439 : : {
11440 : 8052 : rand = pg_prng_uint64_range(state, 0, NBASE / pow10 - 1) * pow10;
11441 : 8052 : res_digits[i] = (NumericDigit) rand;
11442 : : }
11443 : :
11444 : : /* Remove leading/trailing zeroes */
11445 : 22280 : strip_var(result);
11446 : :
11447 : : /* If result > rlen, try again */
11448 : :
11449 [ - + ]: 22280 : } while (cmp_var(result, &rlen) > 0);
11450 : :
11451 : : /* Offset the result to the required range */
11452 : 22280 : add_var(result, rmin, result);
11453 : :
11454 : 22280 : free_var(&rlen);
11455 : : }
11456 : :
11457 : :
11458 : : /* ----------------------------------------------------------------------
11459 : : *
11460 : : * Following are the lowest level functions that operate unsigned
11461 : : * on the variable level
11462 : : *
11463 : : * ----------------------------------------------------------------------
11464 : : */
11465 : :
11466 : :
11467 : : /* ----------
11468 : : * cmp_abs() -
11469 : : *
11470 : : * Compare the absolute values of var1 and var2
11471 : : * Returns: -1 for ABS(var1) < ABS(var2)
11472 : : * 0 for ABS(var1) == ABS(var2)
11473 : : * 1 for ABS(var1) > ABS(var2)
11474 : : * ----------
11475 : : */
11476 : : static int
11477 : 469417 : cmp_abs(const NumericVar *var1, const NumericVar *var2)
11478 : : {
11479 : 938834 : return cmp_abs_common(var1->digits, var1->ndigits, var1->weight,
11480 : 469417 : var2->digits, var2->ndigits, var2->weight);
11481 : : }
11482 : :
11483 : : /* ----------
11484 : : * cmp_abs_common() -
11485 : : *
11486 : : * Main routine of cmp_abs(). This function can be used by both
11487 : : * NumericVar and Numeric.
11488 : : * ----------
11489 : : */
11490 : : static int
11491 : 18449919 : cmp_abs_common(const NumericDigit *var1digits, int var1ndigits, int var1weight,
11492 : : const NumericDigit *var2digits, int var2ndigits, int var2weight)
11493 : : {
11494 : 18449919 : int i1 = 0;
11495 : 18449919 : int i2 = 0;
11496 : :
11497 : : /* Check any digits before the first common digit */
11498 : :
11499 [ + + + + ]: 18449919 : while (var1weight > var2weight && i1 < var1ndigits)
11500 : : {
11501 [ + - ]: 15114 : if (var1digits[i1++] != 0)
11502 : 15114 : return 1;
11503 : 0 : var1weight--;
11504 : : }
11505 [ + + + + ]: 18434805 : while (var2weight > var1weight && i2 < var2ndigits)
11506 : : {
11507 [ + - ]: 100776 : if (var2digits[i2++] != 0)
11508 : 100776 : return -1;
11509 : 0 : var2weight--;
11510 : : }
11511 : :
11512 : : /* At this point, either w1 == w2 or we've run out of digits */
11513 : :
11514 [ + + ]: 18334029 : if (var1weight == var2weight)
11515 : : {
11516 [ + + + + ]: 28819638 : while (i1 < var1ndigits && i2 < var2ndigits)
11517 : : {
11518 : 19356523 : int stat = var1digits[i1++] - var2digits[i2++];
11519 : :
11520 [ + + ]: 19356523 : if (stat)
11521 : : {
11522 [ + + ]: 8866665 : if (stat > 0)
11523 : 5253134 : return 1;
11524 : 3613531 : return -1;
11525 : : }
11526 : : }
11527 : : }
11528 : :
11529 : : /*
11530 : : * At this point, we've run out of digits on one side or the other; so any
11531 : : * remaining nonzero digits imply that side is larger
11532 : : */
11533 [ + + ]: 9467469 : while (i1 < var1ndigits)
11534 : : {
11535 [ + + ]: 6276 : if (var1digits[i1++] != 0)
11536 : 6171 : return 1;
11537 : : }
11538 [ + + ]: 9461445 : while (i2 < var2ndigits)
11539 : : {
11540 [ + + ]: 891 : if (var2digits[i2++] != 0)
11541 : 639 : return -1;
11542 : : }
11543 : :
11544 : 9460554 : return 0;
11545 : : }
11546 : :
11547 : :
11548 : : /*
11549 : : * add_abs() -
11550 : : *
11551 : : * Add the absolute values of two variables into result.
11552 : : * result might point to one of the operands without danger.
11553 : : */
11554 : : static void
11555 : 299693 : add_abs(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
11556 : : {
11557 : : NumericDigit *res_buf;
11558 : : NumericDigit *res_digits;
11559 : : int res_ndigits;
11560 : : int res_weight;
11561 : : int res_rscale,
11562 : : rscale1,
11563 : : rscale2;
11564 : : int res_dscale;
11565 : : int i,
11566 : : i1,
11567 : : i2;
11568 : 299693 : int carry = 0;
11569 : :
11570 : : /* copy these values into local vars for speed in inner loop */
11571 : 299693 : int var1ndigits = var1->ndigits;
11572 : 299693 : int var2ndigits = var2->ndigits;
11573 : 299693 : NumericDigit *var1digits = var1->digits;
11574 : 299693 : NumericDigit *var2digits = var2->digits;
11575 : :
11576 : 299693 : res_weight = Max(var1->weight, var2->weight) + 1;
11577 : :
11578 : 299693 : res_dscale = Max(var1->dscale, var2->dscale);
11579 : :
11580 : : /* Note: here we are figuring rscale in base-NBASE digits */
11581 : 299693 : rscale1 = var1->ndigits - var1->weight - 1;
11582 : 299693 : rscale2 = var2->ndigits - var2->weight - 1;
11583 : 299693 : res_rscale = Max(rscale1, rscale2);
11584 : :
11585 : 299693 : res_ndigits = res_rscale + res_weight + 1;
11586 [ - + ]: 299693 : if (res_ndigits <= 0)
11587 : 0 : res_ndigits = 1;
11588 : :
11589 : 299693 : res_buf = digitbuf_alloc(res_ndigits + 1);
11590 : 299693 : res_buf[0] = 0; /* spare digit for later rounding */
11591 : 299693 : res_digits = res_buf + 1;
11592 : :
11593 : 299693 : i1 = res_rscale + var1->weight + 1;
11594 : 299693 : i2 = res_rscale + var2->weight + 1;
11595 [ + + ]: 2479814 : for (i = res_ndigits - 1; i >= 0; i--)
11596 : : {
11597 : 2180121 : i1--;
11598 : 2180121 : i2--;
11599 [ + + + + ]: 2180121 : if (i1 >= 0 && i1 < var1ndigits)
11600 : 987409 : carry += var1digits[i1];
11601 [ + + + + ]: 2180121 : if (i2 >= 0 && i2 < var2ndigits)
11602 : 779857 : carry += var2digits[i2];
11603 : :
11604 [ + + ]: 2180121 : if (carry >= NBASE)
11605 : : {
11606 : 159502 : res_digits[i] = carry - NBASE;
11607 : 159502 : carry = 1;
11608 : : }
11609 : : else
11610 : : {
11611 : 2020619 : res_digits[i] = carry;
11612 : 2020619 : carry = 0;
11613 : : }
11614 : : }
11615 : :
11616 : : Assert(carry == 0); /* else we failed to allow for carry out */
11617 : :
11618 [ + + ]: 299693 : digitbuf_free(result->buf);
11619 : 299693 : result->ndigits = res_ndigits;
11620 : 299693 : result->buf = res_buf;
11621 : 299693 : result->digits = res_digits;
11622 : 299693 : result->weight = res_weight;
11623 : 299693 : result->dscale = res_dscale;
11624 : :
11625 : : /* Remove leading/trailing zeroes */
11626 : 299693 : strip_var(result);
11627 : 299693 : }
11628 : :
11629 : :
11630 : : /*
11631 : : * sub_abs()
11632 : : *
11633 : : * Subtract the absolute value of var2 from the absolute value of var1
11634 : : * and store in result. result might point to one of the operands
11635 : : * without danger.
11636 : : *
11637 : : * ABS(var1) MUST BE GREATER OR EQUAL ABS(var2) !!!
11638 : : */
11639 : : static void
11640 : 436365 : sub_abs(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
11641 : : {
11642 : : NumericDigit *res_buf;
11643 : : NumericDigit *res_digits;
11644 : : int res_ndigits;
11645 : : int res_weight;
11646 : : int res_rscale,
11647 : : rscale1,
11648 : : rscale2;
11649 : : int res_dscale;
11650 : : int i,
11651 : : i1,
11652 : : i2;
11653 : 436365 : int borrow = 0;
11654 : :
11655 : : /* copy these values into local vars for speed in inner loop */
11656 : 436365 : int var1ndigits = var1->ndigits;
11657 : 436365 : int var2ndigits = var2->ndigits;
11658 : 436365 : NumericDigit *var1digits = var1->digits;
11659 : 436365 : NumericDigit *var2digits = var2->digits;
11660 : :
11661 : 436365 : res_weight = var1->weight;
11662 : :
11663 : 436365 : res_dscale = Max(var1->dscale, var2->dscale);
11664 : :
11665 : : /* Note: here we are figuring rscale in base-NBASE digits */
11666 : 436365 : rscale1 = var1->ndigits - var1->weight - 1;
11667 : 436365 : rscale2 = var2->ndigits - var2->weight - 1;
11668 : 436365 : res_rscale = Max(rscale1, rscale2);
11669 : :
11670 : 436365 : res_ndigits = res_rscale + res_weight + 1;
11671 [ - + ]: 436365 : if (res_ndigits <= 0)
11672 : 0 : res_ndigits = 1;
11673 : :
11674 : 436365 : res_buf = digitbuf_alloc(res_ndigits + 1);
11675 : 436365 : res_buf[0] = 0; /* spare digit for later rounding */
11676 : 436365 : res_digits = res_buf + 1;
11677 : :
11678 : 436365 : i1 = res_rscale + var1->weight + 1;
11679 : 436365 : i2 = res_rscale + var2->weight + 1;
11680 [ + + ]: 3489748 : for (i = res_ndigits - 1; i >= 0; i--)
11681 : : {
11682 : 3053383 : i1--;
11683 : 3053383 : i2--;
11684 [ + - + + ]: 3053383 : if (i1 >= 0 && i1 < var1ndigits)
11685 : 2745534 : borrow += var1digits[i1];
11686 [ + + + + ]: 3053383 : if (i2 >= 0 && i2 < var2ndigits)
11687 : 2694254 : borrow -= var2digits[i2];
11688 : :
11689 [ + + ]: 3053383 : if (borrow < 0)
11690 : : {
11691 : 330538 : res_digits[i] = borrow + NBASE;
11692 : 330538 : borrow = -1;
11693 : : }
11694 : : else
11695 : : {
11696 : 2722845 : res_digits[i] = borrow;
11697 : 2722845 : borrow = 0;
11698 : : }
11699 : : }
11700 : :
11701 : : Assert(borrow == 0); /* else caller gave us var1 < var2 */
11702 : :
11703 [ + + ]: 436365 : digitbuf_free(result->buf);
11704 : 436365 : result->ndigits = res_ndigits;
11705 : 436365 : result->buf = res_buf;
11706 : 436365 : result->digits = res_digits;
11707 : 436365 : result->weight = res_weight;
11708 : 436365 : result->dscale = res_dscale;
11709 : :
11710 : : /* Remove leading/trailing zeroes */
11711 : 436365 : strip_var(result);
11712 : 436365 : }
11713 : :
11714 : : /*
11715 : : * round_var
11716 : : *
11717 : : * Round the value of a variable to no more than rscale decimal digits
11718 : : * after the decimal point. NOTE: we allow rscale < 0 here, implying
11719 : : * rounding before the decimal point.
11720 : : */
11721 : : static void
11722 : 168252 : round_var(NumericVar *var, int rscale)
11723 : : {
11724 : 168252 : NumericDigit *digits = var->digits;
11725 : : int di;
11726 : : int ndigits;
11727 : : int carry;
11728 : :
11729 : 168252 : var->dscale = rscale;
11730 : :
11731 : : /* decimal digits wanted */
11732 : 168252 : di = (var->weight + 1) * DEC_DIGITS + rscale;
11733 : :
11734 : : /*
11735 : : * If di = 0, the value loses all digits, but could round up to 1 if its
11736 : : * first extra digit is >= 5. If di < 0 the result must be 0.
11737 : : */
11738 [ + + ]: 168252 : if (di < 0)
11739 : : {
11740 : 71 : var->ndigits = 0;
11741 : 71 : var->weight = 0;
11742 : 71 : var->sign = NUMERIC_POS;
11743 : : }
11744 : : else
11745 : : {
11746 : : /* NBASE digits wanted */
11747 : 168181 : ndigits = (di + DEC_DIGITS - 1) / DEC_DIGITS;
11748 : :
11749 : : /* 0, or number of decimal digits to keep in last NBASE digit */
11750 : 168181 : di %= DEC_DIGITS;
11751 : :
11752 [ + + ]: 168181 : if (ndigits < var->ndigits ||
11753 [ + + + + ]: 30766 : (ndigits == var->ndigits && di > 0))
11754 : : {
11755 : 139892 : var->ndigits = ndigits;
11756 : :
11757 : : #if DEC_DIGITS == 1
11758 : : /* di must be zero */
11759 : : carry = (digits[ndigits] >= HALF_NBASE) ? 1 : 0;
11760 : : #else
11761 [ + + ]: 139892 : if (di == 0)
11762 : 109908 : carry = (digits[ndigits] >= HALF_NBASE) ? 1 : 0;
11763 : : else
11764 : : {
11765 : : /* Must round within last NBASE digit */
11766 : : int extra,
11767 : : pow10;
11768 : :
11769 : : #if DEC_DIGITS == 4
11770 : 29984 : pow10 = round_powers[di];
11771 : : #elif DEC_DIGITS == 2
11772 : : pow10 = 10;
11773 : : #else
11774 : : #error unsupported NBASE
11775 : : #endif
11776 : 29984 : extra = digits[--ndigits] % pow10;
11777 : 29984 : digits[ndigits] -= extra;
11778 : 29984 : carry = 0;
11779 [ + + ]: 29984 : if (extra >= pow10 / 2)
11780 : : {
11781 : 13983 : pow10 += digits[ndigits];
11782 [ + + ]: 13983 : if (pow10 >= NBASE)
11783 : : {
11784 : 595 : pow10 -= NBASE;
11785 : 595 : carry = 1;
11786 : : }
11787 : 13983 : digits[ndigits] = pow10;
11788 : : }
11789 : : }
11790 : : #endif
11791 : :
11792 : : /* Propagate carry if needed */
11793 [ + + ]: 166770 : while (carry)
11794 : : {
11795 : 26878 : carry += digits[--ndigits];
11796 [ + + ]: 26878 : if (carry >= NBASE)
11797 : : {
11798 : 20528 : digits[ndigits] = carry - NBASE;
11799 : 20528 : carry = 1;
11800 : : }
11801 : : else
11802 : : {
11803 : 6350 : digits[ndigits] = carry;
11804 : 6350 : carry = 0;
11805 : : }
11806 : : }
11807 : :
11808 [ + + ]: 139892 : if (ndigits < 0)
11809 : : {
11810 : : Assert(ndigits == -1); /* better not have added > 1 digit */
11811 : : Assert(var->digits > var->buf);
11812 : 65 : var->digits--;
11813 : 65 : var->ndigits++;
11814 : 65 : var->weight++;
11815 : : }
11816 : : }
11817 : : }
11818 : 168252 : }
11819 : :
11820 : : /*
11821 : : * trunc_var
11822 : : *
11823 : : * Truncate (towards zero) the value of a variable at rscale decimal digits
11824 : : * after the decimal point. NOTE: we allow rscale < 0 here, implying
11825 : : * truncation before the decimal point.
11826 : : */
11827 : : static void
11828 : 280544 : trunc_var(NumericVar *var, int rscale)
11829 : : {
11830 : : int di;
11831 : : int ndigits;
11832 : :
11833 : 280544 : var->dscale = rscale;
11834 : :
11835 : : /* decimal digits wanted */
11836 : 280544 : di = (var->weight + 1) * DEC_DIGITS + rscale;
11837 : :
11838 : : /*
11839 : : * If di <= 0, the value loses all digits.
11840 : : */
11841 [ + + ]: 280544 : if (di <= 0)
11842 : : {
11843 : 66 : var->ndigits = 0;
11844 : 66 : var->weight = 0;
11845 : 66 : var->sign = NUMERIC_POS;
11846 : : }
11847 : : else
11848 : : {
11849 : : /* NBASE digits wanted */
11850 : 280478 : ndigits = (di + DEC_DIGITS - 1) / DEC_DIGITS;
11851 : :
11852 [ + + ]: 280478 : if (ndigits <= var->ndigits)
11853 : : {
11854 : 280290 : var->ndigits = ndigits;
11855 : :
11856 : : #if DEC_DIGITS == 1
11857 : : /* no within-digit stuff to worry about */
11858 : : #else
11859 : : /* 0, or number of decimal digits to keep in last NBASE digit */
11860 : 280290 : di %= DEC_DIGITS;
11861 : :
11862 [ + + ]: 280290 : if (di > 0)
11863 : : {
11864 : : /* Must truncate within last NBASE digit */
11865 : 63 : NumericDigit *digits = var->digits;
11866 : : int extra,
11867 : : pow10;
11868 : :
11869 : : #if DEC_DIGITS == 4
11870 : 63 : pow10 = round_powers[di];
11871 : : #elif DEC_DIGITS == 2
11872 : : pow10 = 10;
11873 : : #else
11874 : : #error unsupported NBASE
11875 : : #endif
11876 : 63 : extra = digits[--ndigits] % pow10;
11877 : 63 : digits[ndigits] -= extra;
11878 : : }
11879 : : #endif
11880 : : }
11881 : : }
11882 : 280544 : }
11883 : :
11884 : : /*
11885 : : * strip_var
11886 : : *
11887 : : * Strip any leading and trailing zeroes from a numeric variable
11888 : : */
11889 : : static void
11890 : 2200812 : strip_var(NumericVar *var)
11891 : : {
11892 : 2200812 : NumericDigit *digits = var->digits;
11893 : 2200812 : int ndigits = var->ndigits;
11894 : :
11895 : : /* Strip leading zeroes */
11896 [ + + + + ]: 3773401 : while (ndigits > 0 && *digits == 0)
11897 : : {
11898 : 1572589 : digits++;
11899 : 1572589 : var->weight--;
11900 : 1572589 : ndigits--;
11901 : : }
11902 : :
11903 : : /* Strip trailing zeroes */
11904 [ + + + + ]: 2652948 : while (ndigits > 0 && digits[ndigits - 1] == 0)
11905 : 452136 : ndigits--;
11906 : :
11907 : : /* If it's zero, normalize the sign and weight */
11908 [ + + ]: 2200812 : if (ndigits == 0)
11909 : : {
11910 : 32520 : var->sign = NUMERIC_POS;
11911 : 32520 : var->weight = 0;
11912 : : }
11913 : :
11914 : 2200812 : var->digits = digits;
11915 : 2200812 : var->ndigits = ndigits;
11916 : 2200812 : }
11917 : :
11918 : :
11919 : : /* ----------------------------------------------------------------------
11920 : : *
11921 : : * Fast sum accumulator functions
11922 : : *
11923 : : * ----------------------------------------------------------------------
11924 : : */
11925 : :
11926 : : /*
11927 : : * Reset the accumulator's value to zero. The buffers to hold the digits
11928 : : * are not free'd.
11929 : : */
11930 : : static void
11931 : 12 : accum_sum_reset(NumericSumAccum *accum)
11932 : : {
11933 : : int i;
11934 : :
11935 : 12 : accum->dscale = 0;
11936 [ + + ]: 44 : for (i = 0; i < accum->ndigits; i++)
11937 : : {
11938 : 32 : accum->pos_digits[i] = 0;
11939 : 32 : accum->neg_digits[i] = 0;
11940 : : }
11941 : 12 : }
11942 : :
11943 : : /*
11944 : : * Accumulate a new value.
11945 : : */
11946 : : static void
11947 : 1570442 : accum_sum_add(NumericSumAccum *accum, const NumericVar *val)
11948 : : {
11949 : : int32 *accum_digits;
11950 : : int val_ndigits;
11951 : : NumericDigit *val_digits;
11952 : :
11953 : : /*
11954 : : * If we have accumulated too many values since the last carry
11955 : : * propagation, do it now, to avoid overflowing. (We could allow more
11956 : : * than NBASE - 1, if we reserved two extra digits, rather than one, for
11957 : : * carry propagation. But even with NBASE - 1, this needs to be done so
11958 : : * seldom, that the performance difference is negligible.)
11959 : : */
11960 [ + + ]: 1570442 : if (accum->num_uncarried == NBASE - 1)
11961 : 110 : accum_sum_carry(accum);
11962 : :
11963 : : /*
11964 : : * Adjust the weight or scale of the old value, so that it can accommodate
11965 : : * the new value.
11966 : : */
11967 : 1570442 : accum_sum_rescale(accum, val);
11968 : :
11969 : : /* */
11970 [ + + ]: 1570442 : if (val->sign == NUMERIC_POS)
11971 : 1169990 : accum_digits = accum->pos_digits;
11972 : : else
11973 : 400452 : accum_digits = accum->neg_digits;
11974 : :
11975 : : /* copy these values into local vars for speed in loop */
11976 : 1570442 : val_ndigits = val->ndigits;
11977 : 1570442 : val_digits = val->digits;
11978 : :
11979 : 1570442 : accum_digits += accum->weight - val->weight;
11980 [ + + ]: 7926574 : for (int i = 0; i < val_ndigits; i++)
11981 : 6356132 : accum_digits[i] += (int32) val_digits[i];
11982 : :
11983 : 1570442 : accum->num_uncarried++;
11984 : 1570442 : }
11985 : :
11986 : : /*
11987 : : * Propagate carries.
11988 : : */
11989 : : static void
11990 : 115162 : accum_sum_carry(NumericSumAccum *accum)
11991 : : {
11992 : : int i;
11993 : : int ndigits;
11994 : : int32 *dig;
11995 : : int32 carry;
11996 : 115162 : int32 newdig = 0;
11997 : :
11998 : : /*
11999 : : * If no new values have been added since last carry propagation, nothing
12000 : : * to do.
12001 : : */
12002 [ + + ]: 115162 : if (accum->num_uncarried == 0)
12003 : 48 : return;
12004 : :
12005 : : /*
12006 : : * We maintain that the weight of the accumulator is always one larger
12007 : : * than needed to hold the current value, before carrying, to make sure
12008 : : * there is enough space for the possible extra digit when carry is
12009 : : * propagated. We cannot expand the buffer here, unless we require
12010 : : * callers of accum_sum_final() to switch to the right memory context.
12011 : : */
12012 : : Assert(accum->pos_digits[0] == 0 && accum->neg_digits[0] == 0);
12013 : :
12014 : 115114 : ndigits = accum->ndigits;
12015 : :
12016 : : /* Propagate carry in the positive sum */
12017 : 115114 : dig = accum->pos_digits;
12018 : 115114 : carry = 0;
12019 [ + + ]: 1736999 : for (i = ndigits - 1; i >= 0; i--)
12020 : : {
12021 : 1621885 : newdig = dig[i] + carry;
12022 [ + + ]: 1621885 : if (newdig >= NBASE)
12023 : : {
12024 : 73880 : carry = newdig / NBASE;
12025 : 73880 : newdig -= carry * NBASE;
12026 : : }
12027 : : else
12028 : 1548005 : carry = 0;
12029 : 1621885 : dig[i] = newdig;
12030 : : }
12031 : : /* Did we use up the digit reserved for carry propagation? */
12032 [ + + ]: 115114 : if (newdig > 0)
12033 : 1759 : accum->have_carry_space = false;
12034 : :
12035 : : /* And the same for the negative sum */
12036 : 115114 : dig = accum->neg_digits;
12037 : 115114 : carry = 0;
12038 [ + + ]: 1736999 : for (i = ndigits - 1; i >= 0; i--)
12039 : : {
12040 : 1621885 : newdig = dig[i] + carry;
12041 [ + + ]: 1621885 : if (newdig >= NBASE)
12042 : : {
12043 : 132 : carry = newdig / NBASE;
12044 : 132 : newdig -= carry * NBASE;
12045 : : }
12046 : : else
12047 : 1621753 : carry = 0;
12048 : 1621885 : dig[i] = newdig;
12049 : : }
12050 [ + + ]: 115114 : if (newdig > 0)
12051 : 20 : accum->have_carry_space = false;
12052 : :
12053 : 115114 : accum->num_uncarried = 0;
12054 : : }
12055 : :
12056 : : /*
12057 : : * Re-scale accumulator to accommodate new value.
12058 : : *
12059 : : * If the new value has more digits than the current digit buffers in the
12060 : : * accumulator, enlarge the buffers.
12061 : : */
12062 : : static void
12063 : 1570442 : accum_sum_rescale(NumericSumAccum *accum, const NumericVar *val)
12064 : : {
12065 : 1570442 : int old_weight = accum->weight;
12066 : 1570442 : int old_ndigits = accum->ndigits;
12067 : : int accum_ndigits;
12068 : : int accum_weight;
12069 : : int accum_rscale;
12070 : : int val_rscale;
12071 : :
12072 : 1570442 : accum_weight = old_weight;
12073 : 1570442 : accum_ndigits = old_ndigits;
12074 : :
12075 : : /*
12076 : : * Does the new value have a larger weight? If so, enlarge the buffers,
12077 : : * and shift the existing value to the new weight, by adding leading
12078 : : * zeros.
12079 : : *
12080 : : * We enforce that the accumulator always has a weight one larger than
12081 : : * needed for the inputs, so that we have space for an extra digit at the
12082 : : * final carry-propagation phase, if necessary.
12083 : : */
12084 [ + + ]: 1570442 : if (val->weight >= accum_weight)
12085 : : {
12086 : 174800 : accum_weight = val->weight + 1;
12087 : 174800 : accum_ndigits = accum_ndigits + (accum_weight - old_weight);
12088 : : }
12089 : :
12090 : : /*
12091 : : * Even though the new value is small, we might've used up the space
12092 : : * reserved for the carry digit in the last call to accum_sum_carry(). If
12093 : : * so, enlarge to make room for another one.
12094 : : */
12095 [ + + ]: 1395642 : else if (!accum->have_carry_space)
12096 : : {
12097 : 59 : accum_weight++;
12098 : 59 : accum_ndigits++;
12099 : : }
12100 : :
12101 : : /* Is the new value wider on the right side? */
12102 : 1570442 : accum_rscale = accum_ndigits - accum_weight - 1;
12103 : 1570442 : val_rscale = val->ndigits - val->weight - 1;
12104 [ + + ]: 1570442 : if (val_rscale > accum_rscale)
12105 : 114816 : accum_ndigits = accum_ndigits + (val_rscale - accum_rscale);
12106 : :
12107 [ + + - + ]: 1570442 : if (accum_ndigits != old_ndigits ||
12108 : : accum_weight != old_weight)
12109 : : {
12110 : : int32 *new_pos_digits;
12111 : : int32 *new_neg_digits;
12112 : : int weightdiff;
12113 : :
12114 : 175065 : weightdiff = accum_weight - old_weight;
12115 : :
12116 : 175065 : new_pos_digits = palloc0_array(int32, accum_ndigits);
12117 : 175065 : new_neg_digits = palloc0_array(int32, accum_ndigits);
12118 : :
12119 [ + + ]: 175065 : if (accum->pos_digits)
12120 : : {
12121 : 60297 : memcpy(&new_pos_digits[weightdiff], accum->pos_digits,
12122 : : old_ndigits * sizeof(int32));
12123 : 60297 : pfree(accum->pos_digits);
12124 : :
12125 : 60297 : memcpy(&new_neg_digits[weightdiff], accum->neg_digits,
12126 : : old_ndigits * sizeof(int32));
12127 : 60297 : pfree(accum->neg_digits);
12128 : : }
12129 : :
12130 : 175065 : accum->pos_digits = new_pos_digits;
12131 : 175065 : accum->neg_digits = new_neg_digits;
12132 : :
12133 : 175065 : accum->weight = accum_weight;
12134 : 175065 : accum->ndigits = accum_ndigits;
12135 : :
12136 : : Assert(accum->pos_digits[0] == 0 && accum->neg_digits[0] == 0);
12137 : 175065 : accum->have_carry_space = true;
12138 : : }
12139 : :
12140 [ + + ]: 1570442 : if (val->dscale > accum->dscale)
12141 : 200 : accum->dscale = val->dscale;
12142 : 1570442 : }
12143 : :
12144 : : /*
12145 : : * Return the current value of the accumulator. This perform final carry
12146 : : * propagation, and adds together the positive and negative sums.
12147 : : *
12148 : : * Unlike all the other routines, the caller is not required to switch to
12149 : : * the memory context that holds the accumulator.
12150 : : */
12151 : : static void
12152 : 115052 : accum_sum_final(NumericSumAccum *accum, NumericVar *result)
12153 : : {
12154 : : int i;
12155 : : NumericVar pos_var;
12156 : : NumericVar neg_var;
12157 : :
12158 [ - + ]: 115052 : if (accum->ndigits == 0)
12159 : : {
12160 : 0 : set_var_from_var(&const_zero, result);
12161 : 0 : return;
12162 : : }
12163 : :
12164 : : /* Perform final carry */
12165 : 115052 : accum_sum_carry(accum);
12166 : :
12167 : : /* Create NumericVars representing the positive and negative sums */
12168 : 115052 : init_var(&pos_var);
12169 : 115052 : init_var(&neg_var);
12170 : :
12171 : 115052 : pos_var.ndigits = neg_var.ndigits = accum->ndigits;
12172 : 115052 : pos_var.weight = neg_var.weight = accum->weight;
12173 : 115052 : pos_var.dscale = neg_var.dscale = accum->dscale;
12174 : 115052 : pos_var.sign = NUMERIC_POS;
12175 : 115052 : neg_var.sign = NUMERIC_NEG;
12176 : :
12177 : 115052 : pos_var.buf = pos_var.digits = digitbuf_alloc(accum->ndigits);
12178 : 115052 : neg_var.buf = neg_var.digits = digitbuf_alloc(accum->ndigits);
12179 : :
12180 [ + + ]: 1736688 : for (i = 0; i < accum->ndigits; i++)
12181 : : {
12182 : : Assert(accum->pos_digits[i] < NBASE);
12183 : 1621636 : pos_var.digits[i] = (int16) accum->pos_digits[i];
12184 : :
12185 : : Assert(accum->neg_digits[i] < NBASE);
12186 : 1621636 : neg_var.digits[i] = (int16) accum->neg_digits[i];
12187 : : }
12188 : :
12189 : : /* And add them together */
12190 : 115052 : add_var(&pos_var, &neg_var, result);
12191 : :
12192 : : /* Remove leading/trailing zeroes */
12193 : 115052 : strip_var(result);
12194 : : }
12195 : :
12196 : : /*
12197 : : * Copy an accumulator's state.
12198 : : *
12199 : : * 'dst' is assumed to be uninitialized beforehand. No attempt is made at
12200 : : * freeing old values.
12201 : : */
12202 : : static void
12203 : 28 : accum_sum_copy(NumericSumAccum *dst, NumericSumAccum *src)
12204 : : {
12205 : 28 : dst->pos_digits = palloc_array(int32, src->ndigits);
12206 : 28 : dst->neg_digits = palloc_array(int32, src->ndigits);
12207 : :
12208 : 28 : memcpy(dst->pos_digits, src->pos_digits, src->ndigits * sizeof(int32));
12209 : 28 : memcpy(dst->neg_digits, src->neg_digits, src->ndigits * sizeof(int32));
12210 : 28 : dst->num_uncarried = src->num_uncarried;
12211 : 28 : dst->ndigits = src->ndigits;
12212 : 28 : dst->weight = src->weight;
12213 : 28 : dst->dscale = src->dscale;
12214 : 28 : }
12215 : :
12216 : : /*
12217 : : * Add the current value of 'accum2' into 'accum'.
12218 : : */
12219 : : static void
12220 : 33 : accum_sum_combine(NumericSumAccum *accum, NumericSumAccum *accum2)
12221 : : {
12222 : : NumericVar tmp_var;
12223 : :
12224 : 33 : init_var(&tmp_var);
12225 : :
12226 : 33 : accum_sum_final(accum2, &tmp_var);
12227 : 33 : accum_sum_add(accum, &tmp_var);
12228 : :
12229 : 33 : free_var(&tmp_var);
12230 : 33 : }
|