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 : 102444 : numeric_in(PG_FUNCTION_ARGS)
627 : : {
628 : 102444 : char *str = PG_GETARG_CSTRING(0);
629 : : #ifdef NOT_USED
630 : : Oid typelem = PG_GETARG_OID(1);
631 : : #endif
632 : 102444 : int32 typmod = PG_GETARG_INT32(2);
633 : 102444 : Node *escontext = fcinfo->context;
634 : : Numeric res;
635 : : const char *cp;
636 : : const char *numstart;
637 : : int sign;
638 : :
639 : : /* Skip leading spaces */
640 : 102444 : cp = str;
641 [ + + ]: 118724 : while (*cp)
642 : : {
643 [ + + ]: 118712 : if (!isspace((unsigned char) *cp))
644 : 102432 : 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 : 102444 : numstart = cp;
654 : 102444 : sign = NUMERIC_POS;
655 : :
656 [ + + ]: 102444 : if (*cp == '+')
657 : 32 : cp++;
658 [ + + ]: 102412 : else if (*cp == '-')
659 : : {
660 : 2484 : sign = NUMERIC_NEG;
661 : 2484 : 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 [ + + + + ]: 102444 : 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 [ + + ]: 1201 : if (pg_strncasecmp(numstart, "NaN", 3) == 0)
678 : : {
679 : 397 : res = make_result(&const_nan);
680 : 397 : cp = numstart + 3;
681 : : }
682 [ + + ]: 804 : 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 [ + + ]: 465 : else if (pg_strncasecmp(cp, "inf", 3) == 0)
688 : : {
689 [ + + ]: 392 : res = make_result(sign == NUMERIC_POS ? &const_pinf : &const_ninf);
690 : 392 : 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 [ + + ]: 1156 : while (*cp)
703 : : {
704 [ - + ]: 28 : if (!isspace((unsigned char) *cp))
705 : 0 : goto invalid_syntax;
706 : 28 : cp++;
707 : : }
708 : :
709 [ - + ]: 1128 : 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 : 101243 : 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 [ + + ]: 101243 : if (cp[0] == '0')
728 : : {
729 [ + + + + ]: 32165 : 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 : 32061 : default:
744 : 32061 : base = 10;
745 : : }
746 : : }
747 : : else
748 : 69078 : base = 10;
749 : :
750 : : /* Parse the rest of the number and apply the sign */
751 [ + + ]: 101243 : if (base == 10)
752 : : {
753 [ - + ]: 101139 : if (!set_var_from_str(str, cp, &value, &cp, escontext))
754 : 16 : PG_RETURN_NULL();
755 : 101107 : 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 [ + + ]: 101251 : while (*cp)
769 : : {
770 [ + + ]: 100 : if (!isspace((unsigned char) *cp))
771 : 48 : goto invalid_syntax;
772 : 52 : cp++;
773 : : }
774 : :
775 [ + + ]: 101151 : if (!apply_typmod(&value, typmod, escontext))
776 : 16 : PG_RETURN_NULL();
777 : :
778 : 101135 : res = make_result_safe(&value, escontext);
779 : :
780 : 101135 : free_var(&value);
781 : : }
782 : :
783 : 102263 : 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 : 536522 : numeric_out(PG_FUNCTION_ARGS)
800 : : {
801 : 536522 : Numeric num = PG_GETARG_NUMERIC(0);
802 : : NumericVar x;
803 : : char *str;
804 : :
805 : : /*
806 : : * Handle NaN and infinities
807 : : */
808 [ + + ]: 536522 : if (NUMERIC_IS_SPECIAL(num))
809 : : {
810 [ + + ]: 2344 : if (NUMERIC_IS_PINF(num))
811 : 688 : PG_RETURN_CSTRING(pstrdup("Infinity"));
812 [ + + ]: 1656 : else if (NUMERIC_IS_NINF(num))
813 : 436 : 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 : 534178 : init_var_from_num(num, &x);
822 : :
823 : 534178 : str = get_str_from_var(&x);
824 : :
825 : 534178 : PG_RETURN_CSTRING(str);
826 : : }
827 : :
828 : : /*
829 : : * numeric_is_nan() -
830 : : *
831 : : * Is Numeric value a NaN?
832 : : */
833 : : bool
834 : 4492 : numeric_is_nan(Numeric num)
835 : : {
836 : 4492 : return NUMERIC_IS_NAN(num);
837 : : }
838 : :
839 : : /*
840 : : * numeric_is_inf() -
841 : : *
842 : : * Is Numeric value an infinity?
843 : : */
844 : : bool
845 : 894 : numeric_is_inf(Numeric num)
846 : : {
847 : 894 : 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 : 118442 : is_valid_numeric_typmod(int32 typmod)
900 : : {
901 : 118442 : 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 : 20637 : numeric_normalize(Numeric num)
1010 : : {
1011 : : NumericVar x;
1012 : : char *str;
1013 : : int last;
1014 : :
1015 : : /*
1016 : : * Handle NaN and infinities
1017 : : */
1018 [ - + ]: 20637 : 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 : 20637 : init_var_from_num(num, &x);
1029 : :
1030 : 20637 : str = get_str_from_var(&x);
1031 : :
1032 : : /* If there's no decimal point, there's certainly nothing to remove. */
1033 [ + + ]: 20637 : 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 : 20637 : 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 : 2476 : numeric_sign_internal(Numeric num)
1470 : : {
1471 [ + + ]: 2476 : if (NUMERIC_IS_SPECIAL(num))
1472 : : {
1473 : : Assert(!NUMERIC_IS_NAN(num));
1474 : : /* Must be Inf or -Inf */
1475 [ + + ]: 223 : if (NUMERIC_IS_PINF(num))
1476 : 129 : 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 [ + + + + ]: 2253 : else if (NUMERIC_NDIGITS(num) == 0)
1487 : 161 : return 0;
1488 [ + + - + : 2092 : else if (NUMERIC_SIGN(num) == NUMERIC_NEG)
+ + ]
1489 : 511 : return -1;
1490 : : else
1491 : 1581 : 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 : 5217 : numeric_round(PG_FUNCTION_ARGS)
1535 : : {
1536 : 5217 : Numeric num = PG_GETARG_NUMERIC(0);
1537 : 5217 : int32 scale = PG_GETARG_INT32(1);
1538 : : Numeric res;
1539 : : NumericVar arg;
1540 : :
1541 : : /*
1542 : : * Handle NaN and infinities
1543 : : */
1544 [ + + ]: 5217 : 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 : 5153 : scale = Max(scale, -(NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS - 1);
1556 : 5153 : scale = Min(scale, NUMERIC_DSCALE_MAX);
1557 : :
1558 : : /*
1559 : : * Unpack the argument and round it at the proper digit position
1560 : : */
1561 : 5153 : init_var(&arg);
1562 : 5153 : set_var_from_num(num, &arg);
1563 : :
1564 : 5153 : round_var(&arg, scale);
1565 : :
1566 : : /* We don't allow negative output dscale */
1567 [ + + ]: 5153 : if (scale < 0)
1568 : 149 : arg.dscale = 0;
1569 : :
1570 : : /*
1571 : : * Return the rounded result
1572 : : */
1573 : 5153 : res = make_result(&arg);
1574 : :
1575 : 5149 : free_var(&arg);
1576 : 5149 : 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 : 808 : numeric_sortsupport(PG_FUNCTION_ARGS)
2117 : : {
2118 : 808 : SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
2119 : :
2120 : 808 : ssup->comparator = numeric_fast_cmp;
2121 : :
2122 [ + + ]: 808 : 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 : 808 : 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 : 17217781 : numeric_fast_cmp(Datum x, Datum y, SortSupport ssup)
2287 : : {
2288 : 17217781 : Numeric nx = DatumGetNumeric(x);
2289 : 17217781 : Numeric ny = DatumGetNumeric(y);
2290 : : int result;
2291 : :
2292 : 17217781 : result = cmp_numerics(nx, ny);
2293 : :
2294 [ + + ]: 17217781 : if (nx != DatumGetPointer(x))
2295 : 7409856 : pfree(nx);
2296 [ + + ]: 17217781 : if (ny != DatumGetPointer(y))
2297 : 7409852 : pfree(ny);
2298 : :
2299 : 17217781 : 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 : 125689 : 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 [ + + ]: 125689 : if (DatumGetNumericAbbrev(x) < DatumGetNumericAbbrev(y))
2315 : 64788 : return 1;
2316 [ + + ]: 60901 : if (DatumGetNumericAbbrev(x) > DatumGetNumericAbbrev(y))
2317 : 60754 : return -1;
2318 : 147 : 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 : 4137 : case 3:
2391 : 4137 : result |= ((int64) var->digits[2]) << 14;
2392 : : pg_fallthrough;
2393 : 12219 : case 2:
2394 : 12219 : 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 : 485669 : numeric_cmp(PG_FUNCTION_ARGS)
2420 : : {
2421 : 485669 : Numeric num1 = PG_GETARG_NUMERIC(0);
2422 : 485669 : Numeric num2 = PG_GETARG_NUMERIC(1);
2423 : : int result;
2424 : :
2425 : 485669 : result = cmp_numerics(num1, num2);
2426 : :
2427 [ + + ]: 485669 : PG_FREE_IF_COPY(num1, 0);
2428 [ + + ]: 485669 : PG_FREE_IF_COPY(num2, 1);
2429 : :
2430 : 485669 : PG_RETURN_INT32(result);
2431 : : }
2432 : :
2433 : :
2434 : : Datum
2435 : 428596 : numeric_eq(PG_FUNCTION_ARGS)
2436 : : {
2437 : 428596 : Numeric num1 = PG_GETARG_NUMERIC(0);
2438 : 428596 : Numeric num2 = PG_GETARG_NUMERIC(1);
2439 : : bool result;
2440 : :
2441 : 428596 : result = cmp_numerics(num1, num2) == 0;
2442 : :
2443 [ + + ]: 428596 : PG_FREE_IF_COPY(num1, 0);
2444 [ + + ]: 428596 : PG_FREE_IF_COPY(num2, 1);
2445 : :
2446 : 428596 : 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 : 33642 : numeric_gt(PG_FUNCTION_ARGS)
2466 : : {
2467 : 33642 : Numeric num1 = PG_GETARG_NUMERIC(0);
2468 : 33642 : Numeric num2 = PG_GETARG_NUMERIC(1);
2469 : : bool result;
2470 : :
2471 : 33642 : result = cmp_numerics(num1, num2) > 0;
2472 : :
2473 [ + + ]: 33642 : PG_FREE_IF_COPY(num1, 0);
2474 [ + + ]: 33642 : PG_FREE_IF_COPY(num2, 1);
2475 : :
2476 : 33642 : PG_RETURN_BOOL(result);
2477 : : }
2478 : :
2479 : : Datum
2480 : 7945 : numeric_ge(PG_FUNCTION_ARGS)
2481 : : {
2482 : 7945 : Numeric num1 = PG_GETARG_NUMERIC(0);
2483 : 7945 : Numeric num2 = PG_GETARG_NUMERIC(1);
2484 : : bool result;
2485 : :
2486 : 7945 : result = cmp_numerics(num1, num2) >= 0;
2487 : :
2488 [ + + ]: 7945 : PG_FREE_IF_COPY(num1, 0);
2489 [ - + ]: 7945 : PG_FREE_IF_COPY(num2, 1);
2490 : :
2491 : 7945 : 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 : 18400456 : 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 [ + + ]: 18400456 : if (NUMERIC_IS_SPECIAL(num1))
2535 : : {
2536 [ + + ]: 2418 : if (NUMERIC_IS_NAN(num1))
2537 : : {
2538 [ + + ]: 1329 : if (NUMERIC_IS_NAN(num2))
2539 : 640 : result = 0; /* NAN = NAN */
2540 : : else
2541 : 689 : 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 [ + + ]: 18398038 : else if (NUMERIC_IS_SPECIAL(num2))
2561 : : {
2562 [ + + ]: 7934 : if (NUMERIC_IS_NINF(num2))
2563 : 12 : result = 1; /* normal > NINF */
2564 : : else
2565 : 7922 : result = -1; /* normal < NAN or PINF */
2566 : : }
2567 : : else
2568 : : {
2569 [ + + + + ]: 36780832 : result = cmp_var_common(NUMERIC_DIGITS(num1), NUMERIC_NDIGITS(num1),
2570 [ + + - + : 18390302 : NUMERIC_WEIGHT(num1), NUMERIC_SIGN(num1),
+ + + + ]
2571 [ + + + + ]: 18390104 : NUMERIC_DIGITS(num2), NUMERIC_NDIGITS(num2),
2572 [ + + - + : 18390530 : NUMERIC_WEIGHT(num2), NUMERIC_SIGN(num2));
+ + + + ]
2573 : : }
2574 : :
2575 : 18400456 : 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 [ + - ]: 404011 : if (digits[i] != (NumericDigit) 0)
2747 : 404011 : 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 : 1111 : PG_RETURN_UINT32(-1);
2764 : :
2765 [ + - + - ]: 404011 : for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--)
2766 : : {
2767 [ + - ]: 404011 : if (digits[i] != (NumericDigit) 0)
2768 : 404011 : 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 [ + - ]: 404011 : hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset;
2783 [ + - ]: 404011 : digit_hash = hash_bytes((unsigned char *) (NUMERIC_DIGITS(key)
2784 : 404011 : + start_offset),
2785 : : hash_len * sizeof(NumericDigit));
2786 : :
2787 : : /* Mix in the weight, via XOR */
2788 : 404011 : result = digit_hash ^ weight;
2789 : :
2790 : 404011 : 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 : 168449 : numeric_add(PG_FUNCTION_ARGS)
2870 : : {
2871 : 168449 : Numeric num1 = PG_GETARG_NUMERIC(0);
2872 : 168449 : Numeric num2 = PG_GETARG_NUMERIC(1);
2873 : : Numeric res;
2874 : :
2875 : 168449 : res = numeric_add_safe(num1, num2, NULL);
2876 : :
2877 : 168449 : 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 : 169143 : 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 [ + + + + ]: 169143 : 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 : 169011 : init_var_from_num(num1, &arg1);
2925 : 169011 : init_var_from_num(num2, &arg2);
2926 : :
2927 : 169011 : init_var(&result);
2928 : 169011 : add_var(&arg1, &arg2, &result);
2929 : :
2930 : 169011 : res = make_result_safe(&result, escontext);
2931 : :
2932 : 169011 : free_var(&result);
2933 : :
2934 : 169011 : return res;
2935 : : }
2936 : :
2937 : :
2938 : : /*
2939 : : * numeric_sub() -
2940 : : *
2941 : : * Subtract one numeric from another
2942 : : */
2943 : : Datum
2944 : 46419 : numeric_sub(PG_FUNCTION_ARGS)
2945 : : {
2946 : 46419 : Numeric num1 = PG_GETARG_NUMERIC(0);
2947 : 46419 : Numeric num2 = PG_GETARG_NUMERIC(1);
2948 : : Numeric res;
2949 : :
2950 : 46419 : res = numeric_sub_safe(num1, num2, NULL);
2951 : :
2952 : 46419 : 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 : 46523 : 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 [ + + + + ]: 46523 : 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 : 46391 : init_var_from_num(num1, &arg1);
3001 : 46391 : init_var_from_num(num2, &arg2);
3002 : :
3003 : 46391 : init_var(&result);
3004 : 46391 : sub_var(&arg1, &arg2, &result);
3005 : :
3006 : 46391 : res = make_result_safe(&result, escontext);
3007 : :
3008 : 46391 : free_var(&result);
3009 : :
3010 : 46391 : 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 : 98476 : numeric_div(PG_FUNCTION_ARGS)
3143 : : {
3144 : 98476 : Numeric num1 = PG_GETARG_NUMERIC(0);
3145 : 98476 : Numeric num2 = PG_GETARG_NUMERIC(1);
3146 : : Numeric res;
3147 : :
3148 : 98476 : res = numeric_div_safe(num1, num2, NULL);
3149 : :
3150 : 98455 : 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 : 99037 : 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 [ + + + + ]: 99037 : 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 : 98904 : init_var_from_num(num1, &arg1);
3219 : 98904 : init_var_from_num(num2, &arg2);
3220 : :
3221 : 98904 : init_var(&result);
3222 : :
3223 : : /*
3224 : : * Select scale for division result
3225 : : */
3226 : 98904 : rscale = select_div_scale(&arg1, &arg2);
3227 : :
3228 : : /* Check for division by zero */
3229 [ + + - + ]: 98904 : 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 : 98871 : div_var(&arg1, &arg2, &result, rscale, true, true);
3236 : :
3237 : 98871 : res = make_result_safe(&result, escontext);
3238 : :
3239 : 98871 : free_var(&result);
3240 : :
3241 : 98871 : 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 : 275234 : numeric_mod(PG_FUNCTION_ARGS)
3346 : : {
3347 : 275234 : Numeric num1 = PG_GETARG_NUMERIC(0);
3348 : 275234 : Numeric num2 = PG_GETARG_NUMERIC(1);
3349 : : Numeric res;
3350 : :
3351 : 275234 : res = numeric_mod_safe(num1, num2, NULL);
3352 : :
3353 : 275222 : 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 : 275242 : 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 [ + + + + ]: 275242 : 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 : 275109 : init_var_from_num(num1, &arg1);
3392 : 275109 : init_var_from_num(num2, &arg2);
3393 : :
3394 : 275109 : init_var(&result);
3395 : :
3396 : : /* Check for division by zero */
3397 [ + + - + ]: 275109 : if (arg2.ndigits == 0 || arg2.digits[0] == 0)
3398 : 8 : goto division_by_zero;
3399 : :
3400 : 275101 : mod_var(&arg1, &arg2, &result);
3401 : :
3402 : 275101 : res = make_result_safe(&result, escontext);
3403 : :
3404 : 275101 : free_var(&result);
3405 : :
3406 : 275101 : 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 : 434 : PG_RETURN_NUMERIC(num1);
3465 : : else
3466 : 109 : 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 : 11889 : PG_RETURN_NUMERIC(num1);
3487 : : else
3488 : 531 : 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 : 240 : numeric_log(PG_FUNCTION_ARGS)
3849 : : {
3850 : 240 : Numeric num1 = PG_GETARG_NUMERIC(0);
3851 : 240 : 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 [ + + + + ]: 240 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3861 : : {
3862 : : int sign1,
3863 : : sign2;
3864 : :
3865 [ + + + + ]: 84 : 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 : 48 : sign1 = numeric_sign_internal(num1);
3869 : 48 : sign2 = numeric_sign_internal(num2);
3870 [ + + + + ]: 48 : 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 [ + - + + ]: 32 : if (sign1 == 0 || sign2 == 0)
3876 [ + - ]: 4 : ereport(ERROR,
3877 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
3878 : : errmsg("cannot take logarithm of zero")));
3879 [ + + ]: 28 : 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 : : /* log(finite-positive, Inf) is Inf */
3889 : 16 : PG_RETURN_NUMERIC(make_result(&const_pinf));
3890 : : }
3891 : :
3892 : : /*
3893 : : * Initialize things
3894 : : */
3895 : 156 : init_var_from_num(num1, &arg1);
3896 : 156 : init_var_from_num(num2, &arg2);
3897 : 156 : init_var(&result);
3898 : :
3899 : : /*
3900 : : * Call log_var() to compute and return the result; note it handles scale
3901 : : * selection itself.
3902 : : */
3903 : 156 : log_var(&arg1, &arg2, &result);
3904 : :
3905 : 116 : res = make_result(&result);
3906 : :
3907 : 116 : free_var(&result);
3908 : :
3909 : 116 : PG_RETURN_NUMERIC(res);
3910 : : }
3911 : :
3912 : :
3913 : : /*
3914 : : * numeric_power() -
3915 : : *
3916 : : * Raise x to the power of y
3917 : : */
3918 : : Datum
3919 : 1149 : numeric_power(PG_FUNCTION_ARGS)
3920 : : {
3921 : 1149 : Numeric num1 = PG_GETARG_NUMERIC(0);
3922 : 1149 : Numeric num2 = PG_GETARG_NUMERIC(1);
3923 : : Numeric res;
3924 : : NumericVar arg1;
3925 : : NumericVar arg2;
3926 : : NumericVar result;
3927 : : int sign1,
3928 : : sign2;
3929 : :
3930 : : /*
3931 : : * Handle NaN and infinities
3932 : : */
3933 [ + + + + ]: 1149 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3934 : : {
3935 : : /*
3936 : : * We follow the POSIX spec for pow(3), which says that NaN ^ 0 = 1,
3937 : : * and 1 ^ NaN = 1, while all other cases with NaN inputs yield NaN
3938 : : * (with no error).
3939 : : */
3940 [ + + ]: 173 : if (NUMERIC_IS_NAN(num1))
3941 : : {
3942 [ + + ]: 39 : if (!NUMERIC_IS_SPECIAL(num2))
3943 : : {
3944 : 26 : init_var_from_num(num2, &arg2);
3945 [ + + ]: 26 : if (cmp_var(&arg2, &const_zero) == 0)
3946 : 9 : PG_RETURN_NUMERIC(make_result(&const_one));
3947 : : }
3948 : 30 : PG_RETURN_NUMERIC(make_result(&const_nan));
3949 : : }
3950 [ + + ]: 134 : if (NUMERIC_IS_NAN(num2))
3951 : : {
3952 [ + + ]: 30 : if (!NUMERIC_IS_SPECIAL(num1))
3953 : : {
3954 : 26 : init_var_from_num(num1, &arg1);
3955 [ + + ]: 26 : if (cmp_var(&arg1, &const_one) == 0)
3956 : 9 : PG_RETURN_NUMERIC(make_result(&const_one));
3957 : : }
3958 : 21 : PG_RETURN_NUMERIC(make_result(&const_nan));
3959 : : }
3960 : : /* At least one input is infinite, but error rules still apply */
3961 : 104 : sign1 = numeric_sign_internal(num1);
3962 : 104 : sign2 = numeric_sign_internal(num2);
3963 [ + + + + ]: 104 : if (sign1 == 0 && sign2 < 0)
3964 [ + - ]: 4 : ereport(ERROR,
3965 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
3966 : : errmsg("zero raised to a negative power is undefined")));
3967 [ + + + + ]: 100 : if (sign1 < 0 && !numeric_is_integral(num2))
3968 [ + - ]: 4 : ereport(ERROR,
3969 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
3970 : : errmsg("a negative number raised to a non-integer power yields a complex result")));
3971 : :
3972 : : /*
3973 : : * POSIX gives this series of rules for pow(3) with infinite inputs:
3974 : : *
3975 : : * For any value of y, if x is +1, 1.0 shall be returned.
3976 : : */
3977 [ + + ]: 96 : if (!NUMERIC_IS_SPECIAL(num1))
3978 : : {
3979 : 31 : init_var_from_num(num1, &arg1);
3980 [ + + ]: 31 : if (cmp_var(&arg1, &const_one) == 0)
3981 : 4 : PG_RETURN_NUMERIC(make_result(&const_one));
3982 : : }
3983 : :
3984 : : /*
3985 : : * For any value of x, if y is [-]0, 1.0 shall be returned.
3986 : : */
3987 [ + + ]: 92 : if (sign2 == 0)
3988 : 9 : PG_RETURN_NUMERIC(make_result(&const_one));
3989 : :
3990 : : /*
3991 : : * For any odd integer value of y > 0, if x is [-]0, [-]0 shall be
3992 : : * returned. For y > 0 and not an odd integer, if x is [-]0, +0 shall
3993 : : * be returned. (Since we don't deal in minus zero, we need not
3994 : : * distinguish these two cases.)
3995 : : */
3996 [ + + + - ]: 83 : if (sign1 == 0 && sign2 > 0)
3997 : 4 : PG_RETURN_NUMERIC(make_result(&const_zero));
3998 : :
3999 : : /*
4000 : : * If x is -1, and y is [-]Inf, 1.0 shall be returned.
4001 : : *
4002 : : * For |x| < 1, if y is -Inf, +Inf shall be returned.
4003 : : *
4004 : : * For |x| > 1, if y is -Inf, +0 shall be returned.
4005 : : *
4006 : : * For |x| < 1, if y is +Inf, +0 shall be returned.
4007 : : *
4008 : : * For |x| > 1, if y is +Inf, +Inf shall be returned.
4009 : : */
4010 [ + + ]: 79 : if (NUMERIC_IS_INF(num2))
4011 : : {
4012 : : bool abs_x_gt_one;
4013 : :
4014 [ + + ]: 42 : if (NUMERIC_IS_SPECIAL(num1))
4015 : 19 : abs_x_gt_one = true; /* x is either Inf or -Inf */
4016 : : else
4017 : : {
4018 : 23 : init_var_from_num(num1, &arg1);
4019 [ + + ]: 23 : if (cmp_var(&arg1, &const_minus_one) == 0)
4020 : 5 : PG_RETURN_NUMERIC(make_result(&const_one));
4021 : 18 : arg1.sign = NUMERIC_POS; /* now arg1 = abs(x) */
4022 : 18 : abs_x_gt_one = (cmp_var(&arg1, &const_one) > 0);
4023 : : }
4024 [ + + ]: 37 : if (abs_x_gt_one == (sign2 > 0))
4025 : 22 : PG_RETURN_NUMERIC(make_result(&const_pinf));
4026 : : else
4027 : 15 : PG_RETURN_NUMERIC(make_result(&const_zero));
4028 : : }
4029 : :
4030 : : /*
4031 : : * For y < 0, if x is +Inf, +0 shall be returned.
4032 : : *
4033 : : * For y > 0, if x is +Inf, +Inf shall be returned.
4034 : : */
4035 [ + + ]: 37 : if (NUMERIC_IS_PINF(num1))
4036 : : {
4037 [ + + ]: 17 : if (sign2 > 0)
4038 : 12 : PG_RETURN_NUMERIC(make_result(&const_pinf));
4039 : : else
4040 : 5 : PG_RETURN_NUMERIC(make_result(&const_zero));
4041 : : }
4042 : :
4043 : : Assert(NUMERIC_IS_NINF(num1));
4044 : :
4045 : : /*
4046 : : * For y an odd integer < 0, if x is -Inf, -0 shall be returned. For
4047 : : * y < 0 and not an odd integer, if x is -Inf, +0 shall be returned.
4048 : : * (Again, we need not distinguish these two cases.)
4049 : : */
4050 [ + + ]: 20 : if (sign2 < 0)
4051 : 10 : PG_RETURN_NUMERIC(make_result(&const_zero));
4052 : :
4053 : : /*
4054 : : * For y an odd integer > 0, if x is -Inf, -Inf shall be returned. For
4055 : : * y > 0 and not an odd integer, if x is -Inf, +Inf shall be returned.
4056 : : */
4057 : 10 : init_var_from_num(num2, &arg2);
4058 [ + - + - ]: 10 : if (arg2.ndigits > 0 && arg2.ndigits == arg2.weight + 1 &&
4059 [ + + ]: 10 : (arg2.digits[arg2.ndigits - 1] & 1))
4060 : 5 : PG_RETURN_NUMERIC(make_result(&const_ninf));
4061 : : else
4062 : 5 : PG_RETURN_NUMERIC(make_result(&const_pinf));
4063 : : }
4064 : :
4065 : : /*
4066 : : * The SQL spec requires that we emit a particular SQLSTATE error code for
4067 : : * certain error conditions. Specifically, we don't return a
4068 : : * divide-by-zero error code for 0 ^ -1. Raising a negative number to a
4069 : : * non-integer power must produce the same error code, but that case is
4070 : : * handled in power_var().
4071 : : */
4072 : 976 : sign1 = numeric_sign_internal(num1);
4073 : 976 : sign2 = numeric_sign_internal(num2);
4074 : :
4075 [ + + + + ]: 976 : if (sign1 == 0 && sign2 < 0)
4076 [ + - ]: 8 : ereport(ERROR,
4077 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
4078 : : errmsg("zero raised to a negative power is undefined")));
4079 : :
4080 : : /*
4081 : : * Initialize things
4082 : : */
4083 : 968 : init_var(&result);
4084 : 968 : init_var_from_num(num1, &arg1);
4085 : 968 : init_var_from_num(num2, &arg2);
4086 : :
4087 : : /*
4088 : : * Call power_var() to compute and return the result; note it handles
4089 : : * scale selection itself.
4090 : : */
4091 : 968 : power_var(&arg1, &arg2, &result);
4092 : :
4093 : 948 : res = make_result(&result);
4094 : :
4095 : 948 : free_var(&result);
4096 : :
4097 : 948 : PG_RETURN_NUMERIC(res);
4098 : : }
4099 : :
4100 : : /*
4101 : : * numeric_scale() -
4102 : : *
4103 : : * Returns the scale, i.e. the count of decimal digits in the fractional part
4104 : : */
4105 : : Datum
4106 : 81 : numeric_scale(PG_FUNCTION_ARGS)
4107 : : {
4108 : 81 : Numeric num = PG_GETARG_NUMERIC(0);
4109 : :
4110 [ + + ]: 81 : if (NUMERIC_IS_SPECIAL(num))
4111 : 14 : PG_RETURN_NULL();
4112 : :
4113 [ + - ]: 67 : PG_RETURN_INT32(NUMERIC_DSCALE(num));
4114 : : }
4115 : :
4116 : : /*
4117 : : * Calculate minimum scale for value.
4118 : : */
4119 : : static int
4120 : 267 : get_min_scale(NumericVar *var)
4121 : : {
4122 : : int min_scale;
4123 : : int last_digit_pos;
4124 : :
4125 : : /*
4126 : : * Ordinarily, the input value will be "stripped" so that the last
4127 : : * NumericDigit is nonzero. But we don't want to get into an infinite
4128 : : * loop if it isn't, so explicitly find the last nonzero digit.
4129 : : */
4130 : 267 : last_digit_pos = var->ndigits - 1;
4131 [ + + ]: 267 : while (last_digit_pos >= 0 &&
4132 [ - + ]: 243 : var->digits[last_digit_pos] == 0)
4133 : 0 : last_digit_pos--;
4134 : :
4135 [ + + ]: 267 : if (last_digit_pos >= 0)
4136 : : {
4137 : : /* compute min_scale assuming that last ndigit has no zeroes */
4138 : 243 : min_scale = (last_digit_pos - var->weight) * DEC_DIGITS;
4139 : :
4140 : : /*
4141 : : * We could get a negative result if there are no digits after the
4142 : : * decimal point. In this case the min_scale must be zero.
4143 : : */
4144 [ + + ]: 243 : if (min_scale > 0)
4145 : : {
4146 : : /*
4147 : : * Reduce min_scale if trailing digit(s) in last NumericDigit are
4148 : : * zero.
4149 : : */
4150 : 135 : NumericDigit last_digit = var->digits[last_digit_pos];
4151 : :
4152 [ + + ]: 365 : while (last_digit % 10 == 0)
4153 : : {
4154 : 230 : min_scale--;
4155 : 230 : last_digit /= 10;
4156 : : }
4157 : : }
4158 : : else
4159 : 108 : min_scale = 0;
4160 : : }
4161 : : else
4162 : 24 : min_scale = 0; /* result if input is zero */
4163 : :
4164 : 267 : return min_scale;
4165 : : }
4166 : :
4167 : : /*
4168 : : * Returns minimum scale required to represent supplied value without loss.
4169 : : */
4170 : : Datum
4171 : 60 : numeric_min_scale(PG_FUNCTION_ARGS)
4172 : : {
4173 : 60 : Numeric num = PG_GETARG_NUMERIC(0);
4174 : : NumericVar arg;
4175 : : int min_scale;
4176 : :
4177 [ + + ]: 60 : if (NUMERIC_IS_SPECIAL(num))
4178 : 10 : PG_RETURN_NULL();
4179 : :
4180 : 50 : init_var_from_num(num, &arg);
4181 : 50 : min_scale = get_min_scale(&arg);
4182 : 50 : free_var(&arg);
4183 : :
4184 : 50 : PG_RETURN_INT32(min_scale);
4185 : : }
4186 : :
4187 : : /*
4188 : : * Reduce scale of numeric value to represent supplied value without loss.
4189 : : */
4190 : : Datum
4191 : 227 : numeric_trim_scale(PG_FUNCTION_ARGS)
4192 : : {
4193 : 227 : Numeric num = PG_GETARG_NUMERIC(0);
4194 : : Numeric res;
4195 : : NumericVar result;
4196 : :
4197 [ + + ]: 227 : if (NUMERIC_IS_SPECIAL(num))
4198 : 10 : PG_RETURN_NUMERIC(duplicate_numeric(num));
4199 : :
4200 : 217 : init_var_from_num(num, &result);
4201 : 217 : result.dscale = get_min_scale(&result);
4202 : 217 : res = make_result(&result);
4203 : 217 : free_var(&result);
4204 : :
4205 : 217 : PG_RETURN_NUMERIC(res);
4206 : : }
4207 : :
4208 : : /*
4209 : : * Return a random numeric value in the range [rmin, rmax].
4210 : : */
4211 : : Numeric
4212 : 22308 : random_numeric(pg_prng_state *state, Numeric rmin, Numeric rmax)
4213 : : {
4214 : : NumericVar rmin_var;
4215 : : NumericVar rmax_var;
4216 : : NumericVar result;
4217 : : Numeric res;
4218 : :
4219 : : /* Range bounds must not be NaN/infinity */
4220 [ + + ]: 22308 : if (NUMERIC_IS_SPECIAL(rmin))
4221 : : {
4222 [ + + ]: 8 : if (NUMERIC_IS_NAN(rmin))
4223 [ + - ]: 4 : ereport(ERROR,
4224 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4225 : : errmsg("lower bound cannot be NaN"));
4226 : : else
4227 [ + - ]: 4 : ereport(ERROR,
4228 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4229 : : errmsg("lower bound cannot be infinity"));
4230 : : }
4231 [ + + ]: 22300 : if (NUMERIC_IS_SPECIAL(rmax))
4232 : : {
4233 [ + + ]: 8 : if (NUMERIC_IS_NAN(rmax))
4234 [ + - ]: 4 : ereport(ERROR,
4235 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4236 : : errmsg("upper bound cannot be NaN"));
4237 : : else
4238 [ + - ]: 4 : ereport(ERROR,
4239 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4240 : : errmsg("upper bound cannot be infinity"));
4241 : : }
4242 : :
4243 : : /* Return a random value in the range [rmin, rmax] */
4244 : 22292 : init_var_from_num(rmin, &rmin_var);
4245 : 22292 : init_var_from_num(rmax, &rmax_var);
4246 : :
4247 : 22292 : init_var(&result);
4248 : :
4249 : 22292 : random_var(state, &rmin_var, &rmax_var, &result);
4250 : :
4251 : 22288 : res = make_result(&result);
4252 : :
4253 : 22288 : free_var(&result);
4254 : :
4255 : 22288 : return res;
4256 : : }
4257 : :
4258 : :
4259 : : /* ----------------------------------------------------------------------
4260 : : *
4261 : : * Type conversion functions
4262 : : *
4263 : : * ----------------------------------------------------------------------
4264 : : */
4265 : :
4266 : : Numeric
4267 : 1245756 : int64_to_numeric(int64 val)
4268 : : {
4269 : : Numeric res;
4270 : : NumericVar result;
4271 : :
4272 : 1245756 : init_var(&result);
4273 : :
4274 : 1245756 : int64_to_numericvar(val, &result);
4275 : :
4276 : 1245756 : res = make_result(&result);
4277 : :
4278 : 1245756 : free_var(&result);
4279 : :
4280 : 1245756 : return res;
4281 : : }
4282 : :
4283 : : /*
4284 : : * Convert val1/(10**log10val2) to numeric. This is much faster than normal
4285 : : * numeric division.
4286 : : */
4287 : : Numeric
4288 : 15151 : int64_div_fast_to_numeric(int64 val1, int log10val2)
4289 : : {
4290 : : Numeric res;
4291 : : NumericVar result;
4292 : : int rscale;
4293 : : int w;
4294 : : int m;
4295 : :
4296 : 15151 : init_var(&result);
4297 : :
4298 : : /* result scale */
4299 : 15151 : rscale = log10val2 < 0 ? 0 : log10val2;
4300 : :
4301 : : /* how much to decrease the weight by */
4302 : 15151 : w = log10val2 / DEC_DIGITS;
4303 : : /* how much is left to divide by */
4304 : 15151 : m = log10val2 % DEC_DIGITS;
4305 [ - + ]: 15151 : if (m < 0)
4306 : : {
4307 : 0 : m += DEC_DIGITS;
4308 : 0 : w--;
4309 : : }
4310 : :
4311 : : /*
4312 : : * If there is anything left to divide by (10^m with 0 < m < DEC_DIGITS),
4313 : : * multiply the dividend by 10^(DEC_DIGITS - m), and shift the weight by
4314 : : * one more.
4315 : : */
4316 [ + - ]: 15151 : if (m > 0)
4317 : : {
4318 : : #if DEC_DIGITS == 4
4319 : : static const int pow10[] = {1, 10, 100, 1000};
4320 : : #elif DEC_DIGITS == 2
4321 : : static const int pow10[] = {1, 10};
4322 : : #elif DEC_DIGITS == 1
4323 : : static const int pow10[] = {1};
4324 : : #else
4325 : : #error unsupported NBASE
4326 : : #endif
4327 : 15151 : int64 factor = pow10[DEC_DIGITS - m];
4328 : : int64 new_val1;
4329 : :
4330 : : StaticAssertDecl(lengthof(pow10) == DEC_DIGITS, "mismatch with DEC_DIGITS");
4331 : :
4332 [ + + ]: 15151 : if (unlikely(pg_mul_s64_overflow(val1, factor, &new_val1)))
4333 : : {
4334 : : /* do the multiplication using 128-bit integers */
4335 : : INT128 tmp;
4336 : :
4337 : 9 : tmp = int64_to_int128(0);
4338 : 9 : int128_add_int64_mul_int64(&tmp, val1, factor);
4339 : :
4340 : 9 : int128_to_numericvar(tmp, &result);
4341 : : }
4342 : : else
4343 : 15142 : int64_to_numericvar(new_val1, &result);
4344 : :
4345 : 15151 : w++;
4346 : : }
4347 : : else
4348 : 0 : int64_to_numericvar(val1, &result);
4349 : :
4350 : 15151 : result.weight -= w;
4351 : 15151 : result.dscale = rscale;
4352 : :
4353 : 15151 : res = make_result(&result);
4354 : :
4355 : 15151 : free_var(&result);
4356 : :
4357 : 15151 : return res;
4358 : : }
4359 : :
4360 : : Datum
4361 : 1037969 : int4_numeric(PG_FUNCTION_ARGS)
4362 : : {
4363 : 1037969 : int32 val = PG_GETARG_INT32(0);
4364 : :
4365 : 1037969 : PG_RETURN_NUMERIC(int64_to_numeric(val));
4366 : : }
4367 : :
4368 : : /*
4369 : : * Internal version of numeric_int4() with support for soft error reporting.
4370 : : */
4371 : : int32
4372 : 4913 : numeric_int4_safe(Numeric num, Node *escontext)
4373 : : {
4374 : : NumericVar x;
4375 : : int32 result;
4376 : :
4377 [ + + ]: 4913 : if (NUMERIC_IS_SPECIAL(num))
4378 : : {
4379 [ + + ]: 12 : if (NUMERIC_IS_NAN(num))
4380 [ + - ]: 4 : ereturn(escontext, 0,
4381 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4382 : : errmsg("cannot convert NaN to %s", "integer")));
4383 : : else
4384 [ + - ]: 8 : ereturn(escontext, 0,
4385 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4386 : : errmsg("cannot convert infinity to %s", "integer")));
4387 : : }
4388 : :
4389 : : /* Convert to variable format, then convert to int4 */
4390 : 4901 : init_var_from_num(num, &x);
4391 : :
4392 [ + + ]: 4901 : if (!numericvar_to_int32(&x, &result))
4393 [ + + ]: 70 : ereturn(escontext, 0,
4394 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4395 : : errmsg("integer out of range")));
4396 : :
4397 : 4831 : return result;
4398 : : }
4399 : :
4400 : : Datum
4401 : 3770 : numeric_int4(PG_FUNCTION_ARGS)
4402 : : {
4403 : 3770 : Numeric num = PG_GETARG_NUMERIC(0);
4404 : : int32 result;
4405 : :
4406 : 3770 : result = numeric_int4_safe(num, fcinfo->context);
4407 : :
4408 [ - + - - : 3750 : if (unlikely(SOFT_ERROR_OCCURRED(fcinfo->context)))
- + - - -
+ ]
4409 : 0 : PG_RETURN_NULL();
4410 : :
4411 : 3750 : PG_RETURN_INT32(result);
4412 : : }
4413 : :
4414 : : /*
4415 : : * Given a NumericVar, convert it to an int32. If the NumericVar
4416 : : * exceeds the range of an int32, false is returned, otherwise true is returned.
4417 : : * The input NumericVar is *not* free'd.
4418 : : */
4419 : : static bool
4420 : 5402 : numericvar_to_int32(const NumericVar *var, int32 *result)
4421 : : {
4422 : : int64 val;
4423 : :
4424 [ + + ]: 5402 : if (!numericvar_to_int64(var, &val))
4425 : 4 : return false;
4426 : :
4427 [ + + + + ]: 5398 : if (unlikely(val < PG_INT32_MIN) || unlikely(val > PG_INT32_MAX))
4428 : 66 : return false;
4429 : :
4430 : : /* Down-convert to int4 */
4431 : 5332 : *result = (int32) val;
4432 : :
4433 : 5332 : return true;
4434 : : }
4435 : :
4436 : : Datum
4437 : 24588 : int8_numeric(PG_FUNCTION_ARGS)
4438 : : {
4439 : 24588 : int64 val = PG_GETARG_INT64(0);
4440 : :
4441 : 24588 : PG_RETURN_NUMERIC(int64_to_numeric(val));
4442 : : }
4443 : :
4444 : : /*
4445 : : * Internal version of numeric_int8() with support for soft error reporting.
4446 : : */
4447 : : int64
4448 : 387 : numeric_int8_safe(Numeric num, Node *escontext)
4449 : : {
4450 : : NumericVar x;
4451 : : int64 result;
4452 : :
4453 [ + + ]: 387 : if (NUMERIC_IS_SPECIAL(num))
4454 : : {
4455 [ + + ]: 12 : if (NUMERIC_IS_NAN(num))
4456 [ + - ]: 4 : ereturn(escontext, 0,
4457 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4458 : : errmsg("cannot convert NaN to %s", "bigint")));
4459 : : else
4460 [ + - ]: 8 : ereturn(escontext, 0,
4461 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4462 : : errmsg("cannot convert infinity to %s", "bigint")));
4463 : : }
4464 : :
4465 : : /* Convert to variable format, then convert to int8 */
4466 : 375 : init_var_from_num(num, &x);
4467 : :
4468 [ + + ]: 375 : if (!numericvar_to_int64(&x, &result))
4469 [ + + ]: 40 : ereturn(escontext, 0,
4470 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4471 : : errmsg("bigint out of range")));
4472 : :
4473 : 335 : return result;
4474 : : }
4475 : :
4476 : : Datum
4477 : 347 : numeric_int8(PG_FUNCTION_ARGS)
4478 : : {
4479 : 347 : Numeric num = PG_GETARG_NUMERIC(0);
4480 : : int64 result;
4481 : :
4482 : 347 : result = numeric_int8_safe(num, fcinfo->context);
4483 : :
4484 [ - + - - : 303 : if (unlikely(SOFT_ERROR_OCCURRED(fcinfo->context)))
- + - - -
+ ]
4485 : 0 : PG_RETURN_NULL();
4486 : :
4487 : 303 : PG_RETURN_INT64(result);
4488 : : }
4489 : :
4490 : :
4491 : : Datum
4492 : 5 : int2_numeric(PG_FUNCTION_ARGS)
4493 : : {
4494 : 5 : int16 val = PG_GETARG_INT16(0);
4495 : :
4496 : 5 : PG_RETURN_NUMERIC(int64_to_numeric(val));
4497 : : }
4498 : :
4499 : :
4500 : : Datum
4501 : 73 : numeric_int2(PG_FUNCTION_ARGS)
4502 : : {
4503 : 73 : Numeric num = PG_GETARG_NUMERIC(0);
4504 : : NumericVar x;
4505 : : int64 val;
4506 : : int16 result;
4507 : :
4508 [ + + ]: 73 : if (NUMERIC_IS_SPECIAL(num))
4509 : : {
4510 [ + + ]: 12 : if (NUMERIC_IS_NAN(num))
4511 [ + - ]: 4 : ereturn(fcinfo->context, (Datum) 0,
4512 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4513 : : errmsg("cannot convert NaN to %s", "smallint")));
4514 : : else
4515 [ + - ]: 8 : ereturn(fcinfo->context, (Datum) 0,
4516 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4517 : : errmsg("cannot convert infinity to %s", "smallint")));
4518 : : }
4519 : :
4520 : : /* Convert to variable format and thence to int8 */
4521 : 61 : init_var_from_num(num, &x);
4522 : :
4523 [ - + ]: 61 : if (!numericvar_to_int64(&x, &val))
4524 [ # # ]: 0 : ereturn(fcinfo->context, (Datum) 0,
4525 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4526 : : errmsg("smallint out of range")));
4527 : :
4528 [ + + + + ]: 61 : if (unlikely(val < PG_INT16_MIN) || unlikely(val > PG_INT16_MAX))
4529 [ + - ]: 8 : ereturn(fcinfo->context, (Datum) 0,
4530 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4531 : : errmsg("smallint out of range")));
4532 : :
4533 : : /* Down-convert to int2 */
4534 : 53 : result = (int16) val;
4535 : :
4536 : 53 : PG_RETURN_INT16(result);
4537 : : }
4538 : :
4539 : :
4540 : : Datum
4541 : 654 : float8_numeric(PG_FUNCTION_ARGS)
4542 : : {
4543 : 654 : float8 val = PG_GETARG_FLOAT8(0);
4544 : : Numeric res;
4545 : : NumericVar result;
4546 : : char buf[DBL_DIG + 100];
4547 : : const char *endptr;
4548 : :
4549 [ + + ]: 654 : if (isnan(val))
4550 : 5 : PG_RETURN_NUMERIC(make_result(&const_nan));
4551 : :
4552 [ + + ]: 649 : if (isinf(val))
4553 : : {
4554 [ + + ]: 10 : if (val < 0)
4555 : 5 : PG_RETURN_NUMERIC(make_result(&const_ninf));
4556 : : else
4557 : 5 : PG_RETURN_NUMERIC(make_result(&const_pinf));
4558 : : }
4559 : :
4560 : 639 : snprintf(buf, sizeof(buf), "%.*g", DBL_DIG, val);
4561 : :
4562 : 639 : init_var(&result);
4563 : :
4564 : : /* Assume we need not worry about leading/trailing spaces */
4565 [ - + ]: 639 : if (!set_var_from_str(buf, buf, &result, &endptr, fcinfo->context))
4566 : 0 : PG_RETURN_NULL();
4567 : :
4568 : 639 : res = make_result(&result);
4569 : :
4570 : 639 : free_var(&result);
4571 : :
4572 : 639 : PG_RETURN_NUMERIC(res);
4573 : : }
4574 : :
4575 : :
4576 : : Datum
4577 : 347603 : numeric_float8(PG_FUNCTION_ARGS)
4578 : : {
4579 : 347603 : Numeric num = PG_GETARG_NUMERIC(0);
4580 : : char *tmp;
4581 : : Datum result;
4582 : :
4583 [ + + ]: 347603 : if (NUMERIC_IS_SPECIAL(num))
4584 : : {
4585 [ + + ]: 56 : if (NUMERIC_IS_PINF(num))
4586 : 17 : PG_RETURN_FLOAT8(get_float8_infinity());
4587 [ + + ]: 39 : else if (NUMERIC_IS_NINF(num))
4588 : 17 : PG_RETURN_FLOAT8(-get_float8_infinity());
4589 : : else
4590 : 22 : PG_RETURN_FLOAT8(get_float8_nan());
4591 : : }
4592 : :
4593 : 347547 : tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
4594 : : NumericGetDatum(num)));
4595 [ - + ]: 347547 : if (!DirectInputFunctionCallSafe(float8in, tmp,
4596 : : InvalidOid, -1,
4597 : : (Node *) fcinfo->context,
4598 : : &result))
4599 : : {
4600 : 0 : pfree(tmp);
4601 : 0 : PG_RETURN_NULL();
4602 : : }
4603 : :
4604 : 347547 : PG_RETURN_DATUM(result);
4605 : : }
4606 : :
4607 : :
4608 : : /*
4609 : : * Convert numeric to float8; if out of range, return +/- HUGE_VAL
4610 : : *
4611 : : * (internal helper function, not directly callable from SQL)
4612 : : */
4613 : : Datum
4614 : 18 : numeric_float8_no_overflow(PG_FUNCTION_ARGS)
4615 : : {
4616 : 18 : Numeric num = PG_GETARG_NUMERIC(0);
4617 : : double val;
4618 : :
4619 [ - + ]: 18 : if (NUMERIC_IS_SPECIAL(num))
4620 : : {
4621 [ # # ]: 0 : if (NUMERIC_IS_PINF(num))
4622 : 0 : val = HUGE_VAL;
4623 [ # # ]: 0 : else if (NUMERIC_IS_NINF(num))
4624 : 0 : val = -HUGE_VAL;
4625 : : else
4626 : 0 : val = get_float8_nan();
4627 : : }
4628 : : else
4629 : : {
4630 : : NumericVar x;
4631 : :
4632 : 18 : init_var_from_num(num, &x);
4633 : 18 : val = numericvar_to_double_no_overflow(&x);
4634 : : }
4635 : :
4636 : 18 : PG_RETURN_FLOAT8(val);
4637 : : }
4638 : :
4639 : : Datum
4640 : 15091 : float4_numeric(PG_FUNCTION_ARGS)
4641 : : {
4642 : 15091 : float4 val = PG_GETARG_FLOAT4(0);
4643 : : Numeric res;
4644 : : NumericVar result;
4645 : : char buf[FLT_DIG + 100];
4646 : : const char *endptr;
4647 : :
4648 [ + + ]: 15091 : if (isnan(val))
4649 : 5 : PG_RETURN_NUMERIC(make_result(&const_nan));
4650 : :
4651 [ + + ]: 15086 : if (isinf(val))
4652 : : {
4653 [ + + ]: 10 : if (val < 0)
4654 : 5 : PG_RETURN_NUMERIC(make_result(&const_ninf));
4655 : : else
4656 : 5 : PG_RETURN_NUMERIC(make_result(&const_pinf));
4657 : : }
4658 : :
4659 : 15076 : snprintf(buf, sizeof(buf), "%.*g", FLT_DIG, val);
4660 : :
4661 : 15076 : init_var(&result);
4662 : :
4663 : : /* Assume we need not worry about leading/trailing spaces */
4664 [ - + ]: 15076 : if (!set_var_from_str(buf, buf, &result, &endptr, fcinfo->context))
4665 : 0 : PG_RETURN_NULL();
4666 : :
4667 : 15076 : res = make_result(&result);
4668 : :
4669 : 15076 : free_var(&result);
4670 : :
4671 : 15076 : PG_RETURN_NUMERIC(res);
4672 : : }
4673 : :
4674 : :
4675 : : Datum
4676 : 1748 : numeric_float4(PG_FUNCTION_ARGS)
4677 : : {
4678 : 1748 : Numeric num = PG_GETARG_NUMERIC(0);
4679 : : char *tmp;
4680 : : Datum result;
4681 : :
4682 [ + + ]: 1748 : if (NUMERIC_IS_SPECIAL(num))
4683 : : {
4684 [ + + ]: 56 : if (NUMERIC_IS_PINF(num))
4685 : 17 : PG_RETURN_FLOAT4(get_float4_infinity());
4686 [ + + ]: 39 : else if (NUMERIC_IS_NINF(num))
4687 : 17 : PG_RETURN_FLOAT4(-get_float4_infinity());
4688 : : else
4689 : 22 : PG_RETURN_FLOAT4(get_float4_nan());
4690 : : }
4691 : :
4692 : 1692 : tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
4693 : : NumericGetDatum(num)));
4694 : :
4695 [ - + ]: 1692 : if (!DirectInputFunctionCallSafe(float4in, tmp,
4696 : : InvalidOid, -1,
4697 : : (Node *) fcinfo->context,
4698 : : &result))
4699 : : {
4700 : 0 : pfree(tmp);
4701 : 0 : PG_RETURN_NULL();
4702 : : }
4703 : :
4704 : 1692 : pfree(tmp);
4705 : :
4706 : 1692 : PG_RETURN_DATUM(result);
4707 : : }
4708 : :
4709 : :
4710 : : Datum
4711 : 105 : numeric_pg_lsn(PG_FUNCTION_ARGS)
4712 : : {
4713 : 105 : Numeric num = PG_GETARG_NUMERIC(0);
4714 : : NumericVar x;
4715 : : XLogRecPtr result;
4716 : :
4717 [ + + ]: 105 : if (NUMERIC_IS_SPECIAL(num))
4718 : : {
4719 [ + - ]: 4 : if (NUMERIC_IS_NAN(num))
4720 [ + - ]: 4 : ereport(ERROR,
4721 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4722 : : errmsg("cannot convert NaN to %s", "pg_lsn")));
4723 : : else
4724 [ # # ]: 0 : ereport(ERROR,
4725 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4726 : : errmsg("cannot convert infinity to %s", "pg_lsn")));
4727 : : }
4728 : :
4729 : : /* Convert to variable format and thence to pg_lsn */
4730 : 101 : init_var_from_num(num, &x);
4731 : :
4732 [ + + ]: 101 : if (!numericvar_to_uint64(&x, (uint64 *) &result))
4733 [ + - ]: 16 : ereport(ERROR,
4734 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4735 : : errmsg("pg_lsn out of range")));
4736 : :
4737 : 85 : PG_RETURN_LSN(result);
4738 : : }
4739 : :
4740 : :
4741 : : /* ----------------------------------------------------------------------
4742 : : *
4743 : : * Aggregate functions
4744 : : *
4745 : : * The transition datatype for all these aggregates is declared as INTERNAL.
4746 : : * Actually, it's a pointer to a NumericAggState allocated in the aggregate
4747 : : * context. The digit buffers for the NumericVars will be there too.
4748 : : *
4749 : : * For integer inputs, some aggregates use special-purpose 64-bit or 128-bit
4750 : : * integer based transition datatypes to speed up calculations.
4751 : : *
4752 : : * ----------------------------------------------------------------------
4753 : : */
4754 : :
4755 : : typedef struct NumericAggState
4756 : : {
4757 : : bool calcSumX2; /* if true, calculate sumX2 */
4758 : : MemoryContext agg_context; /* context we're calculating in */
4759 : : int64 N; /* count of processed numbers */
4760 : : NumericSumAccum sumX; /* sum of processed numbers */
4761 : : NumericSumAccum sumX2; /* sum of squares of processed numbers */
4762 : : int maxScale; /* maximum scale seen so far */
4763 : : int64 maxScaleCount; /* number of values seen with maximum scale */
4764 : : /* These counts are *not* included in N! Use NA_TOTAL_COUNT() as needed */
4765 : : int64 NaNcount; /* count of NaN values */
4766 : : int64 pInfcount; /* count of +Inf values */
4767 : : int64 nInfcount; /* count of -Inf values */
4768 : : } NumericAggState;
4769 : :
4770 : : #define NA_TOTAL_COUNT(na) \
4771 : : ((na)->N + (na)->NaNcount + (na)->pInfcount + (na)->nInfcount)
4772 : :
4773 : : /*
4774 : : * Prepare state data for a numeric aggregate function that needs to compute
4775 : : * sum, count and optionally sum of squares of the input.
4776 : : */
4777 : : static NumericAggState *
4778 : 114080 : makeNumericAggState(FunctionCallInfo fcinfo, bool calcSumX2)
4779 : : {
4780 : : NumericAggState *state;
4781 : : MemoryContext agg_context;
4782 : : MemoryContext old_context;
4783 : :
4784 [ - + ]: 114080 : if (!AggCheckCallContext(fcinfo, &agg_context))
4785 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
4786 : :
4787 : 114080 : old_context = MemoryContextSwitchTo(agg_context);
4788 : :
4789 : 114080 : state = palloc0_object(NumericAggState);
4790 : 114080 : state->calcSumX2 = calcSumX2;
4791 : 114080 : state->agg_context = agg_context;
4792 : :
4793 : 114080 : MemoryContextSwitchTo(old_context);
4794 : :
4795 : 114080 : return state;
4796 : : }
4797 : :
4798 : : /*
4799 : : * Like makeNumericAggState(), but allocate the state in the current memory
4800 : : * context.
4801 : : */
4802 : : static NumericAggState *
4803 : 54 : makeNumericAggStateCurrentContext(bool calcSumX2)
4804 : : {
4805 : : NumericAggState *state;
4806 : :
4807 : 54 : state = palloc0_object(NumericAggState);
4808 : 54 : state->calcSumX2 = calcSumX2;
4809 : 54 : state->agg_context = CurrentMemoryContext;
4810 : :
4811 : 54 : return state;
4812 : : }
4813 : :
4814 : : /*
4815 : : * Accumulate a new input value for numeric aggregate functions.
4816 : : */
4817 : : static void
4818 : 1409012 : do_numeric_accum(NumericAggState *state, Numeric newval)
4819 : : {
4820 : : NumericVar X;
4821 : : NumericVar X2;
4822 : : MemoryContext old_context;
4823 : :
4824 : : /* Count NaN/infinity inputs separately from all else */
4825 [ + + ]: 1409012 : if (NUMERIC_IS_SPECIAL(newval))
4826 : : {
4827 [ + + ]: 108 : if (NUMERIC_IS_PINF(newval))
4828 : 48 : state->pInfcount++;
4829 [ + + ]: 60 : else if (NUMERIC_IS_NINF(newval))
4830 : 24 : state->nInfcount++;
4831 : : else
4832 : 36 : state->NaNcount++;
4833 : 108 : return;
4834 : : }
4835 : :
4836 : : /* load processed number in short-lived context */
4837 : 1408904 : init_var_from_num(newval, &X);
4838 : :
4839 : : /*
4840 : : * Track the highest input dscale that we've seen, to support inverse
4841 : : * transitions (see do_numeric_discard).
4842 : : */
4843 [ + + ]: 1408904 : if (X.dscale > state->maxScale)
4844 : : {
4845 : 104 : state->maxScale = X.dscale;
4846 : 104 : state->maxScaleCount = 1;
4847 : : }
4848 [ + + ]: 1408800 : else if (X.dscale == state->maxScale)
4849 : 1408776 : state->maxScaleCount++;
4850 : :
4851 : : /* if we need X^2, calculate that in short-lived context */
4852 [ + + ]: 1408904 : if (state->calcSumX2)
4853 : : {
4854 : 160488 : init_var(&X2);
4855 : 160488 : mul_var(&X, &X, &X2, X.dscale * 2);
4856 : : }
4857 : :
4858 : : /* The rest of this needs to work in the aggregate context */
4859 : 1408904 : old_context = MemoryContextSwitchTo(state->agg_context);
4860 : :
4861 : 1408904 : state->N++;
4862 : :
4863 : : /* Accumulate sums */
4864 : 1408904 : accum_sum_add(&(state->sumX), &X);
4865 : :
4866 [ + + ]: 1408904 : if (state->calcSumX2)
4867 : 160488 : accum_sum_add(&(state->sumX2), &X2);
4868 : :
4869 : 1408904 : MemoryContextSwitchTo(old_context);
4870 : : }
4871 : :
4872 : : /*
4873 : : * Attempt to remove an input value from the aggregated state.
4874 : : *
4875 : : * If the value cannot be removed then the function will return false; the
4876 : : * possible reasons for failing are described below.
4877 : : *
4878 : : * If we aggregate the values 1.01 and 2 then the result will be 3.01.
4879 : : * If we are then asked to un-aggregate the 1.01 then we must fail as we
4880 : : * won't be able to tell what the new aggregated value's dscale should be.
4881 : : * We don't want to return 2.00 (dscale = 2), since the sum's dscale would
4882 : : * have been zero if we'd really aggregated only 2.
4883 : : *
4884 : : * Note: alternatively, we could count the number of inputs with each possible
4885 : : * dscale (up to some sane limit). Not yet clear if it's worth the trouble.
4886 : : */
4887 : : static bool
4888 : 228 : do_numeric_discard(NumericAggState *state, Numeric newval)
4889 : : {
4890 : : NumericVar X;
4891 : : NumericVar X2;
4892 : : MemoryContext old_context;
4893 : :
4894 : : /* Count NaN/infinity inputs separately from all else */
4895 [ + + ]: 228 : if (NUMERIC_IS_SPECIAL(newval))
4896 : : {
4897 [ - + ]: 4 : if (NUMERIC_IS_PINF(newval))
4898 : 0 : state->pInfcount--;
4899 [ - + ]: 4 : else if (NUMERIC_IS_NINF(newval))
4900 : 0 : state->nInfcount--;
4901 : : else
4902 : 4 : state->NaNcount--;
4903 : 4 : return true;
4904 : : }
4905 : :
4906 : : /* load processed number in short-lived context */
4907 : 224 : init_var_from_num(newval, &X);
4908 : :
4909 : : /*
4910 : : * state->sumX's dscale is the maximum dscale of any of the inputs.
4911 : : * Removing the last input with that dscale would require us to recompute
4912 : : * the maximum dscale of the *remaining* inputs, which we cannot do unless
4913 : : * no more non-NaN inputs remain at all. So we report a failure instead,
4914 : : * and force the aggregation to be redone from scratch.
4915 : : */
4916 [ + - ]: 224 : if (X.dscale == state->maxScale)
4917 : : {
4918 [ + + + + ]: 224 : if (state->maxScaleCount > 1 || state->maxScale == 0)
4919 : : {
4920 : : /*
4921 : : * Some remaining inputs have same dscale, or dscale hasn't gotten
4922 : : * above zero anyway
4923 : : */
4924 : 212 : state->maxScaleCount--;
4925 : : }
4926 [ + + ]: 12 : else if (state->N == 1)
4927 : : {
4928 : : /* No remaining non-NaN inputs at all, so reset maxScale */
4929 : 8 : state->maxScale = 0;
4930 : 8 : state->maxScaleCount = 0;
4931 : : }
4932 : : else
4933 : : {
4934 : : /* Correct new maxScale is uncertain, must fail */
4935 : 4 : return false;
4936 : : }
4937 : : }
4938 : :
4939 : : /* if we need X^2, calculate that in short-lived context */
4940 [ + + ]: 220 : if (state->calcSumX2)
4941 : : {
4942 : 192 : init_var(&X2);
4943 : 192 : mul_var(&X, &X, &X2, X.dscale * 2);
4944 : : }
4945 : :
4946 : : /* The rest of this needs to work in the aggregate context */
4947 : 220 : old_context = MemoryContextSwitchTo(state->agg_context);
4948 : :
4949 [ + + ]: 220 : if (state->N-- > 1)
4950 : : {
4951 : : /* Negate X, to subtract it from the sum */
4952 [ + - ]: 208 : X.sign = (X.sign == NUMERIC_POS ? NUMERIC_NEG : NUMERIC_POS);
4953 : 208 : accum_sum_add(&(state->sumX), &X);
4954 : :
4955 [ + + ]: 208 : if (state->calcSumX2)
4956 : : {
4957 : : /* Negate X^2. X^2 is always positive */
4958 : 192 : X2.sign = NUMERIC_NEG;
4959 : 192 : accum_sum_add(&(state->sumX2), &X2);
4960 : : }
4961 : : }
4962 : : else
4963 : : {
4964 : : /* Zero the sums */
4965 : : Assert(state->N == 0);
4966 : :
4967 : 12 : accum_sum_reset(&state->sumX);
4968 [ - + ]: 12 : if (state->calcSumX2)
4969 : 0 : accum_sum_reset(&state->sumX2);
4970 : : }
4971 : :
4972 : 220 : MemoryContextSwitchTo(old_context);
4973 : :
4974 : 220 : return true;
4975 : : }
4976 : :
4977 : : /*
4978 : : * Generic transition function for numeric aggregates that require sumX2.
4979 : : */
4980 : : Datum
4981 : 428 : numeric_accum(PG_FUNCTION_ARGS)
4982 : : {
4983 : : NumericAggState *state;
4984 : :
4985 [ + + ]: 428 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
4986 : :
4987 : : /* Create the state data on the first call */
4988 [ + + ]: 428 : if (state == NULL)
4989 : 116 : state = makeNumericAggState(fcinfo, true);
4990 : :
4991 [ + + ]: 428 : if (!PG_ARGISNULL(1))
4992 : 416 : do_numeric_accum(state, PG_GETARG_NUMERIC(1));
4993 : :
4994 : 428 : PG_RETURN_POINTER(state);
4995 : : }
4996 : :
4997 : : /*
4998 : : * Generic combine function for numeric aggregates which require sumX2
4999 : : */
5000 : : Datum
5001 : 23 : numeric_combine(PG_FUNCTION_ARGS)
5002 : : {
5003 : : NumericAggState *state1;
5004 : : NumericAggState *state2;
5005 : : MemoryContext agg_context;
5006 : : MemoryContext old_context;
5007 : :
5008 [ - + ]: 23 : if (!AggCheckCallContext(fcinfo, &agg_context))
5009 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5010 : :
5011 [ + + ]: 23 : state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5012 [ + - ]: 23 : state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
5013 : :
5014 [ - + ]: 23 : if (state2 == NULL)
5015 : : {
5016 : : /*
5017 : : * NULL state2 is easy, just return state1, which we know is already
5018 : : * in the agg_context
5019 : : */
5020 [ # # ]: 0 : if (state1 == NULL)
5021 : 0 : PG_RETURN_NULL();
5022 : 0 : PG_RETURN_POINTER(state1);
5023 : : }
5024 : :
5025 : : /* manually copy all fields from state2 to state1 */
5026 [ + + ]: 23 : if (state1 == NULL)
5027 : : {
5028 : 12 : old_context = MemoryContextSwitchTo(agg_context);
5029 : :
5030 : 12 : state1 = makeNumericAggStateCurrentContext(true);
5031 : 12 : state1->N = state2->N;
5032 : 12 : state1->NaNcount = state2->NaNcount;
5033 : 12 : state1->pInfcount = state2->pInfcount;
5034 : 12 : state1->nInfcount = state2->nInfcount;
5035 : 12 : state1->maxScale = state2->maxScale;
5036 : 12 : state1->maxScaleCount = state2->maxScaleCount;
5037 : :
5038 : 12 : accum_sum_copy(&state1->sumX, &state2->sumX);
5039 : 12 : accum_sum_copy(&state1->sumX2, &state2->sumX2);
5040 : :
5041 : 12 : MemoryContextSwitchTo(old_context);
5042 : :
5043 : 12 : PG_RETURN_POINTER(state1);
5044 : : }
5045 : :
5046 : 11 : state1->N += state2->N;
5047 : 11 : state1->NaNcount += state2->NaNcount;
5048 : 11 : state1->pInfcount += state2->pInfcount;
5049 : 11 : state1->nInfcount += state2->nInfcount;
5050 : :
5051 [ + - ]: 11 : if (state2->N > 0)
5052 : : {
5053 : : /*
5054 : : * These are currently only needed for moving aggregates, but let's do
5055 : : * the right thing anyway...
5056 : : */
5057 [ - + ]: 11 : if (state2->maxScale > state1->maxScale)
5058 : : {
5059 : 0 : state1->maxScale = state2->maxScale;
5060 : 0 : state1->maxScaleCount = state2->maxScaleCount;
5061 : : }
5062 [ + - ]: 11 : else if (state2->maxScale == state1->maxScale)
5063 : 11 : state1->maxScaleCount += state2->maxScaleCount;
5064 : :
5065 : : /* The rest of this needs to work in the aggregate context */
5066 : 11 : old_context = MemoryContextSwitchTo(agg_context);
5067 : :
5068 : : /* Accumulate sums */
5069 : 11 : accum_sum_combine(&state1->sumX, &state2->sumX);
5070 : 11 : accum_sum_combine(&state1->sumX2, &state2->sumX2);
5071 : :
5072 : 11 : MemoryContextSwitchTo(old_context);
5073 : : }
5074 : 11 : PG_RETURN_POINTER(state1);
5075 : : }
5076 : :
5077 : : /*
5078 : : * Generic transition function for numeric aggregates that don't require sumX2.
5079 : : */
5080 : : Datum
5081 : 1248516 : numeric_avg_accum(PG_FUNCTION_ARGS)
5082 : : {
5083 : : NumericAggState *state;
5084 : :
5085 [ + + ]: 1248516 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5086 : :
5087 : : /* Create the state data on the first call */
5088 [ + + ]: 1248516 : if (state == NULL)
5089 : 113925 : state = makeNumericAggState(fcinfo, false);
5090 : :
5091 [ + + ]: 1248516 : if (!PG_ARGISNULL(1))
5092 : 1248476 : do_numeric_accum(state, PG_GETARG_NUMERIC(1));
5093 : :
5094 : 1248516 : PG_RETURN_POINTER(state);
5095 : : }
5096 : :
5097 : : /*
5098 : : * Combine function for numeric aggregates which don't require sumX2
5099 : : */
5100 : : Datum
5101 : 15 : numeric_avg_combine(PG_FUNCTION_ARGS)
5102 : : {
5103 : : NumericAggState *state1;
5104 : : NumericAggState *state2;
5105 : : MemoryContext agg_context;
5106 : : MemoryContext old_context;
5107 : :
5108 [ - + ]: 15 : if (!AggCheckCallContext(fcinfo, &agg_context))
5109 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5110 : :
5111 [ + + ]: 15 : state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5112 [ + - ]: 15 : state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
5113 : :
5114 [ - + ]: 15 : if (state2 == NULL)
5115 : : {
5116 : : /*
5117 : : * NULL state2 is easy, just return state1, which we know is already
5118 : : * in the agg_context
5119 : : */
5120 [ # # ]: 0 : if (state1 == NULL)
5121 : 0 : PG_RETURN_NULL();
5122 : 0 : PG_RETURN_POINTER(state1);
5123 : : }
5124 : :
5125 : : /* manually copy all fields from state2 to state1 */
5126 [ + + ]: 15 : if (state1 == NULL)
5127 : : {
5128 : 4 : old_context = MemoryContextSwitchTo(agg_context);
5129 : :
5130 : 4 : state1 = makeNumericAggStateCurrentContext(false);
5131 : 4 : state1->N = state2->N;
5132 : 4 : state1->NaNcount = state2->NaNcount;
5133 : 4 : state1->pInfcount = state2->pInfcount;
5134 : 4 : state1->nInfcount = state2->nInfcount;
5135 : 4 : state1->maxScale = state2->maxScale;
5136 : 4 : state1->maxScaleCount = state2->maxScaleCount;
5137 : :
5138 : 4 : accum_sum_copy(&state1->sumX, &state2->sumX);
5139 : :
5140 : 4 : MemoryContextSwitchTo(old_context);
5141 : :
5142 : 4 : PG_RETURN_POINTER(state1);
5143 : : }
5144 : :
5145 : 11 : state1->N += state2->N;
5146 : 11 : state1->NaNcount += state2->NaNcount;
5147 : 11 : state1->pInfcount += state2->pInfcount;
5148 : 11 : state1->nInfcount += state2->nInfcount;
5149 : :
5150 [ + - ]: 11 : if (state2->N > 0)
5151 : : {
5152 : : /*
5153 : : * These are currently only needed for moving aggregates, but let's do
5154 : : * the right thing anyway...
5155 : : */
5156 [ - + ]: 11 : if (state2->maxScale > state1->maxScale)
5157 : : {
5158 : 0 : state1->maxScale = state2->maxScale;
5159 : 0 : state1->maxScaleCount = state2->maxScaleCount;
5160 : : }
5161 [ + - ]: 11 : else if (state2->maxScale == state1->maxScale)
5162 : 11 : state1->maxScaleCount += state2->maxScaleCount;
5163 : :
5164 : : /* The rest of this needs to work in the aggregate context */
5165 : 11 : old_context = MemoryContextSwitchTo(agg_context);
5166 : :
5167 : : /* Accumulate sums */
5168 : 11 : accum_sum_combine(&state1->sumX, &state2->sumX);
5169 : :
5170 : 11 : MemoryContextSwitchTo(old_context);
5171 : : }
5172 : 11 : PG_RETURN_POINTER(state1);
5173 : : }
5174 : :
5175 : : /*
5176 : : * numeric_avg_serialize
5177 : : * Serialize NumericAggState for numeric aggregates that don't require
5178 : : * sumX2.
5179 : : */
5180 : : Datum
5181 : 15 : numeric_avg_serialize(PG_FUNCTION_ARGS)
5182 : : {
5183 : : NumericAggState *state;
5184 : : StringInfoData buf;
5185 : : bytea *result;
5186 : : NumericVar tmp_var;
5187 : :
5188 : : /* Ensure we disallow calling when not in aggregate context */
5189 [ - + ]: 15 : if (!AggCheckCallContext(fcinfo, NULL))
5190 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5191 : :
5192 : 15 : state = (NumericAggState *) PG_GETARG_POINTER(0);
5193 : :
5194 : 15 : init_var(&tmp_var);
5195 : :
5196 : 15 : pq_begintypsend(&buf);
5197 : :
5198 : : /* N */
5199 : 15 : pq_sendint64(&buf, state->N);
5200 : :
5201 : : /* sumX */
5202 : 15 : accum_sum_final(&state->sumX, &tmp_var);
5203 : 15 : numericvar_serialize(&buf, &tmp_var);
5204 : :
5205 : : /* maxScale */
5206 : 15 : pq_sendint32(&buf, state->maxScale);
5207 : :
5208 : : /* maxScaleCount */
5209 : 15 : pq_sendint64(&buf, state->maxScaleCount);
5210 : :
5211 : : /* NaNcount */
5212 : 15 : pq_sendint64(&buf, state->NaNcount);
5213 : :
5214 : : /* pInfcount */
5215 : 15 : pq_sendint64(&buf, state->pInfcount);
5216 : :
5217 : : /* nInfcount */
5218 : 15 : pq_sendint64(&buf, state->nInfcount);
5219 : :
5220 : 15 : result = pq_endtypsend(&buf);
5221 : :
5222 : 15 : free_var(&tmp_var);
5223 : :
5224 : 15 : PG_RETURN_BYTEA_P(result);
5225 : : }
5226 : :
5227 : : /*
5228 : : * numeric_avg_deserialize
5229 : : * Deserialize bytea into NumericAggState for numeric aggregates that
5230 : : * don't require sumX2.
5231 : : */
5232 : : Datum
5233 : 15 : numeric_avg_deserialize(PG_FUNCTION_ARGS)
5234 : : {
5235 : : bytea *sstate;
5236 : : NumericAggState *result;
5237 : : StringInfoData buf;
5238 : : NumericVar tmp_var;
5239 : :
5240 [ - + ]: 15 : if (!AggCheckCallContext(fcinfo, NULL))
5241 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5242 : :
5243 : 15 : sstate = PG_GETARG_BYTEA_PP(0);
5244 : :
5245 : 15 : init_var(&tmp_var);
5246 : :
5247 : : /*
5248 : : * Initialize a StringInfo so that we can "receive" it using the standard
5249 : : * recv-function infrastructure.
5250 : : */
5251 : 15 : initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
5252 : 15 : VARSIZE_ANY_EXHDR(sstate));
5253 : :
5254 : 15 : result = makeNumericAggStateCurrentContext(false);
5255 : :
5256 : : /* N */
5257 : 15 : result->N = pq_getmsgint64(&buf);
5258 : :
5259 : : /* sumX */
5260 : 15 : numericvar_deserialize(&buf, &tmp_var);
5261 : 15 : accum_sum_add(&(result->sumX), &tmp_var);
5262 : :
5263 : : /* maxScale */
5264 : 15 : result->maxScale = pq_getmsgint(&buf, 4);
5265 : :
5266 : : /* maxScaleCount */
5267 : 15 : result->maxScaleCount = pq_getmsgint64(&buf);
5268 : :
5269 : : /* NaNcount */
5270 : 15 : result->NaNcount = pq_getmsgint64(&buf);
5271 : :
5272 : : /* pInfcount */
5273 : 15 : result->pInfcount = pq_getmsgint64(&buf);
5274 : :
5275 : : /* nInfcount */
5276 : 15 : result->nInfcount = pq_getmsgint64(&buf);
5277 : :
5278 : 15 : pq_getmsgend(&buf);
5279 : :
5280 : 15 : free_var(&tmp_var);
5281 : :
5282 : 15 : PG_RETURN_POINTER(result);
5283 : : }
5284 : :
5285 : : /*
5286 : : * numeric_serialize
5287 : : * Serialization function for NumericAggState for numeric aggregates that
5288 : : * require sumX2.
5289 : : */
5290 : : Datum
5291 : 23 : numeric_serialize(PG_FUNCTION_ARGS)
5292 : : {
5293 : : NumericAggState *state;
5294 : : StringInfoData buf;
5295 : : bytea *result;
5296 : : NumericVar tmp_var;
5297 : :
5298 : : /* Ensure we disallow calling when not in aggregate context */
5299 [ - + ]: 23 : if (!AggCheckCallContext(fcinfo, NULL))
5300 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5301 : :
5302 : 23 : state = (NumericAggState *) PG_GETARG_POINTER(0);
5303 : :
5304 : 23 : init_var(&tmp_var);
5305 : :
5306 : 23 : pq_begintypsend(&buf);
5307 : :
5308 : : /* N */
5309 : 23 : pq_sendint64(&buf, state->N);
5310 : :
5311 : : /* sumX */
5312 : 23 : accum_sum_final(&state->sumX, &tmp_var);
5313 : 23 : numericvar_serialize(&buf, &tmp_var);
5314 : :
5315 : : /* sumX2 */
5316 : 23 : accum_sum_final(&state->sumX2, &tmp_var);
5317 : 23 : numericvar_serialize(&buf, &tmp_var);
5318 : :
5319 : : /* maxScale */
5320 : 23 : pq_sendint32(&buf, state->maxScale);
5321 : :
5322 : : /* maxScaleCount */
5323 : 23 : pq_sendint64(&buf, state->maxScaleCount);
5324 : :
5325 : : /* NaNcount */
5326 : 23 : pq_sendint64(&buf, state->NaNcount);
5327 : :
5328 : : /* pInfcount */
5329 : 23 : pq_sendint64(&buf, state->pInfcount);
5330 : :
5331 : : /* nInfcount */
5332 : 23 : pq_sendint64(&buf, state->nInfcount);
5333 : :
5334 : 23 : result = pq_endtypsend(&buf);
5335 : :
5336 : 23 : free_var(&tmp_var);
5337 : :
5338 : 23 : PG_RETURN_BYTEA_P(result);
5339 : : }
5340 : :
5341 : : /*
5342 : : * numeric_deserialize
5343 : : * Deserialization function for NumericAggState for numeric aggregates that
5344 : : * require sumX2.
5345 : : */
5346 : : Datum
5347 : 23 : numeric_deserialize(PG_FUNCTION_ARGS)
5348 : : {
5349 : : bytea *sstate;
5350 : : NumericAggState *result;
5351 : : StringInfoData buf;
5352 : : NumericVar tmp_var;
5353 : :
5354 [ - + ]: 23 : if (!AggCheckCallContext(fcinfo, NULL))
5355 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5356 : :
5357 : 23 : sstate = PG_GETARG_BYTEA_PP(0);
5358 : :
5359 : 23 : init_var(&tmp_var);
5360 : :
5361 : : /*
5362 : : * Initialize a StringInfo so that we can "receive" it using the standard
5363 : : * recv-function infrastructure.
5364 : : */
5365 : 23 : initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
5366 : 23 : VARSIZE_ANY_EXHDR(sstate));
5367 : :
5368 : 23 : result = makeNumericAggStateCurrentContext(true);
5369 : :
5370 : : /* N */
5371 : 23 : result->N = pq_getmsgint64(&buf);
5372 : :
5373 : : /* sumX */
5374 : 23 : numericvar_deserialize(&buf, &tmp_var);
5375 : 23 : accum_sum_add(&(result->sumX), &tmp_var);
5376 : :
5377 : : /* sumX2 */
5378 : 23 : numericvar_deserialize(&buf, &tmp_var);
5379 : 23 : accum_sum_add(&(result->sumX2), &tmp_var);
5380 : :
5381 : : /* maxScale */
5382 : 23 : result->maxScale = pq_getmsgint(&buf, 4);
5383 : :
5384 : : /* maxScaleCount */
5385 : 23 : result->maxScaleCount = pq_getmsgint64(&buf);
5386 : :
5387 : : /* NaNcount */
5388 : 23 : result->NaNcount = pq_getmsgint64(&buf);
5389 : :
5390 : : /* pInfcount */
5391 : 23 : result->pInfcount = pq_getmsgint64(&buf);
5392 : :
5393 : : /* nInfcount */
5394 : 23 : result->nInfcount = pq_getmsgint64(&buf);
5395 : :
5396 : 23 : pq_getmsgend(&buf);
5397 : :
5398 : 23 : free_var(&tmp_var);
5399 : :
5400 : 23 : PG_RETURN_POINTER(result);
5401 : : }
5402 : :
5403 : : /*
5404 : : * Generic inverse transition function for numeric aggregates
5405 : : * (with or without requirement for X^2).
5406 : : */
5407 : : Datum
5408 : 152 : numeric_accum_inv(PG_FUNCTION_ARGS)
5409 : : {
5410 : : NumericAggState *state;
5411 : :
5412 [ + - ]: 152 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5413 : :
5414 : : /* Should not get here with no state */
5415 [ - + ]: 152 : if (state == NULL)
5416 [ # # ]: 0 : elog(ERROR, "numeric_accum_inv called with NULL state");
5417 : :
5418 [ + + ]: 152 : if (!PG_ARGISNULL(1))
5419 : : {
5420 : : /* If we fail to perform the inverse transition, return NULL */
5421 [ + + ]: 132 : if (!do_numeric_discard(state, PG_GETARG_NUMERIC(1)))
5422 : 4 : PG_RETURN_NULL();
5423 : : }
5424 : :
5425 : 148 : PG_RETURN_POINTER(state);
5426 : : }
5427 : :
5428 : :
5429 : : /*
5430 : : * Integer data types in general use Numeric accumulators to share code and
5431 : : * avoid risk of overflow. However for performance reasons optimized
5432 : : * special-purpose accumulator routines are used when possible:
5433 : : *
5434 : : * For 16-bit and 32-bit inputs, N and sum(X) fit into 64-bit, so 64-bit
5435 : : * accumulators are used for SUM and AVG of these data types.
5436 : : *
5437 : : * For 16-bit and 32-bit inputs, sum(X^2) fits into 128-bit, so 128-bit
5438 : : * accumulators are used for STDDEV_POP, STDDEV_SAMP, VAR_POP, and VAR_SAMP of
5439 : : * these data types.
5440 : : *
5441 : : * For 64-bit inputs, sum(X) fits into 128-bit, so a 128-bit accumulator is
5442 : : * used for SUM(int8) and AVG(int8).
5443 : : */
5444 : :
5445 : : typedef struct Int128AggState
5446 : : {
5447 : : bool calcSumX2; /* if true, calculate sumX2 */
5448 : : int64 N; /* count of processed numbers */
5449 : : INT128 sumX; /* sum of processed numbers */
5450 : : INT128 sumX2; /* sum of squares of processed numbers */
5451 : : } Int128AggState;
5452 : :
5453 : : /*
5454 : : * Prepare state data for a 128-bit aggregate function that needs to compute
5455 : : * sum, count and optionally sum of squares of the input.
5456 : : */
5457 : : static Int128AggState *
5458 : 622 : makeInt128AggState(FunctionCallInfo fcinfo, bool calcSumX2)
5459 : : {
5460 : : Int128AggState *state;
5461 : : MemoryContext agg_context;
5462 : : MemoryContext old_context;
5463 : :
5464 [ - + ]: 622 : if (!AggCheckCallContext(fcinfo, &agg_context))
5465 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5466 : :
5467 : 622 : old_context = MemoryContextSwitchTo(agg_context);
5468 : :
5469 : 622 : state = palloc0_object(Int128AggState);
5470 : 622 : state->calcSumX2 = calcSumX2;
5471 : :
5472 : 622 : MemoryContextSwitchTo(old_context);
5473 : :
5474 : 622 : return state;
5475 : : }
5476 : :
5477 : : /*
5478 : : * Like makeInt128AggState(), but allocate the state in the current memory
5479 : : * context.
5480 : : */
5481 : : static Int128AggState *
5482 : 36 : makeInt128AggStateCurrentContext(bool calcSumX2)
5483 : : {
5484 : : Int128AggState *state;
5485 : :
5486 : 36 : state = palloc0_object(Int128AggState);
5487 : 36 : state->calcSumX2 = calcSumX2;
5488 : :
5489 : 36 : return state;
5490 : : }
5491 : :
5492 : : /*
5493 : : * Accumulate a new input value for 128-bit aggregate functions.
5494 : : */
5495 : : static void
5496 : 370866 : do_int128_accum(Int128AggState *state, int64 newval)
5497 : : {
5498 [ + + ]: 370866 : if (state->calcSumX2)
5499 : 161240 : int128_add_int64_mul_int64(&state->sumX2, newval, newval);
5500 : :
5501 : 370866 : int128_add_int64(&state->sumX, newval);
5502 : 370866 : state->N++;
5503 : 370866 : }
5504 : :
5505 : : /*
5506 : : * Remove an input value from the aggregated state.
5507 : : */
5508 : : static void
5509 : 208 : do_int128_discard(Int128AggState *state, int64 newval)
5510 : : {
5511 [ + + ]: 208 : if (state->calcSumX2)
5512 : 192 : int128_sub_int64_mul_int64(&state->sumX2, newval, newval);
5513 : :
5514 : 208 : int128_sub_int64(&state->sumX, newval);
5515 : 208 : state->N--;
5516 : 208 : }
5517 : :
5518 : : Datum
5519 : 132 : int2_accum(PG_FUNCTION_ARGS)
5520 : : {
5521 : : Int128AggState *state;
5522 : :
5523 [ + + ]: 132 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5524 : :
5525 : : /* Create the state data on the first call */
5526 [ + + ]: 132 : if (state == NULL)
5527 : 24 : state = makeInt128AggState(fcinfo, true);
5528 : :
5529 [ + + ]: 132 : if (!PG_ARGISNULL(1))
5530 : 120 : do_int128_accum(state, PG_GETARG_INT16(1));
5531 : :
5532 : 132 : PG_RETURN_POINTER(state);
5533 : : }
5534 : :
5535 : : Datum
5536 : 161132 : int4_accum(PG_FUNCTION_ARGS)
5537 : : {
5538 : : Int128AggState *state;
5539 : :
5540 [ + + ]: 161132 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5541 : :
5542 : : /* Create the state data on the first call */
5543 [ + + ]: 161132 : if (state == NULL)
5544 : 50 : state = makeInt128AggState(fcinfo, true);
5545 : :
5546 [ + + ]: 161132 : if (!PG_ARGISNULL(1))
5547 : 161120 : do_int128_accum(state, PG_GETARG_INT32(1));
5548 : :
5549 : 161132 : PG_RETURN_POINTER(state);
5550 : : }
5551 : :
5552 : : Datum
5553 : 160132 : int8_accum(PG_FUNCTION_ARGS)
5554 : : {
5555 : : NumericAggState *state;
5556 : :
5557 [ + + ]: 160132 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5558 : :
5559 : : /* Create the state data on the first call */
5560 [ + + ]: 160132 : if (state == NULL)
5561 : 39 : state = makeNumericAggState(fcinfo, true);
5562 : :
5563 [ + + ]: 160132 : if (!PG_ARGISNULL(1))
5564 : 160120 : do_numeric_accum(state, int64_to_numeric(PG_GETARG_INT64(1)));
5565 : :
5566 : 160132 : PG_RETURN_POINTER(state);
5567 : : }
5568 : :
5569 : : /*
5570 : : * Combine function for Int128AggState for aggregates which require sumX2
5571 : : */
5572 : : Datum
5573 : 16 : numeric_poly_combine(PG_FUNCTION_ARGS)
5574 : : {
5575 : : Int128AggState *state1;
5576 : : Int128AggState *state2;
5577 : : MemoryContext agg_context;
5578 : : MemoryContext old_context;
5579 : :
5580 [ - + ]: 16 : if (!AggCheckCallContext(fcinfo, &agg_context))
5581 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5582 : :
5583 [ + + ]: 16 : state1 = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5584 [ + - ]: 16 : state2 = PG_ARGISNULL(1) ? NULL : (Int128AggState *) PG_GETARG_POINTER(1);
5585 : :
5586 [ - + ]: 16 : if (state2 == NULL)
5587 : : {
5588 : : /*
5589 : : * NULL state2 is easy, just return state1, which we know is already
5590 : : * in the agg_context
5591 : : */
5592 [ # # ]: 0 : if (state1 == NULL)
5593 : 0 : PG_RETURN_NULL();
5594 : 0 : PG_RETURN_POINTER(state1);
5595 : : }
5596 : :
5597 : : /* manually copy all fields from state2 to state1 */
5598 [ + + ]: 16 : if (state1 == NULL)
5599 : : {
5600 : 4 : old_context = MemoryContextSwitchTo(agg_context);
5601 : :
5602 : 4 : state1 = makeInt128AggState(fcinfo, true);
5603 : 4 : state1->N = state2->N;
5604 : 4 : state1->sumX = state2->sumX;
5605 : 4 : state1->sumX2 = state2->sumX2;
5606 : :
5607 : 4 : MemoryContextSwitchTo(old_context);
5608 : :
5609 : 4 : PG_RETURN_POINTER(state1);
5610 : : }
5611 : :
5612 [ + - ]: 12 : if (state2->N > 0)
5613 : : {
5614 : 12 : state1->N += state2->N;
5615 : 12 : int128_add_int128(&state1->sumX, state2->sumX);
5616 : 12 : int128_add_int128(&state1->sumX2, state2->sumX2);
5617 : : }
5618 : 12 : PG_RETURN_POINTER(state1);
5619 : : }
5620 : :
5621 : : /*
5622 : : * int128_serialize - serialize a 128-bit integer to binary format
5623 : : */
5624 : : static inline void
5625 : 52 : int128_serialize(StringInfo buf, INT128 val)
5626 : : {
5627 : 52 : pq_sendint64(buf, PG_INT128_HI_INT64(val));
5628 : 52 : pq_sendint64(buf, PG_INT128_LO_UINT64(val));
5629 : 52 : }
5630 : :
5631 : : /*
5632 : : * int128_deserialize - deserialize binary format to a 128-bit integer.
5633 : : */
5634 : : static inline INT128
5635 : 52 : int128_deserialize(StringInfo buf)
5636 : : {
5637 : 52 : int64 hi = pq_getmsgint64(buf);
5638 : 52 : uint64 lo = pq_getmsgint64(buf);
5639 : :
5640 : 52 : return make_int128(hi, lo);
5641 : : }
5642 : :
5643 : : /*
5644 : : * numeric_poly_serialize
5645 : : * Serialize Int128AggState into bytea for aggregate functions which
5646 : : * require sumX2.
5647 : : */
5648 : : Datum
5649 : 16 : numeric_poly_serialize(PG_FUNCTION_ARGS)
5650 : : {
5651 : : Int128AggState *state;
5652 : : StringInfoData buf;
5653 : : bytea *result;
5654 : :
5655 : : /* Ensure we disallow calling when not in aggregate context */
5656 [ - + ]: 16 : if (!AggCheckCallContext(fcinfo, NULL))
5657 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5658 : :
5659 : 16 : state = (Int128AggState *) PG_GETARG_POINTER(0);
5660 : :
5661 : 16 : pq_begintypsend(&buf);
5662 : :
5663 : : /* N */
5664 : 16 : pq_sendint64(&buf, state->N);
5665 : :
5666 : : /* sumX */
5667 : 16 : int128_serialize(&buf, state->sumX);
5668 : :
5669 : : /* sumX2 */
5670 : 16 : int128_serialize(&buf, state->sumX2);
5671 : :
5672 : 16 : result = pq_endtypsend(&buf);
5673 : :
5674 : 16 : PG_RETURN_BYTEA_P(result);
5675 : : }
5676 : :
5677 : : /*
5678 : : * numeric_poly_deserialize
5679 : : * Deserialize Int128AggState from bytea for aggregate functions which
5680 : : * require sumX2.
5681 : : */
5682 : : Datum
5683 : 16 : numeric_poly_deserialize(PG_FUNCTION_ARGS)
5684 : : {
5685 : : bytea *sstate;
5686 : : Int128AggState *result;
5687 : : StringInfoData buf;
5688 : :
5689 [ - + ]: 16 : if (!AggCheckCallContext(fcinfo, NULL))
5690 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5691 : :
5692 : 16 : sstate = PG_GETARG_BYTEA_PP(0);
5693 : :
5694 : : /*
5695 : : * Initialize a StringInfo so that we can "receive" it using the standard
5696 : : * recv-function infrastructure.
5697 : : */
5698 : 16 : initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
5699 : 16 : VARSIZE_ANY_EXHDR(sstate));
5700 : :
5701 : 16 : result = makeInt128AggStateCurrentContext(true);
5702 : :
5703 : : /* N */
5704 : 16 : result->N = pq_getmsgint64(&buf);
5705 : :
5706 : : /* sumX */
5707 : 16 : result->sumX = int128_deserialize(&buf);
5708 : :
5709 : : /* sumX2 */
5710 : 16 : result->sumX2 = int128_deserialize(&buf);
5711 : :
5712 : 16 : pq_getmsgend(&buf);
5713 : :
5714 : 16 : PG_RETURN_POINTER(result);
5715 : : }
5716 : :
5717 : : /*
5718 : : * Transition function for int8 input when we don't need sumX2.
5719 : : */
5720 : : Datum
5721 : 212405 : int8_avg_accum(PG_FUNCTION_ARGS)
5722 : : {
5723 : : Int128AggState *state;
5724 : :
5725 [ + + ]: 212405 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5726 : :
5727 : : /* Create the state data on the first call */
5728 [ + + ]: 212405 : if (state == NULL)
5729 : 536 : state = makeInt128AggState(fcinfo, false);
5730 : :
5731 [ + + ]: 212405 : if (!PG_ARGISNULL(1))
5732 : 209626 : do_int128_accum(state, PG_GETARG_INT64(1));
5733 : :
5734 : 212405 : PG_RETURN_POINTER(state);
5735 : : }
5736 : :
5737 : : /*
5738 : : * Combine function for Int128AggState for aggregates which don't require
5739 : : * sumX2
5740 : : */
5741 : : Datum
5742 : 20 : int8_avg_combine(PG_FUNCTION_ARGS)
5743 : : {
5744 : : Int128AggState *state1;
5745 : : Int128AggState *state2;
5746 : : MemoryContext agg_context;
5747 : : MemoryContext old_context;
5748 : :
5749 [ - + ]: 20 : if (!AggCheckCallContext(fcinfo, &agg_context))
5750 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5751 : :
5752 [ + + ]: 20 : state1 = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5753 [ + - ]: 20 : state2 = PG_ARGISNULL(1) ? NULL : (Int128AggState *) PG_GETARG_POINTER(1);
5754 : :
5755 [ - + ]: 20 : if (state2 == NULL)
5756 : : {
5757 : : /*
5758 : : * NULL state2 is easy, just return state1, which we know is already
5759 : : * in the agg_context
5760 : : */
5761 [ # # ]: 0 : if (state1 == NULL)
5762 : 0 : PG_RETURN_NULL();
5763 : 0 : PG_RETURN_POINTER(state1);
5764 : : }
5765 : :
5766 : : /* manually copy all fields from state2 to state1 */
5767 [ + + ]: 20 : if (state1 == NULL)
5768 : : {
5769 : 8 : old_context = MemoryContextSwitchTo(agg_context);
5770 : :
5771 : 8 : state1 = makeInt128AggState(fcinfo, false);
5772 : 8 : state1->N = state2->N;
5773 : 8 : state1->sumX = state2->sumX;
5774 : :
5775 : 8 : MemoryContextSwitchTo(old_context);
5776 : :
5777 : 8 : PG_RETURN_POINTER(state1);
5778 : : }
5779 : :
5780 [ + - ]: 12 : if (state2->N > 0)
5781 : : {
5782 : 12 : state1->N += state2->N;
5783 : 12 : int128_add_int128(&state1->sumX, state2->sumX);
5784 : : }
5785 : 12 : PG_RETURN_POINTER(state1);
5786 : : }
5787 : :
5788 : : /*
5789 : : * int8_avg_serialize
5790 : : * Serialize Int128AggState into bytea for aggregate functions which
5791 : : * don't require sumX2.
5792 : : */
5793 : : Datum
5794 : 20 : int8_avg_serialize(PG_FUNCTION_ARGS)
5795 : : {
5796 : : Int128AggState *state;
5797 : : StringInfoData buf;
5798 : : bytea *result;
5799 : :
5800 : : /* Ensure we disallow calling when not in aggregate context */
5801 [ - + ]: 20 : if (!AggCheckCallContext(fcinfo, NULL))
5802 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5803 : :
5804 : 20 : state = (Int128AggState *) PG_GETARG_POINTER(0);
5805 : :
5806 : 20 : pq_begintypsend(&buf);
5807 : :
5808 : : /* N */
5809 : 20 : pq_sendint64(&buf, state->N);
5810 : :
5811 : : /* sumX */
5812 : 20 : int128_serialize(&buf, state->sumX);
5813 : :
5814 : 20 : result = pq_endtypsend(&buf);
5815 : :
5816 : 20 : PG_RETURN_BYTEA_P(result);
5817 : : }
5818 : :
5819 : : /*
5820 : : * int8_avg_deserialize
5821 : : * Deserialize Int128AggState from bytea for aggregate functions which
5822 : : * don't require sumX2.
5823 : : */
5824 : : Datum
5825 : 20 : int8_avg_deserialize(PG_FUNCTION_ARGS)
5826 : : {
5827 : : bytea *sstate;
5828 : : Int128AggState *result;
5829 : : StringInfoData buf;
5830 : :
5831 [ - + ]: 20 : if (!AggCheckCallContext(fcinfo, NULL))
5832 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5833 : :
5834 : 20 : sstate = PG_GETARG_BYTEA_PP(0);
5835 : :
5836 : : /*
5837 : : * Initialize a StringInfo so that we can "receive" it using the standard
5838 : : * recv-function infrastructure.
5839 : : */
5840 : 20 : initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
5841 : 20 : VARSIZE_ANY_EXHDR(sstate));
5842 : :
5843 : 20 : result = makeInt128AggStateCurrentContext(false);
5844 : :
5845 : : /* N */
5846 : 20 : result->N = pq_getmsgint64(&buf);
5847 : :
5848 : : /* sumX */
5849 : 20 : result->sumX = int128_deserialize(&buf);
5850 : :
5851 : 20 : pq_getmsgend(&buf);
5852 : :
5853 : 20 : PG_RETURN_POINTER(result);
5854 : : }
5855 : :
5856 : : /*
5857 : : * Inverse transition functions to go with the above.
5858 : : */
5859 : :
5860 : : Datum
5861 : 108 : int2_accum_inv(PG_FUNCTION_ARGS)
5862 : : {
5863 : : Int128AggState *state;
5864 : :
5865 [ + - ]: 108 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5866 : :
5867 : : /* Should not get here with no state */
5868 [ - + ]: 108 : if (state == NULL)
5869 [ # # ]: 0 : elog(ERROR, "int2_accum_inv called with NULL state");
5870 : :
5871 [ + + ]: 108 : if (!PG_ARGISNULL(1))
5872 : 96 : do_int128_discard(state, PG_GETARG_INT16(1));
5873 : :
5874 : 108 : PG_RETURN_POINTER(state);
5875 : : }
5876 : :
5877 : : Datum
5878 : 108 : int4_accum_inv(PG_FUNCTION_ARGS)
5879 : : {
5880 : : Int128AggState *state;
5881 : :
5882 [ + - ]: 108 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5883 : :
5884 : : /* Should not get here with no state */
5885 [ - + ]: 108 : if (state == NULL)
5886 [ # # ]: 0 : elog(ERROR, "int4_accum_inv called with NULL state");
5887 : :
5888 [ + + ]: 108 : if (!PG_ARGISNULL(1))
5889 : 96 : do_int128_discard(state, PG_GETARG_INT32(1));
5890 : :
5891 : 108 : PG_RETURN_POINTER(state);
5892 : : }
5893 : :
5894 : : Datum
5895 : 108 : int8_accum_inv(PG_FUNCTION_ARGS)
5896 : : {
5897 : : NumericAggState *state;
5898 : :
5899 [ + - ]: 108 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5900 : :
5901 : : /* Should not get here with no state */
5902 [ - + ]: 108 : if (state == NULL)
5903 [ # # ]: 0 : elog(ERROR, "int8_accum_inv called with NULL state");
5904 : :
5905 [ + + ]: 108 : if (!PG_ARGISNULL(1))
5906 : : {
5907 : : /* Should never fail, all inputs have dscale 0 */
5908 [ - + ]: 96 : if (!do_numeric_discard(state, int64_to_numeric(PG_GETARG_INT64(1))))
5909 [ # # ]: 0 : elog(ERROR, "do_numeric_discard failed unexpectedly");
5910 : : }
5911 : :
5912 : 108 : PG_RETURN_POINTER(state);
5913 : : }
5914 : :
5915 : : Datum
5916 : 24 : int8_avg_accum_inv(PG_FUNCTION_ARGS)
5917 : : {
5918 : : Int128AggState *state;
5919 : :
5920 [ + - ]: 24 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5921 : :
5922 : : /* Should not get here with no state */
5923 [ - + ]: 24 : if (state == NULL)
5924 [ # # ]: 0 : elog(ERROR, "int8_avg_accum_inv called with NULL state");
5925 : :
5926 [ + + ]: 24 : if (!PG_ARGISNULL(1))
5927 : 16 : do_int128_discard(state, PG_GETARG_INT64(1));
5928 : :
5929 : 24 : PG_RETURN_POINTER(state);
5930 : : }
5931 : :
5932 : : Datum
5933 : 680 : numeric_poly_sum(PG_FUNCTION_ARGS)
5934 : : {
5935 : : Int128AggState *state;
5936 : : Numeric res;
5937 : : NumericVar result;
5938 : :
5939 [ + + ]: 680 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5940 : :
5941 : : /* If there were no non-null inputs, return NULL */
5942 [ + + + + ]: 680 : if (state == NULL || state->N == 0)
5943 : 16 : PG_RETURN_NULL();
5944 : :
5945 : 664 : init_var(&result);
5946 : :
5947 : 664 : int128_to_numericvar(state->sumX, &result);
5948 : :
5949 : 664 : res = make_result(&result);
5950 : :
5951 : 664 : free_var(&result);
5952 : :
5953 : 664 : PG_RETURN_NUMERIC(res);
5954 : : }
5955 : :
5956 : : Datum
5957 : 24 : numeric_poly_avg(PG_FUNCTION_ARGS)
5958 : : {
5959 : : Int128AggState *state;
5960 : : NumericVar result;
5961 : : Datum countd,
5962 : : sumd;
5963 : :
5964 [ + - ]: 24 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5965 : :
5966 : : /* If there were no non-null inputs, return NULL */
5967 [ + - + + ]: 24 : if (state == NULL || state->N == 0)
5968 : 12 : PG_RETURN_NULL();
5969 : :
5970 : 12 : init_var(&result);
5971 : :
5972 : 12 : int128_to_numericvar(state->sumX, &result);
5973 : :
5974 : 12 : countd = NumericGetDatum(int64_to_numeric(state->N));
5975 : 12 : sumd = NumericGetDatum(make_result(&result));
5976 : :
5977 : 12 : free_var(&result);
5978 : :
5979 : 12 : PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumd, countd));
5980 : : }
5981 : :
5982 : : Datum
5983 : 52 : numeric_avg(PG_FUNCTION_ARGS)
5984 : : {
5985 : : NumericAggState *state;
5986 : : Datum N_datum;
5987 : : Datum sumX_datum;
5988 : : NumericVar sumX_var;
5989 : :
5990 [ + - ]: 52 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5991 : :
5992 : : /* If there were no non-null inputs, return NULL */
5993 [ + - + + ]: 52 : if (state == NULL || NA_TOTAL_COUNT(state) == 0)
5994 : 12 : PG_RETURN_NULL();
5995 : :
5996 [ + + ]: 40 : if (state->NaNcount > 0) /* there was at least one NaN input */
5997 : 4 : PG_RETURN_NUMERIC(make_result(&const_nan));
5998 : :
5999 : : /* adding plus and minus infinities gives NaN */
6000 [ + + + + ]: 36 : if (state->pInfcount > 0 && state->nInfcount > 0)
6001 : 4 : PG_RETURN_NUMERIC(make_result(&const_nan));
6002 [ + + ]: 32 : if (state->pInfcount > 0)
6003 : 12 : PG_RETURN_NUMERIC(make_result(&const_pinf));
6004 [ + + ]: 20 : if (state->nInfcount > 0)
6005 : 4 : PG_RETURN_NUMERIC(make_result(&const_ninf));
6006 : :
6007 : 16 : N_datum = NumericGetDatum(int64_to_numeric(state->N));
6008 : :
6009 : 16 : init_var(&sumX_var);
6010 : 16 : accum_sum_final(&state->sumX, &sumX_var);
6011 : 16 : sumX_datum = NumericGetDatum(make_result(&sumX_var));
6012 : 16 : free_var(&sumX_var);
6013 : :
6014 : 16 : PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumX_datum, N_datum));
6015 : : }
6016 : :
6017 : : Datum
6018 : 113926 : numeric_sum(PG_FUNCTION_ARGS)
6019 : : {
6020 : : NumericAggState *state;
6021 : : NumericVar sumX_var;
6022 : : Numeric result;
6023 : :
6024 [ + - ]: 113926 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6025 : :
6026 : : /* If there were no non-null inputs, return NULL */
6027 [ + - + + ]: 113926 : if (state == NULL || NA_TOTAL_COUNT(state) == 0)
6028 : 12 : PG_RETURN_NULL();
6029 : :
6030 [ + + ]: 113914 : if (state->NaNcount > 0) /* there was at least one NaN input */
6031 : 12 : PG_RETURN_NUMERIC(make_result(&const_nan));
6032 : :
6033 : : /* adding plus and minus infinities gives NaN */
6034 [ + + + + ]: 113902 : if (state->pInfcount > 0 && state->nInfcount > 0)
6035 : 4 : PG_RETURN_NUMERIC(make_result(&const_nan));
6036 [ + + ]: 113898 : if (state->pInfcount > 0)
6037 : 12 : PG_RETURN_NUMERIC(make_result(&const_pinf));
6038 [ + + ]: 113886 : if (state->nInfcount > 0)
6039 : 4 : PG_RETURN_NUMERIC(make_result(&const_ninf));
6040 : :
6041 : 113882 : init_var(&sumX_var);
6042 : 113882 : accum_sum_final(&state->sumX, &sumX_var);
6043 : 113882 : result = make_result(&sumX_var);
6044 : 113882 : free_var(&sumX_var);
6045 : :
6046 : 113882 : PG_RETURN_NUMERIC(result);
6047 : : }
6048 : :
6049 : : /*
6050 : : * Workhorse routine for the standard deviance and variance
6051 : : * aggregates. 'state' is aggregate's transition state.
6052 : : * 'variance' specifies whether we should calculate the
6053 : : * variance or the standard deviation. 'sample' indicates whether the
6054 : : * caller is interested in the sample or the population
6055 : : * variance/stddev.
6056 : : *
6057 : : * If appropriate variance statistic is undefined for the input,
6058 : : * *is_null is set to true and NULL is returned.
6059 : : */
6060 : : static Numeric
6061 : 654 : numeric_stddev_internal(NumericAggState *state,
6062 : : bool variance, bool sample,
6063 : : bool *is_null)
6064 : : {
6065 : : Numeric res;
6066 : : NumericVar vN,
6067 : : vsumX,
6068 : : vsumX2,
6069 : : vNminus1;
6070 : : int64 totCount;
6071 : : int rscale;
6072 : :
6073 : : /*
6074 : : * Sample stddev and variance are undefined when N <= 1; population stddev
6075 : : * is undefined when N == 0. Return NULL in either case (note that NaNs
6076 : : * and infinities count as normal inputs for this purpose).
6077 : : */
6078 [ + - - + ]: 654 : if (state == NULL || (totCount = NA_TOTAL_COUNT(state)) == 0)
6079 : : {
6080 : 0 : *is_null = true;
6081 : 0 : return NULL;
6082 : : }
6083 : :
6084 [ + + + + ]: 654 : if (sample && totCount <= 1)
6085 : : {
6086 : 88 : *is_null = true;
6087 : 88 : return NULL;
6088 : : }
6089 : :
6090 : 566 : *is_null = false;
6091 : :
6092 : : /*
6093 : : * Deal with NaN and infinity cases. By analogy to the behavior of the
6094 : : * float8 functions, any infinity input produces NaN output.
6095 : : */
6096 [ + + + + : 566 : if (state->NaNcount > 0 || state->pInfcount > 0 || state->nInfcount > 0)
+ + ]
6097 : 36 : return make_result(&const_nan);
6098 : :
6099 : : /* OK, normal calculation applies */
6100 : 530 : init_var(&vN);
6101 : 530 : init_var(&vsumX);
6102 : 530 : init_var(&vsumX2);
6103 : :
6104 : 530 : int64_to_numericvar(state->N, &vN);
6105 : 530 : accum_sum_final(&(state->sumX), &vsumX);
6106 : 530 : accum_sum_final(&(state->sumX2), &vsumX2);
6107 : :
6108 : 530 : init_var(&vNminus1);
6109 : 530 : sub_var(&vN, &const_one, &vNminus1);
6110 : :
6111 : : /* compute rscale for mul_var calls */
6112 : 530 : rscale = vsumX.dscale * 2;
6113 : :
6114 : 530 : mul_var(&vsumX, &vsumX, &vsumX, rscale); /* vsumX = sumX * sumX */
6115 : 530 : mul_var(&vN, &vsumX2, &vsumX2, rscale); /* vsumX2 = N * sumX2 */
6116 : 530 : sub_var(&vsumX2, &vsumX, &vsumX2); /* N * sumX2 - sumX * sumX */
6117 : :
6118 [ + + ]: 530 : if (cmp_var(&vsumX2, &const_zero) <= 0)
6119 : : {
6120 : : /* Watch out for roundoff error producing a negative numerator */
6121 : 50 : res = make_result(&const_zero);
6122 : : }
6123 : : else
6124 : : {
6125 [ + + ]: 480 : if (sample)
6126 : 328 : mul_var(&vN, &vNminus1, &vNminus1, 0); /* N * (N - 1) */
6127 : : else
6128 : 152 : mul_var(&vN, &vN, &vNminus1, 0); /* N * N */
6129 : 480 : rscale = select_div_scale(&vsumX2, &vNminus1);
6130 : 480 : div_var(&vsumX2, &vNminus1, &vsumX, rscale, true, true); /* variance */
6131 [ + + ]: 480 : if (!variance)
6132 : 252 : sqrt_var(&vsumX, &vsumX, rscale); /* stddev */
6133 : :
6134 : 480 : res = make_result(&vsumX);
6135 : : }
6136 : :
6137 : 530 : free_var(&vNminus1);
6138 : 530 : free_var(&vsumX);
6139 : 530 : free_var(&vsumX2);
6140 : :
6141 : 530 : return res;
6142 : : }
6143 : :
6144 : : Datum
6145 : 120 : numeric_var_samp(PG_FUNCTION_ARGS)
6146 : : {
6147 : : NumericAggState *state;
6148 : : Numeric res;
6149 : : bool is_null;
6150 : :
6151 [ + - ]: 120 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6152 : :
6153 : 120 : res = numeric_stddev_internal(state, true, true, &is_null);
6154 : :
6155 [ + + ]: 120 : if (is_null)
6156 : 28 : PG_RETURN_NULL();
6157 : : else
6158 : 92 : PG_RETURN_NUMERIC(res);
6159 : : }
6160 : :
6161 : : Datum
6162 : 116 : numeric_stddev_samp(PG_FUNCTION_ARGS)
6163 : : {
6164 : : NumericAggState *state;
6165 : : Numeric res;
6166 : : bool is_null;
6167 : :
6168 [ + - ]: 116 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6169 : :
6170 : 116 : res = numeric_stddev_internal(state, false, true, &is_null);
6171 : :
6172 [ + + ]: 116 : if (is_null)
6173 : 28 : PG_RETURN_NULL();
6174 : : else
6175 : 88 : PG_RETURN_NUMERIC(res);
6176 : : }
6177 : :
6178 : : Datum
6179 : 76 : numeric_var_pop(PG_FUNCTION_ARGS)
6180 : : {
6181 : : NumericAggState *state;
6182 : : Numeric res;
6183 : : bool is_null;
6184 : :
6185 [ + - ]: 76 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6186 : :
6187 : 76 : res = numeric_stddev_internal(state, true, false, &is_null);
6188 : :
6189 [ - + ]: 76 : if (is_null)
6190 : 0 : PG_RETURN_NULL();
6191 : : else
6192 : 76 : PG_RETURN_NUMERIC(res);
6193 : : }
6194 : :
6195 : : Datum
6196 : 64 : numeric_stddev_pop(PG_FUNCTION_ARGS)
6197 : : {
6198 : : NumericAggState *state;
6199 : : Numeric res;
6200 : : bool is_null;
6201 : :
6202 [ + - ]: 64 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6203 : :
6204 : 64 : res = numeric_stddev_internal(state, false, false, &is_null);
6205 : :
6206 [ - + ]: 64 : if (is_null)
6207 : 0 : PG_RETURN_NULL();
6208 : : else
6209 : 64 : PG_RETURN_NUMERIC(res);
6210 : : }
6211 : :
6212 : : static Numeric
6213 : 278 : numeric_poly_stddev_internal(Int128AggState *state,
6214 : : bool variance, bool sample,
6215 : : bool *is_null)
6216 : : {
6217 : : NumericAggState numstate;
6218 : : Numeric res;
6219 : :
6220 : : /* Initialize an empty agg state */
6221 : 278 : memset(&numstate, 0, sizeof(NumericAggState));
6222 : :
6223 [ + - ]: 278 : if (state)
6224 : : {
6225 : : NumericVar tmp_var;
6226 : :
6227 : 278 : numstate.N = state->N;
6228 : :
6229 : 278 : init_var(&tmp_var);
6230 : :
6231 : 278 : int128_to_numericvar(state->sumX, &tmp_var);
6232 : 278 : accum_sum_add(&numstate.sumX, &tmp_var);
6233 : :
6234 : 278 : int128_to_numericvar(state->sumX2, &tmp_var);
6235 : 278 : accum_sum_add(&numstate.sumX2, &tmp_var);
6236 : :
6237 : 278 : free_var(&tmp_var);
6238 : : }
6239 : :
6240 : 278 : res = numeric_stddev_internal(&numstate, variance, sample, is_null);
6241 : :
6242 [ + - ]: 278 : if (numstate.sumX.ndigits > 0)
6243 : : {
6244 : 278 : pfree(numstate.sumX.pos_digits);
6245 : 278 : pfree(numstate.sumX.neg_digits);
6246 : : }
6247 [ + - ]: 278 : if (numstate.sumX2.ndigits > 0)
6248 : : {
6249 : 278 : pfree(numstate.sumX2.pos_digits);
6250 : 278 : pfree(numstate.sumX2.neg_digits);
6251 : : }
6252 : :
6253 : 278 : return res;
6254 : : }
6255 : :
6256 : : Datum
6257 : 84 : numeric_poly_var_samp(PG_FUNCTION_ARGS)
6258 : : {
6259 : : Int128AggState *state;
6260 : : Numeric res;
6261 : : bool is_null;
6262 : :
6263 [ + - ]: 84 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
6264 : :
6265 : 84 : res = numeric_poly_stddev_internal(state, true, true, &is_null);
6266 : :
6267 [ + + ]: 84 : if (is_null)
6268 : 16 : PG_RETURN_NULL();
6269 : : else
6270 : 68 : PG_RETURN_NUMERIC(res);
6271 : : }
6272 : :
6273 : : Datum
6274 : 106 : numeric_poly_stddev_samp(PG_FUNCTION_ARGS)
6275 : : {
6276 : : Int128AggState *state;
6277 : : Numeric res;
6278 : : bool is_null;
6279 : :
6280 [ + - ]: 106 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
6281 : :
6282 : 106 : res = numeric_poly_stddev_internal(state, false, true, &is_null);
6283 : :
6284 [ + + ]: 106 : if (is_null)
6285 : 16 : PG_RETURN_NULL();
6286 : : else
6287 : 90 : PG_RETURN_NUMERIC(res);
6288 : : }
6289 : :
6290 : : Datum
6291 : 40 : numeric_poly_var_pop(PG_FUNCTION_ARGS)
6292 : : {
6293 : : Int128AggState *state;
6294 : : Numeric res;
6295 : : bool is_null;
6296 : :
6297 [ + - ]: 40 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
6298 : :
6299 : 40 : res = numeric_poly_stddev_internal(state, true, false, &is_null);
6300 : :
6301 [ - + ]: 40 : if (is_null)
6302 : 0 : PG_RETURN_NULL();
6303 : : else
6304 : 40 : PG_RETURN_NUMERIC(res);
6305 : : }
6306 : :
6307 : : Datum
6308 : 48 : numeric_poly_stddev_pop(PG_FUNCTION_ARGS)
6309 : : {
6310 : : Int128AggState *state;
6311 : : Numeric res;
6312 : : bool is_null;
6313 : :
6314 [ + - ]: 48 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
6315 : :
6316 : 48 : res = numeric_poly_stddev_internal(state, false, false, &is_null);
6317 : :
6318 [ - + ]: 48 : if (is_null)
6319 : 0 : PG_RETURN_NULL();
6320 : : else
6321 : 48 : PG_RETURN_NUMERIC(res);
6322 : : }
6323 : :
6324 : : /*
6325 : : * SUM transition functions for integer datatypes.
6326 : : *
6327 : : * To avoid overflow, we use accumulators wider than the input datatype.
6328 : : * A Numeric accumulator is needed for int8 input; for int4 and int2
6329 : : * inputs, we use int8 accumulators which should be sufficient for practical
6330 : : * purposes. (The latter two therefore don't really belong in this file,
6331 : : * but we keep them here anyway.)
6332 : : *
6333 : : * Because SQL defines the SUM() of no values to be NULL, not zero,
6334 : : * the initial condition of the transition data value needs to be NULL. This
6335 : : * means we can't rely on ExecAgg to automatically insert the first non-null
6336 : : * data value into the transition data: it doesn't know how to do the type
6337 : : * conversion. The upshot is that these routines have to be marked non-strict
6338 : : * and handle substitution of the first non-null input themselves.
6339 : : *
6340 : : * Note: these functions are used only in plain aggregation mode.
6341 : : * In moving-aggregate mode, we use intX_avg_accum and intX_avg_accum_inv.
6342 : : */
6343 : :
6344 : : Datum
6345 : 16 : int2_sum(PG_FUNCTION_ARGS)
6346 : : {
6347 : : int64 oldsum;
6348 : : int64 newval;
6349 : :
6350 [ + + ]: 16 : if (PG_ARGISNULL(0))
6351 : : {
6352 : : /* No non-null input seen so far... */
6353 [ - + ]: 4 : if (PG_ARGISNULL(1))
6354 : 0 : PG_RETURN_NULL(); /* still no non-null */
6355 : : /* This is the first non-null input. */
6356 : 4 : newval = (int64) PG_GETARG_INT16(1);
6357 : 4 : PG_RETURN_INT64(newval);
6358 : : }
6359 : :
6360 : 12 : oldsum = PG_GETARG_INT64(0);
6361 : :
6362 : : /* Leave sum unchanged if new input is null. */
6363 [ - + ]: 12 : if (PG_ARGISNULL(1))
6364 : 0 : PG_RETURN_INT64(oldsum);
6365 : :
6366 : : /* OK to do the addition. */
6367 : 12 : newval = oldsum + (int64) PG_GETARG_INT16(1);
6368 : :
6369 : 12 : PG_RETURN_INT64(newval);
6370 : : }
6371 : :
6372 : : Datum
6373 : 3412700 : int4_sum(PG_FUNCTION_ARGS)
6374 : : {
6375 : : int64 oldsum;
6376 : : int64 newval;
6377 : :
6378 [ + + ]: 3412700 : if (PG_ARGISNULL(0))
6379 : : {
6380 : : /* No non-null input seen so far... */
6381 [ + + ]: 129305 : if (PG_ARGISNULL(1))
6382 : 654 : PG_RETURN_NULL(); /* still no non-null */
6383 : : /* This is the first non-null input. */
6384 : 128651 : newval = (int64) PG_GETARG_INT32(1);
6385 : 128651 : PG_RETURN_INT64(newval);
6386 : : }
6387 : :
6388 : 3283395 : oldsum = PG_GETARG_INT64(0);
6389 : :
6390 : : /* Leave sum unchanged if new input is null. */
6391 [ + + ]: 3283395 : if (PG_ARGISNULL(1))
6392 : 20606 : PG_RETURN_INT64(oldsum);
6393 : :
6394 : : /* OK to do the addition. */
6395 : 3262789 : newval = oldsum + (int64) PG_GETARG_INT32(1);
6396 : :
6397 : 3262789 : PG_RETURN_INT64(newval);
6398 : : }
6399 : :
6400 : : /*
6401 : : * Note: this function is obsolete, it's no longer used for SUM(int8).
6402 : : */
6403 : : Datum
6404 : 0 : int8_sum(PG_FUNCTION_ARGS)
6405 : : {
6406 : : Numeric oldsum;
6407 : :
6408 [ # # ]: 0 : if (PG_ARGISNULL(0))
6409 : : {
6410 : : /* No non-null input seen so far... */
6411 [ # # ]: 0 : if (PG_ARGISNULL(1))
6412 : 0 : PG_RETURN_NULL(); /* still no non-null */
6413 : : /* This is the first non-null input. */
6414 : 0 : PG_RETURN_NUMERIC(int64_to_numeric(PG_GETARG_INT64(1)));
6415 : : }
6416 : :
6417 : : /*
6418 : : * Note that we cannot special-case the aggregate case here, as we do for
6419 : : * int2_sum and int4_sum: numeric is of variable size, so we cannot modify
6420 : : * our first parameter in-place.
6421 : : */
6422 : :
6423 : 0 : oldsum = PG_GETARG_NUMERIC(0);
6424 : :
6425 : : /* Leave sum unchanged if new input is null. */
6426 [ # # ]: 0 : if (PG_ARGISNULL(1))
6427 : 0 : PG_RETURN_NUMERIC(oldsum);
6428 : :
6429 : : /* OK to do the addition. */
6430 : 0 : PG_RETURN_DATUM(DirectFunctionCall2(numeric_add,
6431 : : NumericGetDatum(oldsum),
6432 : : NumericGetDatum(int64_to_numeric(PG_GETARG_INT64(1)))));
6433 : : }
6434 : :
6435 : :
6436 : : /*
6437 : : * Routines for avg(int2) and avg(int4). The transition datatype
6438 : : * is a two-element int8 array, holding count and sum.
6439 : : *
6440 : : * These functions are also used for sum(int2) and sum(int4) when
6441 : : * operating in moving-aggregate mode, since for correct inverse transitions
6442 : : * we need to count the inputs.
6443 : : */
6444 : :
6445 : : typedef struct Int8TransTypeData
6446 : : {
6447 : : int64 count;
6448 : : int64 sum;
6449 : : } Int8TransTypeData;
6450 : :
6451 : : Datum
6452 : 28 : int2_avg_accum(PG_FUNCTION_ARGS)
6453 : : {
6454 : : ArrayType *transarray;
6455 : 28 : int16 newval = PG_GETARG_INT16(1);
6456 : : Int8TransTypeData *transdata;
6457 : :
6458 : : /*
6459 : : * If we're invoked as an aggregate, we can cheat and modify our first
6460 : : * parameter in-place to reduce palloc overhead. Otherwise we need to make
6461 : : * a copy of it before scribbling on it.
6462 : : */
6463 [ + - ]: 28 : if (AggCheckCallContext(fcinfo, NULL))
6464 : 28 : transarray = PG_GETARG_ARRAYTYPE_P(0);
6465 : : else
6466 : 0 : transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6467 : :
6468 [ + - - + ]: 56 : if (ARR_HASNULL(transarray) ||
6469 : 28 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6470 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6471 : :
6472 [ - + ]: 28 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6473 : 28 : transdata->count++;
6474 : 28 : transdata->sum += newval;
6475 : :
6476 : 28 : PG_RETURN_ARRAYTYPE_P(transarray);
6477 : : }
6478 : :
6479 : : Datum
6480 : 1744070 : int4_avg_accum(PG_FUNCTION_ARGS)
6481 : : {
6482 : : ArrayType *transarray;
6483 : 1744070 : int32 newval = PG_GETARG_INT32(1);
6484 : : Int8TransTypeData *transdata;
6485 : :
6486 : : /*
6487 : : * If we're invoked as an aggregate, we can cheat and modify our first
6488 : : * parameter in-place to reduce palloc overhead. Otherwise we need to make
6489 : : * a copy of it before scribbling on it.
6490 : : */
6491 [ + - ]: 1744070 : if (AggCheckCallContext(fcinfo, NULL))
6492 : 1744070 : transarray = PG_GETARG_ARRAYTYPE_P(0);
6493 : : else
6494 : 0 : transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6495 : :
6496 [ + - - + ]: 3488140 : if (ARR_HASNULL(transarray) ||
6497 : 1744070 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6498 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6499 : :
6500 [ - + ]: 1744070 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6501 : 1744070 : transdata->count++;
6502 : 1744070 : transdata->sum += newval;
6503 : :
6504 : 1744070 : PG_RETURN_ARRAYTYPE_P(transarray);
6505 : : }
6506 : :
6507 : : Datum
6508 : 6660 : int4_avg_combine(PG_FUNCTION_ARGS)
6509 : : {
6510 : : ArrayType *transarray1;
6511 : : ArrayType *transarray2;
6512 : : Int8TransTypeData *state1;
6513 : : Int8TransTypeData *state2;
6514 : :
6515 [ - + ]: 6660 : if (!AggCheckCallContext(fcinfo, NULL))
6516 [ # # ]: 0 : elog(ERROR, "aggregate function called in non-aggregate context");
6517 : :
6518 : 6660 : transarray1 = PG_GETARG_ARRAYTYPE_P(0);
6519 : 6660 : transarray2 = PG_GETARG_ARRAYTYPE_P(1);
6520 : :
6521 [ + - - + ]: 13320 : if (ARR_HASNULL(transarray1) ||
6522 : 6660 : ARR_SIZE(transarray1) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6523 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6524 : :
6525 [ + - - + ]: 13320 : if (ARR_HASNULL(transarray2) ||
6526 : 6660 : ARR_SIZE(transarray2) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6527 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6528 : :
6529 [ - + ]: 6660 : state1 = (Int8TransTypeData *) ARR_DATA_PTR(transarray1);
6530 [ - + ]: 6660 : state2 = (Int8TransTypeData *) ARR_DATA_PTR(transarray2);
6531 : :
6532 : 6660 : state1->count += state2->count;
6533 : 6660 : state1->sum += state2->sum;
6534 : :
6535 : 6660 : PG_RETURN_ARRAYTYPE_P(transarray1);
6536 : : }
6537 : :
6538 : : Datum
6539 : 8 : int2_avg_accum_inv(PG_FUNCTION_ARGS)
6540 : : {
6541 : : ArrayType *transarray;
6542 : 8 : int16 newval = PG_GETARG_INT16(1);
6543 : : Int8TransTypeData *transdata;
6544 : :
6545 : : /*
6546 : : * If we're invoked as an aggregate, we can cheat and modify our first
6547 : : * parameter in-place to reduce palloc overhead. Otherwise we need to make
6548 : : * a copy of it before scribbling on it.
6549 : : */
6550 [ + - ]: 8 : if (AggCheckCallContext(fcinfo, NULL))
6551 : 8 : transarray = PG_GETARG_ARRAYTYPE_P(0);
6552 : : else
6553 : 0 : transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6554 : :
6555 [ + - - + ]: 16 : if (ARR_HASNULL(transarray) ||
6556 : 8 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6557 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6558 : :
6559 [ - + ]: 8 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6560 : 8 : transdata->count--;
6561 : 8 : transdata->sum -= newval;
6562 : :
6563 : 8 : PG_RETURN_ARRAYTYPE_P(transarray);
6564 : : }
6565 : :
6566 : : Datum
6567 : 1000 : int4_avg_accum_inv(PG_FUNCTION_ARGS)
6568 : : {
6569 : : ArrayType *transarray;
6570 : 1000 : int32 newval = PG_GETARG_INT32(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 [ + - ]: 1000 : if (AggCheckCallContext(fcinfo, NULL))
6579 : 1000 : transarray = PG_GETARG_ARRAYTYPE_P(0);
6580 : : else
6581 : 0 : transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6582 : :
6583 [ + - - + ]: 2000 : if (ARR_HASNULL(transarray) ||
6584 : 1000 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6585 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6586 : :
6587 [ - + ]: 1000 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6588 : 1000 : transdata->count--;
6589 : 1000 : transdata->sum -= newval;
6590 : :
6591 : 1000 : PG_RETURN_ARRAYTYPE_P(transarray);
6592 : : }
6593 : :
6594 : : Datum
6595 : 6817 : int8_avg(PG_FUNCTION_ARGS)
6596 : : {
6597 : 6817 : ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
6598 : : Int8TransTypeData *transdata;
6599 : : Datum countd,
6600 : : sumd;
6601 : :
6602 [ + - - + ]: 13634 : if (ARR_HASNULL(transarray) ||
6603 : 6817 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6604 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6605 [ - + ]: 6817 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6606 : :
6607 : : /* SQL defines AVG of no values to be NULL */
6608 [ + + ]: 6817 : if (transdata->count == 0)
6609 : 73 : PG_RETURN_NULL();
6610 : :
6611 : 6744 : countd = NumericGetDatum(int64_to_numeric(transdata->count));
6612 : 6744 : sumd = NumericGetDatum(int64_to_numeric(transdata->sum));
6613 : :
6614 : 6744 : PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumd, countd));
6615 : : }
6616 : :
6617 : : /*
6618 : : * SUM(int2) and SUM(int4) both return int8, so we can use this
6619 : : * final function for both.
6620 : : */
6621 : : Datum
6622 : 2716 : int2int4_sum(PG_FUNCTION_ARGS)
6623 : : {
6624 : 2716 : ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
6625 : : Int8TransTypeData *transdata;
6626 : :
6627 [ + - - + ]: 5432 : if (ARR_HASNULL(transarray) ||
6628 : 2716 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6629 [ # # ]: 0 : elog(ERROR, "expected 2-element int8 array");
6630 [ - + ]: 2716 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6631 : :
6632 : : /* SQL defines SUM of no values to be NULL */
6633 [ + + ]: 2716 : if (transdata->count == 0)
6634 : 404 : PG_RETURN_NULL();
6635 : :
6636 : 2312 : PG_RETURN_DATUM(Int64GetDatumFast(transdata->sum));
6637 : : }
6638 : :
6639 : :
6640 : : /* ----------------------------------------------------------------------
6641 : : *
6642 : : * Debug support
6643 : : *
6644 : : * ----------------------------------------------------------------------
6645 : : */
6646 : :
6647 : : #ifdef NUMERIC_DEBUG
6648 : :
6649 : : /*
6650 : : * dump_numeric() - Dump a value in the db storage format for debugging
6651 : : */
6652 : : static void
6653 : : dump_numeric(const char *str, Numeric num)
6654 : : {
6655 : : NumericDigit *digits = NUMERIC_DIGITS(num);
6656 : : int ndigits;
6657 : : int i;
6658 : :
6659 : : ndigits = NUMERIC_NDIGITS(num);
6660 : :
6661 : : printf("%s: NUMERIC w=%d d=%d ", str,
6662 : : NUMERIC_WEIGHT(num), NUMERIC_DSCALE(num));
6663 : : switch (NUMERIC_SIGN(num))
6664 : : {
6665 : : case NUMERIC_POS:
6666 : : printf("POS");
6667 : : break;
6668 : : case NUMERIC_NEG:
6669 : : printf("NEG");
6670 : : break;
6671 : : case NUMERIC_NAN:
6672 : : printf("NaN");
6673 : : break;
6674 : : case NUMERIC_PINF:
6675 : : printf("Infinity");
6676 : : break;
6677 : : case NUMERIC_NINF:
6678 : : printf("-Infinity");
6679 : : break;
6680 : : default:
6681 : : printf("SIGN=0x%x", NUMERIC_SIGN(num));
6682 : : break;
6683 : : }
6684 : :
6685 : : for (i = 0; i < ndigits; i++)
6686 : : printf(" %0*d", DEC_DIGITS, digits[i]);
6687 : : printf("\n");
6688 : : }
6689 : :
6690 : :
6691 : : /*
6692 : : * dump_var() - Dump a value in the variable format for debugging
6693 : : */
6694 : : static void
6695 : : dump_var(const char *str, NumericVar *var)
6696 : : {
6697 : : int i;
6698 : :
6699 : : printf("%s: VAR w=%d d=%d ", str, var->weight, var->dscale);
6700 : : switch (var->sign)
6701 : : {
6702 : : case NUMERIC_POS:
6703 : : printf("POS");
6704 : : break;
6705 : : case NUMERIC_NEG:
6706 : : printf("NEG");
6707 : : break;
6708 : : case NUMERIC_NAN:
6709 : : printf("NaN");
6710 : : break;
6711 : : case NUMERIC_PINF:
6712 : : printf("Infinity");
6713 : : break;
6714 : : case NUMERIC_NINF:
6715 : : printf("-Infinity");
6716 : : break;
6717 : : default:
6718 : : printf("SIGN=0x%x", var->sign);
6719 : : break;
6720 : : }
6721 : :
6722 : : for (i = 0; i < var->ndigits; i++)
6723 : : printf(" %0*d", DEC_DIGITS, var->digits[i]);
6724 : :
6725 : : printf("\n");
6726 : : }
6727 : : #endif /* NUMERIC_DEBUG */
6728 : :
6729 : :
6730 : : /* ----------------------------------------------------------------------
6731 : : *
6732 : : * Local functions follow
6733 : : *
6734 : : * In general, these do not support "special" (NaN or infinity) inputs;
6735 : : * callers should handle those possibilities first.
6736 : : * (There are one or two exceptions, noted in their header comments.)
6737 : : *
6738 : : * ----------------------------------------------------------------------
6739 : : */
6740 : :
6741 : :
6742 : : /*
6743 : : * alloc_var() -
6744 : : *
6745 : : * Allocate a digit buffer of ndigits digits (plus a spare digit for rounding)
6746 : : */
6747 : : static void
6748 : 1443575 : alloc_var(NumericVar *var, int ndigits)
6749 : : {
6750 [ + + ]: 1443575 : digitbuf_free(var->buf);
6751 : 1443575 : var->buf = digitbuf_alloc(ndigits + 1);
6752 : 1443575 : var->buf[0] = 0; /* spare digit for rounding */
6753 : 1443575 : var->digits = var->buf + 1;
6754 : 1443575 : var->ndigits = ndigits;
6755 : 1443575 : }
6756 : :
6757 : :
6758 : : /*
6759 : : * free_var() -
6760 : : *
6761 : : * Return the digit buffer of a variable to the free pool
6762 : : */
6763 : : static void
6764 : 2780012 : free_var(NumericVar *var)
6765 : : {
6766 [ + + ]: 2780012 : digitbuf_free(var->buf);
6767 : 2780012 : var->buf = NULL;
6768 : 2780012 : var->digits = NULL;
6769 : 2780012 : var->sign = NUMERIC_NAN;
6770 : 2780012 : }
6771 : :
6772 : :
6773 : : /*
6774 : : * zero_var() -
6775 : : *
6776 : : * Set a variable to ZERO.
6777 : : * Note: its dscale is not touched.
6778 : : */
6779 : : static void
6780 : 38239 : zero_var(NumericVar *var)
6781 : : {
6782 [ + + ]: 38239 : digitbuf_free(var->buf);
6783 : 38239 : var->buf = NULL;
6784 : 38239 : var->digits = NULL;
6785 : 38239 : var->ndigits = 0;
6786 : 38239 : var->weight = 0; /* by convention; doesn't really matter */
6787 : 38239 : var->sign = NUMERIC_POS; /* anything but NAN... */
6788 : 38239 : }
6789 : :
6790 : :
6791 : : /*
6792 : : * set_var_from_str()
6793 : : *
6794 : : * Parse a string and put the number into a variable
6795 : : *
6796 : : * This function does not handle leading or trailing spaces. It returns
6797 : : * the end+1 position parsed into *endptr, so that caller can check for
6798 : : * trailing spaces/garbage if deemed necessary.
6799 : : *
6800 : : * cp is the place to actually start parsing; str is what to use in error
6801 : : * reports. (Typically cp would be the same except advanced over spaces.)
6802 : : *
6803 : : * Returns true on success, false on failure (if escontext points to an
6804 : : * ErrorSaveContext; otherwise errors are thrown).
6805 : : */
6806 : : static bool
6807 : 116854 : set_var_from_str(const char *str, const char *cp,
6808 : : NumericVar *dest, const char **endptr,
6809 : : Node *escontext)
6810 : : {
6811 : 116854 : bool have_dp = false;
6812 : : int i;
6813 : : unsigned char *decdigits;
6814 : 116854 : int sign = NUMERIC_POS;
6815 : 116854 : int dweight = -1;
6816 : : int ddigits;
6817 : 116854 : int dscale = 0;
6818 : : int weight;
6819 : : int ndigits;
6820 : : int offset;
6821 : : NumericDigit *digits;
6822 : :
6823 : : /*
6824 : : * We first parse the string to extract decimal digits and determine the
6825 : : * correct decimal weight. Then convert to NBASE representation.
6826 : : */
6827 [ - + + ]: 116854 : switch (*cp)
6828 : : {
6829 : 0 : case '+':
6830 : 0 : sign = NUMERIC_POS;
6831 : 0 : cp++;
6832 : 0 : break;
6833 : :
6834 : 183 : case '-':
6835 : 183 : sign = NUMERIC_NEG;
6836 : 183 : cp++;
6837 : 183 : break;
6838 : : }
6839 : :
6840 [ + + ]: 116854 : if (*cp == '.')
6841 : : {
6842 : 252 : have_dp = true;
6843 : 252 : cp++;
6844 : : }
6845 : :
6846 [ - + ]: 116854 : if (!isdigit((unsigned char) *cp))
6847 : 0 : goto invalid_syntax;
6848 : :
6849 : 116854 : decdigits = (unsigned char *) palloc(strlen(cp) + DEC_DIGITS * 2);
6850 : :
6851 : : /* leading padding for digit alignment later */
6852 : 116854 : memset(decdigits, 0, DEC_DIGITS);
6853 : 116854 : i = DEC_DIGITS;
6854 : :
6855 [ + + ]: 509196 : while (*cp)
6856 : : {
6857 [ + + ]: 393412 : if (isdigit((unsigned char) *cp))
6858 : : {
6859 : 380290 : decdigits[i++] = *cp++ - '0';
6860 [ + + ]: 380290 : if (!have_dp)
6861 : 318482 : dweight++;
6862 : : else
6863 : 61808 : dscale++;
6864 : : }
6865 [ + + ]: 13122 : else if (*cp == '.')
6866 : : {
6867 [ - + ]: 11944 : if (have_dp)
6868 : 0 : goto invalid_syntax;
6869 : 11944 : have_dp = true;
6870 : 11944 : cp++;
6871 : : /* decimal point must not be followed by underscore */
6872 [ + + ]: 11944 : if (*cp == '_')
6873 : 4 : goto invalid_syntax;
6874 : : }
6875 [ + + ]: 1178 : else if (*cp == '_')
6876 : : {
6877 : : /* underscore must be followed by more digits */
6878 : 124 : cp++;
6879 [ + + ]: 124 : if (!isdigit((unsigned char) *cp))
6880 : 12 : goto invalid_syntax;
6881 : : }
6882 : : else
6883 : 1054 : break;
6884 : : }
6885 : :
6886 : 116838 : ddigits = i - DEC_DIGITS;
6887 : : /* trailing padding for digit alignment later */
6888 : 116838 : memset(decdigits + i, 0, DEC_DIGITS - 1);
6889 : :
6890 : : /* Handle exponent, if any */
6891 [ + + + + ]: 116838 : if (*cp == 'e' || *cp == 'E')
6892 : : {
6893 : 1022 : int64 exponent = 0;
6894 : 1022 : bool neg = false;
6895 : :
6896 : : /*
6897 : : * At this point, dweight and dscale can't be more than about
6898 : : * INT_MAX/2 due to the MaxAllocSize limit on string length, so
6899 : : * constraining the exponent similarly should be enough to prevent
6900 : : * integer overflow in this function. If the value is too large to
6901 : : * fit in storage format, make_result() will complain about it later;
6902 : : * for consistency use the same ereport errcode/text as make_result().
6903 : : */
6904 : :
6905 : : /* exponent sign */
6906 : 1022 : cp++;
6907 [ + + ]: 1022 : if (*cp == '+')
6908 : 102 : cp++;
6909 [ + + ]: 920 : else if (*cp == '-')
6910 : : {
6911 : 444 : neg = true;
6912 : 444 : cp++;
6913 : : }
6914 : :
6915 : : /* exponent digits */
6916 [ + + ]: 1022 : if (!isdigit((unsigned char) *cp))
6917 : 4 : goto invalid_syntax;
6918 : :
6919 [ + + ]: 3569 : while (*cp)
6920 : : {
6921 [ + + ]: 2563 : if (isdigit((unsigned char) *cp))
6922 : : {
6923 : 2535 : exponent = exponent * 10 + (*cp++ - '0');
6924 [ + + ]: 2535 : if (exponent > PG_INT32_MAX / 2)
6925 : 4 : goto out_of_range;
6926 : : }
6927 [ + - ]: 28 : else if (*cp == '_')
6928 : : {
6929 : : /* underscore must be followed by more digits */
6930 : 28 : cp++;
6931 [ + + ]: 28 : if (!isdigit((unsigned char) *cp))
6932 : 8 : goto invalid_syntax;
6933 : : }
6934 : : else
6935 : 0 : break;
6936 : : }
6937 : :
6938 [ + + ]: 1006 : if (neg)
6939 : 444 : exponent = -exponent;
6940 : :
6941 : 1006 : dweight += (int) exponent;
6942 : 1006 : dscale -= (int) exponent;
6943 [ + + ]: 1006 : if (dscale < 0)
6944 : 426 : dscale = 0;
6945 : : }
6946 : :
6947 : : /*
6948 : : * Okay, convert pure-decimal representation to base NBASE. First we need
6949 : : * to determine the converted weight and ndigits. offset is the number of
6950 : : * decimal zeroes to insert before the first given digit to have a
6951 : : * correctly aligned first NBASE digit.
6952 : : */
6953 [ + + ]: 116822 : if (dweight >= 0)
6954 : 116194 : weight = (dweight + 1 + DEC_DIGITS - 1) / DEC_DIGITS - 1;
6955 : : else
6956 : 628 : weight = -((-dweight - 1) / DEC_DIGITS + 1);
6957 : 116822 : offset = (weight + 1) * DEC_DIGITS - (dweight + 1);
6958 : 116822 : ndigits = (ddigits + offset + DEC_DIGITS - 1) / DEC_DIGITS;
6959 : :
6960 : 116822 : alloc_var(dest, ndigits);
6961 : 116822 : dest->sign = sign;
6962 : 116822 : dest->weight = weight;
6963 : 116822 : dest->dscale = dscale;
6964 : :
6965 : 116822 : i = DEC_DIGITS - offset;
6966 : 116822 : digits = dest->digits;
6967 : :
6968 [ + + ]: 282062 : while (ndigits-- > 0)
6969 : : {
6970 : : #if DEC_DIGITS == 4
6971 : 165240 : *digits++ = ((decdigits[i] * 10 + decdigits[i + 1]) * 10 +
6972 : 165240 : decdigits[i + 2]) * 10 + decdigits[i + 3];
6973 : : #elif DEC_DIGITS == 2
6974 : : *digits++ = decdigits[i] * 10 + decdigits[i + 1];
6975 : : #elif DEC_DIGITS == 1
6976 : : *digits++ = decdigits[i];
6977 : : #else
6978 : : #error unsupported NBASE
6979 : : #endif
6980 : 165240 : i += DEC_DIGITS;
6981 : : }
6982 : :
6983 : 116822 : pfree(decdigits);
6984 : :
6985 : : /* Strip any leading/trailing zeroes, and normalize weight if zero */
6986 : 116822 : strip_var(dest);
6987 : :
6988 : : /* Return end+1 position for caller */
6989 : 116822 : *endptr = cp;
6990 : :
6991 : 116822 : return true;
6992 : :
6993 : 4 : out_of_range:
6994 [ + - ]: 4 : ereturn(escontext, false,
6995 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
6996 : : errmsg("value overflows numeric format")));
6997 : :
6998 : 28 : invalid_syntax:
6999 [ + - ]: 28 : ereturn(escontext, false,
7000 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
7001 : : errmsg("invalid input syntax for type %s: \"%s\"",
7002 : : "numeric", str)));
7003 : : }
7004 : :
7005 : :
7006 : : /*
7007 : : * Return the numeric value of a single hex digit.
7008 : : */
7009 : : static inline int
7010 : 472 : xdigit_value(char dig)
7011 : : {
7012 [ + - + + ]: 596 : return dig >= '0' && dig <= '9' ? dig - '0' :
7013 [ + + + - ]: 196 : dig >= 'a' && dig <= 'f' ? dig - 'a' + 10 :
7014 [ + - + - ]: 72 : dig >= 'A' && dig <= 'F' ? dig - 'A' + 10 : -1;
7015 : : }
7016 : :
7017 : : /*
7018 : : * set_var_from_non_decimal_integer_str()
7019 : : *
7020 : : * Parse a string containing a non-decimal integer
7021 : : *
7022 : : * This function does not handle leading or trailing spaces. It returns
7023 : : * the end+1 position parsed into *endptr, so that caller can check for
7024 : : * trailing spaces/garbage if deemed necessary.
7025 : : *
7026 : : * cp is the place to actually start parsing; str is what to use in error
7027 : : * reports. The number's sign and base prefix indicator (e.g., "0x") are
7028 : : * assumed to have already been parsed, so cp should point to the number's
7029 : : * first digit in the base specified.
7030 : : *
7031 : : * base is expected to be 2, 8 or 16.
7032 : : *
7033 : : * Returns true on success, false on failure (if escontext points to an
7034 : : * ErrorSaveContext; otherwise errors are thrown).
7035 : : */
7036 : : static bool
7037 : 104 : set_var_from_non_decimal_integer_str(const char *str, const char *cp, int sign,
7038 : : int base, NumericVar *dest,
7039 : : const char **endptr, Node *escontext)
7040 : : {
7041 : 104 : const char *firstdigit = cp;
7042 : : int64 tmp;
7043 : : int64 mul;
7044 : : NumericVar tmp_var;
7045 : :
7046 : 104 : init_var(&tmp_var);
7047 : :
7048 : 104 : zero_var(dest);
7049 : :
7050 : : /*
7051 : : * Process input digits in groups that fit in int64. Here "tmp" is the
7052 : : * value of the digits in the group, and "mul" is base^n, where n is the
7053 : : * number of digits in the group. Thus tmp < mul, and we must start a new
7054 : : * group when mul * base threatens to overflow PG_INT64_MAX.
7055 : : */
7056 : 104 : tmp = 0;
7057 : 104 : mul = 1;
7058 : :
7059 [ + + ]: 104 : if (base == 16)
7060 : : {
7061 [ + + ]: 552 : while (*cp)
7062 : : {
7063 [ + + ]: 532 : if (isxdigit((unsigned char) *cp))
7064 : : {
7065 [ + + ]: 472 : if (mul > PG_INT64_MAX / 16)
7066 : : {
7067 : : /* Add the contribution from this group of digits */
7068 : 20 : int64_to_numericvar(mul, &tmp_var);
7069 : 20 : mul_var(dest, &tmp_var, dest, 0);
7070 : 20 : int64_to_numericvar(tmp, &tmp_var);
7071 : 20 : add_var(dest, &tmp_var, dest);
7072 : :
7073 : : /* Result will overflow if weight overflows int16 */
7074 [ - + ]: 20 : if (dest->weight > NUMERIC_WEIGHT_MAX)
7075 : 0 : goto out_of_range;
7076 : :
7077 : : /* Begin a new group */
7078 : 20 : tmp = 0;
7079 : 20 : mul = 1;
7080 : : }
7081 : :
7082 : 472 : tmp = tmp * 16 + xdigit_value(*cp++);
7083 : 472 : mul = mul * 16;
7084 : : }
7085 [ + + ]: 60 : else if (*cp == '_')
7086 : : {
7087 : : /* Underscore must be followed by more digits */
7088 : 44 : cp++;
7089 [ + + ]: 44 : if (!isxdigit((unsigned char) *cp))
7090 : 12 : goto invalid_syntax;
7091 : : }
7092 : : else
7093 : 16 : break;
7094 : : }
7095 : : }
7096 [ + + ]: 56 : else if (base == 8)
7097 : : {
7098 [ + + ]: 424 : while (*cp)
7099 : : {
7100 [ + + + + ]: 404 : if (*cp >= '0' && *cp <= '7')
7101 : : {
7102 [ + + ]: 372 : if (mul > PG_INT64_MAX / 8)
7103 : : {
7104 : : /* Add the contribution from this group of digits */
7105 : 12 : int64_to_numericvar(mul, &tmp_var);
7106 : 12 : mul_var(dest, &tmp_var, dest, 0);
7107 : 12 : int64_to_numericvar(tmp, &tmp_var);
7108 : 12 : add_var(dest, &tmp_var, dest);
7109 : :
7110 : : /* Result will overflow if weight overflows int16 */
7111 [ - + ]: 12 : if (dest->weight > NUMERIC_WEIGHT_MAX)
7112 : 0 : goto out_of_range;
7113 : :
7114 : : /* Begin a new group */
7115 : 12 : tmp = 0;
7116 : 12 : mul = 1;
7117 : : }
7118 : :
7119 : 372 : tmp = tmp * 8 + (*cp++ - '0');
7120 : 372 : mul = mul * 8;
7121 : : }
7122 [ + + ]: 32 : else if (*cp == '_')
7123 : : {
7124 : : /* Underscore must be followed by more digits */
7125 : 24 : cp++;
7126 [ + - - + ]: 24 : if (*cp < '0' || *cp > '7')
7127 : 0 : goto invalid_syntax;
7128 : : }
7129 : : else
7130 : 8 : break;
7131 : : }
7132 : : }
7133 [ + - ]: 28 : else if (base == 2)
7134 : : {
7135 [ + + ]: 1040 : while (*cp)
7136 : : {
7137 [ + + + + ]: 1020 : if (*cp >= '0' && *cp <= '1')
7138 : : {
7139 [ + + ]: 944 : if (mul > PG_INT64_MAX / 2)
7140 : : {
7141 : : /* Add the contribution from this group of digits */
7142 : 12 : int64_to_numericvar(mul, &tmp_var);
7143 : 12 : mul_var(dest, &tmp_var, dest, 0);
7144 : 12 : int64_to_numericvar(tmp, &tmp_var);
7145 : 12 : add_var(dest, &tmp_var, dest);
7146 : :
7147 : : /* Result will overflow if weight overflows int16 */
7148 [ - + ]: 12 : if (dest->weight > NUMERIC_WEIGHT_MAX)
7149 : 0 : goto out_of_range;
7150 : :
7151 : : /* Begin a new group */
7152 : 12 : tmp = 0;
7153 : 12 : mul = 1;
7154 : : }
7155 : :
7156 : 944 : tmp = tmp * 2 + (*cp++ - '0');
7157 : 944 : mul = mul * 2;
7158 : : }
7159 [ + + ]: 76 : else if (*cp == '_')
7160 : : {
7161 : : /* Underscore must be followed by more digits */
7162 : 68 : cp++;
7163 [ + - - + ]: 68 : if (*cp < '0' || *cp > '1')
7164 : 0 : goto invalid_syntax;
7165 : : }
7166 : : else
7167 : 8 : break;
7168 : : }
7169 : : }
7170 : : else
7171 : : /* Should never happen; treat as invalid input */
7172 : 0 : goto invalid_syntax;
7173 : :
7174 : : /* Check that we got at least one digit */
7175 [ - + ]: 92 : if (unlikely(cp == firstdigit))
7176 : 0 : goto invalid_syntax;
7177 : :
7178 : : /* Add the contribution from the final group of digits */
7179 : 92 : int64_to_numericvar(mul, &tmp_var);
7180 : 92 : mul_var(dest, &tmp_var, dest, 0);
7181 : 92 : int64_to_numericvar(tmp, &tmp_var);
7182 : 92 : add_var(dest, &tmp_var, dest);
7183 : :
7184 [ - + ]: 92 : if (dest->weight > NUMERIC_WEIGHT_MAX)
7185 : 0 : goto out_of_range;
7186 : :
7187 : 92 : dest->sign = sign;
7188 : :
7189 : 92 : free_var(&tmp_var);
7190 : :
7191 : : /* Return end+1 position for caller */
7192 : 92 : *endptr = cp;
7193 : :
7194 : 92 : return true;
7195 : :
7196 : 0 : out_of_range:
7197 [ # # ]: 0 : ereturn(escontext, false,
7198 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7199 : : errmsg("value overflows numeric format")));
7200 : :
7201 : 12 : invalid_syntax:
7202 [ + - ]: 12 : ereturn(escontext, false,
7203 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
7204 : : errmsg("invalid input syntax for type %s: \"%s\"",
7205 : : "numeric", str)));
7206 : : }
7207 : :
7208 : :
7209 : : /*
7210 : : * set_var_from_num() -
7211 : : *
7212 : : * Convert the packed db format into a variable
7213 : : */
7214 : : static void
7215 : 8827 : set_var_from_num(Numeric num, NumericVar *dest)
7216 : : {
7217 : : int ndigits;
7218 : :
7219 [ + + ]: 8827 : ndigits = NUMERIC_NDIGITS(num);
7220 : :
7221 : 8827 : alloc_var(dest, ndigits);
7222 : :
7223 [ + + + + ]: 8827 : dest->weight = NUMERIC_WEIGHT(num);
7224 [ + + - + ]: 8827 : dest->sign = NUMERIC_SIGN(num);
7225 [ + + ]: 8827 : dest->dscale = NUMERIC_DSCALE(num);
7226 : :
7227 [ + + ]: 8827 : memcpy(dest->digits, NUMERIC_DIGITS(num), ndigits * sizeof(NumericDigit));
7228 : 8827 : }
7229 : :
7230 : :
7231 : : /*
7232 : : * init_var_from_num() -
7233 : : *
7234 : : * Initialize a variable from packed db format. The digits array is not
7235 : : * copied, which saves some cycles when the resulting var is not modified.
7236 : : * Also, there's no need to call free_var(), as long as you don't assign any
7237 : : * other value to it (with set_var_* functions, or by using the var as the
7238 : : * destination of a function like add_var())
7239 : : *
7240 : : * CAUTION: Do not modify the digits buffer of a var initialized with this
7241 : : * function, e.g by calling round_var() or trunc_var(), as the changes will
7242 : : * propagate to the original Numeric! It's OK to use it as the destination
7243 : : * argument of one of the calculational functions, though.
7244 : : */
7245 : : static void
7246 : 3865697 : init_var_from_num(Numeric num, NumericVar *dest)
7247 : : {
7248 [ + + ]: 3865697 : dest->ndigits = NUMERIC_NDIGITS(num);
7249 [ + + + + ]: 3865697 : dest->weight = NUMERIC_WEIGHT(num);
7250 [ + + - + ]: 3865697 : dest->sign = NUMERIC_SIGN(num);
7251 [ + + ]: 3865697 : dest->dscale = NUMERIC_DSCALE(num);
7252 [ + + ]: 3865697 : dest->digits = NUMERIC_DIGITS(num);
7253 : 3865697 : dest->buf = NULL; /* digits array is not palloc'd */
7254 : 3865697 : }
7255 : :
7256 : :
7257 : : /*
7258 : : * set_var_from_var() -
7259 : : *
7260 : : * Copy one variable into another
7261 : : */
7262 : : static void
7263 : 24642 : set_var_from_var(const NumericVar *value, NumericVar *dest)
7264 : : {
7265 : : NumericDigit *newbuf;
7266 : :
7267 : 24642 : newbuf = digitbuf_alloc(value->ndigits + 1);
7268 : 24642 : newbuf[0] = 0; /* spare digit for rounding */
7269 [ + + ]: 24642 : if (value->ndigits > 0) /* else value->digits might be null */
7270 : 23966 : memcpy(newbuf + 1, value->digits,
7271 : 23966 : value->ndigits * sizeof(NumericDigit));
7272 : :
7273 [ + + ]: 24642 : digitbuf_free(dest->buf);
7274 : :
7275 : 24642 : memmove(dest, value, sizeof(NumericVar));
7276 : 24642 : dest->buf = newbuf;
7277 : 24642 : dest->digits = newbuf + 1;
7278 : 24642 : }
7279 : :
7280 : :
7281 : : /*
7282 : : * get_str_from_var() -
7283 : : *
7284 : : * Convert a var to text representation (guts of numeric_out).
7285 : : * The var is displayed to the number of digits indicated by its dscale.
7286 : : * Returns a palloc'd string.
7287 : : */
7288 : : static char *
7289 : 555328 : get_str_from_var(const NumericVar *var)
7290 : : {
7291 : : int dscale;
7292 : : char *str;
7293 : : char *cp;
7294 : : char *endcp;
7295 : : int i;
7296 : : int d;
7297 : : NumericDigit dig;
7298 : :
7299 : : #if DEC_DIGITS > 1
7300 : : NumericDigit d1;
7301 : : #endif
7302 : :
7303 : 555328 : dscale = var->dscale;
7304 : :
7305 : : /*
7306 : : * Allocate space for the result.
7307 : : *
7308 : : * i is set to the # of decimal digits before decimal point. dscale is the
7309 : : * # of decimal digits we will print after decimal point. We may generate
7310 : : * as many as DEC_DIGITS-1 excess digits at the end, and in addition we
7311 : : * need room for sign, decimal point, null terminator.
7312 : : */
7313 : 555328 : i = (var->weight + 1) * DEC_DIGITS;
7314 [ + + ]: 555328 : if (i <= 0)
7315 : 72490 : i = 1;
7316 : :
7317 : 555328 : str = palloc(i + dscale + DEC_DIGITS + 2);
7318 : 555328 : cp = str;
7319 : :
7320 : : /*
7321 : : * Output a dash for negative values
7322 : : */
7323 [ + + ]: 555328 : if (var->sign == NUMERIC_NEG)
7324 : 5053 : *cp++ = '-';
7325 : :
7326 : : /*
7327 : : * Output all digits before the decimal point
7328 : : */
7329 [ + + ]: 555328 : if (var->weight < 0)
7330 : : {
7331 : 72490 : d = var->weight + 1;
7332 : 72490 : *cp++ = '0';
7333 : : }
7334 : : else
7335 : : {
7336 [ + + ]: 1027692 : for (d = 0; d <= var->weight; d++)
7337 : : {
7338 [ + + ]: 544854 : dig = (d < var->ndigits) ? var->digits[d] : 0;
7339 : : /* In the first digit, suppress extra leading decimal zeroes */
7340 : : #if DEC_DIGITS == 4
7341 : : {
7342 : 544854 : bool putit = (d > 0);
7343 : :
7344 : 544854 : d1 = dig / 1000;
7345 : 544854 : dig -= d1 * 1000;
7346 : 544854 : putit |= (d1 > 0);
7347 [ + + ]: 544854 : if (putit)
7348 : 102575 : *cp++ = d1 + '0';
7349 : 544854 : d1 = dig / 100;
7350 : 544854 : dig -= d1 * 100;
7351 : 544854 : putit |= (d1 > 0);
7352 [ + + ]: 544854 : if (putit)
7353 : 375226 : *cp++ = d1 + '0';
7354 : 544854 : d1 = dig / 10;
7355 : 544854 : dig -= d1 * 10;
7356 : 544854 : putit |= (d1 > 0);
7357 [ + + ]: 544854 : if (putit)
7358 : 458285 : *cp++ = d1 + '0';
7359 : 544854 : *cp++ = dig + '0';
7360 : : }
7361 : : #elif DEC_DIGITS == 2
7362 : : d1 = dig / 10;
7363 : : dig -= d1 * 10;
7364 : : if (d1 > 0 || d > 0)
7365 : : *cp++ = d1 + '0';
7366 : : *cp++ = dig + '0';
7367 : : #elif DEC_DIGITS == 1
7368 : : *cp++ = dig + '0';
7369 : : #else
7370 : : #error unsupported NBASE
7371 : : #endif
7372 : : }
7373 : : }
7374 : :
7375 : : /*
7376 : : * If requested, output a decimal point and all the digits that follow it.
7377 : : * We initially put out a multiple of DEC_DIGITS digits, then truncate if
7378 : : * needed.
7379 : : */
7380 [ + + ]: 555328 : if (dscale > 0)
7381 : : {
7382 : 409223 : *cp++ = '.';
7383 : 409223 : endcp = cp + dscale;
7384 [ + + ]: 1149973 : for (i = 0; i < dscale; d++, i += DEC_DIGITS)
7385 : : {
7386 [ + + + + ]: 740750 : dig = (d >= 0 && d < var->ndigits) ? var->digits[d] : 0;
7387 : : #if DEC_DIGITS == 4
7388 : 740750 : d1 = dig / 1000;
7389 : 740750 : dig -= d1 * 1000;
7390 : 740750 : *cp++ = d1 + '0';
7391 : 740750 : d1 = dig / 100;
7392 : 740750 : dig -= d1 * 100;
7393 : 740750 : *cp++ = d1 + '0';
7394 : 740750 : d1 = dig / 10;
7395 : 740750 : dig -= d1 * 10;
7396 : 740750 : *cp++ = d1 + '0';
7397 : 740750 : *cp++ = dig + '0';
7398 : : #elif DEC_DIGITS == 2
7399 : : d1 = dig / 10;
7400 : : dig -= d1 * 10;
7401 : : *cp++ = d1 + '0';
7402 : : *cp++ = dig + '0';
7403 : : #elif DEC_DIGITS == 1
7404 : : *cp++ = dig + '0';
7405 : : #else
7406 : : #error unsupported NBASE
7407 : : #endif
7408 : : }
7409 : 409223 : cp = endcp;
7410 : : }
7411 : :
7412 : : /*
7413 : : * terminate the string and return it
7414 : : */
7415 : 555328 : *cp = '\0';
7416 : 555328 : return str;
7417 : : }
7418 : :
7419 : : /*
7420 : : * get_str_from_var_sci() -
7421 : : *
7422 : : * Convert a var to a normalised scientific notation text representation.
7423 : : * This function does the heavy lifting for numeric_out_sci().
7424 : : *
7425 : : * This notation has the general form a * 10^b, where a is known as the
7426 : : * "significand" and b is known as the "exponent".
7427 : : *
7428 : : * Because we can't do superscript in ASCII (and because we want to copy
7429 : : * printf's behaviour) we display the exponent using E notation, with a
7430 : : * minimum of two exponent digits.
7431 : : *
7432 : : * For example, the value 1234 could be output as 1.2e+03.
7433 : : *
7434 : : * We assume that the exponent can fit into an int32.
7435 : : *
7436 : : * rscale is the number of decimal digits desired after the decimal point in
7437 : : * the output, negative values will be treated as meaning zero.
7438 : : *
7439 : : * Returns a palloc'd string.
7440 : : */
7441 : : static char *
7442 : 152 : get_str_from_var_sci(const NumericVar *var, int rscale)
7443 : : {
7444 : : int32 exponent;
7445 : : NumericVar tmp_var;
7446 : : size_t len;
7447 : : char *str;
7448 : : char *sig_out;
7449 : :
7450 [ - + ]: 152 : if (rscale < 0)
7451 : 0 : rscale = 0;
7452 : :
7453 : : /*
7454 : : * Determine the exponent of this number in normalised form.
7455 : : *
7456 : : * This is the exponent required to represent the number with only one
7457 : : * significant digit before the decimal place.
7458 : : */
7459 [ + + ]: 152 : if (var->ndigits > 0)
7460 : : {
7461 : 140 : exponent = (var->weight + 1) * DEC_DIGITS;
7462 : :
7463 : : /*
7464 : : * Compensate for leading decimal zeroes in the first numeric digit by
7465 : : * decrementing the exponent.
7466 : : */
7467 : 140 : exponent -= DEC_DIGITS - (int) log10(var->digits[0]);
7468 : : }
7469 : : else
7470 : : {
7471 : : /*
7472 : : * If var has no digits, then it must be zero.
7473 : : *
7474 : : * Zero doesn't technically have a meaningful exponent in normalised
7475 : : * notation, but we just display the exponent as zero for consistency
7476 : : * of output.
7477 : : */
7478 : 12 : exponent = 0;
7479 : : }
7480 : :
7481 : : /*
7482 : : * Divide var by 10^exponent to get the significand, rounding to rscale
7483 : : * decimal digits in the process.
7484 : : */
7485 : 152 : init_var(&tmp_var);
7486 : :
7487 : 152 : power_ten_int(exponent, &tmp_var);
7488 : 152 : div_var(var, &tmp_var, &tmp_var, rscale, true, true);
7489 : 152 : sig_out = get_str_from_var(&tmp_var);
7490 : :
7491 : 152 : free_var(&tmp_var);
7492 : :
7493 : : /*
7494 : : * Allocate space for the result.
7495 : : *
7496 : : * In addition to the significand, we need room for the exponent
7497 : : * decoration ("e"), the sign of the exponent, up to 10 digits for the
7498 : : * exponent itself, and of course the null terminator.
7499 : : */
7500 : 152 : len = strlen(sig_out) + 13;
7501 : 152 : str = palloc(len);
7502 : 152 : snprintf(str, len, "%se%+03d", sig_out, exponent);
7503 : :
7504 : 152 : pfree(sig_out);
7505 : :
7506 : 152 : return str;
7507 : : }
7508 : :
7509 : :
7510 : : /*
7511 : : * numericvar_serialize - serialize NumericVar to binary format
7512 : : *
7513 : : * At variable level, no checks are performed on the weight or dscale, allowing
7514 : : * us to pass around intermediate values with higher precision than supported
7515 : : * by the numeric type. Note: this is incompatible with numeric_send/recv(),
7516 : : * which use 16-bit integers for these fields.
7517 : : */
7518 : : static void
7519 : 61 : numericvar_serialize(StringInfo buf, const NumericVar *var)
7520 : : {
7521 : : int i;
7522 : :
7523 : 61 : pq_sendint32(buf, var->ndigits);
7524 : 61 : pq_sendint32(buf, var->weight);
7525 : 61 : pq_sendint32(buf, var->sign);
7526 : 61 : pq_sendint32(buf, var->dscale);
7527 [ + + ]: 425164 : for (i = 0; i < var->ndigits; i++)
7528 : 425103 : pq_sendint16(buf, var->digits[i]);
7529 : 61 : }
7530 : :
7531 : : /*
7532 : : * numericvar_deserialize - deserialize binary format to NumericVar
7533 : : */
7534 : : static void
7535 : 61 : numericvar_deserialize(StringInfo buf, NumericVar *var)
7536 : : {
7537 : : int len,
7538 : : i;
7539 : :
7540 : 61 : len = pq_getmsgint(buf, sizeof(int32));
7541 : :
7542 : 61 : alloc_var(var, len); /* sets var->ndigits */
7543 : :
7544 : 61 : var->weight = pq_getmsgint(buf, sizeof(int32));
7545 : 61 : var->sign = pq_getmsgint(buf, sizeof(int32));
7546 : 61 : var->dscale = pq_getmsgint(buf, sizeof(int32));
7547 [ + + ]: 425164 : for (i = 0; i < len; i++)
7548 : 425103 : var->digits[i] = pq_getmsgint(buf, sizeof(int16));
7549 : 61 : }
7550 : :
7551 : :
7552 : : /*
7553 : : * duplicate_numeric() - copy a packed-format Numeric
7554 : : *
7555 : : * This will handle NaN and Infinity cases.
7556 : : */
7557 : : static Numeric
7558 : 18826 : duplicate_numeric(Numeric num)
7559 : : {
7560 : : Numeric res;
7561 : :
7562 : 18826 : res = (Numeric) palloc(VARSIZE(num));
7563 : 18826 : memcpy(res, num, VARSIZE(num));
7564 : 18826 : return res;
7565 : : }
7566 : :
7567 : : /*
7568 : : * make_result_safe() -
7569 : : *
7570 : : * Create the packed db numeric format in palloc()'d memory from
7571 : : * a variable. This will handle NaN and Infinity cases.
7572 : : */
7573 : : static Numeric
7574 : 2525312 : make_result_safe(const NumericVar *var, Node *escontext)
7575 : : {
7576 : : Numeric result;
7577 : 2525312 : NumericDigit *digits = var->digits;
7578 : 2525312 : int weight = var->weight;
7579 : 2525312 : int sign = var->sign;
7580 : : int n;
7581 : : Size len;
7582 : :
7583 [ + + ]: 2525312 : if ((sign & NUMERIC_SIGN_MASK) == NUMERIC_SPECIAL)
7584 : : {
7585 : : /*
7586 : : * Verify valid special value. This could be just an Assert, perhaps,
7587 : : * but it seems worthwhile to expend a few cycles to ensure that we
7588 : : * never write any nonzero reserved bits to disk.
7589 : : */
7590 [ + + + + : 2208 : if (!(sign == NUMERIC_NAN ||
- + ]
7591 : : sign == NUMERIC_PINF ||
7592 : : sign == NUMERIC_NINF))
7593 [ # # ]: 0 : elog(ERROR, "invalid numeric sign value 0x%x", sign);
7594 : :
7595 : 2208 : result = (Numeric) palloc(NUMERIC_HDRSZ_SHORT);
7596 : :
7597 : 2208 : SET_VARSIZE(result, NUMERIC_HDRSZ_SHORT);
7598 : 2208 : result->choice.n_header = sign;
7599 : : /* the header word is all we need */
7600 : :
7601 : : dump_numeric("make_result()", result);
7602 : 2208 : return result;
7603 : : }
7604 : :
7605 : 2523104 : n = var->ndigits;
7606 : :
7607 : : /* truncate leading zeroes */
7608 [ + + + + ]: 2523134 : while (n > 0 && *digits == 0)
7609 : : {
7610 : 30 : digits++;
7611 : 30 : weight--;
7612 : 30 : n--;
7613 : : }
7614 : : /* truncate trailing zeroes */
7615 [ + + + + ]: 2575232 : while (n > 0 && digits[n - 1] == 0)
7616 : 52128 : n--;
7617 : :
7618 : : /* If zero result, force to weight=0 and positive sign */
7619 [ + + ]: 2523104 : if (n == 0)
7620 : : {
7621 : 83001 : weight = 0;
7622 : 83001 : sign = NUMERIC_POS;
7623 : : }
7624 : :
7625 : : /* Build the result */
7626 [ + + + + : 2523104 : if (NUMERIC_CAN_BE_SHORT(var->dscale, weight))
+ - ]
7627 : : {
7628 : 2521170 : len = NUMERIC_HDRSZ_SHORT + n * sizeof(NumericDigit);
7629 : 2521170 : result = (Numeric) palloc(len);
7630 : 2521170 : SET_VARSIZE(result, len);
7631 : 2521170 : result->choice.n_short.n_header =
7632 : : (sign == NUMERIC_NEG ? (NUMERIC_SHORT | NUMERIC_SHORT_SIGN_MASK)
7633 : : : NUMERIC_SHORT)
7634 [ + + ]: 2521170 : | (var->dscale << NUMERIC_SHORT_DSCALE_SHIFT)
7635 : 2521170 : | (weight < 0 ? NUMERIC_SHORT_WEIGHT_SIGN_MASK : 0)
7636 : 2521170 : | (weight & NUMERIC_SHORT_WEIGHT_MASK);
7637 : : }
7638 : : else
7639 : : {
7640 : 1934 : len = NUMERIC_HDRSZ + n * sizeof(NumericDigit);
7641 : 1934 : result = (Numeric) palloc(len);
7642 : 1934 : SET_VARSIZE(result, len);
7643 : 1934 : result->choice.n_long.n_sign_dscale =
7644 : 1934 : sign | (var->dscale & NUMERIC_DSCALE_MASK);
7645 : 1934 : result->choice.n_long.n_weight = weight;
7646 : : }
7647 : :
7648 : : Assert(NUMERIC_NDIGITS(result) == n);
7649 [ + + ]: 2523104 : if (n > 0)
7650 [ + + ]: 2440103 : memcpy(NUMERIC_DIGITS(result), digits, n * sizeof(NumericDigit));
7651 : :
7652 : : /* Check for overflow of int16 fields */
7653 [ + + + + : 2523104 : if (NUMERIC_WEIGHT(result) != weight ||
+ + ]
7654 [ + + - + ]: 2523084 : NUMERIC_DSCALE(result) != var->dscale)
7655 [ + + ]: 20 : ereturn(escontext, NULL,
7656 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7657 : : errmsg("value overflows numeric format")));
7658 : :
7659 : : dump_numeric("make_result()", result);
7660 : 2523084 : return result;
7661 : : }
7662 : :
7663 : :
7664 : : /*
7665 : : * make_result() -
7666 : : *
7667 : : * An interface to make_result_safe() without "escontext" argument.
7668 : : */
7669 : : static Numeric
7670 : 1505112 : make_result(const NumericVar *var)
7671 : : {
7672 : 1505112 : return make_result_safe(var, NULL);
7673 : : }
7674 : :
7675 : :
7676 : : /*
7677 : : * apply_typmod() -
7678 : : *
7679 : : * Do bounds checking and rounding according to the specified typmod.
7680 : : * Note that this is only applied to normal finite values.
7681 : : *
7682 : : * Returns true on success, false on failure (if escontext points to an
7683 : : * ErrorSaveContext; otherwise errors are thrown).
7684 : : */
7685 : : static bool
7686 : 104282 : apply_typmod(NumericVar *var, int32 typmod, Node *escontext)
7687 : : {
7688 : : int precision;
7689 : : int scale;
7690 : : int maxdigits;
7691 : : int ddigits;
7692 : : int i;
7693 : :
7694 : : /* Do nothing if we have an invalid typmod */
7695 [ + + ]: 104282 : if (!is_valid_numeric_typmod(typmod))
7696 : 84766 : return true;
7697 : :
7698 : 19516 : precision = numeric_typmod_precision(typmod);
7699 : 19516 : scale = numeric_typmod_scale(typmod);
7700 : 19516 : maxdigits = precision - scale;
7701 : :
7702 : : /* Round to target scale (and set var->dscale) */
7703 : 19516 : round_var(var, scale);
7704 : :
7705 : : /* but don't allow var->dscale to be negative */
7706 [ + + ]: 19516 : if (var->dscale < 0)
7707 : 100 : var->dscale = 0;
7708 : :
7709 : : /*
7710 : : * Check for overflow - note we can't do this before rounding, because
7711 : : * rounding could raise the weight. Also note that the var's weight could
7712 : : * be inflated by leading zeroes, which will be stripped before storage
7713 : : * but perhaps might not have been yet. In any case, we must recognize a
7714 : : * true zero, whose weight doesn't mean anything.
7715 : : */
7716 : 19516 : ddigits = (var->weight + 1) * DEC_DIGITS;
7717 [ + + ]: 19516 : if (ddigits > maxdigits)
7718 : : {
7719 : : /* Determine true weight; and check for all-zero result */
7720 [ + + ]: 4297 : for (i = 0; i < var->ndigits; i++)
7721 : : {
7722 : 4286 : NumericDigit dig = var->digits[i];
7723 : :
7724 [ + - ]: 4286 : if (dig)
7725 : : {
7726 : : /* Adjust for any high-order decimal zero digits */
7727 : : #if DEC_DIGITS == 4
7728 [ + + ]: 4286 : if (dig < 10)
7729 : 206 : ddigits -= 3;
7730 [ + + ]: 4080 : else if (dig < 100)
7731 : 428 : ddigits -= 2;
7732 [ + + ]: 3652 : else if (dig < 1000)
7733 : 3640 : ddigits -= 1;
7734 : : #elif DEC_DIGITS == 2
7735 : : if (dig < 10)
7736 : : ddigits -= 1;
7737 : : #elif DEC_DIGITS == 1
7738 : : /* no adjustment */
7739 : : #else
7740 : : #error unsupported NBASE
7741 : : #endif
7742 [ + + ]: 4286 : if (ddigits > maxdigits)
7743 [ + + + + : 64 : ereturn(escontext, false,
+ + ]
7744 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7745 : : errmsg("numeric field overflow"),
7746 : : errdetail("A field with precision %d, scale %d must round to an absolute value less than %s%d.",
7747 : : precision, scale,
7748 : : /* Display 10^0 as 1 */
7749 : : maxdigits ? "10^" : "",
7750 : : maxdigits ? maxdigits : 1
7751 : : )));
7752 : 4222 : break;
7753 : : }
7754 : 0 : ddigits -= DEC_DIGITS;
7755 : : }
7756 : : }
7757 : :
7758 : 19452 : return true;
7759 : : }
7760 : :
7761 : : /*
7762 : : * apply_typmod_special() -
7763 : : *
7764 : : * Do bounds checking according to the specified typmod, for an Inf or NaN.
7765 : : * For convenience of most callers, the value is presented in packed form.
7766 : : *
7767 : : * Returns true on success, false on failure (if escontext points to an
7768 : : * ErrorSaveContext; otherwise errors are thrown).
7769 : : */
7770 : : static bool
7771 : 1300 : apply_typmod_special(Numeric num, int32 typmod, Node *escontext)
7772 : : {
7773 : : int precision;
7774 : : int scale;
7775 : :
7776 : : Assert(NUMERIC_IS_SPECIAL(num)); /* caller error if not */
7777 : :
7778 : : /*
7779 : : * NaN is allowed regardless of the typmod; that's rather dubious perhaps,
7780 : : * but it's a longstanding behavior. Inf is rejected if we have any
7781 : : * typmod restriction, since an infinity shouldn't be claimed to fit in
7782 : : * any finite number of digits.
7783 : : */
7784 [ + + ]: 1300 : if (NUMERIC_IS_NAN(num))
7785 : 557 : return true;
7786 : :
7787 : : /* Do nothing if we have a default typmod (-1) */
7788 [ + + ]: 743 : if (!is_valid_numeric_typmod(typmod))
7789 : 731 : return true;
7790 : :
7791 : 12 : precision = numeric_typmod_precision(typmod);
7792 : 12 : scale = numeric_typmod_scale(typmod);
7793 : :
7794 [ + - ]: 12 : ereturn(escontext, false,
7795 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7796 : : errmsg("numeric field overflow"),
7797 : : errdetail("A field with precision %d, scale %d cannot hold an infinite value.",
7798 : : precision, scale)));
7799 : : }
7800 : :
7801 : :
7802 : : /*
7803 : : * Convert numeric to int8, rounding if needed.
7804 : : *
7805 : : * If overflow, return false (no error is raised). Return true if okay.
7806 : : */
7807 : : static bool
7808 : 6716 : numericvar_to_int64(const NumericVar *var, int64 *result)
7809 : : {
7810 : : NumericDigit *digits;
7811 : : int ndigits;
7812 : : int weight;
7813 : : int i;
7814 : : int64 val;
7815 : : bool neg;
7816 : : NumericVar rounded;
7817 : :
7818 : : /* Round to nearest integer */
7819 : 6716 : init_var(&rounded);
7820 : 6716 : set_var_from_var(var, &rounded);
7821 : 6716 : round_var(&rounded, 0);
7822 : :
7823 : : /* Check for zero input */
7824 : 6716 : strip_var(&rounded);
7825 : 6716 : ndigits = rounded.ndigits;
7826 [ + + ]: 6716 : if (ndigits == 0)
7827 : : {
7828 : 348 : *result = 0;
7829 : 348 : free_var(&rounded);
7830 : 348 : return true;
7831 : : }
7832 : :
7833 : : /*
7834 : : * For input like 10000000000, we must treat stripped digits as real. So
7835 : : * the loop assumes there are weight+1 digits before the decimal point.
7836 : : */
7837 : 6368 : weight = rounded.weight;
7838 : : Assert(weight >= 0 && ndigits <= weight + 1);
7839 : :
7840 : : /*
7841 : : * Construct the result. To avoid issues with converting a value
7842 : : * corresponding to INT64_MIN (which can't be represented as a positive 64
7843 : : * bit two's complement integer), accumulate value as a negative number.
7844 : : */
7845 : 6368 : digits = rounded.digits;
7846 : 6368 : neg = (rounded.sign == NUMERIC_NEG);
7847 : 6368 : val = -digits[0];
7848 [ + + ]: 8896 : for (i = 1; i <= weight; i++)
7849 : : {
7850 [ + + ]: 2561 : if (unlikely(pg_mul_s64_overflow(val, NBASE, &val)))
7851 : : {
7852 : 21 : free_var(&rounded);
7853 : 21 : return false;
7854 : : }
7855 : :
7856 [ + + ]: 2540 : if (i < ndigits)
7857 : : {
7858 [ + + ]: 2331 : if (unlikely(pg_sub_s64_overflow(val, digits[i], &val)))
7859 : : {
7860 : 12 : free_var(&rounded);
7861 : 12 : return false;
7862 : : }
7863 : : }
7864 : : }
7865 : :
7866 : 6335 : free_var(&rounded);
7867 : :
7868 [ + + ]: 6335 : if (!neg)
7869 : : {
7870 [ + + ]: 5785 : if (unlikely(pg_neg_s64_overflow(val, &val)))
7871 : 16 : return false;
7872 : : }
7873 : 6319 : *result = val;
7874 : :
7875 : 6319 : return true;
7876 : : }
7877 : :
7878 : : /*
7879 : : * Convert int8 value to numeric.
7880 : : */
7881 : : static void
7882 : 1262450 : int64_to_numericvar(int64 val, NumericVar *var)
7883 : : {
7884 : : uint64 uval,
7885 : : newuval;
7886 : : NumericDigit *ptr;
7887 : : int ndigits;
7888 : :
7889 : : /* int64 can require at most 19 decimal digits; add one for safety */
7890 : 1262450 : alloc_var(var, 20 / DEC_DIGITS);
7891 [ + + ]: 1262450 : if (val < 0)
7892 : : {
7893 : 1263 : var->sign = NUMERIC_NEG;
7894 : 1263 : uval = pg_abs_s64(val);
7895 : : }
7896 : : else
7897 : : {
7898 : 1261187 : var->sign = NUMERIC_POS;
7899 : 1261187 : uval = val;
7900 : : }
7901 : 1262450 : var->dscale = 0;
7902 [ + + ]: 1262450 : if (val == 0)
7903 : : {
7904 : 19381 : var->ndigits = 0;
7905 : 19381 : var->weight = 0;
7906 : 19381 : return;
7907 : : }
7908 : 1243069 : ptr = var->digits + var->ndigits;
7909 : 1243069 : ndigits = 0;
7910 : : do
7911 : : {
7912 : 1440611 : ptr--;
7913 : 1440611 : ndigits++;
7914 : 1440611 : newuval = uval / NBASE;
7915 : 1440611 : *ptr = uval - newuval * NBASE;
7916 : 1440611 : uval = newuval;
7917 [ + + ]: 1440611 : } while (uval);
7918 : 1243069 : var->digits = ptr;
7919 : 1243069 : var->ndigits = ndigits;
7920 : 1243069 : var->weight = ndigits - 1;
7921 : : }
7922 : :
7923 : : /*
7924 : : * Convert numeric to uint64, rounding if needed.
7925 : : *
7926 : : * If overflow, return false (no error is raised). Return true if okay.
7927 : : */
7928 : : static bool
7929 : 101 : numericvar_to_uint64(const NumericVar *var, uint64 *result)
7930 : : {
7931 : : NumericDigit *digits;
7932 : : int ndigits;
7933 : : int weight;
7934 : : int i;
7935 : : uint64 val;
7936 : : NumericVar rounded;
7937 : :
7938 : : /* Round to nearest integer */
7939 : 101 : init_var(&rounded);
7940 : 101 : set_var_from_var(var, &rounded);
7941 : 101 : round_var(&rounded, 0);
7942 : :
7943 : : /* Check for zero input */
7944 : 101 : strip_var(&rounded);
7945 : 101 : ndigits = rounded.ndigits;
7946 [ + + ]: 101 : if (ndigits == 0)
7947 : : {
7948 : 15 : *result = 0;
7949 : 15 : free_var(&rounded);
7950 : 15 : return true;
7951 : : }
7952 : :
7953 : : /* Check for negative input */
7954 [ + + ]: 86 : if (rounded.sign == NUMERIC_NEG)
7955 : : {
7956 : 8 : free_var(&rounded);
7957 : 8 : return false;
7958 : : }
7959 : :
7960 : : /*
7961 : : * For input like 10000000000, we must treat stripped digits as real. So
7962 : : * the loop assumes there are weight+1 digits before the decimal point.
7963 : : */
7964 : 78 : weight = rounded.weight;
7965 : : Assert(weight >= 0 && ndigits <= weight + 1);
7966 : :
7967 : : /* Construct the result */
7968 : 78 : digits = rounded.digits;
7969 : 78 : val = digits[0];
7970 [ + + ]: 220 : for (i = 1; i <= weight; i++)
7971 : : {
7972 [ - + ]: 150 : if (unlikely(pg_mul_u64_overflow(val, NBASE, &val)))
7973 : : {
7974 : 0 : free_var(&rounded);
7975 : 0 : return false;
7976 : : }
7977 : :
7978 [ + - ]: 150 : if (i < ndigits)
7979 : : {
7980 [ + + ]: 150 : if (unlikely(pg_add_u64_overflow(val, digits[i], &val)))
7981 : : {
7982 : 8 : free_var(&rounded);
7983 : 8 : return false;
7984 : : }
7985 : : }
7986 : : }
7987 : :
7988 : 70 : free_var(&rounded);
7989 : :
7990 : 70 : *result = val;
7991 : :
7992 : 70 : return true;
7993 : : }
7994 : :
7995 : : /*
7996 : : * Convert 128 bit integer to numeric.
7997 : : */
7998 : : static void
7999 : 6281 : int128_to_numericvar(INT128 val, NumericVar *var)
8000 : : {
8001 : : int sign;
8002 : : NumericDigit *ptr;
8003 : : int ndigits;
8004 : : int32 dig;
8005 : :
8006 : : /* int128 can require at most 39 decimal digits; add one for safety */
8007 : 6281 : alloc_var(var, 40 / DEC_DIGITS);
8008 : 6281 : sign = int128_sign(val);
8009 : 6281 : var->sign = sign < 0 ? NUMERIC_NEG : NUMERIC_POS;
8010 : 6281 : var->dscale = 0;
8011 [ + + ]: 6281 : if (sign == 0)
8012 : : {
8013 : 136 : var->ndigits = 0;
8014 : 136 : var->weight = 0;
8015 : 136 : return;
8016 : : }
8017 : 6145 : ptr = var->digits + var->ndigits;
8018 : 6145 : ndigits = 0;
8019 : : do
8020 : : {
8021 : 33051 : ptr--;
8022 : 33051 : ndigits++;
8023 : 33051 : int128_div_mod_int32(&val, NBASE, &dig);
8024 : 33051 : *ptr = (NumericDigit) abs(dig);
8025 [ + + ]: 33051 : } while (!int128_is_zero(val));
8026 : 6145 : var->digits = ptr;
8027 : 6145 : var->ndigits = ndigits;
8028 : 6145 : var->weight = ndigits - 1;
8029 : : }
8030 : :
8031 : : /*
8032 : : * Convert a NumericVar to float8; if out of range, return +/- HUGE_VAL
8033 : : */
8034 : : static double
8035 : 361 : numericvar_to_double_no_overflow(const NumericVar *var)
8036 : : {
8037 : : char *tmp;
8038 : : double val;
8039 : : char *endptr;
8040 : :
8041 : 361 : tmp = get_str_from_var(var);
8042 : :
8043 : : /* unlike float8in, we ignore ERANGE from strtod */
8044 : 361 : val = strtod(tmp, &endptr);
8045 [ - + ]: 361 : if (*endptr != '\0')
8046 : : {
8047 : : /* shouldn't happen ... */
8048 [ # # ]: 0 : ereport(ERROR,
8049 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
8050 : : errmsg("invalid input syntax for type %s: \"%s\"",
8051 : : "double precision", tmp)));
8052 : : }
8053 : :
8054 : 361 : pfree(tmp);
8055 : :
8056 : 361 : return val;
8057 : : }
8058 : :
8059 : :
8060 : : /*
8061 : : * cmp_var() -
8062 : : *
8063 : : * Compare two values on variable level. We assume zeroes have been
8064 : : * truncated to no digits.
8065 : : */
8066 : : static int
8067 : 114439 : cmp_var(const NumericVar *var1, const NumericVar *var2)
8068 : : {
8069 : 228878 : return cmp_var_common(var1->digits, var1->ndigits,
8070 : 114439 : var1->weight, var1->sign,
8071 : 114439 : var2->digits, var2->ndigits,
8072 : 114439 : var2->weight, var2->sign);
8073 : : }
8074 : :
8075 : : /*
8076 : : * cmp_var_common() -
8077 : : *
8078 : : * Main routine of cmp_var(). This function can be used by both
8079 : : * NumericVar and Numeric.
8080 : : */
8081 : : static int
8082 : 18504543 : cmp_var_common(const NumericDigit *var1digits, int var1ndigits,
8083 : : int var1weight, int var1sign,
8084 : : const NumericDigit *var2digits, int var2ndigits,
8085 : : int var2weight, int var2sign)
8086 : : {
8087 [ + + ]: 18504543 : if (var1ndigits == 0)
8088 : : {
8089 [ + + ]: 423920 : if (var2ndigits == 0)
8090 : 334668 : return 0;
8091 [ + + ]: 89252 : if (var2sign == NUMERIC_NEG)
8092 : 470 : return 1;
8093 : 88782 : return -1;
8094 : : }
8095 [ + + ]: 18080623 : if (var2ndigits == 0)
8096 : : {
8097 [ + + ]: 70107 : if (var1sign == NUMERIC_POS)
8098 : 64283 : return 1;
8099 : 5824 : return -1;
8100 : : }
8101 : :
8102 [ + + ]: 18010516 : if (var1sign == NUMERIC_POS)
8103 : : {
8104 [ + + ]: 17961977 : if (var2sign == NUMERIC_NEG)
8105 : 15974 : return 1;
8106 : 17946003 : return cmp_abs_common(var1digits, var1ndigits, var1weight,
8107 : : var2digits, var2ndigits, var2weight);
8108 : : }
8109 : :
8110 [ + + ]: 48539 : if (var2sign == NUMERIC_POS)
8111 : 13378 : return -1;
8112 : :
8113 : 35161 : return cmp_abs_common(var2digits, var2ndigits, var2weight,
8114 : : var1digits, var1ndigits, var1weight);
8115 : : }
8116 : :
8117 : :
8118 : : /*
8119 : : * add_var() -
8120 : : *
8121 : : * Full version of add functionality on variable level (handling signs).
8122 : : * result might point to one of the operands too without danger.
8123 : : */
8124 : : static void
8125 : 414497 : add_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
8126 : : {
8127 : : /*
8128 : : * Decide on the signs of the two variables what to do
8129 : : */
8130 [ + + ]: 414497 : if (var1->sign == NUMERIC_POS)
8131 : : {
8132 [ + + ]: 413242 : if (var2->sign == NUMERIC_POS)
8133 : : {
8134 : : /*
8135 : : * Both are positive result = +(ABS(var1) + ABS(var2))
8136 : : */
8137 : 279647 : add_abs(var1, var2, result);
8138 : 279647 : result->sign = NUMERIC_POS;
8139 : : }
8140 : : else
8141 : : {
8142 : : /*
8143 : : * var1 is positive, var2 is negative Must compare absolute values
8144 : : */
8145 [ + + + - ]: 133595 : switch (cmp_abs(var1, var2))
8146 : : {
8147 : 147 : case 0:
8148 : : /* ----------
8149 : : * ABS(var1) == ABS(var2)
8150 : : * result = ZERO
8151 : : * ----------
8152 : : */
8153 : 147 : zero_var(result);
8154 : 147 : result->dscale = Max(var1->dscale, var2->dscale);
8155 : 147 : break;
8156 : :
8157 : 124237 : case 1:
8158 : : /* ----------
8159 : : * ABS(var1) > ABS(var2)
8160 : : * result = +(ABS(var1) - ABS(var2))
8161 : : * ----------
8162 : : */
8163 : 124237 : sub_abs(var1, var2, result);
8164 : 124237 : result->sign = NUMERIC_POS;
8165 : 124237 : break;
8166 : :
8167 : 9211 : case -1:
8168 : : /* ----------
8169 : : * ABS(var1) < ABS(var2)
8170 : : * result = -(ABS(var2) - ABS(var1))
8171 : : * ----------
8172 : : */
8173 : 9211 : sub_abs(var2, var1, result);
8174 : 9211 : result->sign = NUMERIC_NEG;
8175 : 9211 : break;
8176 : : }
8177 : : }
8178 : : }
8179 : : else
8180 : : {
8181 [ + + ]: 1255 : if (var2->sign == NUMERIC_POS)
8182 : : {
8183 : : /* ----------
8184 : : * var1 is negative, var2 is positive
8185 : : * Must compare absolute values
8186 : : * ----------
8187 : : */
8188 [ + + + - ]: 318 : switch (cmp_abs(var1, var2))
8189 : : {
8190 : 20 : case 0:
8191 : : /* ----------
8192 : : * ABS(var1) == ABS(var2)
8193 : : * result = ZERO
8194 : : * ----------
8195 : : */
8196 : 20 : zero_var(result);
8197 : 20 : result->dscale = Max(var1->dscale, var2->dscale);
8198 : 20 : break;
8199 : :
8200 : 197 : case 1:
8201 : : /* ----------
8202 : : * ABS(var1) > ABS(var2)
8203 : : * result = -(ABS(var1) - ABS(var2))
8204 : : * ----------
8205 : : */
8206 : 197 : sub_abs(var1, var2, result);
8207 : 197 : result->sign = NUMERIC_NEG;
8208 : 197 : break;
8209 : :
8210 : 101 : case -1:
8211 : : /* ----------
8212 : : * ABS(var1) < ABS(var2)
8213 : : * result = +(ABS(var2) - ABS(var1))
8214 : : * ----------
8215 : : */
8216 : 101 : sub_abs(var2, var1, result);
8217 : 101 : result->sign = NUMERIC_POS;
8218 : 101 : break;
8219 : : }
8220 : : }
8221 : : else
8222 : : {
8223 : : /* ----------
8224 : : * Both are negative
8225 : : * result = -(ABS(var1) + ABS(var2))
8226 : : * ----------
8227 : : */
8228 : 937 : add_abs(var1, var2, result);
8229 : 937 : result->sign = NUMERIC_NEG;
8230 : : }
8231 : : }
8232 : 414497 : }
8233 : :
8234 : :
8235 : : /*
8236 : : * sub_var() -
8237 : : *
8238 : : * Full version of sub functionality on variable level (handling signs).
8239 : : * result might point to one of the operands too without danger.
8240 : : */
8241 : : static void
8242 : 351388 : sub_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
8243 : : {
8244 : : /*
8245 : : * Decide on the signs of the two variables what to do
8246 : : */
8247 [ + + ]: 351388 : if (var1->sign == NUMERIC_POS)
8248 : : {
8249 [ + + ]: 350779 : if (var2->sign == NUMERIC_NEG)
8250 : : {
8251 : : /* ----------
8252 : : * var1 is positive, var2 is negative
8253 : : * result = +(ABS(var1) + ABS(var2))
8254 : : * ----------
8255 : : */
8256 : 18759 : add_abs(var1, var2, result);
8257 : 18759 : result->sign = NUMERIC_POS;
8258 : : }
8259 : : else
8260 : : {
8261 : : /* ----------
8262 : : * Both are positive
8263 : : * Must compare absolute values
8264 : : * ----------
8265 : : */
8266 [ + + + - ]: 332020 : switch (cmp_abs(var1, var2))
8267 : : {
8268 : 29772 : case 0:
8269 : : /* ----------
8270 : : * ABS(var1) == ABS(var2)
8271 : : * result = ZERO
8272 : : * ----------
8273 : : */
8274 : 29772 : zero_var(result);
8275 : 29772 : result->dscale = Max(var1->dscale, var2->dscale);
8276 : 29772 : break;
8277 : :
8278 : 295743 : case 1:
8279 : : /* ----------
8280 : : * ABS(var1) > ABS(var2)
8281 : : * result = +(ABS(var1) - ABS(var2))
8282 : : * ----------
8283 : : */
8284 : 295743 : sub_abs(var1, var2, result);
8285 : 295743 : result->sign = NUMERIC_POS;
8286 : 295743 : break;
8287 : :
8288 : 6505 : case -1:
8289 : : /* ----------
8290 : : * ABS(var1) < ABS(var2)
8291 : : * result = -(ABS(var2) - ABS(var1))
8292 : : * ----------
8293 : : */
8294 : 6505 : sub_abs(var2, var1, result);
8295 : 6505 : result->sign = NUMERIC_NEG;
8296 : 6505 : break;
8297 : : }
8298 : : }
8299 : : }
8300 : : else
8301 : : {
8302 [ + + ]: 609 : if (var2->sign == NUMERIC_NEG)
8303 : : {
8304 : : /* ----------
8305 : : * Both are negative
8306 : : * Must compare absolute values
8307 : : * ----------
8308 : : */
8309 [ + + + - ]: 304 : switch (cmp_abs(var1, var2))
8310 : : {
8311 : 110 : case 0:
8312 : : /* ----------
8313 : : * ABS(var1) == ABS(var2)
8314 : : * result = ZERO
8315 : : * ----------
8316 : : */
8317 : 110 : zero_var(result);
8318 : 110 : result->dscale = Max(var1->dscale, var2->dscale);
8319 : 110 : break;
8320 : :
8321 : 162 : case 1:
8322 : : /* ----------
8323 : : * ABS(var1) > ABS(var2)
8324 : : * result = -(ABS(var1) - ABS(var2))
8325 : : * ----------
8326 : : */
8327 : 162 : sub_abs(var1, var2, result);
8328 : 162 : result->sign = NUMERIC_NEG;
8329 : 162 : break;
8330 : :
8331 : 32 : case -1:
8332 : : /* ----------
8333 : : * ABS(var1) < ABS(var2)
8334 : : * result = +(ABS(var2) - ABS(var1))
8335 : : * ----------
8336 : : */
8337 : 32 : sub_abs(var2, var1, result);
8338 : 32 : result->sign = NUMERIC_POS;
8339 : 32 : break;
8340 : : }
8341 : : }
8342 : : else
8343 : : {
8344 : : /* ----------
8345 : : * var1 is negative, var2 is positive
8346 : : * result = -(ABS(var1) + ABS(var2))
8347 : : * ----------
8348 : : */
8349 : 305 : add_abs(var1, var2, result);
8350 : 305 : result->sign = NUMERIC_NEG;
8351 : : }
8352 : : }
8353 : 351388 : }
8354 : :
8355 : :
8356 : : /*
8357 : : * mul_var() -
8358 : : *
8359 : : * Multiplication on variable level. Product of var1 * var2 is stored
8360 : : * in result. Result is rounded to no more than rscale fractional digits.
8361 : : */
8362 : : static void
8363 : 795653 : mul_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result,
8364 : : int rscale)
8365 : : {
8366 : : int res_ndigits;
8367 : : int res_ndigitpairs;
8368 : : int res_sign;
8369 : : int res_weight;
8370 : : int pair_offset;
8371 : : int maxdigits;
8372 : : int maxdigitpairs;
8373 : : uint64 *dig,
8374 : : *dig_i1_off;
8375 : : uint64 maxdig;
8376 : : uint64 carry;
8377 : : uint64 newdig;
8378 : : int var1ndigits;
8379 : : int var2ndigits;
8380 : : int var1ndigitpairs;
8381 : : int var2ndigitpairs;
8382 : : NumericDigit *var1digits;
8383 : : NumericDigit *var2digits;
8384 : : uint32 var1digitpair;
8385 : : uint32 *var2digitpairs;
8386 : : NumericDigit *res_digits;
8387 : : int i,
8388 : : i1,
8389 : : i2,
8390 : : i2limit;
8391 : :
8392 : : /*
8393 : : * Arrange for var1 to be the shorter of the two numbers. This improves
8394 : : * performance because the inner multiplication loop is much simpler than
8395 : : * the outer loop, so it's better to have a smaller number of iterations
8396 : : * of the outer loop. This also reduces the number of times that the
8397 : : * accumulator array needs to be normalized.
8398 : : */
8399 [ + + ]: 795653 : if (var1->ndigits > var2->ndigits)
8400 : : {
8401 : 10418 : const NumericVar *tmp = var1;
8402 : :
8403 : 10418 : var1 = var2;
8404 : 10418 : var2 = tmp;
8405 : : }
8406 : :
8407 : : /* copy these values into local vars for speed in inner loop */
8408 : 795653 : var1ndigits = var1->ndigits;
8409 : 795653 : var2ndigits = var2->ndigits;
8410 : 795653 : var1digits = var1->digits;
8411 : 795653 : var2digits = var2->digits;
8412 : :
8413 [ + + ]: 795653 : if (var1ndigits == 0)
8414 : : {
8415 : : /* one or both inputs is zero; so is result */
8416 : 1959 : zero_var(result);
8417 : 1959 : result->dscale = rscale;
8418 : 1959 : return;
8419 : : }
8420 : :
8421 : : /*
8422 : : * If var1 has 1-6 digits and the exact result was requested, delegate to
8423 : : * mul_var_short() which uses a faster direct multiplication algorithm.
8424 : : */
8425 [ + + + + ]: 793694 : if (var1ndigits <= 6 && rscale == var1->dscale + var2->dscale)
8426 : : {
8427 : 773025 : mul_var_short(var1, var2, result);
8428 : 773025 : return;
8429 : : }
8430 : :
8431 : : /* Determine result sign */
8432 [ + + ]: 20669 : if (var1->sign == var2->sign)
8433 : 19390 : res_sign = NUMERIC_POS;
8434 : : else
8435 : 1279 : res_sign = NUMERIC_NEG;
8436 : :
8437 : : /*
8438 : : * Determine the number of result digits to compute and the (maximum
8439 : : * possible) result weight. If the exact result would have more than
8440 : : * rscale fractional digits, truncate the computation with
8441 : : * MUL_GUARD_DIGITS guard digits, i.e., ignore input digits that would
8442 : : * only contribute to the right of that. (This will give the exact
8443 : : * rounded-to-rscale answer unless carries out of the ignored positions
8444 : : * would have propagated through more than MUL_GUARD_DIGITS digits.)
8445 : : *
8446 : : * Note: an exact computation could not produce more than var1ndigits +
8447 : : * var2ndigits digits, but we allocate at least one extra output digit in
8448 : : * case rscale-driven rounding produces a carry out of the highest exact
8449 : : * digit.
8450 : : *
8451 : : * The computation itself is done using base-NBASE^2 arithmetic, so we
8452 : : * actually process the input digits in pairs, producing a base-NBASE^2
8453 : : * intermediate result. This significantly improves performance, since
8454 : : * schoolbook multiplication is O(N^2) in the number of input digits, and
8455 : : * working in base NBASE^2 effectively halves "N".
8456 : : *
8457 : : * Note: in a truncated computation, we must compute at least one extra
8458 : : * output digit to ensure that all the guard digits are fully computed.
8459 : : */
8460 : : /* digit pairs in each input */
8461 : 20669 : var1ndigitpairs = (var1ndigits + 1) / 2;
8462 : 20669 : var2ndigitpairs = (var2ndigits + 1) / 2;
8463 : :
8464 : : /* digits in exact result */
8465 : 20669 : res_ndigits = var1ndigits + var2ndigits;
8466 : :
8467 : : /* digit pairs in exact result with at least one extra output digit */
8468 : 20669 : res_ndigitpairs = res_ndigits / 2 + 1;
8469 : :
8470 : : /* pair offset to align result to end of dig[] */
8471 : 20669 : pair_offset = res_ndigitpairs - var1ndigitpairs - var2ndigitpairs + 1;
8472 : :
8473 : : /* maximum possible result weight (odd-length inputs shifted up below) */
8474 : 20669 : res_weight = var1->weight + var2->weight + 1 + 2 * res_ndigitpairs -
8475 : 20669 : res_ndigits - (var1ndigits & 1) - (var2ndigits & 1);
8476 : :
8477 : : /* rscale-based truncation with at least one extra output digit */
8478 : 20669 : maxdigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS +
8479 : : MUL_GUARD_DIGITS;
8480 : 20669 : maxdigitpairs = maxdigits / 2 + 1;
8481 : :
8482 : 20669 : res_ndigitpairs = Min(res_ndigitpairs, maxdigitpairs);
8483 : 20669 : res_ndigits = 2 * res_ndigitpairs;
8484 : :
8485 : : /*
8486 : : * In the computation below, digit pair i1 of var1 and digit pair i2 of
8487 : : * var2 are multiplied and added to digit i1+i2+pair_offset of dig[]. Thus
8488 : : * input digit pairs with index >= res_ndigitpairs - pair_offset don't
8489 : : * contribute to the result, and can be ignored.
8490 : : */
8491 [ + + ]: 20669 : if (res_ndigitpairs <= pair_offset)
8492 : : {
8493 : : /* All input digits will be ignored; so result is zero */
8494 : 10 : zero_var(result);
8495 : 10 : result->dscale = rscale;
8496 : 10 : return;
8497 : : }
8498 : 20659 : var1ndigitpairs = Min(var1ndigitpairs, res_ndigitpairs - pair_offset);
8499 : 20659 : var2ndigitpairs = Min(var2ndigitpairs, res_ndigitpairs - pair_offset);
8500 : :
8501 : : /*
8502 : : * We do the arithmetic in an array "dig[]" of unsigned 64-bit integers.
8503 : : * Since PG_UINT64_MAX is much larger than NBASE^4, this gives us a lot of
8504 : : * headroom to avoid normalizing carries immediately.
8505 : : *
8506 : : * maxdig tracks the maximum possible value of any dig[] entry; when this
8507 : : * threatens to exceed PG_UINT64_MAX, we take the time to propagate
8508 : : * carries. Furthermore, we need to ensure that overflow doesn't occur
8509 : : * during the carry propagation passes either. The carry values could be
8510 : : * as much as PG_UINT64_MAX / NBASE^2, so really we must normalize when
8511 : : * digits threaten to exceed PG_UINT64_MAX - PG_UINT64_MAX / NBASE^2.
8512 : : *
8513 : : * To avoid overflow in maxdig itself, it actually represents the maximum
8514 : : * possible value divided by NBASE^2-1, i.e., at the top of the loop it is
8515 : : * known that no dig[] entry exceeds maxdig * (NBASE^2-1).
8516 : : *
8517 : : * The conversion of var1 to base NBASE^2 is done on the fly, as each new
8518 : : * digit is required. The digits of var2 are converted upfront, and
8519 : : * stored at the end of dig[]. To avoid loss of precision, the input
8520 : : * digits are aligned with the start of digit pair array, effectively
8521 : : * shifting them up (multiplying by NBASE) if the inputs have an odd
8522 : : * number of NBASE digits.
8523 : : */
8524 : 20659 : dig = (uint64 *) palloc(res_ndigitpairs * sizeof(uint64) +
8525 : : var2ndigitpairs * sizeof(uint32));
8526 : :
8527 : : /* convert var2 to base NBASE^2, shifting up if its length is odd */
8528 : 20659 : var2digitpairs = (uint32 *) (dig + res_ndigitpairs);
8529 : :
8530 [ + + ]: 1048389 : for (i2 = 0; i2 < var2ndigitpairs - 1; i2++)
8531 : 1027730 : var2digitpairs[i2] = var2digits[2 * i2] * NBASE + var2digits[2 * i2 + 1];
8532 : :
8533 [ + + ]: 20659 : if (2 * i2 + 1 < var2ndigits)
8534 : 14659 : var2digitpairs[i2] = var2digits[2 * i2] * NBASE + var2digits[2 * i2 + 1];
8535 : : else
8536 : 6000 : var2digitpairs[i2] = var2digits[2 * i2] * NBASE;
8537 : :
8538 : : /*
8539 : : * Start by multiplying var2 by the least significant contributing digit
8540 : : * pair from var1, storing the results at the end of dig[], and filling
8541 : : * the leading digits with zeros.
8542 : : *
8543 : : * The loop here is the same as the inner loop below, except that we set
8544 : : * the results in dig[], rather than adding to them. This is the
8545 : : * performance bottleneck for multiplication, so we want to keep it simple
8546 : : * enough so that it can be auto-vectorized. Accordingly, process the
8547 : : * digits left-to-right even though schoolbook multiplication would
8548 : : * suggest right-to-left. Since we aren't propagating carries in this
8549 : : * loop, the order does not matter.
8550 : : */
8551 : 20659 : i1 = var1ndigitpairs - 1;
8552 [ + + ]: 20659 : if (2 * i1 + 1 < var1ndigits)
8553 : 9183 : var1digitpair = var1digits[2 * i1] * NBASE + var1digits[2 * i1 + 1];
8554 : : else
8555 : 11476 : var1digitpair = var1digits[2 * i1] * NBASE;
8556 : 20659 : maxdig = var1digitpair;
8557 : :
8558 : 20659 : i2limit = Min(var2ndigitpairs, res_ndigitpairs - i1 - pair_offset);
8559 : 20659 : dig_i1_off = &dig[i1 + pair_offset];
8560 : :
8561 : 20659 : memset(dig, 0, (i1 + pair_offset) * sizeof(uint64));
8562 [ + + ]: 930539 : for (i2 = 0; i2 < i2limit; i2++)
8563 : 909880 : dig_i1_off[i2] = (uint64) var1digitpair * var2digitpairs[i2];
8564 : :
8565 : : /*
8566 : : * Next, multiply var2 by the remaining digit pairs from var1, adding the
8567 : : * results to dig[] at the appropriate offsets, and normalizing whenever
8568 : : * there is a risk of any dig[] entry overflowing.
8569 : : */
8570 [ + + ]: 1012436 : for (i1 = i1 - 1; i1 >= 0; i1--)
8571 : : {
8572 : 991777 : var1digitpair = var1digits[2 * i1] * NBASE + var1digits[2 * i1 + 1];
8573 [ + + ]: 991777 : if (var1digitpair == 0)
8574 : 786344 : continue;
8575 : :
8576 : : /* Time to normalize? */
8577 : 205433 : maxdig += var1digitpair;
8578 [ + + ]: 205433 : if (maxdig > (PG_UINT64_MAX - PG_UINT64_MAX / NBASE_SQR) / (NBASE_SQR - 1))
8579 : : {
8580 : : /* Yes, do it (to base NBASE^2) */
8581 : 21 : carry = 0;
8582 [ + + ]: 84074 : for (i = res_ndigitpairs - 1; i >= 0; i--)
8583 : : {
8584 : 84053 : newdig = dig[i] + carry;
8585 [ + + ]: 84053 : if (newdig >= NBASE_SQR)
8586 : : {
8587 : 80719 : carry = newdig / NBASE_SQR;
8588 : 80719 : newdig -= carry * NBASE_SQR;
8589 : : }
8590 : : else
8591 : 3334 : carry = 0;
8592 : 84053 : dig[i] = newdig;
8593 : : }
8594 : : Assert(carry == 0);
8595 : : /* Reset maxdig to indicate new worst-case */
8596 : 21 : maxdig = 1 + var1digitpair;
8597 : : }
8598 : :
8599 : : /* Multiply and add */
8600 : 205433 : i2limit = Min(var2ndigitpairs, res_ndigitpairs - i1 - pair_offset);
8601 : 205433 : dig_i1_off = &dig[i1 + pair_offset];
8602 : :
8603 [ + + ]: 87005259 : for (i2 = 0; i2 < i2limit; i2++)
8604 : 86799826 : dig_i1_off[i2] += (uint64) var1digitpair * var2digitpairs[i2];
8605 : : }
8606 : :
8607 : : /*
8608 : : * Now we do a final carry propagation pass to normalize back to base
8609 : : * NBASE^2, and construct the base-NBASE result digits. Note that this is
8610 : : * still done at full precision w/guard digits.
8611 : : */
8612 : 20659 : alloc_var(result, res_ndigits);
8613 : 20659 : res_digits = result->digits;
8614 : 20659 : carry = 0;
8615 [ + + ]: 1946324 : for (i = res_ndigitpairs - 1; i >= 0; i--)
8616 : : {
8617 : 1925665 : newdig = dig[i] + carry;
8618 [ + + ]: 1925665 : if (newdig >= NBASE_SQR)
8619 : : {
8620 : 290140 : carry = newdig / NBASE_SQR;
8621 : 290140 : newdig -= carry * NBASE_SQR;
8622 : : }
8623 : : else
8624 : 1635525 : carry = 0;
8625 : 1925665 : res_digits[2 * i + 1] = (NumericDigit) ((uint32) newdig % NBASE);
8626 : 1925665 : res_digits[2 * i] = (NumericDigit) ((uint32) newdig / NBASE);
8627 : : }
8628 : : Assert(carry == 0);
8629 : :
8630 : 20659 : pfree(dig);
8631 : :
8632 : : /*
8633 : : * Finally, round the result to the requested precision.
8634 : : */
8635 : 20659 : result->weight = res_weight;
8636 : 20659 : result->sign = res_sign;
8637 : :
8638 : : /* Round to target rscale (and set result->dscale) */
8639 : 20659 : round_var(result, rscale);
8640 : :
8641 : : /* Strip leading and trailing zeroes */
8642 : 20659 : strip_var(result);
8643 : : }
8644 : :
8645 : :
8646 : : /*
8647 : : * mul_var_short() -
8648 : : *
8649 : : * Special-case multiplication function used when var1 has 1-6 digits, var2
8650 : : * has at least as many digits as var1, and the exact product var1 * var2 is
8651 : : * requested.
8652 : : */
8653 : : static void
8654 : 773025 : mul_var_short(const NumericVar *var1, const NumericVar *var2,
8655 : : NumericVar *result)
8656 : : {
8657 : 773025 : int var1ndigits = var1->ndigits;
8658 : 773025 : int var2ndigits = var2->ndigits;
8659 : 773025 : NumericDigit *var1digits = var1->digits;
8660 : 773025 : NumericDigit *var2digits = var2->digits;
8661 : : int res_sign;
8662 : : int res_weight;
8663 : : int res_ndigits;
8664 : : NumericDigit *res_buf;
8665 : : NumericDigit *res_digits;
8666 : 773025 : uint32 carry = 0;
8667 : : uint32 term;
8668 : :
8669 : : /* Check preconditions */
8670 : : Assert(var1ndigits >= 1);
8671 : : Assert(var1ndigits <= 6);
8672 : : Assert(var2ndigits >= var1ndigits);
8673 : :
8674 : : /*
8675 : : * Determine the result sign, weight, and number of digits to calculate.
8676 : : * The weight figured here is correct if the product has no leading zero
8677 : : * digits; otherwise strip_var() will fix things up. Note that, unlike
8678 : : * mul_var(), we do not need to allocate an extra output digit, because we
8679 : : * are not rounding here.
8680 : : */
8681 [ + + ]: 773025 : if (var1->sign == var2->sign)
8682 : 772218 : res_sign = NUMERIC_POS;
8683 : : else
8684 : 807 : res_sign = NUMERIC_NEG;
8685 : 773025 : res_weight = var1->weight + var2->weight + 1;
8686 : 773025 : res_ndigits = var1ndigits + var2ndigits;
8687 : :
8688 : : /* Allocate result digit array */
8689 : 773025 : res_buf = digitbuf_alloc(res_ndigits + 1);
8690 : 773025 : res_buf[0] = 0; /* spare digit for later rounding */
8691 : 773025 : res_digits = res_buf + 1;
8692 : :
8693 : : /*
8694 : : * Compute the result digits in reverse, in one pass, propagating the
8695 : : * carry up as we go. The i'th result digit consists of the sum of the
8696 : : * products var1digits[i1] * var2digits[i2] for which i = i1 + i2 + 1.
8697 : : */
8698 : : #define PRODSUM1(v1,i1,v2,i2) ((v1)[(i1)] * (v2)[(i2)])
8699 : : #define PRODSUM2(v1,i1,v2,i2) (PRODSUM1(v1,i1,v2,i2) + (v1)[(i1)+1] * (v2)[(i2)-1])
8700 : : #define PRODSUM3(v1,i1,v2,i2) (PRODSUM2(v1,i1,v2,i2) + (v1)[(i1)+2] * (v2)[(i2)-2])
8701 : : #define PRODSUM4(v1,i1,v2,i2) (PRODSUM3(v1,i1,v2,i2) + (v1)[(i1)+3] * (v2)[(i2)-3])
8702 : : #define PRODSUM5(v1,i1,v2,i2) (PRODSUM4(v1,i1,v2,i2) + (v1)[(i1)+4] * (v2)[(i2)-4])
8703 : : #define PRODSUM6(v1,i1,v2,i2) (PRODSUM5(v1,i1,v2,i2) + (v1)[(i1)+5] * (v2)[(i2)-5])
8704 : :
8705 [ + + + + : 773025 : switch (var1ndigits)
+ + - ]
8706 : : {
8707 : 768880 : case 1:
8708 : : /* ---------
8709 : : * 1-digit case:
8710 : : * var1ndigits = 1
8711 : : * var2ndigits >= 1
8712 : : * res_ndigits = var2ndigits + 1
8713 : : * ----------
8714 : : */
8715 [ + + ]: 2406354 : for (int i = var2ndigits - 1; i >= 0; i--)
8716 : : {
8717 : 1637474 : term = PRODSUM1(var1digits, 0, var2digits, i) + carry;
8718 : 1637474 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8719 : 1637474 : carry = term / NBASE;
8720 : : }
8721 : 768880 : res_digits[0] = (NumericDigit) carry;
8722 : 768880 : break;
8723 : :
8724 : 519 : case 2:
8725 : : /* ---------
8726 : : * 2-digit case:
8727 : : * var1ndigits = 2
8728 : : * var2ndigits >= 2
8729 : : * res_ndigits = var2ndigits + 2
8730 : : * ----------
8731 : : */
8732 : : /* last result digit and carry */
8733 : 519 : term = PRODSUM1(var1digits, 1, var2digits, var2ndigits - 1);
8734 : 519 : res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
8735 : 519 : carry = term / NBASE;
8736 : :
8737 : : /* remaining digits, except for the first two */
8738 [ + + ]: 1573 : for (int i = var2ndigits - 1; i >= 1; i--)
8739 : : {
8740 : 1054 : term = PRODSUM2(var1digits, 0, var2digits, i) + carry;
8741 : 1054 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8742 : 1054 : carry = term / NBASE;
8743 : : }
8744 : 519 : break;
8745 : :
8746 : 146 : case 3:
8747 : : /* ---------
8748 : : * 3-digit case:
8749 : : * var1ndigits = 3
8750 : : * var2ndigits >= 3
8751 : : * res_ndigits = var2ndigits + 3
8752 : : * ----------
8753 : : */
8754 : : /* last two result digits */
8755 : 146 : term = PRODSUM1(var1digits, 2, var2digits, var2ndigits - 1);
8756 : 146 : res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
8757 : 146 : carry = term / NBASE;
8758 : :
8759 : 146 : term = PRODSUM2(var1digits, 1, var2digits, var2ndigits - 1) + carry;
8760 : 146 : res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
8761 : 146 : carry = term / NBASE;
8762 : :
8763 : : /* remaining digits, except for the first three */
8764 [ + + ]: 387 : for (int i = var2ndigits - 1; i >= 2; i--)
8765 : : {
8766 : 241 : term = PRODSUM3(var1digits, 0, var2digits, i) + carry;
8767 : 241 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8768 : 241 : carry = term / NBASE;
8769 : : }
8770 : 146 : break;
8771 : :
8772 : 2888 : case 4:
8773 : : /* ---------
8774 : : * 4-digit case:
8775 : : * var1ndigits = 4
8776 : : * var2ndigits >= 4
8777 : : * res_ndigits = var2ndigits + 4
8778 : : * ----------
8779 : : */
8780 : : /* last three result digits */
8781 : 2888 : term = PRODSUM1(var1digits, 3, var2digits, var2ndigits - 1);
8782 : 2888 : res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
8783 : 2888 : carry = term / NBASE;
8784 : :
8785 : 2888 : term = PRODSUM2(var1digits, 2, var2digits, var2ndigits - 1) + carry;
8786 : 2888 : res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
8787 : 2888 : carry = term / NBASE;
8788 : :
8789 : 2888 : term = PRODSUM3(var1digits, 1, var2digits, var2ndigits - 1) + carry;
8790 : 2888 : res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
8791 : 2888 : carry = term / NBASE;
8792 : :
8793 : : /* remaining digits, except for the first four */
8794 [ + + ]: 8058 : for (int i = var2ndigits - 1; i >= 3; i--)
8795 : : {
8796 : 5170 : term = PRODSUM4(var1digits, 0, var2digits, i) + carry;
8797 : 5170 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8798 : 5170 : carry = term / NBASE;
8799 : : }
8800 : 2888 : break;
8801 : :
8802 : 91 : case 5:
8803 : : /* ---------
8804 : : * 5-digit case:
8805 : : * var1ndigits = 5
8806 : : * var2ndigits >= 5
8807 : : * res_ndigits = var2ndigits + 5
8808 : : * ----------
8809 : : */
8810 : : /* last four result digits */
8811 : 91 : term = PRODSUM1(var1digits, 4, var2digits, var2ndigits - 1);
8812 : 91 : res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
8813 : 91 : carry = term / NBASE;
8814 : :
8815 : 91 : term = PRODSUM2(var1digits, 3, var2digits, var2ndigits - 1) + carry;
8816 : 91 : res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
8817 : 91 : carry = term / NBASE;
8818 : :
8819 : 91 : term = PRODSUM3(var1digits, 2, var2digits, var2ndigits - 1) + carry;
8820 : 91 : res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
8821 : 91 : carry = term / NBASE;
8822 : :
8823 : 91 : term = PRODSUM4(var1digits, 1, var2digits, var2ndigits - 1) + carry;
8824 : 91 : res_digits[res_ndigits - 4] = (NumericDigit) (term % NBASE);
8825 : 91 : carry = term / NBASE;
8826 : :
8827 : : /* remaining digits, except for the first five */
8828 [ + + ]: 242 : for (int i = var2ndigits - 1; i >= 4; i--)
8829 : : {
8830 : 151 : term = PRODSUM5(var1digits, 0, var2digits, i) + carry;
8831 : 151 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8832 : 151 : carry = term / NBASE;
8833 : : }
8834 : 91 : break;
8835 : :
8836 : 501 : case 6:
8837 : : /* ---------
8838 : : * 6-digit case:
8839 : : * var1ndigits = 6
8840 : : * var2ndigits >= 6
8841 : : * res_ndigits = var2ndigits + 6
8842 : : * ----------
8843 : : */
8844 : : /* last five result digits */
8845 : 501 : term = PRODSUM1(var1digits, 5, var2digits, var2ndigits - 1);
8846 : 501 : res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
8847 : 501 : carry = term / NBASE;
8848 : :
8849 : 501 : term = PRODSUM2(var1digits, 4, var2digits, var2ndigits - 1) + carry;
8850 : 501 : res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
8851 : 501 : carry = term / NBASE;
8852 : :
8853 : 501 : term = PRODSUM3(var1digits, 3, var2digits, var2ndigits - 1) + carry;
8854 : 501 : res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
8855 : 501 : carry = term / NBASE;
8856 : :
8857 : 501 : term = PRODSUM4(var1digits, 2, var2digits, var2ndigits - 1) + carry;
8858 : 501 : res_digits[res_ndigits - 4] = (NumericDigit) (term % NBASE);
8859 : 501 : carry = term / NBASE;
8860 : :
8861 : 501 : term = PRODSUM5(var1digits, 1, var2digits, var2ndigits - 1) + carry;
8862 : 501 : res_digits[res_ndigits - 5] = (NumericDigit) (term % NBASE);
8863 : 501 : carry = term / NBASE;
8864 : :
8865 : : /* remaining digits, except for the first six */
8866 [ + + ]: 1400 : for (int i = var2ndigits - 1; i >= 5; i--)
8867 : : {
8868 : 899 : term = PRODSUM6(var1digits, 0, var2digits, i) + carry;
8869 : 899 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8870 : 899 : carry = term / NBASE;
8871 : : }
8872 : 501 : break;
8873 : : }
8874 : :
8875 : : /*
8876 : : * Finally, for var1ndigits > 1, compute the remaining var1ndigits most
8877 : : * significant result digits.
8878 : : */
8879 [ + + + + : 773025 : switch (var1ndigits)
+ + ]
8880 : : {
8881 : 501 : case 6:
8882 : 501 : term = PRODSUM5(var1digits, 0, var2digits, 4) + carry;
8883 : 501 : res_digits[5] = (NumericDigit) (term % NBASE);
8884 : 501 : carry = term / NBASE;
8885 : : pg_fallthrough;
8886 : 592 : case 5:
8887 : 592 : term = PRODSUM4(var1digits, 0, var2digits, 3) + carry;
8888 : 592 : res_digits[4] = (NumericDigit) (term % NBASE);
8889 : 592 : carry = term / NBASE;
8890 : : pg_fallthrough;
8891 : 3480 : case 4:
8892 : 3480 : term = PRODSUM3(var1digits, 0, var2digits, 2) + carry;
8893 : 3480 : res_digits[3] = (NumericDigit) (term % NBASE);
8894 : 3480 : carry = term / NBASE;
8895 : : pg_fallthrough;
8896 : 3626 : case 3:
8897 : 3626 : term = PRODSUM2(var1digits, 0, var2digits, 1) + carry;
8898 : 3626 : res_digits[2] = (NumericDigit) (term % NBASE);
8899 : 3626 : carry = term / NBASE;
8900 : : pg_fallthrough;
8901 : 4145 : case 2:
8902 : 4145 : term = PRODSUM1(var1digits, 0, var2digits, 0) + carry;
8903 : 4145 : res_digits[1] = (NumericDigit) (term % NBASE);
8904 : 4145 : res_digits[0] = (NumericDigit) (term / NBASE);
8905 : 4145 : break;
8906 : : }
8907 : :
8908 : : /* Store the product in result */
8909 [ + + ]: 773025 : digitbuf_free(result->buf);
8910 : 773025 : result->ndigits = res_ndigits;
8911 : 773025 : result->buf = res_buf;
8912 : 773025 : result->digits = res_digits;
8913 : 773025 : result->weight = res_weight;
8914 : 773025 : result->sign = res_sign;
8915 : 773025 : result->dscale = var1->dscale + var2->dscale;
8916 : :
8917 : : /* Strip leading and trailing zeroes */
8918 : 773025 : strip_var(result);
8919 : 773025 : }
8920 : :
8921 : :
8922 : : /*
8923 : : * div_var() -
8924 : : *
8925 : : * Compute the quotient var1 / var2 to rscale fractional digits.
8926 : : *
8927 : : * If "round" is true, the result is rounded at the rscale'th digit; if
8928 : : * false, it is truncated (towards zero) at that digit.
8929 : : *
8930 : : * If "exact" is true, the exact result is computed to the specified rscale;
8931 : : * if false, successive quotient digits are approximated up to rscale plus
8932 : : * DIV_GUARD_DIGITS extra digits, ignoring all contributions from digits to
8933 : : * the right of that, before rounding or truncating to the specified rscale.
8934 : : * This can be significantly faster, and usually gives the same result as the
8935 : : * exact computation, but it may occasionally be off by one in the final
8936 : : * digit, if contributions from the ignored digits would have propagated
8937 : : * through the guard digits. This is good enough for the transcendental
8938 : : * functions, where small errors are acceptable.
8939 : : */
8940 : : static void
8941 : 380419 : div_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result,
8942 : : int rscale, bool round, bool exact)
8943 : : {
8944 : 380419 : int var1ndigits = var1->ndigits;
8945 : 380419 : int var2ndigits = var2->ndigits;
8946 : : int res_sign;
8947 : : int res_weight;
8948 : : int res_ndigits;
8949 : : int var1ndigitpairs;
8950 : : int var2ndigitpairs;
8951 : : int res_ndigitpairs;
8952 : : int div_ndigitpairs;
8953 : : int64 *dividend;
8954 : : int32 *divisor;
8955 : : double fdivisor,
8956 : : fdivisorinverse,
8957 : : fdividend,
8958 : : fquotient;
8959 : : int64 maxdiv;
8960 : : int qi;
8961 : : int32 qdigit;
8962 : : int64 carry;
8963 : : int64 newdig;
8964 : : int64 *remainder;
8965 : : NumericDigit *res_digits;
8966 : : int i;
8967 : :
8968 : : /*
8969 : : * First of all division by zero check; we must not be handed an
8970 : : * unnormalized divisor.
8971 : : */
8972 [ + + - + ]: 380419 : if (var2ndigits == 0 || var2->digits[0] == 0)
8973 [ + - ]: 8 : ereport(ERROR,
8974 : : (errcode(ERRCODE_DIVISION_BY_ZERO),
8975 : : errmsg("division by zero")));
8976 : :
8977 : : /*
8978 : : * If the divisor has just one or two digits, delegate to div_var_int(),
8979 : : * which uses fast short division.
8980 : : *
8981 : : * Similarly, on platforms with 128-bit integer support, delegate to
8982 : : * div_var_int64() for divisors with three or four digits.
8983 : : */
8984 [ + + ]: 380411 : if (var2ndigits <= 2)
8985 : : {
8986 : : int idivisor;
8987 : : int idivisor_weight;
8988 : :
8989 : 376059 : idivisor = var2->digits[0];
8990 : 376059 : idivisor_weight = var2->weight;
8991 [ + + ]: 376059 : if (var2ndigits == 2)
8992 : : {
8993 : 2263 : idivisor = idivisor * NBASE + var2->digits[1];
8994 : 2263 : idivisor_weight--;
8995 : : }
8996 [ + + ]: 376059 : if (var2->sign == NUMERIC_NEG)
8997 : 440 : idivisor = -idivisor;
8998 : :
8999 : 376059 : div_var_int(var1, idivisor, idivisor_weight, result, rscale, round);
9000 : 376059 : return;
9001 : : }
9002 : : #ifdef HAVE_INT128
9003 [ + + ]: 4352 : if (var2ndigits <= 4)
9004 : : {
9005 : : int64 idivisor;
9006 : : int idivisor_weight;
9007 : :
9008 : 360 : idivisor = var2->digits[0];
9009 : 360 : idivisor_weight = var2->weight;
9010 [ + + ]: 1340 : for (i = 1; i < var2ndigits; i++)
9011 : : {
9012 : 980 : idivisor = idivisor * NBASE + var2->digits[i];
9013 : 980 : idivisor_weight--;
9014 : : }
9015 [ + + ]: 360 : if (var2->sign == NUMERIC_NEG)
9016 : 80 : idivisor = -idivisor;
9017 : :
9018 : 360 : div_var_int64(var1, idivisor, idivisor_weight, result, rscale, round);
9019 : 360 : return;
9020 : : }
9021 : : #endif
9022 : :
9023 : : /*
9024 : : * Otherwise, perform full long division.
9025 : : */
9026 : :
9027 : : /* Result zero check */
9028 [ + + ]: 3992 : if (var1ndigits == 0)
9029 : : {
9030 : 24 : zero_var(result);
9031 : 24 : result->dscale = rscale;
9032 : 24 : return;
9033 : : }
9034 : :
9035 : : /*
9036 : : * The approximate computation can be significantly faster than the exact
9037 : : * one, since the working dividend is var2ndigitpairs base-NBASE^2 digits
9038 : : * shorter below. However, that comes with the tradeoff of computing
9039 : : * DIV_GUARD_DIGITS extra base-NBASE result digits. Ignoring all other
9040 : : * overheads, that suggests that, in theory, the approximate computation
9041 : : * will only be faster than the exact one when var2ndigits is greater than
9042 : : * 2 * (DIV_GUARD_DIGITS + 1), independent of the size of var1.
9043 : : *
9044 : : * Thus, we're better off doing an exact computation when var2 is shorter
9045 : : * than this. Empirically, it has been found that the exact threshold is
9046 : : * a little higher, due to other overheads in the outer division loop.
9047 : : */
9048 [ + + ]: 3968 : if (var2ndigits <= 2 * (DIV_GUARD_DIGITS + 2))
9049 : 2712 : exact = true;
9050 : :
9051 : : /*
9052 : : * Determine the result sign, weight and number of digits to calculate.
9053 : : * The weight figured here is correct if the emitted quotient has no
9054 : : * leading zero digits; otherwise strip_var() will fix things up.
9055 : : */
9056 [ + + ]: 3968 : if (var1->sign == var2->sign)
9057 : 3866 : res_sign = NUMERIC_POS;
9058 : : else
9059 : 102 : res_sign = NUMERIC_NEG;
9060 : 3968 : res_weight = var1->weight - var2->weight + 1;
9061 : : /* The number of accurate result digits we need to produce: */
9062 : 3968 : res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
9063 : : /* ... but always at least 1 */
9064 : 3968 : res_ndigits = Max(res_ndigits, 1);
9065 : : /* If rounding needed, figure one more digit to ensure correct result */
9066 [ + + ]: 3968 : if (round)
9067 : 658 : res_ndigits++;
9068 : : /* Add guard digits for roundoff error when producing approx result */
9069 [ + + ]: 3968 : if (!exact)
9070 : 1246 : res_ndigits += DIV_GUARD_DIGITS;
9071 : :
9072 : : /*
9073 : : * The computation itself is done using base-NBASE^2 arithmetic, so we
9074 : : * actually process the input digits in pairs, producing a base-NBASE^2
9075 : : * intermediate result. This significantly improves performance, since
9076 : : * the computation is O(N^2) in the number of input digits, and working in
9077 : : * base NBASE^2 effectively halves "N".
9078 : : */
9079 : 3968 : var1ndigitpairs = (var1ndigits + 1) / 2;
9080 : 3968 : var2ndigitpairs = (var2ndigits + 1) / 2;
9081 : 3968 : res_ndigitpairs = (res_ndigits + 1) / 2;
9082 : 3968 : res_ndigits = 2 * res_ndigitpairs;
9083 : :
9084 : : /*
9085 : : * We do the arithmetic in an array "dividend[]" of signed 64-bit
9086 : : * integers. Since PG_INT64_MAX is much larger than NBASE^4, this gives
9087 : : * us a lot of headroom to avoid normalizing carries immediately.
9088 : : *
9089 : : * When performing an exact computation, the working dividend requires
9090 : : * res_ndigitpairs + var2ndigitpairs digits. If var1 is larger than that,
9091 : : * the extra digits do not contribute to the result, and are ignored.
9092 : : *
9093 : : * When performing an approximate computation, the working dividend only
9094 : : * requires res_ndigitpairs digits (which includes the extra guard
9095 : : * digits). All input digits beyond that are ignored.
9096 : : */
9097 [ + + ]: 3968 : if (exact)
9098 : : {
9099 : 2722 : div_ndigitpairs = res_ndigitpairs + var2ndigitpairs;
9100 : 2722 : var1ndigitpairs = Min(var1ndigitpairs, div_ndigitpairs);
9101 : : }
9102 : : else
9103 : : {
9104 : 1246 : div_ndigitpairs = res_ndigitpairs;
9105 : 1246 : var1ndigitpairs = Min(var1ndigitpairs, div_ndigitpairs);
9106 : 1246 : var2ndigitpairs = Min(var2ndigitpairs, div_ndigitpairs);
9107 : : }
9108 : :
9109 : : /*
9110 : : * Allocate room for the working dividend (div_ndigitpairs 64-bit digits)
9111 : : * plus the divisor (var2ndigitpairs 32-bit base-NBASE^2 digits).
9112 : : *
9113 : : * For convenience, we allocate one extra dividend digit, which is set to
9114 : : * zero and not counted in div_ndigitpairs, so that the main loop below
9115 : : * can safely read and write the (qi+1)'th digit in the approximate case.
9116 : : */
9117 : 3968 : dividend = (int64 *) palloc((div_ndigitpairs + 1) * sizeof(int64) +
9118 : : var2ndigitpairs * sizeof(int32));
9119 : 3968 : divisor = (int32 *) (dividend + div_ndigitpairs + 1);
9120 : :
9121 : : /* load var1 into dividend[0 .. var1ndigitpairs-1], zeroing the rest */
9122 [ + + ]: 37128 : for (i = 0; i < var1ndigitpairs - 1; i++)
9123 : 33160 : dividend[i] = var1->digits[2 * i] * NBASE + var1->digits[2 * i + 1];
9124 : :
9125 [ + + ]: 3968 : if (2 * i + 1 < var1ndigits)
9126 : 2341 : dividend[i] = var1->digits[2 * i] * NBASE + var1->digits[2 * i + 1];
9127 : : else
9128 : 1627 : dividend[i] = var1->digits[2 * i] * NBASE;
9129 : :
9130 : 3968 : memset(dividend + i + 1, 0, (div_ndigitpairs - i) * sizeof(int64));
9131 : :
9132 : : /* load var2 into divisor[0 .. var2ndigitpairs-1] */
9133 [ + + ]: 29424 : for (i = 0; i < var2ndigitpairs - 1; i++)
9134 : 25456 : divisor[i] = var2->digits[2 * i] * NBASE + var2->digits[2 * i + 1];
9135 : :
9136 [ + + ]: 3968 : if (2 * i + 1 < var2ndigits)
9137 : 2138 : divisor[i] = var2->digits[2 * i] * NBASE + var2->digits[2 * i + 1];
9138 : : else
9139 : 1830 : divisor[i] = var2->digits[2 * i] * NBASE;
9140 : :
9141 : : /*
9142 : : * We estimate each quotient digit using floating-point arithmetic, taking
9143 : : * the first 2 base-NBASE^2 digits of the (current) dividend and divisor.
9144 : : * This must be float to avoid overflow.
9145 : : *
9146 : : * Since the floating-point dividend and divisor use 4 base-NBASE input
9147 : : * digits, they include roughly 40-53 bits of information from their
9148 : : * respective inputs (assuming NBASE is 10000), which fits well in IEEE
9149 : : * double-precision variables. The relative error in the floating-point
9150 : : * quotient digit will then be less than around 2/NBASE^3, so the
9151 : : * estimated base-NBASE^2 quotient digit will typically be correct, and
9152 : : * should not be off by more than one from the correct value.
9153 : : */
9154 : 3968 : fdivisor = (double) divisor[0] * NBASE_SQR;
9155 [ + - ]: 3968 : if (var2ndigitpairs > 1)
9156 : 3968 : fdivisor += (double) divisor[1];
9157 : 3968 : fdivisorinverse = 1.0 / fdivisor;
9158 : :
9159 : : /*
9160 : : * maxdiv tracks the maximum possible absolute value of any dividend[]
9161 : : * entry; when this threatens to exceed PG_INT64_MAX, we take the time to
9162 : : * propagate carries. Furthermore, we need to ensure that overflow
9163 : : * doesn't occur during the carry propagation passes either. The carry
9164 : : * values may have an absolute value as high as PG_INT64_MAX/NBASE^2 + 1,
9165 : : * so really we must normalize when digits threaten to exceed PG_INT64_MAX
9166 : : * - PG_INT64_MAX/NBASE^2 - 1.
9167 : : *
9168 : : * To avoid overflow in maxdiv itself, it represents the max absolute
9169 : : * value divided by NBASE^2-1, i.e., at the top of the loop it is known
9170 : : * that no dividend[] entry has an absolute value exceeding maxdiv *
9171 : : * (NBASE^2-1).
9172 : : *
9173 : : * Actually, though, that holds good only for dividend[] entries after
9174 : : * dividend[qi]; the adjustment done at the bottom of the loop may cause
9175 : : * dividend[qi + 1] to exceed the maxdiv limit, so that dividend[qi] in
9176 : : * the next iteration is beyond the limit. This does not cause problems,
9177 : : * as explained below.
9178 : : */
9179 : 3968 : maxdiv = 1;
9180 : :
9181 : : /*
9182 : : * Outer loop computes next quotient digit, which goes in dividend[qi].
9183 : : */
9184 [ + + ]: 36464 : for (qi = 0; qi < res_ndigitpairs; qi++)
9185 : : {
9186 : : /* Approximate the current dividend value */
9187 : 32496 : fdividend = (double) dividend[qi] * NBASE_SQR;
9188 : 32496 : fdividend += (double) dividend[qi + 1];
9189 : :
9190 : : /* Compute the (approximate) quotient digit */
9191 : 32496 : fquotient = fdividend * fdivisorinverse;
9192 [ + + ]: 32496 : qdigit = (fquotient >= 0.0) ? ((int32) fquotient) :
9193 : 5 : (((int32) fquotient) - 1); /* truncate towards -infinity */
9194 : :
9195 [ + + ]: 32496 : if (qdigit != 0)
9196 : : {
9197 : : /* Do we need to normalize now? */
9198 : 29863 : maxdiv += i64abs(qdigit);
9199 [ + + ]: 29863 : if (maxdiv > (PG_INT64_MAX - PG_INT64_MAX / NBASE_SQR - 1) / (NBASE_SQR - 1))
9200 : : {
9201 : : /*
9202 : : * Yes, do it. Note that if var2ndigitpairs is much smaller
9203 : : * than div_ndigitpairs, we can save a significant amount of
9204 : : * effort here by noting that we only need to normalise those
9205 : : * dividend[] entries touched where prior iterations
9206 : : * subtracted multiples of the divisor.
9207 : : */
9208 : 5 : carry = 0;
9209 [ + + ]: 5625 : for (i = Min(qi + var2ndigitpairs - 2, div_ndigitpairs - 1); i > qi; i--)
9210 : : {
9211 : 5620 : newdig = dividend[i] + carry;
9212 [ + - ]: 5620 : if (newdig < 0)
9213 : : {
9214 : 5620 : carry = -((-newdig - 1) / NBASE_SQR) - 1;
9215 : 5620 : newdig -= carry * NBASE_SQR;
9216 : : }
9217 [ # # ]: 0 : else if (newdig >= NBASE_SQR)
9218 : : {
9219 : 0 : carry = newdig / NBASE_SQR;
9220 : 0 : newdig -= carry * NBASE_SQR;
9221 : : }
9222 : : else
9223 : 0 : carry = 0;
9224 : 5620 : dividend[i] = newdig;
9225 : : }
9226 : 5 : dividend[qi] += carry;
9227 : :
9228 : : /*
9229 : : * All the dividend[] digits except possibly dividend[qi] are
9230 : : * now in the range 0..NBASE^2-1. We do not need to consider
9231 : : * dividend[qi] in the maxdiv value anymore, so we can reset
9232 : : * maxdiv to 1.
9233 : : */
9234 : 5 : maxdiv = 1;
9235 : :
9236 : : /*
9237 : : * Recompute the quotient digit since new info may have
9238 : : * propagated into the top two dividend digits.
9239 : : */
9240 : 5 : fdividend = (double) dividend[qi] * NBASE_SQR;
9241 : 5 : fdividend += (double) dividend[qi + 1];
9242 : 5 : fquotient = fdividend * fdivisorinverse;
9243 [ + - ]: 5 : qdigit = (fquotient >= 0.0) ? ((int32) fquotient) :
9244 : 0 : (((int32) fquotient) - 1); /* truncate towards -infinity */
9245 : :
9246 : 5 : maxdiv += i64abs(qdigit);
9247 : : }
9248 : :
9249 : : /*
9250 : : * Subtract off the appropriate multiple of the divisor.
9251 : : *
9252 : : * The digits beyond dividend[qi] cannot overflow, because we know
9253 : : * they will fall within the maxdiv limit. As for dividend[qi]
9254 : : * itself, note that qdigit is approximately trunc(dividend[qi] /
9255 : : * divisor[0]), which would make the new value simply dividend[qi]
9256 : : * mod divisor[0]. The lower-order terms in qdigit can change
9257 : : * this result by not more than about twice PG_INT64_MAX/NBASE^2,
9258 : : * so overflow is impossible.
9259 : : *
9260 : : * This inner loop is the performance bottleneck for division, so
9261 : : * code it in the same way as the inner loop of mul_var() so that
9262 : : * it can be auto-vectorized.
9263 : : */
9264 [ + - ]: 29863 : if (qdigit != 0)
9265 : : {
9266 : 29863 : int istop = Min(var2ndigitpairs, div_ndigitpairs - qi);
9267 : 29863 : int64 *dividend_qi = ÷nd[qi];
9268 : :
9269 [ + + ]: 6518873 : for (i = 0; i < istop; i++)
9270 : 6489010 : dividend_qi[i] -= (int64) qdigit * divisor[i];
9271 : : }
9272 : : }
9273 : :
9274 : : /*
9275 : : * The dividend digit we are about to replace might still be nonzero.
9276 : : * Fold it into the next digit position.
9277 : : *
9278 : : * There is no risk of overflow here, although proving that requires
9279 : : * some care. Much as with the argument for dividend[qi] not
9280 : : * overflowing, if we consider the first two terms in the numerator
9281 : : * and denominator of qdigit, we can see that the final value of
9282 : : * dividend[qi + 1] will be approximately a remainder mod
9283 : : * (divisor[0]*NBASE^2 + divisor[1]). Accounting for the lower-order
9284 : : * terms is a bit complicated but ends up adding not much more than
9285 : : * PG_INT64_MAX/NBASE^2 to the possible range. Thus, dividend[qi + 1]
9286 : : * cannot overflow here, and in its role as dividend[qi] in the next
9287 : : * loop iteration, it can't be large enough to cause overflow in the
9288 : : * carry propagation step (if any), either.
9289 : : *
9290 : : * But having said that: dividend[qi] can be more than
9291 : : * PG_INT64_MAX/NBASE^2, as noted above, which means that the product
9292 : : * dividend[qi] * NBASE^2 *can* overflow. When that happens, adding
9293 : : * it to dividend[qi + 1] will always cause a canceling overflow so
9294 : : * that the end result is correct. We could avoid the intermediate
9295 : : * overflow by doing the multiplication and addition using unsigned
9296 : : * int64 arithmetic, which is modulo 2^64, but so far there appears no
9297 : : * need.
9298 : : */
9299 : 32496 : dividend[qi + 1] += dividend[qi] * NBASE_SQR;
9300 : :
9301 : 32496 : dividend[qi] = qdigit;
9302 : : }
9303 : :
9304 : : /*
9305 : : * If an exact result was requested, use the remainder to correct the
9306 : : * approximate quotient. The remainder is in dividend[], immediately
9307 : : * after the quotient digits. Note, however, that although the remainder
9308 : : * starts at dividend[qi = res_ndigitpairs], the first digit is the result
9309 : : * of folding two remainder digits into one above, and the remainder
9310 : : * currently only occupies var2ndigitpairs - 1 digits (the last digit of
9311 : : * the working dividend was untouched by the computation above). Thus we
9312 : : * expand the remainder down by one base-NBASE^2 digit when we normalize
9313 : : * it, so that it completely fills the last var2ndigitpairs digits of the
9314 : : * dividend array.
9315 : : */
9316 [ + + ]: 3968 : if (exact)
9317 : : {
9318 : : /* Normalize the remainder, expanding it down by one digit */
9319 : 2722 : remainder = ÷nd[qi];
9320 : 2722 : carry = 0;
9321 [ + + ]: 15518 : for (i = var2ndigitpairs - 2; i >= 0; i--)
9322 : : {
9323 : 12796 : newdig = remainder[i] + carry;
9324 [ + + ]: 12796 : if (newdig < 0)
9325 : : {
9326 : 10044 : carry = -((-newdig - 1) / NBASE_SQR) - 1;
9327 : 10044 : newdig -= carry * NBASE_SQR;
9328 : : }
9329 [ + + ]: 2752 : else if (newdig >= NBASE_SQR)
9330 : : {
9331 : 2696 : carry = newdig / NBASE_SQR;
9332 : 2696 : newdig -= carry * NBASE_SQR;
9333 : : }
9334 : : else
9335 : 56 : carry = 0;
9336 : 12796 : remainder[i + 1] = newdig;
9337 : : }
9338 : 2722 : remainder[0] = carry;
9339 : :
9340 [ + + ]: 2722 : if (remainder[0] < 0)
9341 : : {
9342 : : /*
9343 : : * The remainder is negative, so the approximate quotient is too
9344 : : * large. Correct by reducing the quotient by one and adding the
9345 : : * divisor to the remainder until the remainder is positive. We
9346 : : * expect the quotient to be off by at most one, which has been
9347 : : * borne out in all testing, but not conclusively proven, so we
9348 : : * allow for larger corrections, just in case.
9349 : : */
9350 : : do
9351 : : {
9352 : : /* Add the divisor to the remainder */
9353 : 5 : carry = 0;
9354 [ + + ]: 65 : for (i = var2ndigitpairs - 1; i > 0; i--)
9355 : : {
9356 : 60 : newdig = remainder[i] + divisor[i] + carry;
9357 [ - + ]: 60 : if (newdig >= NBASE_SQR)
9358 : : {
9359 : 0 : remainder[i] = newdig - NBASE_SQR;
9360 : 0 : carry = 1;
9361 : : }
9362 : : else
9363 : : {
9364 : 60 : remainder[i] = newdig;
9365 : 60 : carry = 0;
9366 : : }
9367 : : }
9368 : 5 : remainder[0] += divisor[0] + carry;
9369 : :
9370 : : /* Subtract 1 from the quotient (propagating carries later) */
9371 : 5 : dividend[qi - 1]--;
9372 : :
9373 [ - + ]: 5 : } while (remainder[0] < 0);
9374 : : }
9375 : : else
9376 : : {
9377 : : /*
9378 : : * The remainder is nonnegative. If it's greater than or equal to
9379 : : * the divisor, then the approximate quotient is too small and
9380 : : * must be corrected. As above, we don't expect to have to apply
9381 : : * more than one correction, but allow for it just in case.
9382 : : */
9383 : : while (true)
9384 : 5 : {
9385 : 2722 : bool less = false;
9386 : :
9387 : : /* Is remainder < divisor? */
9388 [ + + ]: 2737 : for (i = 0; i < var2ndigitpairs; i++)
9389 : : {
9390 [ + + ]: 2732 : if (remainder[i] < divisor[i])
9391 : : {
9392 : 2717 : less = true;
9393 : 2717 : break;
9394 : : }
9395 [ - + ]: 15 : if (remainder[i] > divisor[i])
9396 : 0 : break; /* remainder > divisor */
9397 : : }
9398 [ + + ]: 2722 : if (less)
9399 : 2717 : break; /* quotient is correct */
9400 : :
9401 : : /* Subtract the divisor from the remainder */
9402 : 5 : carry = 0;
9403 [ + + ]: 15 : for (i = var2ndigitpairs - 1; i > 0; i--)
9404 : : {
9405 : 10 : newdig = remainder[i] - divisor[i] + carry;
9406 [ - + ]: 10 : if (newdig < 0)
9407 : : {
9408 : 0 : remainder[i] = newdig + NBASE_SQR;
9409 : 0 : carry = -1;
9410 : : }
9411 : : else
9412 : : {
9413 : 10 : remainder[i] = newdig;
9414 : 10 : carry = 0;
9415 : : }
9416 : : }
9417 : 5 : remainder[0] = remainder[0] - divisor[0] + carry;
9418 : :
9419 : : /* Add 1 to the quotient (propagating carries later) */
9420 : 5 : dividend[qi - 1]++;
9421 : : }
9422 : : }
9423 : : }
9424 : :
9425 : : /*
9426 : : * Because the quotient digits were estimates that might have been off by
9427 : : * one (and we didn't bother propagating carries when adjusting the
9428 : : * quotient above), some quotient digits might be out of range, so do a
9429 : : * final carry propagation pass to normalize back to base NBASE^2, and
9430 : : * construct the base-NBASE result digits. Note that this is still done
9431 : : * at full precision w/guard digits.
9432 : : */
9433 : 3968 : alloc_var(result, res_ndigits);
9434 : 3968 : res_digits = result->digits;
9435 : 3968 : carry = 0;
9436 [ + + ]: 36464 : for (i = res_ndigitpairs - 1; i >= 0; i--)
9437 : : {
9438 : 32496 : newdig = dividend[i] + carry;
9439 [ + + ]: 32496 : if (newdig < 0)
9440 : : {
9441 : 5 : carry = -((-newdig - 1) / NBASE_SQR) - 1;
9442 : 5 : newdig -= carry * NBASE_SQR;
9443 : : }
9444 [ - + ]: 32491 : else if (newdig >= NBASE_SQR)
9445 : : {
9446 : 0 : carry = newdig / NBASE_SQR;
9447 : 0 : newdig -= carry * NBASE_SQR;
9448 : : }
9449 : : else
9450 : 32491 : carry = 0;
9451 : 32496 : res_digits[2 * i + 1] = (NumericDigit) ((uint32) newdig % NBASE);
9452 : 32496 : res_digits[2 * i] = (NumericDigit) ((uint32) newdig / NBASE);
9453 : : }
9454 : : Assert(carry == 0);
9455 : :
9456 : 3968 : pfree(dividend);
9457 : :
9458 : : /*
9459 : : * Finally, round or truncate the result to the requested precision.
9460 : : */
9461 : 3968 : result->weight = res_weight;
9462 : 3968 : result->sign = res_sign;
9463 : :
9464 : : /* Round or truncate to target rscale (and set result->dscale) */
9465 [ + + ]: 3968 : if (round)
9466 : 658 : round_var(result, rscale);
9467 : : else
9468 : 3310 : trunc_var(result, rscale);
9469 : :
9470 : : /* Strip leading and trailing zeroes */
9471 : 3968 : strip_var(result);
9472 : : }
9473 : :
9474 : :
9475 : : /*
9476 : : * div_var_int() -
9477 : : *
9478 : : * Divide a numeric variable by a 32-bit integer with the specified weight.
9479 : : * The quotient var / (ival * NBASE^ival_weight) is stored in result.
9480 : : */
9481 : : static void
9482 : 389817 : div_var_int(const NumericVar *var, int ival, int ival_weight,
9483 : : NumericVar *result, int rscale, bool round)
9484 : : {
9485 : 389817 : NumericDigit *var_digits = var->digits;
9486 : 389817 : int var_ndigits = var->ndigits;
9487 : : int res_sign;
9488 : : int res_weight;
9489 : : int res_ndigits;
9490 : : NumericDigit *res_buf;
9491 : : NumericDigit *res_digits;
9492 : : uint32 divisor;
9493 : : int i;
9494 : :
9495 : : /* Guard against division by zero */
9496 [ - + ]: 389817 : if (ival == 0)
9497 [ # # ]: 0 : ereport(ERROR,
9498 : : errcode(ERRCODE_DIVISION_BY_ZERO),
9499 : : errmsg("division by zero"));
9500 : :
9501 : : /* Result zero check */
9502 [ + + ]: 389817 : if (var_ndigits == 0)
9503 : : {
9504 : 1583 : zero_var(result);
9505 : 1583 : result->dscale = rscale;
9506 : 1583 : return;
9507 : : }
9508 : :
9509 : : /*
9510 : : * Determine the result sign, weight and number of digits to calculate.
9511 : : * The weight figured here is correct if the emitted quotient has no
9512 : : * leading zero digits; otherwise strip_var() will fix things up.
9513 : : */
9514 [ + + ]: 388234 : if (var->sign == NUMERIC_POS)
9515 [ + + ]: 385990 : res_sign = ival > 0 ? NUMERIC_POS : NUMERIC_NEG;
9516 : : else
9517 [ + + ]: 2244 : res_sign = ival > 0 ? NUMERIC_NEG : NUMERIC_POS;
9518 : 388234 : res_weight = var->weight - ival_weight;
9519 : : /* The number of accurate result digits we need to produce: */
9520 : 388234 : res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
9521 : : /* ... but always at least 1 */
9522 : 388234 : res_ndigits = Max(res_ndigits, 1);
9523 : : /* If rounding needed, figure one more digit to ensure correct result */
9524 [ + + ]: 388234 : if (round)
9525 : 111705 : res_ndigits++;
9526 : :
9527 : 388234 : res_buf = digitbuf_alloc(res_ndigits + 1);
9528 : 388234 : res_buf[0] = 0; /* spare digit for later rounding */
9529 : 388234 : res_digits = res_buf + 1;
9530 : :
9531 : : /*
9532 : : * Now compute the quotient digits. This is the short division algorithm
9533 : : * described in Knuth volume 2, section 4.3.1 exercise 16, except that we
9534 : : * allow the divisor to exceed the internal base.
9535 : : *
9536 : : * In this algorithm, the carry from one digit to the next is at most
9537 : : * divisor - 1. Therefore, while processing the next digit, carry may
9538 : : * become as large as divisor * NBASE - 1, and so it requires a 64-bit
9539 : : * integer if this exceeds UINT_MAX.
9540 : : */
9541 : 388234 : divisor = abs(ival);
9542 : :
9543 [ + + ]: 388234 : if (divisor <= UINT_MAX / NBASE)
9544 : : {
9545 : : /* carry cannot overflow 32 bits */
9546 : 386382 : uint32 carry = 0;
9547 : :
9548 [ + + ]: 1914314 : for (i = 0; i < res_ndigits; i++)
9549 : : {
9550 [ + + ]: 1527932 : carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
9551 : 1527932 : res_digits[i] = (NumericDigit) (carry / divisor);
9552 : 1527932 : carry = carry % divisor;
9553 : : }
9554 : : }
9555 : : else
9556 : : {
9557 : : /* carry may exceed 32 bits */
9558 : 1852 : uint64 carry = 0;
9559 : :
9560 [ + + ]: 6005 : for (i = 0; i < res_ndigits; i++)
9561 : : {
9562 [ + + ]: 4153 : carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
9563 : 4153 : res_digits[i] = (NumericDigit) (carry / divisor);
9564 : 4153 : carry = carry % divisor;
9565 : : }
9566 : : }
9567 : :
9568 : : /* Store the quotient in result */
9569 [ + + ]: 388234 : digitbuf_free(result->buf);
9570 : 388234 : result->ndigits = res_ndigits;
9571 : 388234 : result->buf = res_buf;
9572 : 388234 : result->digits = res_digits;
9573 : 388234 : result->weight = res_weight;
9574 : 388234 : result->sign = res_sign;
9575 : :
9576 : : /* Round or truncate to target rscale (and set result->dscale) */
9577 [ + + ]: 388234 : if (round)
9578 : 111705 : round_var(result, rscale);
9579 : : else
9580 : 276529 : trunc_var(result, rscale);
9581 : :
9582 : : /* Strip leading/trailing zeroes */
9583 : 388234 : strip_var(result);
9584 : : }
9585 : :
9586 : :
9587 : : #ifdef HAVE_INT128
9588 : : /*
9589 : : * div_var_int64() -
9590 : : *
9591 : : * Divide a numeric variable by a 64-bit integer with the specified weight.
9592 : : * The quotient var / (ival * NBASE^ival_weight) is stored in result.
9593 : : *
9594 : : * This duplicates the logic in div_var_int(), so any changes made there
9595 : : * should be made here too.
9596 : : */
9597 : : static void
9598 : 360 : div_var_int64(const NumericVar *var, int64 ival, int ival_weight,
9599 : : NumericVar *result, int rscale, bool round)
9600 : : {
9601 : 360 : NumericDigit *var_digits = var->digits;
9602 : 360 : int var_ndigits = var->ndigits;
9603 : : int res_sign;
9604 : : int res_weight;
9605 : : int res_ndigits;
9606 : : NumericDigit *res_buf;
9607 : : NumericDigit *res_digits;
9608 : : uint64 divisor;
9609 : : int i;
9610 : :
9611 : : /* Guard against division by zero */
9612 [ - + ]: 360 : if (ival == 0)
9613 [ # # ]: 0 : ereport(ERROR,
9614 : : errcode(ERRCODE_DIVISION_BY_ZERO),
9615 : : errmsg("division by zero"));
9616 : :
9617 : : /* Result zero check */
9618 [ + + ]: 360 : if (var_ndigits == 0)
9619 : : {
9620 : 64 : zero_var(result);
9621 : 64 : result->dscale = rscale;
9622 : 64 : return;
9623 : : }
9624 : :
9625 : : /*
9626 : : * Determine the result sign, weight and number of digits to calculate.
9627 : : * The weight figured here is correct if the emitted quotient has no
9628 : : * leading zero digits; otherwise strip_var() will fix things up.
9629 : : */
9630 [ + + ]: 296 : if (var->sign == NUMERIC_POS)
9631 [ + + ]: 175 : res_sign = ival > 0 ? NUMERIC_POS : NUMERIC_NEG;
9632 : : else
9633 [ + + ]: 121 : res_sign = ival > 0 ? NUMERIC_NEG : NUMERIC_POS;
9634 : 296 : res_weight = var->weight - ival_weight;
9635 : : /* The number of accurate result digits we need to produce: */
9636 : 296 : res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
9637 : : /* ... but always at least 1 */
9638 : 296 : res_ndigits = Max(res_ndigits, 1);
9639 : : /* If rounding needed, figure one more digit to ensure correct result */
9640 [ + + ]: 296 : if (round)
9641 : 291 : res_ndigits++;
9642 : :
9643 : 296 : res_buf = digitbuf_alloc(res_ndigits + 1);
9644 : 296 : res_buf[0] = 0; /* spare digit for later rounding */
9645 : 296 : res_digits = res_buf + 1;
9646 : :
9647 : : /*
9648 : : * Now compute the quotient digits. This is the short division algorithm
9649 : : * described in Knuth volume 2, section 4.3.1 exercise 16, except that we
9650 : : * allow the divisor to exceed the internal base.
9651 : : *
9652 : : * In this algorithm, the carry from one digit to the next is at most
9653 : : * divisor - 1. Therefore, while processing the next digit, carry may
9654 : : * become as large as divisor * NBASE - 1, and so it requires a 128-bit
9655 : : * integer if this exceeds PG_UINT64_MAX.
9656 : : */
9657 : 296 : divisor = i64abs(ival);
9658 : :
9659 [ + + ]: 296 : if (divisor <= PG_UINT64_MAX / NBASE)
9660 : : {
9661 : : /* carry cannot overflow 64 bits */
9662 : 232 : uint64 carry = 0;
9663 : :
9664 [ + + ]: 2361 : for (i = 0; i < res_ndigits; i++)
9665 : : {
9666 [ + + ]: 2129 : carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
9667 : 2129 : res_digits[i] = (NumericDigit) (carry / divisor);
9668 : 2129 : carry = carry % divisor;
9669 : : }
9670 : : }
9671 : : else
9672 : : {
9673 : : /* carry may exceed 64 bits */
9674 : 64 : uint128 carry = 0;
9675 : :
9676 [ + + ]: 688 : for (i = 0; i < res_ndigits; i++)
9677 : : {
9678 [ + + ]: 624 : carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
9679 : 624 : res_digits[i] = (NumericDigit) (carry / divisor);
9680 : 624 : carry = carry % divisor;
9681 : : }
9682 : : }
9683 : :
9684 : : /* Store the quotient in result */
9685 [ + + ]: 296 : digitbuf_free(result->buf);
9686 : 296 : result->ndigits = res_ndigits;
9687 : 296 : result->buf = res_buf;
9688 : 296 : result->digits = res_digits;
9689 : 296 : result->weight = res_weight;
9690 : 296 : result->sign = res_sign;
9691 : :
9692 : : /* Round or truncate to target rscale (and set result->dscale) */
9693 [ + + ]: 296 : if (round)
9694 : 291 : round_var(result, rscale);
9695 : : else
9696 : 5 : trunc_var(result, rscale);
9697 : :
9698 : : /* Strip leading/trailing zeroes */
9699 : 296 : strip_var(result);
9700 : : }
9701 : : #endif
9702 : :
9703 : :
9704 : : /*
9705 : : * Default scale selection for division
9706 : : *
9707 : : * Returns the appropriate result scale for the division result.
9708 : : */
9709 : : static int
9710 : 99384 : select_div_scale(const NumericVar *var1, const NumericVar *var2)
9711 : : {
9712 : : int weight1,
9713 : : weight2,
9714 : : qweight,
9715 : : i;
9716 : : NumericDigit firstdigit1,
9717 : : firstdigit2;
9718 : : int rscale;
9719 : :
9720 : : /*
9721 : : * The result scale of a division isn't specified in any SQL standard. For
9722 : : * PostgreSQL we select a result scale that will give at least
9723 : : * NUMERIC_MIN_SIG_DIGITS significant digits, so that numeric gives a
9724 : : * result no less accurate than float8; but use a scale not less than
9725 : : * either input's display scale.
9726 : : */
9727 : :
9728 : : /* Get the actual (normalized) weight and first digit of each input */
9729 : :
9730 : 99384 : weight1 = 0; /* values to use if var1 is zero */
9731 : 99384 : firstdigit1 = 0;
9732 [ + + ]: 99384 : for (i = 0; i < var1->ndigits; i++)
9733 : : {
9734 : 98251 : firstdigit1 = var1->digits[i];
9735 [ + - ]: 98251 : if (firstdigit1 != 0)
9736 : : {
9737 : 98251 : weight1 = var1->weight - i;
9738 : 98251 : break;
9739 : : }
9740 : : }
9741 : :
9742 : 99384 : weight2 = 0; /* values to use if var2 is zero */
9743 : 99384 : firstdigit2 = 0;
9744 [ + + ]: 99384 : for (i = 0; i < var2->ndigits; i++)
9745 : : {
9746 : 99351 : firstdigit2 = var2->digits[i];
9747 [ + - ]: 99351 : if (firstdigit2 != 0)
9748 : : {
9749 : 99351 : weight2 = var2->weight - i;
9750 : 99351 : break;
9751 : : }
9752 : : }
9753 : :
9754 : : /*
9755 : : * Estimate weight of quotient. If the two first digits are equal, we
9756 : : * can't be sure, but assume that var1 is less than var2.
9757 : : */
9758 : 99384 : qweight = weight1 - weight2;
9759 [ + + ]: 99384 : if (firstdigit1 <= firstdigit2)
9760 : 88545 : qweight--;
9761 : :
9762 : : /* Select result scale */
9763 : 99384 : rscale = NUMERIC_MIN_SIG_DIGITS - qweight * DEC_DIGITS;
9764 : 99384 : rscale = Max(rscale, var1->dscale);
9765 : 99384 : rscale = Max(rscale, var2->dscale);
9766 : 99384 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
9767 : 99384 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
9768 : :
9769 : 99384 : return rscale;
9770 : : }
9771 : :
9772 : :
9773 : : /*
9774 : : * mod_var() -
9775 : : *
9776 : : * Calculate the modulo of two numerics at variable level
9777 : : */
9778 : : static void
9779 : 275493 : mod_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
9780 : : {
9781 : : NumericVar tmp;
9782 : :
9783 : 275493 : init_var(&tmp);
9784 : :
9785 : : /* ---------
9786 : : * We do this using the equation
9787 : : * mod(x,y) = x - trunc(x/y)*y
9788 : : * div_var can be persuaded to give us trunc(x/y) directly.
9789 : : * ----------
9790 : : */
9791 : 275493 : div_var(var1, var2, &tmp, 0, false, true);
9792 : :
9793 : 275493 : mul_var(var2, &tmp, &tmp, var2->dscale);
9794 : :
9795 : 275493 : sub_var(var1, &tmp, result);
9796 : :
9797 : 275493 : free_var(&tmp);
9798 : 275493 : }
9799 : :
9800 : :
9801 : : /*
9802 : : * div_mod_var() -
9803 : : *
9804 : : * Calculate the truncated integer quotient and numeric remainder of two
9805 : : * numeric variables. The remainder is precise to var2's dscale.
9806 : : */
9807 : : static void
9808 : 3295 : div_mod_var(const NumericVar *var1, const NumericVar *var2,
9809 : : NumericVar *quot, NumericVar *rem)
9810 : : {
9811 : : NumericVar q;
9812 : : NumericVar r;
9813 : :
9814 : 3295 : init_var(&q);
9815 : 3295 : init_var(&r);
9816 : :
9817 : : /*
9818 : : * Use div_var() with exact = false to get an initial estimate for the
9819 : : * integer quotient (truncated towards zero). This might be slightly
9820 : : * inaccurate, but we correct it below.
9821 : : */
9822 : 3295 : div_var(var1, var2, &q, 0, false, false);
9823 : :
9824 : : /* Compute initial estimate of remainder using the quotient estimate. */
9825 : 3295 : mul_var(var2, &q, &r, var2->dscale);
9826 : 3295 : sub_var(var1, &r, &r);
9827 : :
9828 : : /*
9829 : : * Adjust the results if necessary --- the remainder should have the same
9830 : : * sign as var1, and its absolute value should be less than the absolute
9831 : : * value of var2.
9832 : : */
9833 [ + - - + ]: 3295 : while (r.ndigits != 0 && r.sign != var1->sign)
9834 : : {
9835 : : /* The absolute value of the quotient is too large */
9836 [ # # ]: 0 : if (var1->sign == var2->sign)
9837 : : {
9838 : 0 : sub_var(&q, &const_one, &q);
9839 : 0 : add_var(&r, var2, &r);
9840 : : }
9841 : : else
9842 : : {
9843 : 0 : add_var(&q, &const_one, &q);
9844 : 0 : sub_var(&r, var2, &r);
9845 : : }
9846 : : }
9847 : :
9848 [ - + ]: 3295 : while (cmp_abs(&r, var2) >= 0)
9849 : : {
9850 : : /* The absolute value of the quotient is too small */
9851 [ # # ]: 0 : if (var1->sign == var2->sign)
9852 : : {
9853 : 0 : add_var(&q, &const_one, &q);
9854 : 0 : sub_var(&r, var2, &r);
9855 : : }
9856 : : else
9857 : : {
9858 : 0 : sub_var(&q, &const_one, &q);
9859 : 0 : add_var(&r, var2, &r);
9860 : : }
9861 : : }
9862 : :
9863 : 3295 : set_var_from_var(&q, quot);
9864 : 3295 : set_var_from_var(&r, rem);
9865 : :
9866 : 3295 : free_var(&q);
9867 : 3295 : free_var(&r);
9868 : 3295 : }
9869 : :
9870 : :
9871 : : /*
9872 : : * ceil_var() -
9873 : : *
9874 : : * Return the smallest integer greater than or equal to the argument
9875 : : * on variable level
9876 : : */
9877 : : static void
9878 : 136 : ceil_var(const NumericVar *var, NumericVar *result)
9879 : : {
9880 : : NumericVar tmp;
9881 : :
9882 : 136 : init_var(&tmp);
9883 : 136 : set_var_from_var(var, &tmp);
9884 : :
9885 : 136 : trunc_var(&tmp, 0);
9886 : :
9887 [ + + + + ]: 136 : if (var->sign == NUMERIC_POS && cmp_var(var, &tmp) != 0)
9888 : 40 : add_var(&tmp, &const_one, &tmp);
9889 : :
9890 : 136 : set_var_from_var(&tmp, result);
9891 : 136 : free_var(&tmp);
9892 : 136 : }
9893 : :
9894 : :
9895 : : /*
9896 : : * floor_var() -
9897 : : *
9898 : : * Return the largest integer equal to or less than the argument
9899 : : * on variable level
9900 : : */
9901 : : static void
9902 : 72 : floor_var(const NumericVar *var, NumericVar *result)
9903 : : {
9904 : : NumericVar tmp;
9905 : :
9906 : 72 : init_var(&tmp);
9907 : 72 : set_var_from_var(var, &tmp);
9908 : :
9909 : 72 : trunc_var(&tmp, 0);
9910 : :
9911 [ + + + + ]: 72 : if (var->sign == NUMERIC_NEG && cmp_var(var, &tmp) != 0)
9912 : 20 : sub_var(&tmp, &const_one, &tmp);
9913 : :
9914 : 72 : set_var_from_var(&tmp, result);
9915 : 72 : free_var(&tmp);
9916 : 72 : }
9917 : :
9918 : :
9919 : : /*
9920 : : * gcd_var() -
9921 : : *
9922 : : * Calculate the greatest common divisor of two numerics at variable level
9923 : : */
9924 : : static void
9925 : 148 : gcd_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
9926 : : {
9927 : : int res_dscale;
9928 : : int cmp;
9929 : : NumericVar tmp_arg;
9930 : : NumericVar mod;
9931 : :
9932 : 148 : res_dscale = Max(var1->dscale, var2->dscale);
9933 : :
9934 : : /*
9935 : : * Arrange for var1 to be the number with the greater absolute value.
9936 : : *
9937 : : * This would happen automatically in the loop below, but avoids an
9938 : : * expensive modulo operation.
9939 : : */
9940 : 148 : cmp = cmp_abs(var1, var2);
9941 [ + + ]: 148 : if (cmp < 0)
9942 : : {
9943 : 56 : const NumericVar *tmp = var1;
9944 : :
9945 : 56 : var1 = var2;
9946 : 56 : var2 = tmp;
9947 : : }
9948 : :
9949 : : /*
9950 : : * Also avoid the taking the modulo if the inputs have the same absolute
9951 : : * value, or if the smaller input is zero.
9952 : : */
9953 [ + + + + ]: 148 : if (cmp == 0 || var2->ndigits == 0)
9954 : : {
9955 : 48 : set_var_from_var(var1, result);
9956 : 48 : result->sign = NUMERIC_POS;
9957 : 48 : result->dscale = res_dscale;
9958 : 48 : return;
9959 : : }
9960 : :
9961 : 100 : init_var(&tmp_arg);
9962 : 100 : init_var(&mod);
9963 : :
9964 : : /* Use the Euclidean algorithm to find the GCD */
9965 : 100 : set_var_from_var(var1, &tmp_arg);
9966 : 100 : set_var_from_var(var2, result);
9967 : :
9968 : : for (;;)
9969 : : {
9970 : : /* this loop can take a while, so allow it to be interrupted */
9971 [ - + ]: 392 : CHECK_FOR_INTERRUPTS();
9972 : :
9973 : 392 : mod_var(&tmp_arg, result, &mod);
9974 [ + + ]: 392 : if (mod.ndigits == 0)
9975 : 100 : break;
9976 : 292 : set_var_from_var(result, &tmp_arg);
9977 : 292 : set_var_from_var(&mod, result);
9978 : : }
9979 : 100 : result->sign = NUMERIC_POS;
9980 : 100 : result->dscale = res_dscale;
9981 : :
9982 : 100 : free_var(&tmp_arg);
9983 : 100 : free_var(&mod);
9984 : : }
9985 : :
9986 : :
9987 : : /*
9988 : : * sqrt_var() -
9989 : : *
9990 : : * Compute the square root of x using the Karatsuba Square Root algorithm.
9991 : : * NOTE: we allow rscale < 0 here, implying rounding before the decimal
9992 : : * point.
9993 : : */
9994 : : static void
9995 : 3048 : sqrt_var(const NumericVar *arg, NumericVar *result, int rscale)
9996 : : {
9997 : : int stat;
9998 : : int res_weight;
9999 : : int res_ndigits;
10000 : : int src_ndigits;
10001 : : int step;
10002 : : int ndigits[32];
10003 : : int blen;
10004 : : int64 arg_int64;
10005 : : int src_idx;
10006 : : int64 s_int64;
10007 : : int64 r_int64;
10008 : : NumericVar s_var;
10009 : : NumericVar r_var;
10010 : : NumericVar a0_var;
10011 : : NumericVar a1_var;
10012 : : NumericVar q_var;
10013 : : NumericVar u_var;
10014 : :
10015 : 3048 : stat = cmp_var(arg, &const_zero);
10016 [ + + ]: 3048 : if (stat == 0)
10017 : : {
10018 : 12 : zero_var(result);
10019 : 12 : result->dscale = rscale;
10020 : 12 : return;
10021 : : }
10022 : :
10023 : : /*
10024 : : * SQL2003 defines sqrt() in terms of power, so we need to emit the right
10025 : : * SQLSTATE error code if the operand is negative.
10026 : : */
10027 [ + + ]: 3036 : if (stat < 0)
10028 [ + - ]: 4 : ereport(ERROR,
10029 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
10030 : : errmsg("cannot take square root of a negative number")));
10031 : :
10032 : 3032 : init_var(&s_var);
10033 : 3032 : init_var(&r_var);
10034 : 3032 : init_var(&a0_var);
10035 : 3032 : init_var(&a1_var);
10036 : 3032 : init_var(&q_var);
10037 : 3032 : init_var(&u_var);
10038 : :
10039 : : /*
10040 : : * The result weight is half the input weight, rounded towards minus
10041 : : * infinity --- res_weight = floor(arg->weight / 2).
10042 : : */
10043 [ + + ]: 3032 : if (arg->weight >= 0)
10044 : 2761 : res_weight = arg->weight / 2;
10045 : : else
10046 : 271 : res_weight = -((-arg->weight - 1) / 2 + 1);
10047 : :
10048 : : /*
10049 : : * Number of NBASE digits to compute. To ensure correct rounding, compute
10050 : : * at least 1 extra decimal digit. We explicitly allow rscale to be
10051 : : * negative here, but must always compute at least 1 NBASE digit. Thus
10052 : : * res_ndigits = res_weight + 1 + ceil((rscale + 1) / DEC_DIGITS) or 1.
10053 : : */
10054 [ + - ]: 3032 : if (rscale + 1 >= 0)
10055 : 3032 : res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS) / DEC_DIGITS;
10056 : : else
10057 : 0 : res_ndigits = res_weight + 1 - (-rscale - 1) / DEC_DIGITS;
10058 : 3032 : res_ndigits = Max(res_ndigits, 1);
10059 : :
10060 : : /*
10061 : : * Number of source NBASE digits logically required to produce a result
10062 : : * with this precision --- every digit before the decimal point, plus 2
10063 : : * for each result digit after the decimal point (or minus 2 for each
10064 : : * result digit we round before the decimal point).
10065 : : */
10066 : 3032 : src_ndigits = arg->weight + 1 + (res_ndigits - res_weight - 1) * 2;
10067 : 3032 : src_ndigits = Max(src_ndigits, 1);
10068 : :
10069 : : /* ----------
10070 : : * From this point on, we treat the input and the result as integers and
10071 : : * compute the integer square root and remainder using the Karatsuba
10072 : : * Square Root algorithm, which may be written recursively as follows:
10073 : : *
10074 : : * SqrtRem(n = a3*b^3 + a2*b^2 + a1*b + a0):
10075 : : * [ for some base b, and coefficients a0,a1,a2,a3 chosen so that
10076 : : * 0 <= a0,a1,a2 < b and a3 >= b/4 ]
10077 : : * Let (s,r) = SqrtRem(a3*b + a2)
10078 : : * Let (q,u) = DivRem(r*b + a1, 2*s)
10079 : : * Let s = s*b + q
10080 : : * Let r = u*b + a0 - q^2
10081 : : * If r < 0 Then
10082 : : * Let r = r + s
10083 : : * Let s = s - 1
10084 : : * Let r = r + s
10085 : : * Return (s,r)
10086 : : *
10087 : : * See "Karatsuba Square Root", Paul Zimmermann, INRIA Research Report
10088 : : * RR-3805, November 1999. At the time of writing this was available
10089 : : * on the net at <https://hal.inria.fr/inria-00072854>.
10090 : : *
10091 : : * The way to read the assumption "n = a3*b^3 + a2*b^2 + a1*b + a0" is
10092 : : * "choose a base b such that n requires at least four base-b digits to
10093 : : * express; then those digits are a3,a2,a1,a0, with a3 possibly larger
10094 : : * than b". For optimal performance, b should have approximately a
10095 : : * quarter the number of digits in the input, so that the outer square
10096 : : * root computes roughly twice as many digits as the inner one. For
10097 : : * simplicity, we choose b = NBASE^blen, an integer power of NBASE.
10098 : : *
10099 : : * We implement the algorithm iteratively rather than recursively, to
10100 : : * allow the working variables to be reused. With this approach, each
10101 : : * digit of the input is read precisely once --- src_idx tracks the number
10102 : : * of input digits used so far.
10103 : : *
10104 : : * The array ndigits[] holds the number of NBASE digits of the input that
10105 : : * will have been used at the end of each iteration, which roughly doubles
10106 : : * each time. Note that the array elements are stored in reverse order,
10107 : : * so if the final iteration requires src_ndigits = 37 input digits, the
10108 : : * array will contain [37,19,11,7,5,3], and we would start by computing
10109 : : * the square root of the 3 most significant NBASE digits.
10110 : : *
10111 : : * In each iteration, we choose blen to be the largest integer for which
10112 : : * the input number has a3 >= b/4, when written in the form above. In
10113 : : * general, this means blen = src_ndigits / 4 (truncated), but if
10114 : : * src_ndigits is a multiple of 4, that might lead to the coefficient a3
10115 : : * being less than b/4 (if the first input digit is less than NBASE/4), in
10116 : : * which case we choose blen = src_ndigits / 4 - 1. The number of digits
10117 : : * in the inner square root is then src_ndigits - 2*blen. So, for
10118 : : * example, if we have src_ndigits = 26 initially, the array ndigits[]
10119 : : * will be either [26,14,8,4] or [26,14,8,6,4], depending on the size of
10120 : : * the first input digit.
10121 : : *
10122 : : * Additionally, we can put an upper bound on the number of steps required
10123 : : * as follows --- suppose that the number of source digits is an n-bit
10124 : : * number in the range [2^(n-1), 2^n-1], then blen will be in the range
10125 : : * [2^(n-3)-1, 2^(n-2)-1] and the number of digits in the inner square
10126 : : * root will be in the range [2^(n-2), 2^(n-1)+1]. In the next step, blen
10127 : : * will be in the range [2^(n-4)-1, 2^(n-3)] and the number of digits in
10128 : : * the next inner square root will be in the range [2^(n-3), 2^(n-2)+1].
10129 : : * This pattern repeats, and in the worst case the array ndigits[] will
10130 : : * contain [2^n-1, 2^(n-1)+1, 2^(n-2)+1, ... 9, 5, 3], and the computation
10131 : : * will require n steps. Therefore, since all digit array sizes are
10132 : : * signed 32-bit integers, the number of steps required is guaranteed to
10133 : : * be less than 32.
10134 : : * ----------
10135 : : */
10136 : 3032 : step = 0;
10137 [ + + ]: 14531 : while ((ndigits[step] = src_ndigits) > 4)
10138 : : {
10139 : : /* Choose b so that a3 >= b/4, as described above */
10140 : 11499 : blen = src_ndigits / 4;
10141 [ + + + + ]: 11499 : if (blen * 4 == src_ndigits && arg->digits[0] < NBASE / 4)
10142 : 259 : blen--;
10143 : :
10144 : : /* Number of digits in the next step (inner square root) */
10145 : 11499 : src_ndigits -= 2 * blen;
10146 : 11499 : step++;
10147 : : }
10148 : :
10149 : : /*
10150 : : * First iteration (innermost square root and remainder):
10151 : : *
10152 : : * Here src_ndigits <= 4, and the input fits in an int64. Its square root
10153 : : * has at most 9 decimal digits, so estimate it using double precision
10154 : : * arithmetic, which will in fact almost certainly return the correct
10155 : : * result with no further correction required.
10156 : : */
10157 : 3032 : arg_int64 = arg->digits[0];
10158 [ + + ]: 9695 : for (src_idx = 1; src_idx < src_ndigits; src_idx++)
10159 : : {
10160 : 6663 : arg_int64 *= NBASE;
10161 [ + + ]: 6663 : if (src_idx < arg->ndigits)
10162 : 5647 : arg_int64 += arg->digits[src_idx];
10163 : : }
10164 : :
10165 : 3032 : s_int64 = (int64) sqrt((double) arg_int64);
10166 : 3032 : r_int64 = arg_int64 - s_int64 * s_int64;
10167 : :
10168 : : /*
10169 : : * Use Newton's method to correct the result, if necessary.
10170 : : *
10171 : : * This uses integer division with truncation to compute the truncated
10172 : : * integer square root by iterating using the formula x -> (x + n/x) / 2.
10173 : : * This is known to converge to isqrt(n), unless n+1 is a perfect square.
10174 : : * If n+1 is a perfect square, the sequence will oscillate between the two
10175 : : * values isqrt(n) and isqrt(n)+1, so we can be assured of convergence by
10176 : : * checking the remainder.
10177 : : */
10178 [ - + - + ]: 3032 : while (r_int64 < 0 || r_int64 > 2 * s_int64)
10179 : : {
10180 : 0 : s_int64 = (s_int64 + arg_int64 / s_int64) / 2;
10181 : 0 : r_int64 = arg_int64 - s_int64 * s_int64;
10182 : : }
10183 : :
10184 : : /*
10185 : : * Iterations with src_ndigits <= 8:
10186 : : *
10187 : : * The next 1 or 2 iterations compute larger (outer) square roots with
10188 : : * src_ndigits <= 8, so the result still fits in an int64 (even though the
10189 : : * input no longer does) and we can continue to compute using int64
10190 : : * variables to avoid more expensive numeric computations.
10191 : : *
10192 : : * It is fairly easy to see that there is no risk of the intermediate
10193 : : * values below overflowing 64-bit integers. In the worst case, the
10194 : : * previous iteration will have computed a 3-digit square root (of a
10195 : : * 6-digit input less than NBASE^6 / 4), so at the start of this
10196 : : * iteration, s will be less than NBASE^3 / 2 = 10^12 / 2, and r will be
10197 : : * less than 10^12. In this case, blen will be 1, so numer will be less
10198 : : * than 10^17, and denom will be less than 10^12 (and hence u will also be
10199 : : * less than 10^12). Finally, since q^2 = u*b + a0 - r, we can also be
10200 : : * sure that q^2 < 10^17. Therefore all these quantities fit comfortably
10201 : : * in 64-bit integers.
10202 : : */
10203 : 3032 : step--;
10204 [ + - + + ]: 7672 : while (step >= 0 && (src_ndigits = ndigits[step]) <= 8)
10205 : : {
10206 : : int b;
10207 : : int a0;
10208 : : int a1;
10209 : : int i;
10210 : : int64 numer;
10211 : : int64 denom;
10212 : : int64 q;
10213 : : int64 u;
10214 : :
10215 : 4640 : blen = (src_ndigits - src_idx) / 2;
10216 : :
10217 : : /* Extract a1 and a0, and compute b */
10218 : 4640 : a0 = 0;
10219 : 4640 : a1 = 0;
10220 : 4640 : b = 1;
10221 : :
10222 [ + + ]: 9399 : for (i = 0; i < blen; i++, src_idx++)
10223 : : {
10224 : 4759 : b *= NBASE;
10225 : 4759 : a1 *= NBASE;
10226 [ + + ]: 4759 : if (src_idx < arg->ndigits)
10227 : 3532 : a1 += arg->digits[src_idx];
10228 : : }
10229 : :
10230 [ + + ]: 9399 : for (i = 0; i < blen; i++, src_idx++)
10231 : : {
10232 : 4759 : a0 *= NBASE;
10233 [ + + ]: 4759 : if (src_idx < arg->ndigits)
10234 : 3420 : a0 += arg->digits[src_idx];
10235 : : }
10236 : :
10237 : : /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
10238 : 4640 : numer = r_int64 * b + a1;
10239 : 4640 : denom = 2 * s_int64;
10240 : 4640 : q = numer / denom;
10241 : 4640 : u = numer - q * denom;
10242 : :
10243 : : /* Compute s = s*b + q and r = u*b + a0 - q^2 */
10244 : 4640 : s_int64 = s_int64 * b + q;
10245 : 4640 : r_int64 = u * b + a0 - q * q;
10246 : :
10247 [ + + ]: 4640 : if (r_int64 < 0)
10248 : : {
10249 : : /* s is too large by 1; set r += s, s--, r += s */
10250 : 161 : r_int64 += s_int64;
10251 : 161 : s_int64--;
10252 : 161 : r_int64 += s_int64;
10253 : : }
10254 : :
10255 : : Assert(src_idx == src_ndigits); /* All input digits consumed */
10256 : 4640 : step--;
10257 : : }
10258 : :
10259 : : /*
10260 : : * On platforms with 128-bit integer support, we can further delay the
10261 : : * need to use numeric variables.
10262 : : */
10263 : : #ifdef HAVE_INT128
10264 [ + - ]: 3032 : if (step >= 0)
10265 : : {
10266 : : int128 s_int128;
10267 : : int128 r_int128;
10268 : :
10269 : 3032 : s_int128 = s_int64;
10270 : 3032 : r_int128 = r_int64;
10271 : :
10272 : : /*
10273 : : * Iterations with src_ndigits <= 16:
10274 : : *
10275 : : * The result fits in an int128 (even though the input doesn't) so we
10276 : : * use int128 variables to avoid more expensive numeric computations.
10277 : : */
10278 [ + + + + ]: 6596 : while (step >= 0 && (src_ndigits = ndigits[step]) <= 16)
10279 : : {
10280 : : int64 b;
10281 : : int64 a0;
10282 : : int64 a1;
10283 : : int64 i;
10284 : : int128 numer;
10285 : : int128 denom;
10286 : : int128 q;
10287 : : int128 u;
10288 : :
10289 : 3564 : blen = (src_ndigits - src_idx) / 2;
10290 : :
10291 : : /* Extract a1 and a0, and compute b */
10292 : 3564 : a0 = 0;
10293 : 3564 : a1 = 0;
10294 : 3564 : b = 1;
10295 : :
10296 [ + + ]: 11796 : for (i = 0; i < blen; i++, src_idx++)
10297 : : {
10298 : 8232 : b *= NBASE;
10299 : 8232 : a1 *= NBASE;
10300 [ + + ]: 8232 : if (src_idx < arg->ndigits)
10301 : 4947 : a1 += arg->digits[src_idx];
10302 : : }
10303 : :
10304 [ + + ]: 11796 : for (i = 0; i < blen; i++, src_idx++)
10305 : : {
10306 : 8232 : a0 *= NBASE;
10307 [ + + ]: 8232 : if (src_idx < arg->ndigits)
10308 : 3407 : a0 += arg->digits[src_idx];
10309 : : }
10310 : :
10311 : : /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
10312 : 3564 : numer = r_int128 * b + a1;
10313 : 3564 : denom = 2 * s_int128;
10314 : 3564 : q = numer / denom;
10315 : 3564 : u = numer - q * denom;
10316 : :
10317 : : /* Compute s = s*b + q and r = u*b + a0 - q^2 */
10318 : 3564 : s_int128 = s_int128 * b + q;
10319 : 3564 : r_int128 = u * b + a0 - q * q;
10320 : :
10321 [ + + ]: 3564 : if (r_int128 < 0)
10322 : : {
10323 : : /* s is too large by 1; set r += s, s--, r += s */
10324 : 146 : r_int128 += s_int128;
10325 : 146 : s_int128--;
10326 : 146 : r_int128 += s_int128;
10327 : : }
10328 : :
10329 : : Assert(src_idx == src_ndigits); /* All input digits consumed */
10330 : 3564 : step--;
10331 : : }
10332 : :
10333 : : /*
10334 : : * All remaining iterations require numeric variables. Convert the
10335 : : * integer values to NumericVar and continue. Note that in the final
10336 : : * iteration we don't need the remainder, so we can save a few cycles
10337 : : * there by not fully computing it.
10338 : : */
10339 : 3032 : int128_to_numericvar(s_int128, &s_var);
10340 [ + + ]: 3032 : if (step >= 0)
10341 : 2008 : int128_to_numericvar(r_int128, &r_var);
10342 : : }
10343 : : else
10344 : : {
10345 : 0 : int64_to_numericvar(s_int64, &s_var);
10346 : : /* step < 0, so we certainly don't need r */
10347 : : }
10348 : : #else /* !HAVE_INT128 */
10349 : : int64_to_numericvar(s_int64, &s_var);
10350 : : if (step >= 0)
10351 : : int64_to_numericvar(r_int64, &r_var);
10352 : : #endif /* HAVE_INT128 */
10353 : :
10354 : : /*
10355 : : * The remaining iterations with src_ndigits > 8 (or 16, if have int128)
10356 : : * use numeric variables.
10357 : : */
10358 [ + + ]: 6327 : while (step >= 0)
10359 : : {
10360 : : int tmp_len;
10361 : :
10362 : 3295 : src_ndigits = ndigits[step];
10363 : 3295 : blen = (src_ndigits - src_idx) / 2;
10364 : :
10365 : : /* Extract a1 and a0 */
10366 [ + + ]: 3295 : if (src_idx < arg->ndigits)
10367 : : {
10368 : 1088 : tmp_len = Min(blen, arg->ndigits - src_idx);
10369 : 1088 : alloc_var(&a1_var, tmp_len);
10370 : 1088 : memcpy(a1_var.digits, arg->digits + src_idx,
10371 : : tmp_len * sizeof(NumericDigit));
10372 : 1088 : a1_var.weight = blen - 1;
10373 : 1088 : a1_var.sign = NUMERIC_POS;
10374 : 1088 : a1_var.dscale = 0;
10375 : 1088 : strip_var(&a1_var);
10376 : : }
10377 : : else
10378 : : {
10379 : 2207 : zero_var(&a1_var);
10380 : 2207 : a1_var.dscale = 0;
10381 : : }
10382 : 3295 : src_idx += blen;
10383 : :
10384 [ + + ]: 3295 : if (src_idx < arg->ndigits)
10385 : : {
10386 : 1088 : tmp_len = Min(blen, arg->ndigits - src_idx);
10387 : 1088 : alloc_var(&a0_var, tmp_len);
10388 : 1088 : memcpy(a0_var.digits, arg->digits + src_idx,
10389 : : tmp_len * sizeof(NumericDigit));
10390 : 1088 : a0_var.weight = blen - 1;
10391 : 1088 : a0_var.sign = NUMERIC_POS;
10392 : 1088 : a0_var.dscale = 0;
10393 : 1088 : strip_var(&a0_var);
10394 : : }
10395 : : else
10396 : : {
10397 : 2207 : zero_var(&a0_var);
10398 : 2207 : a0_var.dscale = 0;
10399 : : }
10400 : 3295 : src_idx += blen;
10401 : :
10402 : : /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
10403 : 3295 : set_var_from_var(&r_var, &q_var);
10404 : 3295 : q_var.weight += blen;
10405 : 3295 : add_var(&q_var, &a1_var, &q_var);
10406 : 3295 : add_var(&s_var, &s_var, &u_var);
10407 : 3295 : div_mod_var(&q_var, &u_var, &q_var, &u_var);
10408 : :
10409 : : /* Compute s = s*b + q */
10410 : 3295 : s_var.weight += blen;
10411 : 3295 : add_var(&s_var, &q_var, &s_var);
10412 : :
10413 : : /*
10414 : : * Compute r = u*b + a0 - q^2.
10415 : : *
10416 : : * In the final iteration, we don't actually need r; we just need to
10417 : : * know whether it is negative, so that we know whether to adjust s.
10418 : : * So instead of the final subtraction we can just compare.
10419 : : */
10420 : 3295 : u_var.weight += blen;
10421 : 3295 : add_var(&u_var, &a0_var, &u_var);
10422 : 3295 : mul_var(&q_var, &q_var, &q_var, 0);
10423 : :
10424 [ + + ]: 3295 : if (step > 0)
10425 : : {
10426 : : /* Need r for later iterations */
10427 : 1287 : sub_var(&u_var, &q_var, &r_var);
10428 [ + + ]: 1287 : if (r_var.sign == NUMERIC_NEG)
10429 : : {
10430 : : /* s is too large by 1; set r += s, s--, r += s */
10431 : 85 : add_var(&r_var, &s_var, &r_var);
10432 : 85 : sub_var(&s_var, &const_one, &s_var);
10433 : 85 : add_var(&r_var, &s_var, &r_var);
10434 : : }
10435 : : }
10436 : : else
10437 : : {
10438 : : /* Don't need r anymore, except to test if s is too large by 1 */
10439 [ + + ]: 2008 : if (cmp_var(&u_var, &q_var) < 0)
10440 : 27 : sub_var(&s_var, &const_one, &s_var);
10441 : : }
10442 : :
10443 : : Assert(src_idx == src_ndigits); /* All input digits consumed */
10444 : 3295 : step--;
10445 : : }
10446 : :
10447 : : /*
10448 : : * Construct the final result, rounding it to the requested precision.
10449 : : */
10450 : 3032 : set_var_from_var(&s_var, result);
10451 : 3032 : result->weight = res_weight;
10452 : 3032 : result->sign = NUMERIC_POS;
10453 : :
10454 : : /* Round to target rscale (and set result->dscale) */
10455 : 3032 : round_var(result, rscale);
10456 : :
10457 : : /* Strip leading and trailing zeroes */
10458 : 3032 : strip_var(result);
10459 : :
10460 : 3032 : free_var(&s_var);
10461 : 3032 : free_var(&r_var);
10462 : 3032 : free_var(&a0_var);
10463 : 3032 : free_var(&a1_var);
10464 : 3032 : free_var(&q_var);
10465 : 3032 : free_var(&u_var);
10466 : : }
10467 : :
10468 : :
10469 : : /*
10470 : : * exp_var() -
10471 : : *
10472 : : * Raise e to the power of x, computed to rscale fractional digits
10473 : : */
10474 : : static void
10475 : 139 : exp_var(const NumericVar *arg, NumericVar *result, int rscale)
10476 : : {
10477 : : NumericVar x;
10478 : : NumericVar elem;
10479 : : int ni;
10480 : : double val;
10481 : : int dweight;
10482 : : int ndiv2;
10483 : : int sig_digits;
10484 : : int local_rscale;
10485 : :
10486 : 139 : init_var(&x);
10487 : 139 : init_var(&elem);
10488 : :
10489 : 139 : set_var_from_var(arg, &x);
10490 : :
10491 : : /*
10492 : : * Estimate the dweight of the result using floating point arithmetic, so
10493 : : * that we can choose an appropriate local rscale for the calculation.
10494 : : */
10495 : 139 : val = numericvar_to_double_no_overflow(&x);
10496 : :
10497 : : /* Guard against overflow/underflow */
10498 : : /* If you change this limit, see also power_var()'s limit */
10499 [ + + ]: 139 : if (fabs(val) >= NUMERIC_MAX_RESULT_SCALE * 3)
10500 : : {
10501 [ - + ]: 5 : if (val > 0)
10502 [ # # ]: 0 : ereport(ERROR,
10503 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
10504 : : errmsg("value overflows numeric format")));
10505 : 5 : zero_var(result);
10506 : 5 : result->dscale = rscale;
10507 : 5 : return;
10508 : : }
10509 : :
10510 : : /* decimal weight = log10(e^x) = x * log10(e) */
10511 : 134 : dweight = (int) (val * 0.434294481903252);
10512 : :
10513 : : /*
10514 : : * Reduce x to the range -0.01 <= x <= 0.01 (approximately) by dividing by
10515 : : * 2^ndiv2, to improve the convergence rate of the Taylor series.
10516 : : *
10517 : : * Note that the overflow check above ensures that fabs(x) < 6000, which
10518 : : * means that ndiv2 <= 20 here.
10519 : : */
10520 [ + + ]: 134 : if (fabs(val) > 0.01)
10521 : : {
10522 : 110 : ndiv2 = 1;
10523 : 110 : val /= 2;
10524 : :
10525 [ + + ]: 1402 : while (fabs(val) > 0.01)
10526 : : {
10527 : 1292 : ndiv2++;
10528 : 1292 : val /= 2;
10529 : : }
10530 : :
10531 : 110 : local_rscale = x.dscale + ndiv2;
10532 : 110 : div_var_int(&x, 1 << ndiv2, 0, &x, local_rscale, true);
10533 : : }
10534 : : else
10535 : 24 : ndiv2 = 0;
10536 : :
10537 : : /*
10538 : : * Set the scale for the Taylor series expansion. The final result has
10539 : : * (dweight + rscale + 1) significant digits. In addition, we have to
10540 : : * raise the Taylor series result to the power 2^ndiv2, which introduces
10541 : : * an error of up to around log10(2^ndiv2) digits, so work with this many
10542 : : * extra digits of precision (plus a few more for good measure).
10543 : : */
10544 : 134 : sig_digits = 1 + dweight + rscale + (int) (ndiv2 * 0.301029995663981);
10545 : 134 : sig_digits = Max(sig_digits, 0) + 8;
10546 : :
10547 : 134 : local_rscale = sig_digits - 1;
10548 : :
10549 : : /*
10550 : : * Use the Taylor series
10551 : : *
10552 : : * exp(x) = 1 + x + x^2/2! + x^3/3! + ...
10553 : : *
10554 : : * Given the limited range of x, this should converge reasonably quickly.
10555 : : * We run the series until the terms fall below the local_rscale limit.
10556 : : */
10557 : 134 : add_var(&const_one, &x, result);
10558 : :
10559 : 134 : mul_var(&x, &x, &elem, local_rscale);
10560 : 134 : ni = 2;
10561 : 134 : div_var_int(&elem, ni, 0, &elem, local_rscale, true);
10562 : :
10563 [ + + ]: 3639 : while (elem.ndigits != 0)
10564 : : {
10565 : 3505 : add_var(result, &elem, result);
10566 : :
10567 : 3505 : mul_var(&elem, &x, &elem, local_rscale);
10568 : 3505 : ni++;
10569 : 3505 : div_var_int(&elem, ni, 0, &elem, local_rscale, true);
10570 : : }
10571 : :
10572 : : /*
10573 : : * Compensate for the argument range reduction. Since the weight of the
10574 : : * result doubles with each multiplication, we can reduce the local rscale
10575 : : * as we proceed.
10576 : : */
10577 [ + + ]: 1536 : while (ndiv2-- > 0)
10578 : : {
10579 : 1402 : local_rscale = sig_digits - result->weight * 2 * DEC_DIGITS;
10580 : 1402 : local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
10581 : 1402 : mul_var(result, result, result, local_rscale);
10582 : : }
10583 : :
10584 : : /* Round to requested rscale */
10585 : 134 : round_var(result, rscale);
10586 : :
10587 : 134 : free_var(&x);
10588 : 134 : free_var(&elem);
10589 : : }
10590 : :
10591 : :
10592 : : /*
10593 : : * Estimate the dweight of the most significant decimal digit of the natural
10594 : : * logarithm of a number.
10595 : : *
10596 : : * Essentially, we're approximating log10(abs(ln(var))). This is used to
10597 : : * determine the appropriate rscale when computing natural logarithms.
10598 : : *
10599 : : * Note: many callers call this before range-checking the input. Therefore,
10600 : : * we must be robust against values that are invalid to apply ln() to.
10601 : : * We don't wish to throw an error here, so just return zero in such cases.
10602 : : */
10603 : : static int
10604 : 534 : estimate_ln_dweight(const NumericVar *var)
10605 : : {
10606 : : int ln_dweight;
10607 : :
10608 : : /* Caller should fail on ln(negative), but for the moment return zero */
10609 [ + + ]: 534 : if (var->sign != NUMERIC_POS)
10610 : 28 : return 0;
10611 : :
10612 [ + + + + ]: 953 : if (cmp_var(var, &const_zero_point_nine) >= 0 &&
10613 : 447 : cmp_var(var, &const_one_point_one) <= 0)
10614 : 70 : {
10615 : : /*
10616 : : * 0.9 <= var <= 1.1
10617 : : *
10618 : : * ln(var) has a negative weight (possibly very large). To get a
10619 : : * reasonably accurate result, estimate it using ln(1+x) ~= x.
10620 : : */
10621 : : NumericVar x;
10622 : :
10623 : 70 : init_var(&x);
10624 : 70 : sub_var(var, &const_one, &x);
10625 : :
10626 [ + + ]: 70 : if (x.ndigits > 0)
10627 : : {
10628 : : /* Use weight of most significant decimal digit of x */
10629 : 35 : ln_dweight = x.weight * DEC_DIGITS + (int) log10(x.digits[0]);
10630 : : }
10631 : : else
10632 : : {
10633 : : /* x = 0. Since ln(1) = 0 exactly, we don't need extra digits */
10634 : 35 : ln_dweight = 0;
10635 : : }
10636 : :
10637 : 70 : free_var(&x);
10638 : : }
10639 : : else
10640 : : {
10641 : : /*
10642 : : * Estimate the logarithm using the first couple of digits from the
10643 : : * input number. This will give an accurate result whenever the input
10644 : : * is not too close to 1.
10645 : : */
10646 [ + + ]: 436 : if (var->ndigits > 0)
10647 : : {
10648 : : int digits;
10649 : : int dweight;
10650 : : double ln_var;
10651 : :
10652 : 408 : digits = var->digits[0];
10653 : 408 : dweight = var->weight * DEC_DIGITS;
10654 : :
10655 [ + + ]: 408 : if (var->ndigits > 1)
10656 : : {
10657 : 250 : digits = digits * NBASE + var->digits[1];
10658 : 250 : dweight -= DEC_DIGITS;
10659 : : }
10660 : :
10661 : : /*----------
10662 : : * We have var ~= digits * 10^dweight
10663 : : * so ln(var) ~= ln(digits) + dweight * ln(10)
10664 : : *----------
10665 : : */
10666 : 408 : ln_var = log((double) digits) + dweight * 2.302585092994046;
10667 : 408 : ln_dweight = (int) log10(fabs(ln_var));
10668 : : }
10669 : : else
10670 : : {
10671 : : /* Caller should fail on ln(0), but for the moment return zero */
10672 : 28 : ln_dweight = 0;
10673 : : }
10674 : : }
10675 : :
10676 : 506 : return ln_dweight;
10677 : : }
10678 : :
10679 : :
10680 : : /*
10681 : : * ln_var() -
10682 : : *
10683 : : * Compute the natural log of x
10684 : : */
10685 : : static void
10686 : 607 : ln_var(const NumericVar *arg, NumericVar *result, int rscale)
10687 : : {
10688 : : NumericVar x;
10689 : : NumericVar xx;
10690 : : int ni;
10691 : : NumericVar elem;
10692 : : NumericVar fact;
10693 : : int nsqrt;
10694 : : int local_rscale;
10695 : : int cmp;
10696 : :
10697 : 607 : cmp = cmp_var(arg, &const_zero);
10698 [ + + ]: 607 : if (cmp == 0)
10699 [ + - ]: 28 : ereport(ERROR,
10700 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
10701 : : errmsg("cannot take logarithm of zero")));
10702 [ + + ]: 579 : else if (cmp < 0)
10703 [ + - ]: 24 : ereport(ERROR,
10704 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
10705 : : errmsg("cannot take logarithm of a negative number")));
10706 : :
10707 : 555 : init_var(&x);
10708 : 555 : init_var(&xx);
10709 : 555 : init_var(&elem);
10710 : 555 : init_var(&fact);
10711 : :
10712 : 555 : set_var_from_var(arg, &x);
10713 : 555 : set_var_from_var(&const_two, &fact);
10714 : :
10715 : : /*
10716 : : * Reduce input into range 0.9 < x < 1.1 with repeated sqrt() operations.
10717 : : *
10718 : : * The final logarithm will have up to around rscale+6 significant digits.
10719 : : * Each sqrt() will roughly halve the weight of x, so adjust the local
10720 : : * rscale as we work so that we keep this many significant digits at each
10721 : : * step (plus a few more for good measure).
10722 : : *
10723 : : * Note that we allow local_rscale < 0 during this input reduction
10724 : : * process, which implies rounding before the decimal point. sqrt_var()
10725 : : * explicitly supports this, and it significantly reduces the work
10726 : : * required to reduce very large inputs to the required range. Once the
10727 : : * input reduction is complete, x.weight will be 0 and its display scale
10728 : : * will be non-negative again.
10729 : : */
10730 : 555 : nsqrt = 0;
10731 [ + + ]: 826 : while (cmp_var(&x, &const_zero_point_nine) <= 0)
10732 : : {
10733 : 271 : local_rscale = rscale - x.weight * DEC_DIGITS / 2 + 8;
10734 : 271 : sqrt_var(&x, &x, local_rscale);
10735 : 271 : mul_var(&fact, &const_two, &fact, 0);
10736 : 271 : nsqrt++;
10737 : : }
10738 [ + + ]: 2984 : while (cmp_var(&x, &const_one_point_one) >= 0)
10739 : : {
10740 : 2429 : local_rscale = rscale - x.weight * DEC_DIGITS / 2 + 8;
10741 : 2429 : sqrt_var(&x, &x, local_rscale);
10742 : 2429 : mul_var(&fact, &const_two, &fact, 0);
10743 : 2429 : nsqrt++;
10744 : : }
10745 : :
10746 : : /*
10747 : : * We use the Taylor series for 0.5 * ln((1+z)/(1-z)),
10748 : : *
10749 : : * z + z^3/3 + z^5/5 + ...
10750 : : *
10751 : : * where z = (x-1)/(x+1) is in the range (approximately) -0.053 .. 0.048
10752 : : * due to the above range-reduction of x.
10753 : : *
10754 : : * The convergence of this is not as fast as one would like, but is
10755 : : * tolerable given that z is small.
10756 : : *
10757 : : * The Taylor series result will be multiplied by 2^(nsqrt+1), which has a
10758 : : * decimal weight of (nsqrt+1) * log10(2), so work with this many extra
10759 : : * digits of precision (plus a few more for good measure).
10760 : : */
10761 : 555 : local_rscale = rscale + (int) ((nsqrt + 1) * 0.301029995663981) + 8;
10762 : :
10763 : 555 : sub_var(&x, &const_one, result);
10764 : 555 : add_var(&x, &const_one, &elem);
10765 : 555 : div_var(result, &elem, result, local_rscale, true, false);
10766 : 555 : set_var_from_var(result, &xx);
10767 : 555 : mul_var(result, result, &x, local_rscale);
10768 : :
10769 : 555 : ni = 1;
10770 : :
10771 : : for (;;)
10772 : : {
10773 : 10009 : ni += 2;
10774 : 10009 : mul_var(&xx, &x, &xx, local_rscale);
10775 : 10009 : div_var_int(&xx, ni, 0, &elem, local_rscale, true);
10776 : :
10777 [ + + ]: 10009 : if (elem.ndigits == 0)
10778 : 555 : break;
10779 : :
10780 : 9454 : add_var(result, &elem, result);
10781 : :
10782 [ - + ]: 9454 : if (elem.weight < (result->weight - local_rscale * 2 / DEC_DIGITS))
10783 : 0 : break;
10784 : : }
10785 : :
10786 : : /* Compensate for argument range reduction, round to requested rscale */
10787 : 555 : mul_var(result, &fact, result, rscale);
10788 : :
10789 : 555 : free_var(&x);
10790 : 555 : free_var(&xx);
10791 : 555 : free_var(&elem);
10792 : 555 : free_var(&fact);
10793 : 555 : }
10794 : :
10795 : :
10796 : : /*
10797 : : * log_var() -
10798 : : *
10799 : : * Compute the logarithm of num in a given base.
10800 : : *
10801 : : * Note: this routine chooses dscale of the result.
10802 : : */
10803 : : static void
10804 : 156 : log_var(const NumericVar *base, const NumericVar *num, NumericVar *result)
10805 : : {
10806 : : NumericVar ln_base;
10807 : : NumericVar ln_num;
10808 : : int ln_base_dweight;
10809 : : int ln_num_dweight;
10810 : : int result_dweight;
10811 : : int rscale;
10812 : : int ln_base_rscale;
10813 : : int ln_num_rscale;
10814 : :
10815 : 156 : init_var(&ln_base);
10816 : 156 : init_var(&ln_num);
10817 : :
10818 : : /* Estimated dweights of ln(base), ln(num) and the final result */
10819 : 156 : ln_base_dweight = estimate_ln_dweight(base);
10820 : 156 : ln_num_dweight = estimate_ln_dweight(num);
10821 : 156 : result_dweight = ln_num_dweight - ln_base_dweight;
10822 : :
10823 : : /*
10824 : : * Select the scale of the result so that it will have at least
10825 : : * NUMERIC_MIN_SIG_DIGITS significant digits and is not less than either
10826 : : * input's display scale.
10827 : : */
10828 : 156 : rscale = NUMERIC_MIN_SIG_DIGITS - result_dweight;
10829 : 156 : rscale = Max(rscale, base->dscale);
10830 : 156 : rscale = Max(rscale, num->dscale);
10831 : 156 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
10832 : 156 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
10833 : :
10834 : : /*
10835 : : * Set the scales for ln(base) and ln(num) so that they each have more
10836 : : * significant digits than the final result.
10837 : : */
10838 : 156 : ln_base_rscale = rscale + result_dweight - ln_base_dweight + 8;
10839 : 156 : ln_base_rscale = Max(ln_base_rscale, NUMERIC_MIN_DISPLAY_SCALE);
10840 : :
10841 : 156 : ln_num_rscale = rscale + result_dweight - ln_num_dweight + 8;
10842 : 156 : ln_num_rscale = Max(ln_num_rscale, NUMERIC_MIN_DISPLAY_SCALE);
10843 : :
10844 : : /* Form natural logarithms */
10845 : 156 : ln_var(base, &ln_base, ln_base_rscale);
10846 : 140 : ln_var(num, &ln_num, ln_num_rscale);
10847 : :
10848 : : /* Divide and round to the required scale */
10849 : 120 : div_var(&ln_num, &ln_base, result, rscale, true, false);
10850 : :
10851 : 116 : free_var(&ln_num);
10852 : 116 : free_var(&ln_base);
10853 : 116 : }
10854 : :
10855 : :
10856 : : /*
10857 : : * power_var() -
10858 : : *
10859 : : * Raise base to the power of exp
10860 : : *
10861 : : * Note: this routine chooses dscale of the result.
10862 : : */
10863 : : static void
10864 : 968 : power_var(const NumericVar *base, const NumericVar *exp, NumericVar *result)
10865 : : {
10866 : : int res_sign;
10867 : : NumericVar abs_base;
10868 : : NumericVar ln_base;
10869 : : NumericVar ln_num;
10870 : : int ln_dweight;
10871 : : int rscale;
10872 : : int sig_digits;
10873 : : int local_rscale;
10874 : : double val;
10875 : :
10876 : : /* If exp can be represented as an integer, use power_var_int */
10877 [ + + + + ]: 968 : if (exp->ndigits == 0 || exp->ndigits <= exp->weight + 1)
10878 : : {
10879 : : /* exact integer, but does it fit in int? */
10880 : : int64 expval64;
10881 : :
10882 [ + + ]: 878 : if (numericvar_to_int64(exp, &expval64))
10883 : : {
10884 [ + - + + ]: 873 : if (expval64 >= PG_INT32_MIN && expval64 <= PG_INT32_MAX)
10885 : : {
10886 : : /* Okay, use power_var_int */
10887 : 848 : power_var_int(base, (int) expval64, exp->dscale, result);
10888 : 840 : return;
10889 : : }
10890 : : }
10891 : : }
10892 : :
10893 : : /*
10894 : : * This avoids log(0) for cases of 0 raised to a non-integer. 0 ^ 0 is
10895 : : * handled by power_var_int().
10896 : : */
10897 [ + + ]: 120 : if (cmp_var(base, &const_zero) == 0)
10898 : : {
10899 : 14 : set_var_from_var(&const_zero, result);
10900 : 14 : result->dscale = NUMERIC_MIN_SIG_DIGITS; /* no need to round */
10901 : 14 : return;
10902 : : }
10903 : :
10904 : 106 : init_var(&abs_base);
10905 : 106 : init_var(&ln_base);
10906 : 106 : init_var(&ln_num);
10907 : :
10908 : : /*
10909 : : * If base is negative, insist that exp be an integer. The result is then
10910 : : * positive if exp is even and negative if exp is odd.
10911 : : */
10912 [ + + ]: 106 : if (base->sign == NUMERIC_NEG)
10913 : : {
10914 : : /*
10915 : : * Check that exp is an integer. This error code is defined by the
10916 : : * SQL standard, and matches other errors in numeric_power().
10917 : : */
10918 [ + - + + ]: 27 : if (exp->ndigits > 0 && exp->ndigits > exp->weight + 1)
10919 [ + - ]: 12 : ereport(ERROR,
10920 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
10921 : : errmsg("a negative number raised to a non-integer power yields a complex result")));
10922 : :
10923 : : /* Test if exp is odd or even */
10924 [ + - + + ]: 15 : if (exp->ndigits > 0 && exp->ndigits == exp->weight + 1 &&
10925 [ + + ]: 10 : (exp->digits[exp->ndigits - 1] & 1))
10926 : 5 : res_sign = NUMERIC_NEG;
10927 : : else
10928 : 10 : res_sign = NUMERIC_POS;
10929 : :
10930 : : /* Then work with abs(base) below */
10931 : 15 : set_var_from_var(base, &abs_base);
10932 : 15 : abs_base.sign = NUMERIC_POS;
10933 : 15 : base = &abs_base;
10934 : : }
10935 : : else
10936 : 79 : res_sign = NUMERIC_POS;
10937 : :
10938 : : /*----------
10939 : : * Decide on the scale for the ln() calculation. For this we need an
10940 : : * estimate of the weight of the result, which we obtain by doing an
10941 : : * initial low-precision calculation of exp * ln(base).
10942 : : *
10943 : : * We want result = e ^ (exp * ln(base))
10944 : : * so result dweight = log10(result) = exp * ln(base) * log10(e)
10945 : : *
10946 : : * We also perform a crude overflow test here so that we can exit early if
10947 : : * the full-precision result is sure to overflow, and to guard against
10948 : : * integer overflow when determining the scale for the real calculation.
10949 : : * exp_var() supports inputs up to NUMERIC_MAX_RESULT_SCALE * 3, so the
10950 : : * result will overflow if exp * ln(base) >= NUMERIC_MAX_RESULT_SCALE * 3.
10951 : : * Since the values here are only approximations, we apply a small fuzz
10952 : : * factor to this overflow test and let exp_var() determine the exact
10953 : : * overflow threshold so that it is consistent for all inputs.
10954 : : *----------
10955 : : */
10956 : 94 : ln_dweight = estimate_ln_dweight(base);
10957 : :
10958 : : /*
10959 : : * Set the scale for the low-precision calculation, computing ln(base) to
10960 : : * around 8 significant digits. Note that ln_dweight may be as small as
10961 : : * -NUMERIC_DSCALE_MAX, so the scale may exceed NUMERIC_MAX_DISPLAY_SCALE
10962 : : * here.
10963 : : */
10964 : 94 : local_rscale = 8 - ln_dweight;
10965 : 94 : local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
10966 : :
10967 : 94 : ln_var(base, &ln_base, local_rscale);
10968 : :
10969 : 94 : mul_var(&ln_base, exp, &ln_num, local_rscale);
10970 : :
10971 : 94 : val = numericvar_to_double_no_overflow(&ln_num);
10972 : :
10973 : : /* initial overflow/underflow test with fuzz factor */
10974 [ + + ]: 94 : if (fabs(val) > NUMERIC_MAX_RESULT_SCALE * 3.01)
10975 : : {
10976 [ - + ]: 5 : if (val > 0)
10977 [ # # ]: 0 : ereport(ERROR,
10978 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
10979 : : errmsg("value overflows numeric format")));
10980 : 5 : zero_var(result);
10981 : 5 : result->dscale = NUMERIC_MAX_DISPLAY_SCALE;
10982 : 5 : return;
10983 : : }
10984 : :
10985 : 89 : val *= 0.434294481903252; /* approximate decimal result weight */
10986 : :
10987 : : /* choose the result scale */
10988 : 89 : rscale = NUMERIC_MIN_SIG_DIGITS - (int) val;
10989 : 89 : rscale = Max(rscale, base->dscale);
10990 : 89 : rscale = Max(rscale, exp->dscale);
10991 : 89 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
10992 : 89 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
10993 : :
10994 : : /* significant digits required in the result */
10995 : 89 : sig_digits = rscale + (int) val;
10996 : 89 : sig_digits = Max(sig_digits, 0);
10997 : :
10998 : : /* set the scale for the real exp * ln(base) calculation */
10999 : 89 : local_rscale = sig_digits - ln_dweight + 8;
11000 : 89 : local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11001 : :
11002 : : /* and do the real calculation */
11003 : :
11004 : 89 : ln_var(base, &ln_base, local_rscale);
11005 : :
11006 : 89 : mul_var(&ln_base, exp, &ln_num, local_rscale);
11007 : :
11008 : 89 : exp_var(&ln_num, result, rscale);
11009 : :
11010 [ + + + - ]: 89 : if (res_sign == NUMERIC_NEG && result->ndigits > 0)
11011 : 5 : result->sign = NUMERIC_NEG;
11012 : :
11013 : 89 : free_var(&ln_num);
11014 : 89 : free_var(&ln_base);
11015 : 89 : free_var(&abs_base);
11016 : : }
11017 : :
11018 : : /*
11019 : : * power_var_int() -
11020 : : *
11021 : : * Raise base to the power of exp, where exp is an integer.
11022 : : *
11023 : : * Note: this routine chooses dscale of the result.
11024 : : */
11025 : : static void
11026 : 848 : power_var_int(const NumericVar *base, int exp, int exp_dscale,
11027 : : NumericVar *result)
11028 : : {
11029 : : double f;
11030 : : int p;
11031 : : int i;
11032 : : int rscale;
11033 : : int sig_digits;
11034 : : unsigned int mask;
11035 : : bool neg;
11036 : : NumericVar base_prod;
11037 : : int local_rscale;
11038 : :
11039 : : /*
11040 : : * Choose the result scale. For this we need an estimate of the decimal
11041 : : * weight of the result, which we obtain by approximating using double
11042 : : * precision arithmetic.
11043 : : *
11044 : : * We also perform crude overflow/underflow tests here so that we can exit
11045 : : * early if the result is sure to overflow/underflow, and to guard against
11046 : : * integer overflow when choosing the result scale.
11047 : : */
11048 [ + + ]: 848 : if (base->ndigits != 0)
11049 : : {
11050 : : /*----------
11051 : : * Choose f (double) and p (int) such that base ~= f * 10^p.
11052 : : * Then log10(result) = log10(base^exp) ~= exp * (log10(f) + p).
11053 : : *----------
11054 : : */
11055 : 826 : f = base->digits[0];
11056 : 826 : p = base->weight * DEC_DIGITS;
11057 : :
11058 [ + + + - ]: 891 : for (i = 1; i < base->ndigits && i * DEC_DIGITS < 16; i++)
11059 : : {
11060 : 65 : f = f * NBASE + base->digits[i];
11061 : 65 : p -= DEC_DIGITS;
11062 : : }
11063 : :
11064 : 826 : f = exp * (log10(f) + p); /* approximate decimal result weight */
11065 : : }
11066 : : else
11067 : 22 : f = 0; /* result is 0 or 1 (weight 0), or error */
11068 : :
11069 : : /* overflow/underflow tests with fuzz factors */
11070 [ + + ]: 848 : if (f > (NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS)
11071 [ + - ]: 8 : ereport(ERROR,
11072 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
11073 : : errmsg("value overflows numeric format")));
11074 [ + + ]: 840 : if (f + 1 < -NUMERIC_MAX_DISPLAY_SCALE)
11075 : : {
11076 : 10 : zero_var(result);
11077 : 10 : result->dscale = NUMERIC_MAX_DISPLAY_SCALE;
11078 : 151 : return;
11079 : : }
11080 : :
11081 : : /*
11082 : : * Choose the result scale in the same way as power_var(), so it has at
11083 : : * least NUMERIC_MIN_SIG_DIGITS significant digits and is not less than
11084 : : * either input's display scale.
11085 : : */
11086 : 830 : rscale = NUMERIC_MIN_SIG_DIGITS - (int) f;
11087 : 830 : rscale = Max(rscale, base->dscale);
11088 : 830 : rscale = Max(rscale, exp_dscale);
11089 : 830 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
11090 : 830 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
11091 : :
11092 : : /* Handle some common special cases, as well as corner cases */
11093 [ + + + + : 830 : switch (exp)
+ ]
11094 : : {
11095 : 52 : case 0:
11096 : :
11097 : : /*
11098 : : * While 0 ^ 0 can be either 1 or indeterminate (error), we treat
11099 : : * it as 1 because most programming languages do this. SQL:2003
11100 : : * also requires a return value of 1.
11101 : : * https://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_zero_power
11102 : : */
11103 : 52 : set_var_from_var(&const_one, result);
11104 : 52 : result->dscale = rscale; /* no need to round */
11105 : 52 : return;
11106 : 32 : case 1:
11107 : 32 : set_var_from_var(base, result);
11108 : 32 : round_var(result, rscale);
11109 : 32 : return;
11110 : 21 : case -1:
11111 : 21 : div_var(&const_one, base, result, rscale, true, true);
11112 : 21 : return;
11113 : 36 : case 2:
11114 : 36 : mul_var(base, base, result, rscale);
11115 : 36 : return;
11116 : 689 : default:
11117 : 689 : break;
11118 : : }
11119 : :
11120 : : /* Handle the special case where the base is zero */
11121 [ - + ]: 689 : if (base->ndigits == 0)
11122 : : {
11123 [ # # ]: 0 : if (exp < 0)
11124 [ # # ]: 0 : ereport(ERROR,
11125 : : (errcode(ERRCODE_DIVISION_BY_ZERO),
11126 : : errmsg("division by zero")));
11127 : 0 : zero_var(result);
11128 : 0 : result->dscale = rscale;
11129 : 0 : return;
11130 : : }
11131 : :
11132 : : /*
11133 : : * The general case repeatedly multiplies base according to the bit
11134 : : * pattern of exp.
11135 : : *
11136 : : * The local rscale used for each multiplication is varied to keep a fixed
11137 : : * number of significant digits, sufficient to give the required result
11138 : : * scale.
11139 : : */
11140 : :
11141 : : /*
11142 : : * Approximate number of significant digits in the result. Note that the
11143 : : * underflow test above, together with the choice of rscale, ensures that
11144 : : * this approximation is necessarily > 0.
11145 : : */
11146 : 689 : sig_digits = 1 + rscale + (int) f;
11147 : :
11148 : : /*
11149 : : * The multiplications to produce the result may introduce an error of up
11150 : : * to around log10(abs(exp)) digits, so work with this many extra digits
11151 : : * of precision (plus a few more for good measure).
11152 : : */
11153 : 689 : sig_digits += (int) log(fabs((double) exp)) + 8;
11154 : :
11155 : : /*
11156 : : * Now we can proceed with the multiplications.
11157 : : */
11158 : 689 : neg = (exp < 0);
11159 : 689 : mask = pg_abs_s32(exp);
11160 : :
11161 : 689 : init_var(&base_prod);
11162 : 689 : set_var_from_var(base, &base_prod);
11163 : :
11164 [ + + ]: 689 : if (mask & 1)
11165 : 343 : set_var_from_var(base, result);
11166 : : else
11167 : 346 : set_var_from_var(&const_one, result);
11168 : :
11169 [ + + ]: 3618 : while ((mask >>= 1) > 0)
11170 : : {
11171 : : /*
11172 : : * Do the multiplications using rscales large enough to hold the
11173 : : * results to the required number of significant digits, but don't
11174 : : * waste time by exceeding the scales of the numbers themselves.
11175 : : */
11176 : 2929 : local_rscale = sig_digits - 2 * base_prod.weight * DEC_DIGITS;
11177 : 2929 : local_rscale = Min(local_rscale, 2 * base_prod.dscale);
11178 : 2929 : local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11179 : :
11180 : 2929 : mul_var(&base_prod, &base_prod, &base_prod, local_rscale);
11181 : :
11182 [ + + ]: 2929 : if (mask & 1)
11183 : : {
11184 : 1932 : local_rscale = sig_digits -
11185 : 1932 : (base_prod.weight + result->weight) * DEC_DIGITS;
11186 : 1932 : local_rscale = Min(local_rscale,
11187 : : base_prod.dscale + result->dscale);
11188 : 1932 : local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11189 : :
11190 : 1932 : mul_var(&base_prod, result, result, local_rscale);
11191 : : }
11192 : :
11193 : : /*
11194 : : * When abs(base) > 1, the number of digits to the left of the decimal
11195 : : * point in base_prod doubles at each iteration, so if exp is large we
11196 : : * could easily spend large amounts of time and memory space doing the
11197 : : * multiplications. But once the weight exceeds what will fit in
11198 : : * int16, the final result is guaranteed to overflow (or underflow, if
11199 : : * exp < 0), so we can give up before wasting too many cycles.
11200 : : */
11201 [ + - ]: 2929 : if (base_prod.weight > NUMERIC_WEIGHT_MAX ||
11202 [ - + ]: 2929 : result->weight > NUMERIC_WEIGHT_MAX)
11203 : : {
11204 : : /* overflow, unless neg, in which case result should be 0 */
11205 [ # # ]: 0 : if (!neg)
11206 [ # # ]: 0 : ereport(ERROR,
11207 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
11208 : : errmsg("value overflows numeric format")));
11209 : 0 : zero_var(result);
11210 : 0 : neg = false;
11211 : 0 : break;
11212 : : }
11213 : : }
11214 : :
11215 : 689 : free_var(&base_prod);
11216 : :
11217 : : /* Compensate for input sign, and round to requested rscale */
11218 [ + + ]: 689 : if (neg)
11219 : 328 : div_var(&const_one, result, result, rscale, true, false);
11220 : : else
11221 : 361 : round_var(result, rscale);
11222 : : }
11223 : :
11224 : : /*
11225 : : * power_ten_int() -
11226 : : *
11227 : : * Raise ten to the power of exp, where exp is an integer. Note that unlike
11228 : : * power_var_int(), this does no overflow/underflow checking or rounding.
11229 : : */
11230 : : static void
11231 : 152 : power_ten_int(int exp, NumericVar *result)
11232 : : {
11233 : : /* Construct the result directly, starting from 10^0 = 1 */
11234 : 152 : set_var_from_var(&const_one, result);
11235 : :
11236 : : /* Scale needed to represent the result exactly */
11237 [ + + ]: 152 : result->dscale = exp < 0 ? -exp : 0;
11238 : :
11239 : : /* Base-NBASE weight of result and remaining exponent */
11240 [ + + ]: 152 : if (exp >= 0)
11241 : 108 : result->weight = exp / DEC_DIGITS;
11242 : : else
11243 : 44 : result->weight = (exp + 1) / DEC_DIGITS - 1;
11244 : :
11245 : 152 : exp -= result->weight * DEC_DIGITS;
11246 : :
11247 : : /* Final adjustment of the result's single NBASE digit */
11248 [ + + ]: 396 : while (exp-- > 0)
11249 : 244 : result->digits[0] *= 10;
11250 : 152 : }
11251 : :
11252 : : /*
11253 : : * random_var() - return a random value in the range [rmin, rmax].
11254 : : */
11255 : : static void
11256 : 22292 : random_var(pg_prng_state *state, const NumericVar *rmin,
11257 : : const NumericVar *rmax, NumericVar *result)
11258 : : {
11259 : : int rscale;
11260 : : NumericVar rlen;
11261 : : int res_ndigits;
11262 : : int n;
11263 : : int pow10;
11264 : : int i;
11265 : : uint64 rlen64;
11266 : : int rlen64_ndigits;
11267 : :
11268 : 22292 : rscale = Max(rmin->dscale, rmax->dscale);
11269 : :
11270 : : /* Compute rlen = rmax - rmin and check the range bounds */
11271 : 22292 : init_var(&rlen);
11272 : 22292 : sub_var(rmax, rmin, &rlen);
11273 : :
11274 [ + + ]: 22292 : if (rlen.sign == NUMERIC_NEG)
11275 [ + - ]: 4 : ereport(ERROR,
11276 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
11277 : : errmsg("lower bound must be less than or equal to upper bound"));
11278 : :
11279 : : /* Special case for an empty range */
11280 [ + + ]: 22288 : if (rlen.ndigits == 0)
11281 : : {
11282 : 8 : set_var_from_var(rmin, result);
11283 : 8 : result->dscale = rscale;
11284 : 8 : free_var(&rlen);
11285 : 8 : return;
11286 : : }
11287 : :
11288 : : /*
11289 : : * Otherwise, select a random value in the range [0, rlen = rmax - rmin],
11290 : : * and shift it to the required range by adding rmin.
11291 : : */
11292 : :
11293 : : /* Required result digits */
11294 : 22280 : res_ndigits = rlen.weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
11295 : :
11296 : : /*
11297 : : * To get the required rscale, the final result digit must be a multiple
11298 : : * of pow10 = 10^n, where n = (-rscale) mod DEC_DIGITS.
11299 : : */
11300 : 22280 : n = ((rscale + DEC_DIGITS - 1) / DEC_DIGITS) * DEC_DIGITS - rscale;
11301 : 22280 : pow10 = 1;
11302 [ + + ]: 58600 : for (i = 0; i < n; i++)
11303 : 36320 : pow10 *= 10;
11304 : :
11305 : : /*
11306 : : * To choose a random value uniformly from the range [0, rlen], we choose
11307 : : * from the slightly larger range [0, rlen2], where rlen2 is formed from
11308 : : * rlen by copying the first 4 NBASE digits, and setting all remaining
11309 : : * decimal digits to "9".
11310 : : *
11311 : : * Without loss of generality, we can ignore the weight of rlen2 and treat
11312 : : * it as a pure integer for the purposes of this discussion. The process
11313 : : * above gives rlen2 + 1 = rlen64 * 10^N, for some integer N, where rlen64
11314 : : * is a 64-bit integer formed from the first 4 NBASE digits copied from
11315 : : * rlen. Since this trivially factors into smaller pieces that fit in
11316 : : * 64-bit integers, the task of choosing a random value uniformly from the
11317 : : * rlen2 + 1 possible values in [0, rlen2] is much simpler.
11318 : : *
11319 : : * If the random value selected is too large, it is rejected, and we try
11320 : : * again until we get a result <= rlen, ensuring that the overall result
11321 : : * is uniform (no particular value is any more likely than any other).
11322 : : *
11323 : : * Since rlen64 holds 4 NBASE digits from rlen, it contains at least
11324 : : * DEC_DIGITS * 3 + 1 decimal digits (i.e., at least 13 decimal digits,
11325 : : * when DEC_DIGITS is 4). Therefore the probability of needing to reject
11326 : : * the value chosen and retry is less than 1e-13.
11327 : : */
11328 : 22280 : rlen64 = (uint64) rlen.digits[0];
11329 : 22280 : rlen64_ndigits = 1;
11330 [ + + + + ]: 50808 : while (rlen64_ndigits < res_ndigits && rlen64_ndigits < 4)
11331 : : {
11332 : 28528 : rlen64 *= NBASE;
11333 [ + + ]: 28528 : if (rlen64_ndigits < rlen.ndigits)
11334 : 4408 : rlen64 += rlen.digits[rlen64_ndigits];
11335 : 28528 : rlen64_ndigits++;
11336 : : }
11337 : :
11338 : : /* Loop until we get a result <= rlen */
11339 : : do
11340 : : {
11341 : : NumericDigit *res_digits;
11342 : : uint64 rand;
11343 : : int whole_ndigits;
11344 : :
11345 : 22280 : alloc_var(result, res_ndigits);
11346 : 22280 : result->sign = NUMERIC_POS;
11347 : 22280 : result->weight = rlen.weight;
11348 : 22280 : result->dscale = rscale;
11349 : 22280 : res_digits = result->digits;
11350 : :
11351 : : /*
11352 : : * Set the first rlen64_ndigits using a random value in [0, rlen64].
11353 : : *
11354 : : * If this is the whole result, and rscale is not a multiple of
11355 : : * DEC_DIGITS (pow10 from above is not 1), then we need this to be a
11356 : : * multiple of pow10.
11357 : : */
11358 [ + + + + ]: 22280 : if (rlen64_ndigits == res_ndigits && pow10 != 1)
11359 : 14088 : rand = pg_prng_uint64_range(state, 0, rlen64 / pow10) * pow10;
11360 : : else
11361 : 8192 : rand = pg_prng_uint64_range(state, 0, rlen64);
11362 : :
11363 [ + + ]: 73088 : for (i = rlen64_ndigits - 1; i >= 0; i--)
11364 : : {
11365 : 50808 : res_digits[i] = (NumericDigit) (rand % NBASE);
11366 : 50808 : rand = rand / NBASE;
11367 : : }
11368 : :
11369 : : /*
11370 : : * Set the remaining digits to random values in range [0, NBASE),
11371 : : * noting that the last digit needs to be a multiple of pow10.
11372 : : */
11373 : 22280 : whole_ndigits = res_ndigits;
11374 [ + + ]: 22280 : if (pow10 != 1)
11375 : 22140 : whole_ndigits--;
11376 : :
11377 : : /* Set whole digits in groups of 4 for best performance */
11378 : 22280 : i = rlen64_ndigits;
11379 [ + + ]: 22320 : while (i < whole_ndigits - 3)
11380 : : {
11381 : 40 : rand = pg_prng_uint64_range(state, 0,
11382 : : (uint64) NBASE * NBASE * NBASE * NBASE - 1);
11383 : 40 : res_digits[i++] = (NumericDigit) (rand % NBASE);
11384 : 40 : rand = rand / NBASE;
11385 : 40 : res_digits[i++] = (NumericDigit) (rand % NBASE);
11386 : 40 : rand = rand / NBASE;
11387 : 40 : res_digits[i++] = (NumericDigit) (rand % NBASE);
11388 : 40 : rand = rand / NBASE;
11389 : 40 : res_digits[i++] = (NumericDigit) rand;
11390 : : }
11391 : :
11392 : : /* Remaining whole digits */
11393 [ + + ]: 22420 : while (i < whole_ndigits)
11394 : : {
11395 : 140 : rand = pg_prng_uint64_range(state, 0, NBASE - 1);
11396 : 140 : res_digits[i++] = (NumericDigit) rand;
11397 : : }
11398 : :
11399 : : /* Final partial digit (multiple of pow10) */
11400 [ + + ]: 22280 : if (i < res_ndigits)
11401 : : {
11402 : 8052 : rand = pg_prng_uint64_range(state, 0, NBASE / pow10 - 1) * pow10;
11403 : 8052 : res_digits[i] = (NumericDigit) rand;
11404 : : }
11405 : :
11406 : : /* Remove leading/trailing zeroes */
11407 : 22280 : strip_var(result);
11408 : :
11409 : : /* If result > rlen, try again */
11410 : :
11411 [ - + ]: 22280 : } while (cmp_var(result, &rlen) > 0);
11412 : :
11413 : : /* Offset the result to the required range */
11414 : 22280 : add_var(result, rmin, result);
11415 : :
11416 : 22280 : free_var(&rlen);
11417 : : }
11418 : :
11419 : :
11420 : : /* ----------------------------------------------------------------------
11421 : : *
11422 : : * Following are the lowest level functions that operate unsigned
11423 : : * on the variable level
11424 : : *
11425 : : * ----------------------------------------------------------------------
11426 : : */
11427 : :
11428 : :
11429 : : /* ----------
11430 : : * cmp_abs() -
11431 : : *
11432 : : * Compare the absolute values of var1 and var2
11433 : : * Returns: -1 for ABS(var1) < ABS(var2)
11434 : : * 0 for ABS(var1) == ABS(var2)
11435 : : * 1 for ABS(var1) > ABS(var2)
11436 : : * ----------
11437 : : */
11438 : : static int
11439 : 469680 : cmp_abs(const NumericVar *var1, const NumericVar *var2)
11440 : : {
11441 : 939360 : return cmp_abs_common(var1->digits, var1->ndigits, var1->weight,
11442 : 469680 : var2->digits, var2->ndigits, var2->weight);
11443 : : }
11444 : :
11445 : : /* ----------
11446 : : * cmp_abs_common() -
11447 : : *
11448 : : * Main routine of cmp_abs(). This function can be used by both
11449 : : * NumericVar and Numeric.
11450 : : * ----------
11451 : : */
11452 : : static int
11453 : 18450844 : cmp_abs_common(const NumericDigit *var1digits, int var1ndigits, int var1weight,
11454 : : const NumericDigit *var2digits, int var2ndigits, int var2weight)
11455 : : {
11456 : 18450844 : int i1 = 0;
11457 : 18450844 : int i2 = 0;
11458 : :
11459 : : /* Check any digits before the first common digit */
11460 : :
11461 [ + + + + ]: 18450844 : while (var1weight > var2weight && i1 < var1ndigits)
11462 : : {
11463 [ + - ]: 15075 : if (var1digits[i1++] != 0)
11464 : 15075 : return 1;
11465 : 0 : var1weight--;
11466 : : }
11467 [ + + + + ]: 18435769 : while (var2weight > var1weight && i2 < var2ndigits)
11468 : : {
11469 [ + - ]: 100870 : if (var2digits[i2++] != 0)
11470 : 100870 : return -1;
11471 : 0 : var2weight--;
11472 : : }
11473 : :
11474 : : /* At this point, either w1 == w2 or we've run out of digits */
11475 : :
11476 [ + + ]: 18334899 : if (var1weight == var2weight)
11477 : : {
11478 [ + + + + ]: 28821918 : while (i1 < var1ndigits && i2 < var2ndigits)
11479 : : {
11480 : 19358181 : int stat = var1digits[i1++] - var2digits[i2++];
11481 : :
11482 [ + + ]: 19358181 : if (stat)
11483 : : {
11484 [ + + ]: 8866918 : if (stat > 0)
11485 : 5253814 : return 1;
11486 : 3613104 : return -1;
11487 : : }
11488 : : }
11489 : : }
11490 : :
11491 : : /*
11492 : : * At this point, we've run out of digits on one side or the other; so any
11493 : : * remaining nonzero digits imply that side is larger
11494 : : */
11495 [ + + ]: 9468081 : while (i1 < var1ndigits)
11496 : : {
11497 [ + + ]: 6276 : if (var1digits[i1++] != 0)
11498 : 6176 : return 1;
11499 : : }
11500 [ + + ]: 9462057 : while (i2 < var2ndigits)
11501 : : {
11502 [ + + ]: 887 : if (var2digits[i2++] != 0)
11503 : 635 : return -1;
11504 : : }
11505 : :
11506 : 9461170 : return 0;
11507 : : }
11508 : :
11509 : :
11510 : : /*
11511 : : * add_abs() -
11512 : : *
11513 : : * Add the absolute values of two variables into result.
11514 : : * result might point to one of the operands without danger.
11515 : : */
11516 : : static void
11517 : 299648 : add_abs(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
11518 : : {
11519 : : NumericDigit *res_buf;
11520 : : NumericDigit *res_digits;
11521 : : int res_ndigits;
11522 : : int res_weight;
11523 : : int res_rscale,
11524 : : rscale1,
11525 : : rscale2;
11526 : : int res_dscale;
11527 : : int i,
11528 : : i1,
11529 : : i2;
11530 : 299648 : int carry = 0;
11531 : :
11532 : : /* copy these values into local vars for speed in inner loop */
11533 : 299648 : int var1ndigits = var1->ndigits;
11534 : 299648 : int var2ndigits = var2->ndigits;
11535 : 299648 : NumericDigit *var1digits = var1->digits;
11536 : 299648 : NumericDigit *var2digits = var2->digits;
11537 : :
11538 : 299648 : res_weight = Max(var1->weight, var2->weight) + 1;
11539 : :
11540 : 299648 : res_dscale = Max(var1->dscale, var2->dscale);
11541 : :
11542 : : /* Note: here we are figuring rscale in base-NBASE digits */
11543 : 299648 : rscale1 = var1->ndigits - var1->weight - 1;
11544 : 299648 : rscale2 = var2->ndigits - var2->weight - 1;
11545 : 299648 : res_rscale = Max(rscale1, rscale2);
11546 : :
11547 : 299648 : res_ndigits = res_rscale + res_weight + 1;
11548 [ - + ]: 299648 : if (res_ndigits <= 0)
11549 : 0 : res_ndigits = 1;
11550 : :
11551 : 299648 : res_buf = digitbuf_alloc(res_ndigits + 1);
11552 : 299648 : res_buf[0] = 0; /* spare digit for later rounding */
11553 : 299648 : res_digits = res_buf + 1;
11554 : :
11555 : 299648 : i1 = res_rscale + var1->weight + 1;
11556 : 299648 : i2 = res_rscale + var2->weight + 1;
11557 [ + + ]: 2480432 : for (i = res_ndigits - 1; i >= 0; i--)
11558 : : {
11559 : 2180784 : i1--;
11560 : 2180784 : i2--;
11561 [ + + + + ]: 2180784 : if (i1 >= 0 && i1 < var1ndigits)
11562 : 987934 : carry += var1digits[i1];
11563 [ + + + + ]: 2180784 : if (i2 >= 0 && i2 < var2ndigits)
11564 : 779929 : carry += var2digits[i2];
11565 : :
11566 [ + + ]: 2180784 : if (carry >= NBASE)
11567 : : {
11568 : 159465 : res_digits[i] = carry - NBASE;
11569 : 159465 : carry = 1;
11570 : : }
11571 : : else
11572 : : {
11573 : 2021319 : res_digits[i] = carry;
11574 : 2021319 : carry = 0;
11575 : : }
11576 : : }
11577 : :
11578 : : Assert(carry == 0); /* else we failed to allow for carry out */
11579 : :
11580 [ + + ]: 299648 : digitbuf_free(result->buf);
11581 : 299648 : result->ndigits = res_ndigits;
11582 : 299648 : result->buf = res_buf;
11583 : 299648 : result->digits = res_digits;
11584 : 299648 : result->weight = res_weight;
11585 : 299648 : result->dscale = res_dscale;
11586 : :
11587 : : /* Remove leading/trailing zeroes */
11588 : 299648 : strip_var(result);
11589 : 299648 : }
11590 : :
11591 : :
11592 : : /*
11593 : : * sub_abs()
11594 : : *
11595 : : * Subtract the absolute value of var2 from the absolute value of var1
11596 : : * and store in result. result might point to one of the operands
11597 : : * without danger.
11598 : : *
11599 : : * ABS(var1) MUST BE GREATER OR EQUAL ABS(var2) !!!
11600 : : */
11601 : : static void
11602 : 436188 : sub_abs(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
11603 : : {
11604 : : NumericDigit *res_buf;
11605 : : NumericDigit *res_digits;
11606 : : int res_ndigits;
11607 : : int res_weight;
11608 : : int res_rscale,
11609 : : rscale1,
11610 : : rscale2;
11611 : : int res_dscale;
11612 : : int i,
11613 : : i1,
11614 : : i2;
11615 : 436188 : int borrow = 0;
11616 : :
11617 : : /* copy these values into local vars for speed in inner loop */
11618 : 436188 : int var1ndigits = var1->ndigits;
11619 : 436188 : int var2ndigits = var2->ndigits;
11620 : 436188 : NumericDigit *var1digits = var1->digits;
11621 : 436188 : NumericDigit *var2digits = var2->digits;
11622 : :
11623 : 436188 : res_weight = var1->weight;
11624 : :
11625 : 436188 : res_dscale = Max(var1->dscale, var2->dscale);
11626 : :
11627 : : /* Note: here we are figuring rscale in base-NBASE digits */
11628 : 436188 : rscale1 = var1->ndigits - var1->weight - 1;
11629 : 436188 : rscale2 = var2->ndigits - var2->weight - 1;
11630 : 436188 : res_rscale = Max(rscale1, rscale2);
11631 : :
11632 : 436188 : res_ndigits = res_rscale + res_weight + 1;
11633 [ - + ]: 436188 : if (res_ndigits <= 0)
11634 : 0 : res_ndigits = 1;
11635 : :
11636 : 436188 : res_buf = digitbuf_alloc(res_ndigits + 1);
11637 : 436188 : res_buf[0] = 0; /* spare digit for later rounding */
11638 : 436188 : res_digits = res_buf + 1;
11639 : :
11640 : 436188 : i1 = res_rscale + var1->weight + 1;
11641 : 436188 : i2 = res_rscale + var2->weight + 1;
11642 [ + + ]: 3489404 : for (i = res_ndigits - 1; i >= 0; i--)
11643 : : {
11644 : 3053216 : i1--;
11645 : 3053216 : i2--;
11646 [ + - + + ]: 3053216 : if (i1 >= 0 && i1 < var1ndigits)
11647 : 2743429 : borrow += var1digits[i1];
11648 [ + + + + ]: 3053216 : if (i2 >= 0 && i2 < var2ndigits)
11649 : 2695949 : borrow -= var2digits[i2];
11650 : :
11651 [ + + ]: 3053216 : if (borrow < 0)
11652 : : {
11653 : 332355 : res_digits[i] = borrow + NBASE;
11654 : 332355 : borrow = -1;
11655 : : }
11656 : : else
11657 : : {
11658 : 2720861 : res_digits[i] = borrow;
11659 : 2720861 : borrow = 0;
11660 : : }
11661 : : }
11662 : :
11663 : : Assert(borrow == 0); /* else caller gave us var1 < var2 */
11664 : :
11665 [ + + ]: 436188 : digitbuf_free(result->buf);
11666 : 436188 : result->ndigits = res_ndigits;
11667 : 436188 : result->buf = res_buf;
11668 : 436188 : result->digits = res_digits;
11669 : 436188 : result->weight = res_weight;
11670 : 436188 : result->dscale = res_dscale;
11671 : :
11672 : : /* Remove leading/trailing zeroes */
11673 : 436188 : strip_var(result);
11674 : 436188 : }
11675 : :
11676 : : /*
11677 : : * round_var
11678 : : *
11679 : : * Round the value of a variable to no more than rscale decimal digits
11680 : : * after the decimal point. NOTE: we allow rscale < 0 here, implying
11681 : : * rounding before the decimal point.
11682 : : */
11683 : : static void
11684 : 168363 : round_var(NumericVar *var, int rscale)
11685 : : {
11686 : 168363 : NumericDigit *digits = var->digits;
11687 : : int di;
11688 : : int ndigits;
11689 : : int carry;
11690 : :
11691 : 168363 : var->dscale = rscale;
11692 : :
11693 : : /* decimal digits wanted */
11694 : 168363 : di = (var->weight + 1) * DEC_DIGITS + rscale;
11695 : :
11696 : : /*
11697 : : * If di = 0, the value loses all digits, but could round up to 1 if its
11698 : : * first extra digit is >= 5. If di < 0 the result must be 0.
11699 : : */
11700 [ + + ]: 168363 : if (di < 0)
11701 : : {
11702 : 71 : var->ndigits = 0;
11703 : 71 : var->weight = 0;
11704 : 71 : var->sign = NUMERIC_POS;
11705 : : }
11706 : : else
11707 : : {
11708 : : /* NBASE digits wanted */
11709 : 168292 : ndigits = (di + DEC_DIGITS - 1) / DEC_DIGITS;
11710 : :
11711 : : /* 0, or number of decimal digits to keep in last NBASE digit */
11712 : 168292 : di %= DEC_DIGITS;
11713 : :
11714 [ + + ]: 168292 : if (ndigits < var->ndigits ||
11715 [ + + + + ]: 30754 : (ndigits == var->ndigits && di > 0))
11716 : : {
11717 : 140015 : var->ndigits = ndigits;
11718 : :
11719 : : #if DEC_DIGITS == 1
11720 : : /* di must be zero */
11721 : : carry = (digits[ndigits] >= HALF_NBASE) ? 1 : 0;
11722 : : #else
11723 [ + + ]: 140015 : if (di == 0)
11724 : 109935 : carry = (digits[ndigits] >= HALF_NBASE) ? 1 : 0;
11725 : : else
11726 : : {
11727 : : /* Must round within last NBASE digit */
11728 : : int extra,
11729 : : pow10;
11730 : :
11731 : : #if DEC_DIGITS == 4
11732 : 30080 : pow10 = round_powers[di];
11733 : : #elif DEC_DIGITS == 2
11734 : : pow10 = 10;
11735 : : #else
11736 : : #error unsupported NBASE
11737 : : #endif
11738 : 30080 : extra = digits[--ndigits] % pow10;
11739 : 30080 : digits[ndigits] -= extra;
11740 : 30080 : carry = 0;
11741 [ + + ]: 30080 : if (extra >= pow10 / 2)
11742 : : {
11743 : 14019 : pow10 += digits[ndigits];
11744 [ + + ]: 14019 : if (pow10 >= NBASE)
11745 : : {
11746 : 595 : pow10 -= NBASE;
11747 : 595 : carry = 1;
11748 : : }
11749 : 14019 : digits[ndigits] = pow10;
11750 : : }
11751 : : }
11752 : : #endif
11753 : :
11754 : : /* Propagate carry if needed */
11755 [ + + ]: 166905 : while (carry)
11756 : : {
11757 : 26890 : carry += digits[--ndigits];
11758 [ + + ]: 26890 : if (carry >= NBASE)
11759 : : {
11760 : 20528 : digits[ndigits] = carry - NBASE;
11761 : 20528 : carry = 1;
11762 : : }
11763 : : else
11764 : : {
11765 : 6362 : digits[ndigits] = carry;
11766 : 6362 : carry = 0;
11767 : : }
11768 : : }
11769 : :
11770 [ + + ]: 140015 : if (ndigits < 0)
11771 : : {
11772 : : Assert(ndigits == -1); /* better not have added > 1 digit */
11773 : : Assert(var->digits > var->buf);
11774 : 65 : var->digits--;
11775 : 65 : var->ndigits++;
11776 : 65 : var->weight++;
11777 : : }
11778 : : }
11779 : : }
11780 : 168363 : }
11781 : :
11782 : : /*
11783 : : * trunc_var
11784 : : *
11785 : : * Truncate (towards zero) the value of a variable at rscale decimal digits
11786 : : * after the decimal point. NOTE: we allow rscale < 0 here, implying
11787 : : * truncation before the decimal point.
11788 : : */
11789 : : static void
11790 : 280556 : trunc_var(NumericVar *var, int rscale)
11791 : : {
11792 : : int di;
11793 : : int ndigits;
11794 : :
11795 : 280556 : var->dscale = rscale;
11796 : :
11797 : : /* decimal digits wanted */
11798 : 280556 : di = (var->weight + 1) * DEC_DIGITS + rscale;
11799 : :
11800 : : /*
11801 : : * If di <= 0, the value loses all digits.
11802 : : */
11803 [ + + ]: 280556 : if (di <= 0)
11804 : : {
11805 : 66 : var->ndigits = 0;
11806 : 66 : var->weight = 0;
11807 : 66 : var->sign = NUMERIC_POS;
11808 : : }
11809 : : else
11810 : : {
11811 : : /* NBASE digits wanted */
11812 : 280490 : ndigits = (di + DEC_DIGITS - 1) / DEC_DIGITS;
11813 : :
11814 [ + + ]: 280490 : if (ndigits <= var->ndigits)
11815 : : {
11816 : 280302 : var->ndigits = ndigits;
11817 : :
11818 : : #if DEC_DIGITS == 1
11819 : : /* no within-digit stuff to worry about */
11820 : : #else
11821 : : /* 0, or number of decimal digits to keep in last NBASE digit */
11822 : 280302 : di %= DEC_DIGITS;
11823 : :
11824 [ + + ]: 280302 : if (di > 0)
11825 : : {
11826 : : /* Must truncate within last NBASE digit */
11827 : 63 : NumericDigit *digits = var->digits;
11828 : : int extra,
11829 : : pow10;
11830 : :
11831 : : #if DEC_DIGITS == 4
11832 : 63 : pow10 = round_powers[di];
11833 : : #elif DEC_DIGITS == 2
11834 : : pow10 = 10;
11835 : : #else
11836 : : #error unsupported NBASE
11837 : : #endif
11838 : 63 : extra = digits[--ndigits] % pow10;
11839 : 63 : digits[ndigits] -= extra;
11840 : : }
11841 : : #endif
11842 : : }
11843 : : }
11844 : 280556 : }
11845 : :
11846 : : /*
11847 : : * strip_var
11848 : : *
11849 : : * Strip any leading and trailing zeroes from a numeric variable
11850 : : */
11851 : : static void
11852 : 2188197 : strip_var(NumericVar *var)
11853 : : {
11854 : 2188197 : NumericDigit *digits = var->digits;
11855 : 2188197 : int ndigits = var->ndigits;
11856 : :
11857 : : /* Strip leading zeroes */
11858 [ + + + + ]: 3761007 : while (ndigits > 0 && *digits == 0)
11859 : : {
11860 : 1572810 : digits++;
11861 : 1572810 : var->weight--;
11862 : 1572810 : ndigits--;
11863 : : }
11864 : :
11865 : : /* Strip trailing zeroes */
11866 [ + + + + ]: 2640160 : while (ndigits > 0 && digits[ndigits - 1] == 0)
11867 : 451963 : ndigits--;
11868 : :
11869 : : /* If it's zero, normalize the sign and weight */
11870 [ + + ]: 2188197 : if (ndigits == 0)
11871 : : {
11872 : 32757 : var->sign = NUMERIC_POS;
11873 : 32757 : var->weight = 0;
11874 : : }
11875 : :
11876 : 2188197 : var->digits = digits;
11877 : 2188197 : var->ndigits = ndigits;
11878 : 2188197 : }
11879 : :
11880 : :
11881 : : /* ----------------------------------------------------------------------
11882 : : *
11883 : : * Fast sum accumulator functions
11884 : : *
11885 : : * ----------------------------------------------------------------------
11886 : : */
11887 : :
11888 : : /*
11889 : : * Reset the accumulator's value to zero. The buffers to hold the digits
11890 : : * are not free'd.
11891 : : */
11892 : : static void
11893 : 12 : accum_sum_reset(NumericSumAccum *accum)
11894 : : {
11895 : : int i;
11896 : :
11897 : 12 : accum->dscale = 0;
11898 [ + + ]: 44 : for (i = 0; i < accum->ndigits; i++)
11899 : : {
11900 : 32 : accum->pos_digits[i] = 0;
11901 : 32 : accum->neg_digits[i] = 0;
11902 : : }
11903 : 12 : }
11904 : :
11905 : : /*
11906 : : * Accumulate a new value.
11907 : : */
11908 : : static void
11909 : 1570442 : accum_sum_add(NumericSumAccum *accum, const NumericVar *val)
11910 : : {
11911 : : int32 *accum_digits;
11912 : : int i,
11913 : : val_i;
11914 : : int val_ndigits;
11915 : : NumericDigit *val_digits;
11916 : :
11917 : : /*
11918 : : * If we have accumulated too many values since the last carry
11919 : : * propagation, do it now, to avoid overflowing. (We could allow more
11920 : : * than NBASE - 1, if we reserved two extra digits, rather than one, for
11921 : : * carry propagation. But even with NBASE - 1, this needs to be done so
11922 : : * seldom, that the performance difference is negligible.)
11923 : : */
11924 [ + + ]: 1570442 : if (accum->num_uncarried == NBASE - 1)
11925 : 101 : accum_sum_carry(accum);
11926 : :
11927 : : /*
11928 : : * Adjust the weight or scale of the old value, so that it can accommodate
11929 : : * the new value.
11930 : : */
11931 : 1570442 : accum_sum_rescale(accum, val);
11932 : :
11933 : : /* */
11934 [ + + ]: 1570442 : if (val->sign == NUMERIC_POS)
11935 : 1169990 : accum_digits = accum->pos_digits;
11936 : : else
11937 : 400452 : accum_digits = accum->neg_digits;
11938 : :
11939 : : /* copy these values into local vars for speed in loop */
11940 : 1570442 : val_ndigits = val->ndigits;
11941 : 1570442 : val_digits = val->digits;
11942 : :
11943 : 1570442 : i = accum->weight - val->weight;
11944 [ + + ]: 7926576 : for (val_i = 0; val_i < val_ndigits; val_i++)
11945 : : {
11946 : 6356134 : accum_digits[i] += (int32) val_digits[val_i];
11947 : 6356134 : i++;
11948 : : }
11949 : :
11950 : 1570442 : accum->num_uncarried++;
11951 : 1570442 : }
11952 : :
11953 : : /*
11954 : : * Propagate carries.
11955 : : */
11956 : : static void
11957 : 115153 : accum_sum_carry(NumericSumAccum *accum)
11958 : : {
11959 : : int i;
11960 : : int ndigits;
11961 : : int32 *dig;
11962 : : int32 carry;
11963 : 115153 : int32 newdig = 0;
11964 : :
11965 : : /*
11966 : : * If no new values have been added since last carry propagation, nothing
11967 : : * to do.
11968 : : */
11969 [ + + ]: 115153 : if (accum->num_uncarried == 0)
11970 : 48 : return;
11971 : :
11972 : : /*
11973 : : * We maintain that the weight of the accumulator is always one larger
11974 : : * than needed to hold the current value, before carrying, to make sure
11975 : : * there is enough space for the possible extra digit when carry is
11976 : : * propagated. We cannot expand the buffer here, unless we require
11977 : : * callers of accum_sum_final() to switch to the right memory context.
11978 : : */
11979 : : Assert(accum->pos_digits[0] == 0 && accum->neg_digits[0] == 0);
11980 : :
11981 : 115105 : ndigits = accum->ndigits;
11982 : :
11983 : : /* Propagate carry in the positive sum */
11984 : 115105 : dig = accum->pos_digits;
11985 : 115105 : carry = 0;
11986 [ + + ]: 1736960 : for (i = ndigits - 1; i >= 0; i--)
11987 : : {
11988 : 1621855 : newdig = dig[i] + carry;
11989 [ + + ]: 1621855 : if (newdig >= NBASE)
11990 : : {
11991 : 73868 : carry = newdig / NBASE;
11992 : 73868 : newdig -= carry * NBASE;
11993 : : }
11994 : : else
11995 : 1547987 : carry = 0;
11996 : 1621855 : dig[i] = newdig;
11997 : : }
11998 : : /* Did we use up the digit reserved for carry propagation? */
11999 [ + + ]: 115105 : if (newdig > 0)
12000 : 1759 : accum->have_carry_space = false;
12001 : :
12002 : : /* And the same for the negative sum */
12003 : 115105 : dig = accum->neg_digits;
12004 : 115105 : carry = 0;
12005 [ + + ]: 1736960 : for (i = ndigits - 1; i >= 0; i--)
12006 : : {
12007 : 1621855 : newdig = dig[i] + carry;
12008 [ + + ]: 1621855 : if (newdig >= NBASE)
12009 : : {
12010 : 132 : carry = newdig / NBASE;
12011 : 132 : newdig -= carry * NBASE;
12012 : : }
12013 : : else
12014 : 1621723 : carry = 0;
12015 : 1621855 : dig[i] = newdig;
12016 : : }
12017 [ + + ]: 115105 : if (newdig > 0)
12018 : 20 : accum->have_carry_space = false;
12019 : :
12020 : 115105 : accum->num_uncarried = 0;
12021 : : }
12022 : :
12023 : : /*
12024 : : * Re-scale accumulator to accommodate new value.
12025 : : *
12026 : : * If the new value has more digits than the current digit buffers in the
12027 : : * accumulator, enlarge the buffers.
12028 : : */
12029 : : static void
12030 : 1570442 : accum_sum_rescale(NumericSumAccum *accum, const NumericVar *val)
12031 : : {
12032 : 1570442 : int old_weight = accum->weight;
12033 : 1570442 : int old_ndigits = accum->ndigits;
12034 : : int accum_ndigits;
12035 : : int accum_weight;
12036 : : int accum_rscale;
12037 : : int val_rscale;
12038 : :
12039 : 1570442 : accum_weight = old_weight;
12040 : 1570442 : accum_ndigits = old_ndigits;
12041 : :
12042 : : /*
12043 : : * Does the new value have a larger weight? If so, enlarge the buffers,
12044 : : * and shift the existing value to the new weight, by adding leading
12045 : : * zeros.
12046 : : *
12047 : : * We enforce that the accumulator always has a weight one larger than
12048 : : * needed for the inputs, so that we have space for an extra digit at the
12049 : : * final carry-propagation phase, if necessary.
12050 : : */
12051 [ + + ]: 1570442 : if (val->weight >= accum_weight)
12052 : : {
12053 : 174802 : accum_weight = val->weight + 1;
12054 : 174802 : accum_ndigits = accum_ndigits + (accum_weight - old_weight);
12055 : : }
12056 : :
12057 : : /*
12058 : : * Even though the new value is small, we might've used up the space
12059 : : * reserved for the carry digit in the last call to accum_sum_carry(). If
12060 : : * so, enlarge to make room for another one.
12061 : : */
12062 [ + + ]: 1395640 : else if (!accum->have_carry_space)
12063 : : {
12064 : 48 : accum_weight++;
12065 : 48 : accum_ndigits++;
12066 : : }
12067 : :
12068 : : /* Is the new value wider on the right side? */
12069 : 1570442 : accum_rscale = accum_ndigits - accum_weight - 1;
12070 : 1570442 : val_rscale = val->ndigits - val->weight - 1;
12071 [ + + ]: 1570442 : if (val_rscale > accum_rscale)
12072 : 114816 : accum_ndigits = accum_ndigits + (val_rscale - accum_rscale);
12073 : :
12074 [ + + - + ]: 1570442 : if (accum_ndigits != old_ndigits ||
12075 : : accum_weight != old_weight)
12076 : : {
12077 : : int32 *new_pos_digits;
12078 : : int32 *new_neg_digits;
12079 : : int weightdiff;
12080 : :
12081 : 175055 : weightdiff = accum_weight - old_weight;
12082 : :
12083 : 175055 : new_pos_digits = palloc0_array(int32, accum_ndigits);
12084 : 175055 : new_neg_digits = palloc0_array(int32, accum_ndigits);
12085 : :
12086 [ + + ]: 175055 : if (accum->pos_digits)
12087 : : {
12088 : 60287 : memcpy(&new_pos_digits[weightdiff], accum->pos_digits,
12089 : : old_ndigits * sizeof(int32));
12090 : 60287 : pfree(accum->pos_digits);
12091 : :
12092 : 60287 : memcpy(&new_neg_digits[weightdiff], accum->neg_digits,
12093 : : old_ndigits * sizeof(int32));
12094 : 60287 : pfree(accum->neg_digits);
12095 : : }
12096 : :
12097 : 175055 : accum->pos_digits = new_pos_digits;
12098 : 175055 : accum->neg_digits = new_neg_digits;
12099 : :
12100 : 175055 : accum->weight = accum_weight;
12101 : 175055 : accum->ndigits = accum_ndigits;
12102 : :
12103 : : Assert(accum->pos_digits[0] == 0 && accum->neg_digits[0] == 0);
12104 : 175055 : accum->have_carry_space = true;
12105 : : }
12106 : :
12107 [ + + ]: 1570442 : if (val->dscale > accum->dscale)
12108 : 200 : accum->dscale = val->dscale;
12109 : 1570442 : }
12110 : :
12111 : : /*
12112 : : * Return the current value of the accumulator. This perform final carry
12113 : : * propagation, and adds together the positive and negative sums.
12114 : : *
12115 : : * Unlike all the other routines, the caller is not required to switch to
12116 : : * the memory context that holds the accumulator.
12117 : : */
12118 : : static void
12119 : 115052 : accum_sum_final(NumericSumAccum *accum, NumericVar *result)
12120 : : {
12121 : : int i;
12122 : : NumericVar pos_var;
12123 : : NumericVar neg_var;
12124 : :
12125 [ - + ]: 115052 : if (accum->ndigits == 0)
12126 : : {
12127 : 0 : set_var_from_var(&const_zero, result);
12128 : 0 : return;
12129 : : }
12130 : :
12131 : : /* Perform final carry */
12132 : 115052 : accum_sum_carry(accum);
12133 : :
12134 : : /* Create NumericVars representing the positive and negative sums */
12135 : 115052 : init_var(&pos_var);
12136 : 115052 : init_var(&neg_var);
12137 : :
12138 : 115052 : pos_var.ndigits = neg_var.ndigits = accum->ndigits;
12139 : 115052 : pos_var.weight = neg_var.weight = accum->weight;
12140 : 115052 : pos_var.dscale = neg_var.dscale = accum->dscale;
12141 : 115052 : pos_var.sign = NUMERIC_POS;
12142 : 115052 : neg_var.sign = NUMERIC_NEG;
12143 : :
12144 : 115052 : pos_var.buf = pos_var.digits = digitbuf_alloc(accum->ndigits);
12145 : 115052 : neg_var.buf = neg_var.digits = digitbuf_alloc(accum->ndigits);
12146 : :
12147 [ + + ]: 1736679 : for (i = 0; i < accum->ndigits; i++)
12148 : : {
12149 : : Assert(accum->pos_digits[i] < NBASE);
12150 : 1621627 : pos_var.digits[i] = (int16) accum->pos_digits[i];
12151 : :
12152 : : Assert(accum->neg_digits[i] < NBASE);
12153 : 1621627 : neg_var.digits[i] = (int16) accum->neg_digits[i];
12154 : : }
12155 : :
12156 : : /* And add them together */
12157 : 115052 : add_var(&pos_var, &neg_var, result);
12158 : :
12159 : : /* Remove leading/trailing zeroes */
12160 : 115052 : strip_var(result);
12161 : : }
12162 : :
12163 : : /*
12164 : : * Copy an accumulator's state.
12165 : : *
12166 : : * 'dst' is assumed to be uninitialized beforehand. No attempt is made at
12167 : : * freeing old values.
12168 : : */
12169 : : static void
12170 : 28 : accum_sum_copy(NumericSumAccum *dst, NumericSumAccum *src)
12171 : : {
12172 : 28 : dst->pos_digits = palloc_array(int32, src->ndigits);
12173 : 28 : dst->neg_digits = palloc_array(int32, src->ndigits);
12174 : :
12175 : 28 : memcpy(dst->pos_digits, src->pos_digits, src->ndigits * sizeof(int32));
12176 : 28 : memcpy(dst->neg_digits, src->neg_digits, src->ndigits * sizeof(int32));
12177 : 28 : dst->num_uncarried = src->num_uncarried;
12178 : 28 : dst->ndigits = src->ndigits;
12179 : 28 : dst->weight = src->weight;
12180 : 28 : dst->dscale = src->dscale;
12181 : 28 : }
12182 : :
12183 : : /*
12184 : : * Add the current value of 'accum2' into 'accum'.
12185 : : */
12186 : : static void
12187 : 33 : accum_sum_combine(NumericSumAccum *accum, NumericSumAccum *accum2)
12188 : : {
12189 : : NumericVar tmp_var;
12190 : :
12191 : 33 : init_var(&tmp_var);
12192 : :
12193 : 33 : accum_sum_final(accum2, &tmp_var);
12194 : 33 : accum_sum_add(accum, &tmp_var);
12195 : :
12196 : 33 : free_var(&tmp_var);
12197 : 33 : }
|