Age Owner Branch data TLA 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
9664 tgl@sss.pgh.pa.us 626 :CBC 133836 : numeric_in(PG_FUNCTION_ARGS)
627 : : {
628 : 133836 : char *str = PG_GETARG_CSTRING(0);
629 : : #ifdef NOT_USED
630 : : Oid typelem = PG_GETARG_OID(1);
631 : : #endif
632 : 133836 : int32 typmod = PG_GETARG_INT32(2);
1450 633 : 133836 : Node *escontext = fcinfo->context;
634 : : Numeric res;
635 : : const char *cp;
636 : : const char *numstart;
637 : : int sign;
638 : :
639 : : /* Skip leading spaces */
6443 640 : 133836 : cp = str;
641 [ + + ]: 150124 : while (*cp)
642 : : {
643 [ + + ]: 150112 : if (!isspace((unsigned char) *cp))
644 : 133824 : break;
645 : 16288 : 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 : : */
1405 dean.a.rasheed@gmail 653 : 133836 : numstart = cp;
654 : 133836 : sign = NUMERIC_POS;
655 : :
656 [ + + ]: 133836 : if (*cp == '+')
657 : 32 : cp++;
658 [ + + ]: 133804 : else if (*cp == '-')
659 : : {
660 : 2513 : sign = NUMERIC_NEG;
661 : 2513 : 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 [ + + + + ]: 133836 : 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 [ + + ]: 1222 : if (pg_strncasecmp(numstart, "NaN", 3) == 0)
678 : : {
679 : 408 : res = make_result(&const_nan);
680 : 408 : cp = numstart + 3;
681 : : }
682 [ + + ]: 814 : else if (pg_strncasecmp(cp, "Infinity", 8) == 0)
683 : : {
684 [ + + ]: 341 : res = make_result(sign == NUMERIC_POS ? &const_pinf : &const_ninf);
685 : 341 : cp += 8;
686 : : }
687 [ + + ]: 473 : else if (pg_strncasecmp(cp, "inf", 3) == 0)
688 : : {
689 [ + + ]: 400 : res = make_result(sign == NUMERIC_POS ? &const_pinf : &const_ninf);
690 : 400 : cp += 3;
691 : : }
692 : : else
693 : 73 : goto invalid_syntax;
694 : :
695 : : /*
696 : : * Check for trailing junk; there should be nothing left but spaces.
697 : : *
698 : : * We intentionally do this check before applying the typmod because
699 : : * we would like to throw any trailing-junk syntax error before any
700 : : * semantic error resulting from apply_typmod_special().
701 : : */
702 [ + + ]: 1177 : while (*cp)
703 : : {
704 [ - + ]: 28 : if (!isspace((unsigned char) *cp))
1405 dean.a.rasheed@gmail 705 :UBC 0 : goto invalid_syntax;
1405 dean.a.rasheed@gmail 706 :CBC 28 : cp++;
707 : : }
708 : :
709 [ - + ]: 1149 : if (!apply_typmod_special(res, typmod, escontext))
1405 dean.a.rasheed@gmail 710 :UBC 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 : :
6443 tgl@sss.pgh.pa.us 721 :CBC 132614 : 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 : : */
1405 dean.a.rasheed@gmail 727 [ + + ]: 132614 : if (cp[0] == '0')
728 : : {
729 [ + + + + ]: 34963 : 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 : 34859 : default:
744 : 34859 : base = 10;
745 : : }
746 : : }
747 : : else
748 : 97651 : base = 10;
749 : :
750 : : /* Parse the rest of the number and apply the sign */
751 [ + + ]: 132614 : if (base == 10)
752 : : {
753 [ - + ]: 132510 : if (!set_var_from_str(str, cp, &value, &cp, escontext))
754 : 16 : PG_RETURN_NULL();
755 : 132478 : 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))
1405 dean.a.rasheed@gmail 761 :UBC 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 : : */
6443 tgl@sss.pgh.pa.us 768 [ + + ]:CBC 132622 : while (*cp)
769 : : {
770 [ + + ]: 100 : if (!isspace((unsigned char) *cp))
1405 dean.a.rasheed@gmail 771 : 48 : goto invalid_syntax;
6443 tgl@sss.pgh.pa.us 772 : 52 : cp++;
773 : : }
774 : :
1450 775 [ + + ]: 132522 : if (!apply_typmod(&value, typmod, escontext))
776 : 16 : PG_RETURN_NULL();
777 : :
449 michael@paquier.xyz 778 : 132506 : res = make_result_safe(&value, escontext);
779 : :
6443 tgl@sss.pgh.pa.us 780 : 132506 : free_var(&value);
781 : : }
782 : :
9664 783 : 133655 : PG_RETURN_NUMERIC(res);
784 : :
1405 dean.a.rasheed@gmail 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
9664 tgl@sss.pgh.pa.us 799 : 563612 : numeric_out(PG_FUNCTION_ARGS)
800 : : {
801 : 563612 : Numeric num = PG_GETARG_NUMERIC(0);
802 : : NumericVar x;
803 : : char *str;
804 : :
805 : : /*
806 : : * Handle NaN and infinities
807 : : */
2320 808 [ + + ]: 563612 : if (NUMERIC_IS_SPECIAL(num))
809 : : {
810 [ + + ]: 2349 : if (NUMERIC_IS_PINF(num))
811 : 688 : PG_RETURN_CSTRING(pstrdup("Infinity"));
812 [ + + ]: 1661 : else if (NUMERIC_IS_NINF(num))
813 : 440 : PG_RETURN_CSTRING(pstrdup("-Infinity"));
814 : : else
815 : 1221 : PG_RETURN_CSTRING(pstrdup("NaN"));
816 : : }
817 : :
818 : : /*
819 : : * Get the number in the variable format.
820 : : */
5120 heikki.linnakangas@i 821 : 561263 : init_var_from_num(num, &x);
822 : :
823 : 561263 : str = get_str_from_var(&x);
824 : :
9664 tgl@sss.pgh.pa.us 825 : 561263 : PG_RETURN_CSTRING(str);
826 : : }
827 : :
828 : : /*
829 : : * numeric_is_nan() -
830 : : *
831 : : * Is Numeric value a NaN?
832 : : */
833 : : bool
5965 rhaas@postgresql.org 834 : 7587 : numeric_is_nan(Numeric num)
835 : : {
836 : 7587 : return NUMERIC_IS_NAN(num);
837 : : }
838 : :
839 : : /*
840 : : * numeric_is_inf() -
841 : : *
842 : : * Is Numeric value an infinity?
843 : : */
844 : : bool
2320 tgl@sss.pgh.pa.us 845 : 5373 : numeric_is_inf(Numeric num)
846 : : {
847 : 5373 : return NUMERIC_IS_INF(num);
848 : : }
849 : :
850 : : /*
851 : : * get_numeric_nan() -
852 : : *
853 : : * Produce a numeric NaN value
854 : : */
855 : : Numeric
1 tgl@sss.pgh.pa.us 856 :UNC 0 : get_numeric_nan(void)
857 : : {
858 : 0 : return make_result(&const_nan);
859 : : }
860 : :
861 : : /*
862 : : * get_numeric_infinity() -
863 : : *
864 : : * Produce a numeric +Infinity value
865 : : */
866 : : Numeric
1 tgl@sss.pgh.pa.us 867 :GNC 5 : get_numeric_infinity(void)
868 : : {
869 : 5 : return make_result(&const_pinf);
870 : : }
871 : :
872 : : /*
873 : : * numeric_is_integral() -
874 : : *
875 : : * Is Numeric value integral?
876 : : */
877 : : static bool
2320 tgl@sss.pgh.pa.us 878 :CBC 54 : numeric_is_integral(Numeric num)
879 : : {
880 : : NumericVar arg;
881 : :
882 : : /* Reject NaN, but infinities are considered integral */
883 [ + + ]: 54 : if (NUMERIC_IS_SPECIAL(num))
884 : : {
885 [ - + ]: 25 : if (NUMERIC_IS_NAN(num))
2320 tgl@sss.pgh.pa.us 886 :UBC 0 : return false;
2320 tgl@sss.pgh.pa.us 887 :CBC 25 : return true;
888 : : }
889 : :
890 : : /* Integral if there are no digits to the right of the decimal point */
891 : 29 : init_var_from_num(num, &arg);
892 : :
893 [ + + + + ]: 29 : return (arg.ndigits == 0 || arg.ndigits <= arg.weight + 1);
894 : : }
895 : :
896 : : /*
897 : : * make_numeric_typmod() -
898 : : *
899 : : * Pack numeric precision and scale values into a typmod. The upper 16 bits
900 : : * are used for the precision (though actually not all these bits are needed,
901 : : * since the maximum allowed precision is 1000). The lower 16 bits are for
902 : : * the scale, but since the scale is constrained to the range [-1000, 1000],
903 : : * we use just the lower 11 of those 16 bits, and leave the remaining 5 bits
904 : : * unset, for possible future use.
905 : : *
906 : : * For purely historical reasons VARHDRSZ is then added to the result, thus
907 : : * the unused space in the upper 16 bits is not all as freely available as it
908 : : * might seem. (We can't let the result overflow to a negative int32, as
909 : : * other parts of the system would interpret that as not-a-valid-typmod.)
910 : : */
911 : : static inline int32
1951 dean.a.rasheed@gmail 912 : 1079 : make_numeric_typmod(int precision, int scale)
913 : : {
914 : 1079 : return ((precision << 16) | (scale & 0x7ff)) + VARHDRSZ;
915 : : }
916 : :
917 : : /*
918 : : * Because of the offset, valid numeric typmods are at least VARHDRSZ
919 : : */
920 : : static inline bool
921 : 149774 : is_valid_numeric_typmod(int32 typmod)
922 : : {
923 : 149774 : return typmod >= (int32) VARHDRSZ;
924 : : }
925 : :
926 : : /*
927 : : * numeric_typmod_precision() -
928 : : *
929 : : * Extract the precision from a numeric typmod --- see make_numeric_typmod().
930 : : */
931 : : static inline int
932 : 32896 : numeric_typmod_precision(int32 typmod)
933 : : {
934 : 32896 : return ((typmod - VARHDRSZ) >> 16) & 0xffff;
935 : : }
936 : :
937 : : /*
938 : : * numeric_typmod_scale() -
939 : : *
940 : : * Extract the scale from a numeric typmod --- see make_numeric_typmod().
941 : : *
942 : : * Note that the scale may be negative, so we must do sign extension when
943 : : * unpacking it. We do this using the bit hack (x^1024)-1024, which sign
944 : : * extends an 11-bit two's complement number x.
945 : : */
946 : : static inline int
947 : 28004 : numeric_typmod_scale(int32 typmod)
948 : : {
949 : 28004 : return (((typmod - VARHDRSZ) & 0x7ff) ^ 1024) - 1024;
950 : : }
951 : :
952 : : /*
953 : : * numeric_maximum_size() -
954 : : *
955 : : * Maximum size of a numeric with given typmod, or -1 if unlimited/unknown.
956 : : */
957 : : int32
5960 rhaas@postgresql.org 958 : 4892 : numeric_maximum_size(int32 typmod)
959 : : {
960 : : int precision;
961 : : int numeric_digits;
962 : :
1951 dean.a.rasheed@gmail 963 [ - + ]: 4892 : if (!is_valid_numeric_typmod(typmod))
5965 rhaas@postgresql.org 964 :UBC 0 : return -1;
965 : :
966 : : /* precision (ie, max # of digits) is in upper bits of typmod */
1951 dean.a.rasheed@gmail 967 :CBC 4892 : precision = numeric_typmod_precision(typmod);
968 : :
969 : : /*
970 : : * This formula computes the maximum number of NumericDigits we could need
971 : : * in order to store the specified number of decimal digits. Because the
972 : : * weight is stored as a number of NumericDigits rather than a number of
973 : : * decimal digits, it's possible that the first NumericDigit will contain
974 : : * only a single decimal digit. Thus, the first two decimal digits can
975 : : * require two NumericDigits to store, but it isn't until we reach
976 : : * DEC_DIGITS + 2 decimal digits that we potentially need a third
977 : : * NumericDigit.
978 : : */
5960 rhaas@postgresql.org 979 : 4892 : numeric_digits = (precision + 2 * (DEC_DIGITS - 1)) / DEC_DIGITS;
980 : :
981 : : /*
982 : : * In most cases, the size of a numeric will be smaller than the value
983 : : * computed below, because the varlena header will typically get toasted
984 : : * down to a single byte before being stored on disk, and it may also be
985 : : * possible to use a short numeric header. But our job here is to compute
986 : : * the worst case.
987 : : */
988 : 4892 : return NUMERIC_HDRSZ + (numeric_digits * sizeof(NumericDigit));
989 : : }
990 : :
991 : : /*
992 : : * numeric_out_sci() -
993 : : *
994 : : * Output function for numeric data type in scientific notation.
995 : : */
996 : : char *
6319 tgl@sss.pgh.pa.us 997 : 196 : numeric_out_sci(Numeric num, int scale)
998 : : {
999 : : NumericVar x;
1000 : : char *str;
1001 : :
1002 : : /*
1003 : : * Handle NaN and infinities
1004 : : */
2320 1005 [ + + ]: 196 : if (NUMERIC_IS_SPECIAL(num))
1006 : : {
1007 [ + + ]: 12 : if (NUMERIC_IS_PINF(num))
1008 : 4 : return pstrdup("Infinity");
1009 [ + + ]: 8 : else if (NUMERIC_IS_NINF(num))
1010 : 4 : return pstrdup("-Infinity");
1011 : : else
1012 : 4 : return pstrdup("NaN");
1013 : : }
1014 : :
5120 heikki.linnakangas@i 1015 : 184 : init_var_from_num(num, &x);
1016 : :
6319 tgl@sss.pgh.pa.us 1017 : 184 : str = get_str_from_var_sci(&x, scale);
1018 : :
1019 : 184 : return str;
1020 : : }
1021 : :
1022 : : /*
1023 : : * numeric_normalize() -
1024 : : *
1025 : : * Output function for numeric data type, suppressing insignificant trailing
1026 : : * zeroes and then any trailing decimal point. The intent of this is to
1027 : : * produce strings that are equal if and only if the input numeric values
1028 : : * compare equal.
1029 : : */
1030 : : char *
4633 andrew@dunslane.net 1031 : 21991 : numeric_normalize(Numeric num)
1032 : : {
1033 : : NumericVar x;
1034 : : char *str;
1035 : : int last;
1036 : :
1037 : : /*
1038 : : * Handle NaN and infinities
1039 : : */
2320 tgl@sss.pgh.pa.us 1040 [ - + ]: 21991 : if (NUMERIC_IS_SPECIAL(num))
1041 : : {
2320 tgl@sss.pgh.pa.us 1042 [ # # ]:UBC 0 : if (NUMERIC_IS_PINF(num))
1043 : 0 : return pstrdup("Infinity");
1044 [ # # ]: 0 : else if (NUMERIC_IS_NINF(num))
1045 : 0 : return pstrdup("-Infinity");
1046 : : else
1047 : 0 : return pstrdup("NaN");
1048 : : }
1049 : :
4633 andrew@dunslane.net 1050 :CBC 21991 : init_var_from_num(num, &x);
1051 : :
1052 : 21991 : str = get_str_from_var(&x);
1053 : :
1054 : : /* If there's no decimal point, there's certainly nothing to remove. */
4405 tgl@sss.pgh.pa.us 1055 [ + + ]: 21991 : if (strchr(str, '.') != NULL)
1056 : : {
1057 : : /*
1058 : : * Back up over trailing fractional zeroes. Since there is a decimal
1059 : : * point, this loop will terminate safely.
1060 : : */
1061 : 31 : last = strlen(str) - 1;
1062 [ + + ]: 62 : while (str[last] == '0')
1063 : 31 : last--;
1064 : :
1065 : : /* We want to get rid of the decimal point too, if it's now last. */
1066 [ + - ]: 31 : if (str[last] == '.')
1067 : 31 : last--;
1068 : :
1069 : : /* Delete whatever we backed up over. */
1070 : 31 : str[last + 1] = '\0';
1071 : : }
1072 : :
4633 andrew@dunslane.net 1073 : 21991 : return str;
1074 : : }
1075 : :
1076 : : /*
1077 : : * numeric_recv - converts external binary format to numeric
1078 : : *
1079 : : * External format is a sequence of int16's:
1080 : : * ndigits, weight, sign, dscale, NumericDigits.
1081 : : */
1082 : : Datum
8601 tgl@sss.pgh.pa.us 1083 : 51 : numeric_recv(PG_FUNCTION_ARGS)
1084 : : {
1085 : 51 : StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
1086 : :
1087 : : #ifdef NOT_USED
1088 : : Oid typelem = PG_GETARG_OID(1);
1089 : : #endif
7811 1090 : 51 : int32 typmod = PG_GETARG_INT32(2);
1091 : : NumericVar value;
1092 : : Numeric res;
1093 : : int len,
1094 : : i;
1095 : :
8601 1096 : 51 : init_var(&value);
1097 : :
1098 : 51 : len = (uint16) pq_getmsgint(buf, sizeof(uint16));
1099 : :
1100 : 51 : alloc_var(&value, len);
1101 : :
1102 : 51 : value.weight = (int16) pq_getmsgint(buf, sizeof(int16));
1103 : : /* we allow any int16 for weight --- OK? */
1104 : :
1105 : 51 : value.sign = (uint16) pq_getmsgint(buf, sizeof(uint16));
1106 [ - + ]: 51 : if (!(value.sign == NUMERIC_POS ||
8601 tgl@sss.pgh.pa.us 1107 [ # # ]:UBC 0 : value.sign == NUMERIC_NEG ||
2320 1108 [ # # ]: 0 : value.sign == NUMERIC_NAN ||
1109 [ # # ]: 0 : value.sign == NUMERIC_PINF ||
1110 [ # # ]: 0 : value.sign == NUMERIC_NINF))
8525 1111 [ # # ]: 0 : ereport(ERROR,
1112 : : (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1113 : : errmsg("invalid sign in external \"numeric\" value")));
1114 : :
8601 tgl@sss.pgh.pa.us 1115 :CBC 51 : value.dscale = (uint16) pq_getmsgint(buf, sizeof(uint16));
4380 1116 [ - + ]: 51 : if ((value.dscale & NUMERIC_DSCALE_MASK) != value.dscale)
4380 tgl@sss.pgh.pa.us 1117 [ # # ]:UBC 0 : ereport(ERROR,
1118 : : (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1119 : : errmsg("invalid scale in external \"numeric\" value")));
1120 : :
8601 tgl@sss.pgh.pa.us 1121 [ + + ]:CBC 137 : for (i = 0; i < len; i++)
1122 : : {
8517 bruce@momjian.us 1123 : 86 : NumericDigit d = pq_getmsgint(buf, sizeof(NumericDigit));
1124 : :
8601 tgl@sss.pgh.pa.us 1125 [ + - - + ]: 86 : if (d < 0 || d >= NBASE)
8525 tgl@sss.pgh.pa.us 1126 [ # # ]:UBC 0 : ereport(ERROR,
1127 : : (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1128 : : errmsg("invalid digit in external \"numeric\" value")));
8601 tgl@sss.pgh.pa.us 1129 :CBC 86 : value.digits[i] = d;
1130 : : }
1131 : :
1132 : : /*
1133 : : * If the given dscale would hide any digits, truncate those digits away.
1134 : : * We could alternatively throw an error, but that would take a bunch of
1135 : : * extra code (about as much as trunc_var involves), and it might cause
1136 : : * client compatibility issues. Be careful not to apply trunc_var to
1137 : : * special values, as it could do the wrong thing; we don't need it
1138 : : * anyway, since make_result will ignore all but the sign field.
1139 : : *
1140 : : * After doing that, be sure to check the typmod restriction.
1141 : : */
2320 1142 [ - + ]: 51 : if (value.sign == NUMERIC_POS ||
2320 tgl@sss.pgh.pa.us 1143 [ # # ]:UBC 0 : value.sign == NUMERIC_NEG)
1144 : : {
2320 tgl@sss.pgh.pa.us 1145 :CBC 51 : trunc_var(&value, value.dscale);
1146 : :
1450 1147 : 51 : (void) apply_typmod(&value, typmod, NULL);
1148 : :
2320 1149 : 51 : res = make_result(&value);
1150 : : }
1151 : : else
1152 : : {
1153 : : /* apply_typmod_special wants us to make the Numeric first */
2320 tgl@sss.pgh.pa.us 1154 :UBC 0 : res = make_result(&value);
1155 : :
1450 1156 : 0 : (void) apply_typmod_special(res, typmod, NULL);
1157 : : }
1158 : :
8601 tgl@sss.pgh.pa.us 1159 :CBC 51 : free_var(&value);
1160 : :
1161 : 51 : PG_RETURN_NUMERIC(res);
1162 : : }
1163 : :
1164 : : /*
1165 : : * numeric_send - converts numeric to binary format
1166 : : */
1167 : : Datum
1168 : 35 : numeric_send(PG_FUNCTION_ARGS)
1169 : : {
1170 : 35 : Numeric num = PG_GETARG_NUMERIC(0);
1171 : : NumericVar x;
1172 : : StringInfoData buf;
1173 : : int i;
1174 : :
5120 heikki.linnakangas@i 1175 : 35 : init_var_from_num(num, &x);
1176 : :
8601 tgl@sss.pgh.pa.us 1177 : 35 : pq_begintypsend(&buf);
1178 : :
3335 andres@anarazel.de 1179 : 35 : pq_sendint16(&buf, x.ndigits);
1180 : 35 : pq_sendint16(&buf, x.weight);
1181 : 35 : pq_sendint16(&buf, x.sign);
1182 : 35 : pq_sendint16(&buf, x.dscale);
8601 tgl@sss.pgh.pa.us 1183 [ + + ]: 97 : for (i = 0; i < x.ndigits; i++)
3335 andres@anarazel.de 1184 : 62 : pq_sendint16(&buf, x.digits[i]);
1185 : :
8601 tgl@sss.pgh.pa.us 1186 : 35 : PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
1187 : : }
1188 : :
1189 : :
1190 : : /*
1191 : : * numeric_support()
1192 : : *
1193 : : * Planner support function for the numeric() length coercion function.
1194 : : *
1195 : : * Flatten calls that solely represent increases in allowable precision.
1196 : : * Scale changes mutate every datum, so they are unoptimizable. Some values,
1197 : : * e.g. 1E-1001, can only fit into an unconstrained numeric, so a change from
1198 : : * an unconstrained numeric to any constrained numeric is also unoptimizable.
1199 : : */
1200 : : Datum
2849 1201 : 427 : numeric_support(PG_FUNCTION_ARGS)
1202 : : {
1203 : 427 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
5408 rhaas@postgresql.org 1204 : 427 : Node *ret = NULL;
1205 : :
2849 tgl@sss.pgh.pa.us 1206 [ + + ]: 427 : if (IsA(rawreq, SupportRequestSimplify))
1207 : : {
1208 : 187 : SupportRequestSimplify *req = (SupportRequestSimplify *) rawreq;
1209 : 187 : FuncExpr *expr = req->fcall;
1210 : : Node *typmod;
1211 : :
1212 [ - + ]: 187 : Assert(list_length(expr->args) >= 2);
1213 : :
1214 : 187 : typmod = (Node *) lsecond(expr->args);
1215 : :
2387 1216 [ + - + - ]: 187 : if (IsA(typmod, Const) && !((Const *) typmod)->constisnull)
1217 : : {
2849 1218 : 187 : Node *source = (Node *) linitial(expr->args);
1219 : 187 : int32 old_typmod = exprTypmod(source);
1220 : 187 : int32 new_typmod = DatumGetInt32(((Const *) typmod)->constvalue);
1951 dean.a.rasheed@gmail 1221 : 187 : int32 old_scale = numeric_typmod_scale(old_typmod);
1222 : 187 : int32 new_scale = numeric_typmod_scale(new_typmod);
1223 : 187 : int32 old_precision = numeric_typmod_precision(old_typmod);
1224 : 187 : int32 new_precision = numeric_typmod_precision(new_typmod);
1225 : :
1226 : : /*
1227 : : * If new_typmod is invalid, the destination is unconstrained;
1228 : : * that's always OK. If old_typmod is valid, the source is
1229 : : * constrained, and we're OK if the scale is unchanged and the
1230 : : * precision is not decreasing. See further notes in function
1231 : : * header comment.
1232 : : */
1233 [ + - + + ]: 374 : if (!is_valid_numeric_typmod(new_typmod) ||
1234 [ + + ]: 196 : (is_valid_numeric_typmod(old_typmod) &&
2849 tgl@sss.pgh.pa.us 1235 [ + - ]: 4 : new_scale == old_scale && new_precision >= old_precision))
1236 : 4 : ret = relabel_to_typmod(source, new_typmod);
1237 : : }
1238 : : }
1239 : :
5408 rhaas@postgresql.org 1240 : 427 : PG_RETURN_POINTER(ret);
1241 : : }
1242 : :
1243 : : /*
1244 : : * numeric() -
1245 : : *
1246 : : * This is a special function called by the Postgres database system
1247 : : * before a value is stored in a tuple's attribute. The precision and
1248 : : * scale of the attribute have to be applied on the value.
1249 : : */
1250 : : Datum
6953 bruce@momjian.us 1251 : 8077 : numeric (PG_FUNCTION_ARGS)
1252 : : {
9664 tgl@sss.pgh.pa.us 1253 : 8077 : Numeric num = PG_GETARG_NUMERIC(0);
1254 : 8077 : int32 typmod = PG_GETARG_INT32(1);
1255 : : Numeric new;
1256 : : int precision;
1257 : : int scale;
1258 : : int ddigits;
1259 : : int maxdigits;
1260 : : int dscale;
1261 : : NumericVar var;
1262 : :
1263 : : /*
1264 : : * Handle NaN and infinities: if apply_typmod_special doesn't complain,
1265 : : * just return a copy of the input.
1266 : : */
2320 1267 [ + + ]: 8077 : if (NUMERIC_IS_SPECIAL(num))
1268 : : {
249 peter@eisentraut.org 1269 [ - + ]: 172 : if (!apply_typmod_special(num, typmod, fcinfo->context))
249 peter@eisentraut.org 1270 :UBC 0 : PG_RETURN_NULL();
2320 tgl@sss.pgh.pa.us 1271 :CBC 160 : PG_RETURN_NUMERIC(duplicate_numeric(num));
1272 : : }
1273 : :
1274 : : /*
1275 : : * If the value isn't a valid type modifier, simply return a copy of the
1276 : : * input value
1277 : : */
1951 dean.a.rasheed@gmail 1278 [ - + ]: 7905 : if (!is_valid_numeric_typmod(typmod))
2320 tgl@sss.pgh.pa.us 1279 :UBC 0 : PG_RETURN_NUMERIC(duplicate_numeric(num));
1280 : :
1281 : : /*
1282 : : * Get the precision and scale out of the typmod value
1283 : : */
1951 dean.a.rasheed@gmail 1284 :CBC 7905 : precision = numeric_typmod_precision(typmod);
1285 : 7905 : scale = numeric_typmod_scale(typmod);
8653 tgl@sss.pgh.pa.us 1286 : 7905 : maxdigits = precision - scale;
1287 : :
1288 : : /* The target display scale is non-negative */
1951 dean.a.rasheed@gmail 1289 : 7905 : dscale = Max(scale, 0);
1290 : :
1291 : : /*
1292 : : * If the number is certainly in bounds and due to the target scale no
1293 : : * rounding could be necessary, just make a copy of the input and modify
1294 : : * its scale fields, unless the larger scale forces us to abandon the
1295 : : * short representation. (Note we assume the existing dscale is
1296 : : * honest...)
1297 : : */
5961 rhaas@postgresql.org 1298 [ + + + + ]: 7905 : ddigits = (NUMERIC_WEIGHT(num) + 1) * DEC_DIGITS;
1299 [ + + + + : 7905 : if (ddigits <= maxdigits && scale >= NUMERIC_DSCALE(num)
+ + ]
1951 dean.a.rasheed@gmail 1300 [ + - + - : 4837 : && (NUMERIC_CAN_BE_SHORT(dscale, NUMERIC_WEIGHT(num))
+ + + - -
- + - + +
- + - - ]
5711 bruce@momjian.us 1301 [ # # ]:UBC 0 : || !NUMERIC_IS_SHORT(num)))
1302 : : {
2320 tgl@sss.pgh.pa.us 1303 :CBC 4837 : new = duplicate_numeric(num);
5961 rhaas@postgresql.org 1304 [ + - ]: 4837 : if (NUMERIC_IS_SHORT(num))
1305 : 4837 : new->choice.n_short.n_header =
1306 : 4837 : (num->choice.n_short.n_header & ~NUMERIC_SHORT_DSCALE_MASK)
1951 dean.a.rasheed@gmail 1307 : 4837 : | (dscale << NUMERIC_SHORT_DSCALE_SHIFT);
1308 : : else
5961 rhaas@postgresql.org 1309 [ # # # # ]:UBC 0 : new->choice.n_long.n_sign_dscale = NUMERIC_SIGN(new) |
1951 dean.a.rasheed@gmail 1310 : 0 : ((uint16) dscale & NUMERIC_DSCALE_MASK);
9664 tgl@sss.pgh.pa.us 1311 :CBC 4837 : PG_RETURN_NUMERIC(new);
1312 : : }
1313 : :
1314 : : /*
1315 : : * We really need to fiddle with things - unpack the number into a
1316 : : * variable and let apply_typmod() do it.
1317 : : */
10195 JanWieck@Yahoo.com 1318 : 3068 : init_var(&var);
1319 : :
1320 : 3068 : set_var_from_num(num, &var);
249 peter@eisentraut.org 1321 [ - + ]: 3068 : if (!apply_typmod(&var, typmod, fcinfo->context))
249 peter@eisentraut.org 1322 :UBC 0 : PG_RETURN_NULL();
249 peter@eisentraut.org 1323 :CBC 3020 : new = make_result_safe(&var, fcinfo->context);
1324 : :
10195 JanWieck@Yahoo.com 1325 : 3020 : free_var(&var);
1326 : :
9664 tgl@sss.pgh.pa.us 1327 : 3020 : PG_RETURN_NUMERIC(new);
1328 : : }
1329 : :
1330 : : /*
1331 : : * make_numeric_typmod_safe() -
1332 : : *
1333 : : * Validate a numeric precision/scale and pack them into a typmod value,
1334 : : * with soft error handling.
1335 : : */
1336 : : int32
149 michael@paquier.xyz 1337 : 1124 : make_numeric_typmod_safe(int32 precision, int32 scale, Node *escontext)
1338 : : {
1339 [ + + + + ]: 1124 : if (precision < 1 || precision > NUMERIC_MAX_PRECISION)
1340 [ + + ]: 29 : ereturn(escontext, -1,
1341 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1342 : : errmsg("NUMERIC precision %d must be between 1 and %d",
1343 : : precision, NUMERIC_MAX_PRECISION)));
1344 [ + + + + ]: 1095 : if (scale < NUMERIC_MIN_SCALE || scale > NUMERIC_MAX_SCALE)
1345 [ + + ]: 16 : ereturn(escontext, -1,
1346 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1347 : : errmsg("NUMERIC scale %d must be between %d and %d",
1348 : : scale, NUMERIC_MIN_SCALE, NUMERIC_MAX_SCALE)));
1349 : :
1350 : 1079 : return make_numeric_typmod(precision, scale);
1351 : : }
1352 : :
1353 : : Datum
7273 tgl@sss.pgh.pa.us 1354 : 1047 : numerictypmodin(PG_FUNCTION_ARGS)
1355 : : {
6953 bruce@momjian.us 1356 : 1047 : ArrayType *ta = PG_GETARG_ARRAYTYPE_P(0);
1357 : : int32 *tl;
1358 : : int n;
1359 : : int32 typmod;
1360 : :
7106 tgl@sss.pgh.pa.us 1361 : 1047 : tl = ArrayGetIntegerTypmods(ta, &n);
1362 : :
7273 1363 [ + + ]: 1047 : if (n == 2)
149 michael@paquier.xyz 1364 : 1037 : typmod = make_numeric_typmod_safe(tl[0], tl[1], NULL);
7273 tgl@sss.pgh.pa.us 1365 [ + + ]: 10 : else if (n == 1)
1366 : : {
1367 : : /* scale defaults to zero */
149 michael@paquier.xyz 1368 : 2 : typmod = make_numeric_typmod_safe(tl[0], 0, NULL);
1369 : : }
1370 : : else
1371 : : {
7273 tgl@sss.pgh.pa.us 1372 [ + - ]: 8 : ereport(ERROR,
1373 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1374 : : errmsg("invalid NUMERIC type modifier")));
1375 : : typmod = 0; /* keep compiler quiet */
1376 : : }
1377 : :
1378 : 1039 : PG_RETURN_INT32(typmod);
1379 : : }
1380 : :
1381 : : Datum
1382 : 209 : numerictypmodout(PG_FUNCTION_ARGS)
1383 : : {
6953 bruce@momjian.us 1384 : 209 : int32 typmod = PG_GETARG_INT32(0);
1385 : 209 : char *res = (char *) palloc(64);
1386 : :
1951 dean.a.rasheed@gmail 1387 [ + - ]: 209 : if (is_valid_numeric_typmod(typmod))
7273 tgl@sss.pgh.pa.us 1388 : 209 : snprintf(res, 64, "(%d,%d)",
1389 : : numeric_typmod_precision(typmod),
1390 : : numeric_typmod_scale(typmod));
1391 : : else
7273 tgl@sss.pgh.pa.us 1392 :UBC 0 : *res = '\0';
1393 : :
7273 tgl@sss.pgh.pa.us 1394 :CBC 209 : PG_RETURN_CSTRING(res);
1395 : : }
1396 : :
1397 : :
1398 : : /* ----------------------------------------------------------------------
1399 : : *
1400 : : * Sign manipulation, rounding and the like
1401 : : *
1402 : : * ----------------------------------------------------------------------
1403 : : */
1404 : :
1405 : : Datum
9618 1406 : 13004 : numeric_abs(PG_FUNCTION_ARGS)
1407 : : {
1408 : 13004 : Numeric num = PG_GETARG_NUMERIC(0);
1409 : : Numeric res;
1410 : :
1411 : : /*
1412 : : * Do it the easy way directly on the packed format
1413 : : */
2320 1414 : 13004 : res = duplicate_numeric(num);
1415 : :
5961 rhaas@postgresql.org 1416 [ + + ]: 13004 : if (NUMERIC_IS_SHORT(num))
1417 : 12960 : res->choice.n_short.n_header =
1418 : 12960 : num->choice.n_short.n_header & ~NUMERIC_SHORT_SIGN_MASK;
2320 tgl@sss.pgh.pa.us 1419 [ + + ]: 44 : else if (NUMERIC_IS_SPECIAL(num))
1420 : : {
1421 : : /* This changes -Inf to Inf, and doesn't affect NaN */
1422 : 12 : res->choice.n_short.n_header =
1423 : 12 : num->choice.n_short.n_header & ~NUMERIC_INF_SIGN_MASK;
1424 : : }
1425 : : else
5961 rhaas@postgresql.org 1426 [ - + ]: 32 : res->choice.n_long.n_sign_dscale = NUMERIC_POS | NUMERIC_DSCALE(num);
1427 : :
9618 tgl@sss.pgh.pa.us 1428 : 13004 : PG_RETURN_NUMERIC(res);
1429 : : }
1430 : :
1431 : :
1432 : : Datum
1433 : 636 : numeric_uminus(PG_FUNCTION_ARGS)
1434 : : {
1435 : 636 : Numeric num = PG_GETARG_NUMERIC(0);
1436 : : Numeric res;
1437 : :
1438 : : /*
1439 : : * Do it the easy way directly on the packed format
1440 : : */
2320 1441 : 636 : res = duplicate_numeric(num);
1442 : :
1443 [ + + ]: 636 : if (NUMERIC_IS_SPECIAL(num))
1444 : : {
1445 : : /* Flip the sign, if it's Inf or -Inf */
1446 [ + + ]: 84 : if (!NUMERIC_IS_NAN(num))
1447 : 56 : res->choice.n_short.n_header =
1448 : 56 : num->choice.n_short.n_header ^ NUMERIC_INF_SIGN_MASK;
1449 : : }
1450 : :
1451 : : /*
1452 : : * The packed format is known to be totally zero digit trimmed always. So
1453 : : * once we've eliminated specials, we can identify a zero by the fact that
1454 : : * there are no digits at all. Do nothing to a zero.
1455 : : */
1456 [ + + + + ]: 552 : else if (NUMERIC_NDIGITS(num) != 0)
1457 : : {
1458 : : /* Else, flip the sign */
5961 rhaas@postgresql.org 1459 [ + + ]: 476 : if (NUMERIC_IS_SHORT(num))
1460 : 471 : res->choice.n_short.n_header =
1461 : 471 : num->choice.n_short.n_header ^ NUMERIC_SHORT_SIGN_MASK;
1462 [ - + - + : 5 : else if (NUMERIC_SIGN(num) == NUMERIC_POS)
+ - ]
1463 : 5 : res->choice.n_long.n_sign_dscale =
1464 [ - + ]: 5 : NUMERIC_NEG | NUMERIC_DSCALE(num);
1465 : : else
5961 rhaas@postgresql.org 1466 :UBC 0 : res->choice.n_long.n_sign_dscale =
1467 [ # # ]: 0 : NUMERIC_POS | NUMERIC_DSCALE(num);
1468 : : }
1469 : :
9618 tgl@sss.pgh.pa.us 1470 :CBC 636 : PG_RETURN_NUMERIC(res);
1471 : : }
1472 : :
1473 : :
1474 : : Datum
9305 bruce@momjian.us 1475 :UBC 0 : numeric_uplus(PG_FUNCTION_ARGS)
1476 : : {
1477 : 0 : Numeric num = PG_GETARG_NUMERIC(0);
1478 : :
2320 tgl@sss.pgh.pa.us 1479 : 0 : PG_RETURN_NUMERIC(duplicate_numeric(num));
1480 : : }
1481 : :
1482 : :
1483 : : /*
1484 : : * numeric_sign_internal() -
1485 : : *
1486 : : * Returns -1 if the argument is less than 0, 0 if the argument is equal
1487 : : * to 0, and 1 if the argument is greater than zero. Caller must have
1488 : : * taken care of the NaN case, but we can handle infinities here.
1489 : : */
1490 : : static int
2320 tgl@sss.pgh.pa.us 1491 :CBC 2494 : numeric_sign_internal(Numeric num)
1492 : : {
1493 [ + + ]: 2494 : if (NUMERIC_IS_SPECIAL(num))
1494 : : {
1495 [ - + ]: 232 : Assert(!NUMERIC_IS_NAN(num));
1496 : : /* Must be Inf or -Inf */
1497 [ + + ]: 232 : if (NUMERIC_IS_PINF(num))
1498 : 138 : return 1;
1499 : : else
1500 : 94 : return -1;
1501 : : }
1502 : :
1503 : : /*
1504 : : * The packed format is known to be totally zero digit trimmed always. So
1505 : : * once we've eliminated specials, we can identify a zero by the fact that
1506 : : * there are no digits at all.
1507 : : */
1508 [ + + + + ]: 2262 : else if (NUMERIC_NDIGITS(num) == 0)
1509 : 161 : return 0;
1510 [ + + - + : 2101 : else if (NUMERIC_SIGN(num) == NUMERIC_NEG)
+ + ]
1511 : 511 : return -1;
1512 : : else
1513 : 1590 : return 1;
1514 : : }
1515 : :
1516 : : /*
1517 : : * numeric_sign() -
1518 : : *
1519 : : * returns -1 if the argument is less than 0, 0 if the argument is equal
1520 : : * to 0, and 1 if the argument is greater than zero.
1521 : : */
1522 : : Datum
9618 1523 : 32 : numeric_sign(PG_FUNCTION_ARGS)
1524 : : {
1525 : 32 : Numeric num = PG_GETARG_NUMERIC(0);
1526 : :
1527 : : /*
1528 : : * Handle NaN (infinities can be handled normally)
1529 : : */
10195 JanWieck@Yahoo.com 1530 [ + + ]: 32 : if (NUMERIC_IS_NAN(num))
9618 tgl@sss.pgh.pa.us 1531 : 4 : PG_RETURN_NUMERIC(make_result(&const_nan));
1532 : :
2320 1533 [ + + + - ]: 28 : switch (numeric_sign_internal(num))
1534 : : {
1535 : 4 : case 0:
1536 : 4 : PG_RETURN_NUMERIC(make_result(&const_zero));
1537 : 12 : case 1:
1538 : 12 : PG_RETURN_NUMERIC(make_result(&const_one));
1539 : 12 : case -1:
1540 : 12 : PG_RETURN_NUMERIC(make_result(&const_minus_one));
1541 : : }
1542 : :
2320 tgl@sss.pgh.pa.us 1543 :UBC 0 : Assert(false);
1544 : : return (Datum) 0;
1545 : : }
1546 : :
1547 : :
1548 : : /*
1549 : : * numeric_round() -
1550 : : *
1551 : : * Round a value to have 'scale' digits after the decimal point.
1552 : : * We allow negative 'scale', implying rounding before the decimal
1553 : : * point --- Oracle interprets rounding that way.
1554 : : */
1555 : : Datum
9664 tgl@sss.pgh.pa.us 1556 :CBC 5221 : numeric_round(PG_FUNCTION_ARGS)
1557 : : {
1558 : 5221 : Numeric num = PG_GETARG_NUMERIC(0);
1559 : 5221 : int32 scale = PG_GETARG_INT32(1);
1560 : : Numeric res;
1561 : : NumericVar arg;
1562 : :
1563 : : /*
1564 : : * Handle NaN and infinities
1565 : : */
2320 1566 [ + + ]: 5221 : if (NUMERIC_IS_SPECIAL(num))
1567 : 64 : PG_RETURN_NUMERIC(duplicate_numeric(num));
1568 : :
1569 : : /*
1570 : : * Limit the scale value to avoid possible overflow in calculations.
1571 : : *
1572 : : * These limits are based on the maximum number of digits a Numeric value
1573 : : * can have before and after the decimal point, but we must allow for one
1574 : : * extra digit before the decimal point, in case the most significant
1575 : : * digit rounds up; we must check if that causes Numeric overflow.
1576 : : */
873 dean.a.rasheed@gmail 1577 : 5157 : scale = Max(scale, -(NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS - 1);
1578 : 5157 : scale = Min(scale, NUMERIC_DSCALE_MAX);
1579 : :
1580 : : /*
1581 : : * Unpack the argument and round it at the proper digit position
1582 : : */
9756 tgl@sss.pgh.pa.us 1583 : 5157 : init_var(&arg);
1584 : 5157 : set_var_from_num(num, &arg);
1585 : :
8653 1586 : 5157 : round_var(&arg, scale);
1587 : :
1588 : : /* We don't allow negative output dscale */
1589 [ + + ]: 5157 : if (scale < 0)
1590 : 149 : arg.dscale = 0;
1591 : :
1592 : : /*
1593 : : * Return the rounded result
1594 : : */
9756 1595 : 5157 : res = make_result(&arg);
1596 : :
1597 : 5153 : free_var(&arg);
9664 1598 : 5153 : PG_RETURN_NUMERIC(res);
1599 : : }
1600 : :
1601 : :
1602 : : /*
1603 : : * numeric_trunc() -
1604 : : *
1605 : : * Truncate a value to have 'scale' digits after the decimal point.
1606 : : * We allow negative 'scale', implying a truncation before the decimal
1607 : : * point --- Oracle interprets truncation that way.
1608 : : */
1609 : : Datum
1610 : 442 : numeric_trunc(PG_FUNCTION_ARGS)
1611 : : {
1612 : 442 : Numeric num = PG_GETARG_NUMERIC(0);
1613 : 442 : int32 scale = PG_GETARG_INT32(1);
1614 : : Numeric res;
1615 : : NumericVar arg;
1616 : :
1617 : : /*
1618 : : * Handle NaN and infinities
1619 : : */
2320 1620 [ + + ]: 442 : if (NUMERIC_IS_SPECIAL(num))
1621 : 24 : PG_RETURN_NUMERIC(duplicate_numeric(num));
1622 : :
1623 : : /*
1624 : : * Limit the scale value to avoid possible overflow in calculations.
1625 : : *
1626 : : * These limits are based on the maximum number of digits a Numeric value
1627 : : * can have before and after the decimal point.
1628 : : */
873 dean.a.rasheed@gmail 1629 : 418 : scale = Max(scale, -(NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS);
1630 : 418 : scale = Min(scale, NUMERIC_DSCALE_MAX);
1631 : :
1632 : : /*
1633 : : * Unpack the argument and truncate it at the proper digit position
1634 : : */
10195 JanWieck@Yahoo.com 1635 : 418 : init_var(&arg);
1636 : 418 : set_var_from_num(num, &arg);
1637 : :
8653 tgl@sss.pgh.pa.us 1638 : 418 : trunc_var(&arg, scale);
1639 : :
1640 : : /* We don't allow negative output dscale */
1641 [ + + ]: 418 : if (scale < 0)
1642 : 20 : arg.dscale = 0;
1643 : :
1644 : : /*
1645 : : * Return the truncated result
1646 : : */
10195 JanWieck@Yahoo.com 1647 : 418 : res = make_result(&arg);
1648 : :
1649 : 418 : free_var(&arg);
9664 tgl@sss.pgh.pa.us 1650 : 418 : PG_RETURN_NUMERIC(res);
1651 : : }
1652 : :
1653 : :
1654 : : /*
1655 : : * numeric_ceil() -
1656 : : *
1657 : : * Return the smallest integer greater than or equal to the argument
1658 : : */
1659 : : Datum
9618 1660 : 148 : numeric_ceil(PG_FUNCTION_ARGS)
1661 : : {
1662 : 148 : Numeric num = PG_GETARG_NUMERIC(0);
1663 : : Numeric res;
1664 : : NumericVar result;
1665 : :
1666 : : /*
1667 : : * Handle NaN and infinities
1668 : : */
2320 1669 [ + + ]: 148 : if (NUMERIC_IS_SPECIAL(num))
1670 : 12 : PG_RETURN_NUMERIC(duplicate_numeric(num));
1671 : :
5120 heikki.linnakangas@i 1672 : 136 : init_var_from_num(num, &result);
10195 JanWieck@Yahoo.com 1673 : 136 : ceil_var(&result, &result);
1674 : :
1675 : 136 : res = make_result(&result);
1676 : 136 : free_var(&result);
1677 : :
9618 tgl@sss.pgh.pa.us 1678 : 136 : PG_RETURN_NUMERIC(res);
1679 : : }
1680 : :
1681 : :
1682 : : /*
1683 : : * numeric_floor() -
1684 : : *
1685 : : * Return the largest integer equal to or less than the argument
1686 : : */
1687 : : Datum
1688 : 84 : numeric_floor(PG_FUNCTION_ARGS)
1689 : : {
1690 : 84 : Numeric num = PG_GETARG_NUMERIC(0);
1691 : : Numeric res;
1692 : : NumericVar result;
1693 : :
1694 : : /*
1695 : : * Handle NaN and infinities
1696 : : */
2320 1697 [ + + ]: 84 : if (NUMERIC_IS_SPECIAL(num))
1698 : 12 : PG_RETURN_NUMERIC(duplicate_numeric(num));
1699 : :
5120 heikki.linnakangas@i 1700 : 72 : init_var_from_num(num, &result);
10195 JanWieck@Yahoo.com 1701 : 72 : floor_var(&result, &result);
1702 : :
1703 : 72 : res = make_result(&result);
1704 : 72 : free_var(&result);
1705 : :
9618 tgl@sss.pgh.pa.us 1706 : 72 : PG_RETURN_NUMERIC(res);
1707 : : }
1708 : :
1709 : :
1710 : : /*
1711 : : * generate_series_numeric() -
1712 : : *
1713 : : * Generate series of numeric.
1714 : : */
1715 : : Datum
4400 fujii@postgresql.org 1716 : 80256 : generate_series_numeric(PG_FUNCTION_ARGS)
1717 : : {
1718 : 80256 : return generate_series_step_numeric(fcinfo);
1719 : : }
1720 : :
1721 : : Datum
1722 : 80556 : generate_series_step_numeric(PG_FUNCTION_ARGS)
1723 : : {
1724 : : generate_series_numeric_fctx *fctx;
1725 : : FuncCallContext *funcctx;
1726 : : MemoryContext oldcontext;
1727 : :
1728 [ + + ]: 80556 : if (SRF_IS_FIRSTCALL())
1729 : : {
1730 : 116 : Numeric start_num = PG_GETARG_NUMERIC(0);
1731 : 116 : Numeric stop_num = PG_GETARG_NUMERIC(1);
1732 : 116 : NumericVar steploc = const_one;
1733 : :
1734 : : /* Reject NaN and infinities in start and stop values */
2320 tgl@sss.pgh.pa.us 1735 [ + + ]: 116 : if (NUMERIC_IS_SPECIAL(start_num))
1736 : : {
1737 [ + + ]: 8 : if (NUMERIC_IS_NAN(start_num))
1738 [ + - ]: 4 : ereport(ERROR,
1739 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1740 : : errmsg("start value cannot be NaN")));
1741 : : else
1742 [ + - ]: 4 : ereport(ERROR,
1743 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1744 : : errmsg("start value cannot be infinity")));
1745 : : }
1746 [ + + ]: 108 : if (NUMERIC_IS_SPECIAL(stop_num))
1747 : : {
1748 [ + + ]: 8 : if (NUMERIC_IS_NAN(stop_num))
1749 [ + - ]: 4 : ereport(ERROR,
1750 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1751 : : errmsg("stop value cannot be NaN")));
1752 : : else
1753 [ + - ]: 4 : ereport(ERROR,
1754 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1755 : : errmsg("stop value cannot be infinity")));
1756 : : }
1757 : :
1758 : : /* see if we were given an explicit step size */
4400 fujii@postgresql.org 1759 [ + + ]: 100 : if (PG_NARGS() == 3)
1760 : : {
4298 tgl@sss.pgh.pa.us 1761 : 48 : Numeric step_num = PG_GETARG_NUMERIC(2);
1762 : :
2320 1763 [ + + ]: 48 : if (NUMERIC_IS_SPECIAL(step_num))
1764 : : {
1765 [ + + ]: 8 : if (NUMERIC_IS_NAN(step_num))
1766 [ + - ]: 4 : ereport(ERROR,
1767 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1768 : : errmsg("step size cannot be NaN")));
1769 : : else
1770 [ + - ]: 4 : ereport(ERROR,
1771 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1772 : : errmsg("step size cannot be infinity")));
1773 : : }
1774 : :
4400 fujii@postgresql.org 1775 : 40 : init_var_from_num(step_num, &steploc);
1776 : :
1777 [ + + ]: 40 : if (cmp_var(&steploc, &const_zero) == 0)
1778 [ + - ]: 4 : ereport(ERROR,
1779 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1780 : : errmsg("step size cannot equal zero")));
1781 : : }
1782 : :
1783 : : /* create a function context for cross-call persistence */
1784 : 88 : funcctx = SRF_FIRSTCALL_INIT();
1785 : :
1786 : : /*
1787 : : * Switch to memory context appropriate for multiple function calls.
1788 : : */
1789 : 88 : oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1790 : :
1791 : : /* allocate memory for user context */
353 michael@paquier.xyz 1792 : 88 : fctx = palloc_object(generate_series_numeric_fctx);
1793 : :
1794 : : /*
1795 : : * Use fctx to keep state from call to call. Seed current with the
1796 : : * original start value. We must copy the start_num and stop_num
1797 : : * values rather than pointing to them, since we may have detoasted
1798 : : * them in the per-call context.
1799 : : */
4363 fujii@postgresql.org 1800 : 88 : init_var(&fctx->current);
1801 : 88 : init_var(&fctx->stop);
4400 1802 : 88 : init_var(&fctx->step);
1803 : :
4363 1804 : 88 : set_var_from_num(start_num, &fctx->current);
1805 : 88 : set_var_from_num(stop_num, &fctx->stop);
4400 1806 : 88 : set_var_from_var(&steploc, &fctx->step);
1807 : :
1808 : 88 : funcctx->user_fctx = fctx;
1809 : 88 : MemoryContextSwitchTo(oldcontext);
1810 : : }
1811 : :
1812 : : /* stuff done on every call of the function */
1813 : 80528 : funcctx = SRF_PERCALL_SETUP();
1814 : :
1815 : : /*
1816 : : * Get the saved state and use current state as the result of this
1817 : : * iteration.
1818 : : */
1819 : 80528 : fctx = funcctx->user_fctx;
1820 : :
1821 [ + + + + ]: 160936 : if ((fctx->step.sign == NUMERIC_POS &&
1822 : 80408 : cmp_var(&fctx->current, &fctx->stop) <= 0) ||
1823 [ + + + + ]: 320 : (fctx->step.sign == NUMERIC_NEG &&
1824 : 120 : cmp_var(&fctx->current, &fctx->stop) >= 0))
1825 : : {
4298 tgl@sss.pgh.pa.us 1826 : 80440 : Numeric result = make_result(&fctx->current);
1827 : :
1828 : : /* switch to memory context appropriate for iteration calculation */
4400 fujii@postgresql.org 1829 : 80440 : oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1830 : :
1831 : : /* increment current in preparation for next iteration */
1832 : 80440 : add_var(&fctx->current, &fctx->step, &fctx->current);
1833 : 80440 : MemoryContextSwitchTo(oldcontext);
1834 : :
1835 : : /* do when there is more left to send */
1836 : 80440 : SRF_RETURN_NEXT(funcctx, NumericGetDatum(result));
1837 : : }
1838 : : else
1839 : : /* do when there is no more left */
1840 : 88 : SRF_RETURN_DONE(funcctx);
1841 : : }
1842 : :
1843 : : /*
1844 : : * Planner support function for generate_series(numeric, numeric [, numeric])
1845 : : */
1846 : : Datum
726 dean.a.rasheed@gmail 1847 : 535 : generate_series_numeric_support(PG_FUNCTION_ARGS)
1848 : : {
1849 : 535 : Node *rawreq = (Node *) PG_GETARG_POINTER(0);
1850 : 535 : Node *ret = NULL;
1851 : :
1852 [ + + ]: 535 : if (IsA(rawreq, SupportRequestRows))
1853 : : {
1854 : : /* Try to estimate the number of rows returned */
1855 : 130 : SupportRequestRows *req = (SupportRequestRows *) rawreq;
1856 : :
1857 [ + - ]: 130 : if (is_funcclause(req->node)) /* be paranoid */
1858 : : {
1859 : 130 : List *args = ((FuncExpr *) req->node)->args;
1860 : : Node *arg1,
1861 : : *arg2,
1862 : : *arg3;
1863 : :
1864 : : /* We can use estimated argument values here */
1865 : 130 : arg1 = estimate_expression_value(req->root, linitial(args));
1866 : 130 : arg2 = estimate_expression_value(req->root, lsecond(args));
1867 [ + + ]: 130 : if (list_length(args) >= 3)
1868 : 85 : arg3 = estimate_expression_value(req->root, lthird(args));
1869 : : else
1870 : 45 : arg3 = NULL;
1871 : :
1872 : : /*
1873 : : * If any argument is constant NULL, we can safely assume that
1874 : : * zero rows are returned. Otherwise, if they're all non-NULL
1875 : : * constants, we can calculate the number of rows that will be
1876 : : * returned.
1877 : : */
1878 [ + + ]: 130 : if ((IsA(arg1, Const) &&
1879 [ + - ]: 125 : ((Const *) arg1)->constisnull) ||
1880 [ + + ]: 130 : (IsA(arg2, Const) &&
1881 [ + - + + ]: 130 : ((Const *) arg2)->constisnull) ||
1882 [ + + ]: 85 : (arg3 != NULL && IsA(arg3, Const) &&
1883 [ - + ]: 80 : ((Const *) arg3)->constisnull))
1884 : : {
726 dean.a.rasheed@gmail 1885 :UBC 0 : req->rows = 0;
1886 : 0 : ret = (Node *) req;
1887 : : }
726 dean.a.rasheed@gmail 1888 [ + + ]:CBC 130 : else if (IsA(arg1, Const) &&
1889 [ + + + + ]: 125 : IsA(arg2, Const) &&
1890 [ + + ]: 85 : (arg3 == NULL || IsA(arg3, Const)))
1891 : : {
1892 : : Numeric start_num;
1893 : : Numeric stop_num;
1894 : 115 : NumericVar step = const_one;
1895 : :
1896 : : /*
1897 : : * If any argument is NaN or infinity, generate_series() will
1898 : : * error out, so we needn't produce an estimate.
1899 : : */
1900 : 115 : start_num = DatumGetNumeric(((Const *) arg1)->constvalue);
1901 : 115 : stop_num = DatumGetNumeric(((Const *) arg2)->constvalue);
1902 : :
1903 [ + + ]: 115 : if (NUMERIC_IS_SPECIAL(start_num) ||
1904 [ + + ]: 100 : NUMERIC_IS_SPECIAL(stop_num))
1905 : 40 : PG_RETURN_POINTER(NULL);
1906 : :
1907 [ + + ]: 90 : if (arg3)
1908 : : {
1909 : : Numeric step_num;
1910 : :
1911 : 55 : step_num = DatumGetNumeric(((Const *) arg3)->constvalue);
1912 : :
1913 [ + + ]: 55 : if (NUMERIC_IS_SPECIAL(step_num))
1914 : 15 : PG_RETURN_POINTER(NULL);
1915 : :
1916 : 40 : init_var_from_num(step_num, &step);
1917 : : }
1918 : :
1919 : : /*
1920 : : * The number of rows that will be returned is given by
1921 : : * floor((stop - start) / step) + 1, if the sign of step
1922 : : * matches the sign of stop - start. Otherwise, no rows will
1923 : : * be returned.
1924 : : */
1925 [ + + ]: 75 : if (cmp_var(&step, &const_zero) != 0)
1926 : : {
1927 : : NumericVar start;
1928 : : NumericVar stop;
1929 : : NumericVar res;
1930 : :
1931 : 65 : init_var_from_num(start_num, &start);
1932 : 65 : init_var_from_num(stop_num, &stop);
1933 : :
1934 : 65 : init_var(&res);
1935 : 65 : sub_var(&stop, &start, &res);
1936 : :
1937 [ + + ]: 65 : if (step.sign != res.sign)
1938 : : {
1939 : : /* no rows will be returned */
1940 : 5 : req->rows = 0;
1941 : 5 : ret = (Node *) req;
1942 : : }
1943 : : else
1944 : : {
1945 [ + + ]: 60 : if (arg3)
1946 : 25 : div_var(&res, &step, &res, 0, false, false);
1947 : : else
1948 : 35 : trunc_var(&res, 0); /* step = 1 */
1949 : :
1950 : 60 : req->rows = numericvar_to_double_no_overflow(&res) + 1;
1951 : 60 : ret = (Node *) req;
1952 : : }
1953 : :
1954 : 65 : free_var(&res);
1955 : : }
1956 : : }
1957 : : }
1958 : : }
1959 : :
1960 : 495 : PG_RETURN_POINTER(ret);
1961 : : }
1962 : :
1963 : :
1964 : : /*
1965 : : * Implements the numeric version of the width_bucket() function
1966 : : * defined by SQL2003. See also width_bucket_float8().
1967 : : *
1968 : : * 'bound1' and 'bound2' are the lower and upper bounds of the
1969 : : * histogram's range, respectively. 'count' is the number of buckets
1970 : : * in the histogram. width_bucket() returns an integer indicating the
1971 : : * bucket number that 'operand' belongs to in an equiwidth histogram
1972 : : * with the specified characteristics. An operand smaller than the
1973 : : * lower bound is assigned to bucket 0. An operand greater than or equal
1974 : : * to the upper bound is assigned to an additional bucket (with number
1975 : : * count+1). We don't allow the histogram bounds to be NaN or +/- infinity,
1976 : : * but we do allow those values for the operand (taking NaN to be larger
1977 : : * than any other value, as we do in comparisons).
1978 : : */
1979 : : Datum
8233 neilc@samurai.com 1980 : 529 : width_bucket_numeric(PG_FUNCTION_ARGS)
1981 : : {
1982 : 529 : Numeric operand = PG_GETARG_NUMERIC(0);
1983 : 529 : Numeric bound1 = PG_GETARG_NUMERIC(1);
1984 : 529 : Numeric bound2 = PG_GETARG_NUMERIC(2);
1985 : 529 : int32 count = PG_GETARG_INT32(3);
1986 : : NumericVar count_var;
1987 : : NumericVar result_var;
1988 : : int32 result;
1989 : :
1990 [ + + ]: 529 : if (count <= 0)
1991 [ + - ]: 8 : ereport(ERROR,
1992 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
1993 : : errmsg("count must be greater than zero")));
1994 : :
514 tgl@sss.pgh.pa.us 1995 [ + + + + ]: 521 : if (NUMERIC_IS_SPECIAL(bound1) || NUMERIC_IS_SPECIAL(bound2))
1996 : : {
1997 [ + + - + ]: 16 : if (NUMERIC_IS_NAN(bound1) || NUMERIC_IS_NAN(bound2))
2320 1998 [ + - ]: 4 : ereport(ERROR,
1999 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
2000 : : errmsg("lower and upper bounds cannot be NaN")));
2001 : :
2242 2002 [ + + + - ]: 12 : if (NUMERIC_IS_INF(bound1) || NUMERIC_IS_INF(bound2))
2320 2003 [ + - ]: 12 : ereport(ERROR,
2004 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
2005 : : errmsg("lower and upper bounds must be finite")));
2006 : : }
2007 : :
8233 neilc@samurai.com 2008 : 505 : init_var(&result_var);
2009 : 505 : init_var(&count_var);
2010 : :
2011 : : /* Convert 'count' to a numeric, for ease of use later */
4271 andres@anarazel.de 2012 : 505 : int64_to_numericvar((int64) count, &count_var);
2013 : :
8233 neilc@samurai.com 2014 [ + + + - ]: 505 : switch (cmp_numerics(bound1, bound2))
2015 : : {
2016 : 4 : case 0:
2017 [ + - ]: 4 : ereport(ERROR,
2018 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
2019 : : errmsg("lower bound cannot equal upper bound")));
2020 : : break;
2021 : :
2022 : : /* bound1 < bound2 */
2023 : 372 : case -1:
2024 [ + + ]: 372 : if (cmp_numerics(operand, bound1) < 0)
2025 : 77 : set_var_from_var(&const_zero, &result_var);
2026 [ + + ]: 295 : else if (cmp_numerics(operand, bound2) >= 0)
2027 : 78 : add_var(&count_var, &const_one, &result_var);
2028 : : else
871 dean.a.rasheed@gmail 2029 : 217 : compute_bucket(operand, bound1, bound2, &count_var,
2030 : : &result_var);
8233 neilc@samurai.com 2031 : 372 : break;
2032 : :
2033 : : /* bound1 > bound2 */
2034 : 129 : case 1:
2035 [ + + ]: 129 : if (cmp_numerics(operand, bound1) > 0)
2036 : 8 : set_var_from_var(&const_zero, &result_var);
2037 [ + + ]: 121 : else if (cmp_numerics(operand, bound2) <= 0)
2038 : 16 : add_var(&count_var, &const_one, &result_var);
2039 : : else
871 dean.a.rasheed@gmail 2040 : 105 : compute_bucket(operand, bound1, bound2, &count_var,
2041 : : &result_var);
8233 neilc@samurai.com 2042 : 129 : break;
2043 : : }
2044 : :
2045 : : /* if result exceeds the range of a legal int4, we ereport here */
2814 akorotkov@postgresql 2046 [ - + ]: 501 : if (!numericvar_to_int32(&result_var, &result))
2814 akorotkov@postgresql 2047 [ # # ]:UBC 0 : ereport(ERROR,
2048 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
2049 : : errmsg("integer out of range")));
2050 : :
8233 neilc@samurai.com 2051 :CBC 501 : free_var(&count_var);
2052 : 501 : free_var(&result_var);
2053 : :
2054 : 501 : PG_RETURN_INT32(result);
2055 : : }
2056 : :
2057 : : /*
2058 : : * 'operand' is inside the bucket range, so determine the correct
2059 : : * bucket for it to go in. The calculations performed by this function
2060 : : * are derived directly from the SQL2003 spec. Note however that we
2061 : : * multiply by count before dividing, to avoid unnecessary roundoff error.
2062 : : */
2063 : : static void
2064 : 322 : compute_bucket(Numeric operand, Numeric bound1, Numeric bound2,
2065 : : const NumericVar *count_var, NumericVar *result_var)
2066 : : {
2067 : : NumericVar bound1_var;
2068 : : NumericVar bound2_var;
2069 : : NumericVar operand_var;
2070 : :
5120 heikki.linnakangas@i 2071 : 322 : init_var_from_num(bound1, &bound1_var);
2072 : 322 : init_var_from_num(bound2, &bound2_var);
2073 : 322 : init_var_from_num(operand, &operand_var);
2074 : :
2075 : : /*
2076 : : * Per spec, bound1 is inclusive and bound2 is exclusive, and so we have
2077 : : * bound1 <= operand < bound2 or bound1 >= operand > bound2. Either way,
2078 : : * the result is ((operand - bound1) * count) / (bound2 - bound1) + 1,
2079 : : * where the quotient is computed using floor division (i.e., division to
2080 : : * zero decimal places with truncation), which guarantees that the result
2081 : : * is in the range [1, count]. Reversing the bounds doesn't affect the
2082 : : * computation, because the signs cancel out when dividing.
2083 : : */
871 dean.a.rasheed@gmail 2084 : 322 : sub_var(&operand_var, &bound1_var, &operand_var);
2085 : 322 : sub_var(&bound2_var, &bound1_var, &bound2_var);
2086 : :
2242 tgl@sss.pgh.pa.us 2087 : 322 : mul_var(&operand_var, count_var, &operand_var,
2088 : 322 : operand_var.dscale + count_var->dscale);
785 dean.a.rasheed@gmail 2089 : 322 : div_var(&operand_var, &bound2_var, result_var, 0, false, true);
871 2090 : 322 : add_var(result_var, &const_one, result_var);
2091 : :
8233 neilc@samurai.com 2092 : 322 : free_var(&bound1_var);
2093 : 322 : free_var(&bound2_var);
2094 : 322 : free_var(&operand_var);
8126 bruce@momjian.us 2095 : 322 : }
2096 : :
2097 : : /* ----------------------------------------------------------------------
2098 : : *
2099 : : * Comparison functions
2100 : : *
2101 : : * Note: btree indexes need these routines not to leak memory; therefore,
2102 : : * be careful to free working copies of toasted datums. Most places don't
2103 : : * need to be so careful.
2104 : : *
2105 : : * Sort support:
2106 : : *
2107 : : * We implement the sortsupport strategy routine in order to get the benefit of
2108 : : * abbreviation. The ordinary numeric comparison can be quite slow as a result
2109 : : * of palloc/pfree cycles (due to detoasting packed values for alignment);
2110 : : * while this could be worked on itself, the abbreviation strategy gives more
2111 : : * speedup in many common cases.
2112 : : *
2113 : : * The abbreviated format is an int64. The representation is negated relative
2114 : : * to the original value, because we use the largest negative value for NaN,
2115 : : * which sorts higher than other values. We convert the absolute value of the
2116 : : * numeric to a 63-bit positive value, and then negate it if the original
2117 : : * number was positive.
2118 : : *
2119 : : * We abort the abbreviation process if the abbreviation cardinality is below
2120 : : * 0.01% of the row count (1 per 10k non-null rows). The actual break-even
2121 : : * point is somewhat below that, perhaps 1 per 30k (at 1 per 100k there's a
2122 : : * very small penalty), but we don't want to build up too many abbreviated
2123 : : * values before first testing for abort, so we take the slightly pessimistic
2124 : : * number. We make no attempt to estimate the cardinality of the real values,
2125 : : * since it plays no part in the cost model here (if the abbreviation is equal,
2126 : : * the cost of comparing equal and unequal underlying values is comparable).
2127 : : * We discontinue even checking for abort (saving us the hashing overhead) if
2128 : : * the estimated cardinality gets to 100k; that would be enough to support many
2129 : : * billions of rows while doing no worse than breaking even.
2130 : : *
2131 : : * ----------------------------------------------------------------------
2132 : : */
2133 : :
2134 : : /*
2135 : : * Sort support strategy routine.
2136 : : */
2137 : : Datum
4258 rhaas@postgresql.org 2138 : 810 : numeric_sortsupport(PG_FUNCTION_ARGS)
2139 : : {
2140 : 810 : SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
2141 : :
2142 : 810 : ssup->comparator = numeric_fast_cmp;
2143 : :
2144 [ + + ]: 810 : if (ssup->abbreviate)
2145 : : {
2146 : : NumericSortSupport *nss;
2147 : 185 : MemoryContext oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
2148 : :
353 michael@paquier.xyz 2149 : 185 : nss = palloc_object(NumericSortSupport);
2150 : :
2151 : : /*
2152 : : * palloc a buffer for handling unaligned packed values in addition to
2153 : : * the support struct
2154 : : */
4258 rhaas@postgresql.org 2155 : 185 : nss->buf = palloc(VARATT_SHORT_MAX + VARHDRSZ + 1);
2156 : :
2157 : 185 : nss->input_count = 0;
2158 : 185 : nss->estimating = true;
2159 : 185 : initHyperLogLog(&nss->abbr_card, 10);
2160 : :
2161 : 185 : ssup->ssup_extra = nss;
2162 : :
2163 : 185 : ssup->abbrev_full_comparator = ssup->comparator;
2164 : 185 : ssup->comparator = numeric_cmp_abbrev;
2165 : 185 : ssup->abbrev_converter = numeric_abbrev_convert;
2166 : 185 : ssup->abbrev_abort = numeric_abbrev_abort;
2167 : :
2168 : 185 : MemoryContextSwitchTo(oldcontext);
2169 : : }
2170 : :
2171 : 810 : PG_RETURN_VOID();
2172 : : }
2173 : :
2174 : : /*
2175 : : * Abbreviate a numeric datum, handling NaNs and detoasting
2176 : : * (must not leak memory!)
2177 : : */
2178 : : static Datum
2179 : 12779 : numeric_abbrev_convert(Datum original_datum, SortSupport ssup)
2180 : : {
2181 : 12779 : NumericSortSupport *nss = ssup->ssup_extra;
2182 : 12779 : void *original_varatt = PG_DETOAST_DATUM_PACKED(original_datum);
2183 : : Numeric value;
2184 : : Datum result;
2185 : :
2186 : 12779 : nss->input_count += 1;
2187 : :
2188 : : /*
2189 : : * This is to handle packed datums without needing a palloc/pfree cycle;
2190 : : * we keep and reuse a buffer large enough to handle any short datum.
2191 : : */
2192 [ + + ]: 12779 : if (VARATT_IS_SHORT(original_varatt))
2193 : : {
2194 : 679 : void *buf = nss->buf;
2195 : 679 : Size sz = VARSIZE_SHORT(original_varatt) - VARHDRSZ_SHORT;
2196 : :
2197 [ - + ]: 679 : Assert(sz <= VARATT_SHORT_MAX - VARHDRSZ_SHORT);
2198 : :
2199 : 679 : SET_VARSIZE(buf, VARHDRSZ + sz);
2200 : 679 : memcpy(VARDATA(buf), VARDATA_SHORT(original_varatt), sz);
2201 : :
2202 : 679 : value = (Numeric) buf;
2203 : : }
2204 : : else
2205 : 12100 : value = (Numeric) original_varatt;
2206 : :
2320 tgl@sss.pgh.pa.us 2207 [ + + ]: 12779 : if (NUMERIC_IS_SPECIAL(value))
2208 : : {
2209 [ + + ]: 100 : if (NUMERIC_IS_PINF(value))
2210 : 32 : result = NUMERIC_ABBREV_PINF;
2211 [ + + ]: 68 : else if (NUMERIC_IS_NINF(value))
2212 : 32 : result = NUMERIC_ABBREV_NINF;
2213 : : else
2214 : 36 : result = NUMERIC_ABBREV_NAN;
2215 : : }
2216 : : else
2217 : : {
2218 : : NumericVar var;
2219 : :
4258 rhaas@postgresql.org 2220 : 12679 : init_var_from_num(value, &var);
2221 : :
2222 : 12679 : result = numeric_abbrev_convert_var(&var, nss);
2223 : : }
2224 : :
2225 : : /* should happen only for external/compressed toasts */
359 peter@eisentraut.org 2226 [ - + ]: 12779 : if (original_varatt != DatumGetPointer(original_datum))
4258 rhaas@postgresql.org 2227 :UBC 0 : pfree(original_varatt);
2228 : :
4258 rhaas@postgresql.org 2229 :CBC 12779 : return result;
2230 : : }
2231 : :
2232 : : /*
2233 : : * Consider whether to abort abbreviation.
2234 : : *
2235 : : * We pay no attention to the cardinality of the non-abbreviated data. There is
2236 : : * no reason to do so: unlike text, we have no fast check for equal values, so
2237 : : * we pay the full overhead whenever the abbreviations are equal regardless of
2238 : : * whether the underlying values are also equal.
2239 : : */
2240 : : static bool
2241 : 96 : numeric_abbrev_abort(int memtupcount, SortSupport ssup)
2242 : : {
2243 : 96 : NumericSortSupport *nss = ssup->ssup_extra;
2244 : : double abbr_card;
2245 : :
2246 [ - + - - : 96 : if (memtupcount < 10000 || nss->input_count < 10000 || !nss->estimating)
- - ]
2247 : 96 : return false;
2248 : :
4258 rhaas@postgresql.org 2249 :UBC 0 : abbr_card = estimateHyperLogLog(&nss->abbr_card);
2250 : :
2251 : : /*
2252 : : * If we have >100k distinct values, then even if we were sorting many
2253 : : * billion rows we'd likely still break even, and the penalty of undoing
2254 : : * that many rows of abbrevs would probably not be worth it. Stop even
2255 : : * counting at that point.
2256 : : */
2257 [ # # ]: 0 : if (abbr_card > 100000.0)
2258 : : {
2259 [ # # ]: 0 : if (trace_sort)
2260 [ # # ]: 0 : elog(LOG,
2261 : : "numeric_abbrev: estimation ends at cardinality %f"
2262 : : " after " INT64_FORMAT " values (%d rows)",
2263 : : abbr_card, nss->input_count, memtupcount);
2264 : 0 : nss->estimating = false;
2265 : 0 : return false;
2266 : : }
2267 : :
2268 : : /*
2269 : : * Target minimum cardinality is 1 per ~10k of non-null inputs. (The
2270 : : * break even point is somewhere between one per 100k rows, where
2271 : : * abbreviation has a very slight penalty, and 1 per 10k where it wins by
2272 : : * a measurable percentage.) We use the relatively pessimistic 10k
2273 : : * threshold, and add a 0.5 row fudge factor, because it allows us to
2274 : : * abort earlier on genuinely pathological data where we've had exactly
2275 : : * one abbreviated value in the first 10k (non-null) rows.
2276 : : */
2277 [ # # ]: 0 : if (abbr_card < nss->input_count / 10000.0 + 0.5)
2278 : : {
2279 [ # # ]: 0 : if (trace_sort)
2280 [ # # ]: 0 : elog(LOG,
2281 : : "numeric_abbrev: aborting abbreviation at cardinality %f"
2282 : : " below threshold %f after " INT64_FORMAT " values (%d rows)",
2283 : : abbr_card, nss->input_count / 10000.0 + 0.5,
2284 : : nss->input_count, memtupcount);
2285 : 0 : return true;
2286 : : }
2287 : :
2288 [ # # ]: 0 : if (trace_sort)
2289 [ # # ]: 0 : elog(LOG,
2290 : : "numeric_abbrev: cardinality %f"
2291 : : " after " INT64_FORMAT " values (%d rows)",
2292 : : abbr_card, nss->input_count, memtupcount);
2293 : :
2294 : 0 : return false;
2295 : : }
2296 : :
2297 : : /*
2298 : : * Non-fmgr interface to the comparison routine to allow sortsupport to elide
2299 : : * the fmgr call. The saving here is small given how slow numeric comparisons
2300 : : * are, but it is a required part of the sort support API when abbreviations
2301 : : * are performed.
2302 : : *
2303 : : * Two palloc/pfree cycles could be saved here by using persistent buffers for
2304 : : * aligning short-varlena inputs, but this has not so far been considered to
2305 : : * be worth the effort.
2306 : : */
2307 : : static int
4258 rhaas@postgresql.org 2308 :CBC 17322710 : numeric_fast_cmp(Datum x, Datum y, SortSupport ssup)
2309 : : {
2310 : 17322710 : Numeric nx = DatumGetNumeric(x);
2311 : 17322710 : Numeric ny = DatumGetNumeric(y);
2312 : : int result;
2313 : :
2314 : 17322710 : result = cmp_numerics(nx, ny);
2315 : :
359 peter@eisentraut.org 2316 [ + + ]: 17322710 : if (nx != DatumGetPointer(x))
4258 rhaas@postgresql.org 2317 : 7429456 : pfree(nx);
359 peter@eisentraut.org 2318 [ + + ]: 17322710 : if (ny != DatumGetPointer(y))
4258 rhaas@postgresql.org 2319 : 7429452 : pfree(ny);
2320 : :
2321 : 17322710 : return result;
2322 : : }
2323 : :
2324 : : /*
2325 : : * Compare abbreviations of values. (Abbreviations may be equal where the true
2326 : : * values differ, but if the abbreviations differ, they must reflect the
2327 : : * ordering of the true values.)
2328 : : */
2329 : : static int
2330 : 127098 : numeric_cmp_abbrev(Datum x, Datum y, SortSupport ssup)
2331 : : {
2332 : : /*
2333 : : * NOTE WELL: this is intentionally backwards, because the abbreviation is
2334 : : * negated relative to the original value, to handle NaN/infinity cases.
2335 : : */
2336 [ + + ]: 127098 : if (DatumGetNumericAbbrev(x) < DatumGetNumericAbbrev(y))
2337 : 65584 : return 1;
2338 [ + + ]: 61514 : if (DatumGetNumericAbbrev(x) > DatumGetNumericAbbrev(y))
2339 : 61364 : return -1;
2340 : 150 : return 0;
2341 : : }
2342 : :
2343 : : /*
2344 : : * Abbreviate a NumericVar into the 64-bit sortsupport size.
2345 : : *
2346 : : * The 31-bit value is constructed as:
2347 : : *
2348 : : * 0 + 7bits digit weight + 24 bits digit value
2349 : : *
2350 : : * where the digit weight is in single decimal digits, not digit words, and
2351 : : * stored in excess-44 representation[1]. The 24-bit digit value is the 7 most
2352 : : * significant decimal digits of the value converted to binary. Values whose
2353 : : * weights would fall outside the representable range are rounded off to zero
2354 : : * (which is also used to represent actual zeros) or to 0x7FFFFFFF (which
2355 : : * otherwise cannot occur). Abbreviation therefore fails to gain any advantage
2356 : : * where values are outside the range 10^-44 to 10^83, which is not considered
2357 : : * to be a serious limitation, or when values are of the same magnitude and
2358 : : * equal in the first 7 decimal digits, which is considered to be an
2359 : : * unavoidable limitation given the available bits. (Stealing three more bits
2360 : : * to compare another digit would narrow the range of representable weights by
2361 : : * a factor of 8, which starts to look like a real limiting factor.)
2362 : : *
2363 : : * (The value 44 for the excess is essentially arbitrary)
2364 : : *
2365 : : * The 63-bit value is constructed as:
2366 : : *
2367 : : * 0 + 7bits weight + 4 x 14-bit packed digit words
2368 : : *
2369 : : * The weight in this case is again stored in excess-44, but this time it is
2370 : : * the original weight in digit words (i.e. powers of 10000). The first four
2371 : : * digit words of the value (if present; trailing zeros are assumed as needed)
2372 : : * are packed into 14 bits each to form the rest of the value. Again,
2373 : : * out-of-range values are rounded off to 0 or 0x7FFFFFFFFFFFFFFF. The
2374 : : * representable range in this case is 10^-176 to 10^332, which is considered
2375 : : * to be good enough for all practical purposes, and comparison of 4 words
2376 : : * means that at least 13 decimal digits are compared, which is considered to
2377 : : * be a reasonable compromise between effectiveness and efficiency in computing
2378 : : * the abbreviation.
2379 : : *
2380 : : * (The value 44 for the excess is even more arbitrary here, it was chosen just
2381 : : * to match the value used in the 31-bit case)
2382 : : *
2383 : : * [1] - Excess-k representation means that the value is offset by adding 'k'
2384 : : * and then treated as unsigned, so the smallest representable value is stored
2385 : : * with all bits zero. This allows simple comparisons to work on the composite
2386 : : * value.
2387 : : */
2388 : : static Datum
3366 andres@anarazel.de 2389 : 12679 : numeric_abbrev_convert_var(const NumericVar *var, NumericSortSupport *nss)
2390 : : {
4258 rhaas@postgresql.org 2391 : 12679 : int ndigits = var->ndigits;
2392 : 12679 : int weight = var->weight;
2393 : : int64 result;
2394 : :
2395 [ + + - + ]: 12679 : if (ndigits == 0 || weight < -44)
2396 : : {
2397 : 34 : result = 0;
2398 : : }
2399 [ + + ]: 12645 : else if (weight > 83)
2400 : : {
2401 : 8 : result = PG_INT64_MAX;
2402 : : }
2403 : : else
2404 : : {
2405 : 12637 : result = ((int64) (weight + 44) << 56);
2406 : :
2407 [ - + + + ]: 12637 : switch (ndigits)
2408 : : {
4258 rhaas@postgresql.org 2409 :UBC 0 : default:
2410 : 0 : result |= ((int64) var->digits[3]);
2411 : : pg_fallthrough;
4258 rhaas@postgresql.org 2412 :CBC 4135 : case 3:
2413 : 4135 : result |= ((int64) var->digits[2]) << 14;
2414 : : pg_fallthrough;
2415 : 12210 : case 2:
2416 : 12210 : result |= ((int64) var->digits[1]) << 28;
2417 : : pg_fallthrough;
2418 : 12637 : case 1:
2419 : 12637 : result |= ((int64) var->digits[0]) << 42;
2420 : 12637 : break;
2421 : : }
2422 : : }
2423 : :
2424 : : /* the abbrev is negated relative to the original */
2425 [ + + ]: 12679 : if (var->sign == NUMERIC_POS)
2426 : 12615 : result = -result;
2427 : :
2428 [ + - ]: 12679 : if (nss->estimating)
68 john.naylor@postgres 2429 :GNC 12679 : addHyperLogLog(&nss->abbr_card,
2430 : 12679 : (uint32) murmurhash64((uint64) result));
2431 : :
4257 rhaas@postgresql.org 2432 :CBC 12679 : return NumericAbbrevGetDatum(result);
2433 : : }
2434 : :
2435 : :
2436 : : /*
2437 : : * Ordinary (non-sortsupport) comparisons follow.
2438 : : */
2439 : :
2440 : : Datum
9618 tgl@sss.pgh.pa.us 2441 : 624132 : numeric_cmp(PG_FUNCTION_ARGS)
2442 : : {
2443 : 624132 : Numeric num1 = PG_GETARG_NUMERIC(0);
2444 : 624132 : Numeric num2 = PG_GETARG_NUMERIC(1);
2445 : : int result;
2446 : :
9340 2447 : 624132 : result = cmp_numerics(num1, num2);
2448 : :
9618 2449 [ + + ]: 624132 : PG_FREE_IF_COPY(num1, 0);
2450 [ + + ]: 624132 : PG_FREE_IF_COPY(num2, 1);
2451 : :
2452 : 624132 : PG_RETURN_INT32(result);
2453 : : }
2454 : :
2455 : :
2456 : : Datum
2457 : 448652 : numeric_eq(PG_FUNCTION_ARGS)
2458 : : {
2459 : 448652 : Numeric num1 = PG_GETARG_NUMERIC(0);
2460 : 448652 : Numeric num2 = PG_GETARG_NUMERIC(1);
2461 : : bool result;
2462 : :
9340 2463 : 448652 : result = cmp_numerics(num1, num2) == 0;
2464 : :
9618 2465 [ + + ]: 448652 : PG_FREE_IF_COPY(num1, 0);
2466 [ + + ]: 448652 : PG_FREE_IF_COPY(num2, 1);
2467 : :
2468 : 448652 : PG_RETURN_BOOL(result);
2469 : : }
2470 : :
2471 : : Datum
2472 : 3584 : numeric_ne(PG_FUNCTION_ARGS)
2473 : : {
2474 : 3584 : Numeric num1 = PG_GETARG_NUMERIC(0);
2475 : 3584 : Numeric num2 = PG_GETARG_NUMERIC(1);
2476 : : bool result;
2477 : :
9340 2478 : 3584 : result = cmp_numerics(num1, num2) != 0;
2479 : :
9618 2480 [ + + ]: 3584 : PG_FREE_IF_COPY(num1, 0);
2481 [ + + ]: 3584 : PG_FREE_IF_COPY(num2, 1);
2482 : :
2483 : 3584 : PG_RETURN_BOOL(result);
2484 : : }
2485 : :
2486 : : Datum
2487 : 34680 : numeric_gt(PG_FUNCTION_ARGS)
2488 : : {
2489 : 34680 : Numeric num1 = PG_GETARG_NUMERIC(0);
2490 : 34680 : Numeric num2 = PG_GETARG_NUMERIC(1);
2491 : : bool result;
2492 : :
9340 2493 : 34680 : result = cmp_numerics(num1, num2) > 0;
2494 : :
9618 2495 [ + + ]: 34680 : PG_FREE_IF_COPY(num1, 0);
2496 [ + + ]: 34680 : PG_FREE_IF_COPY(num2, 1);
2497 : :
2498 : 34680 : PG_RETURN_BOOL(result);
2499 : : }
2500 : :
2501 : : Datum
2502 : 7949 : numeric_ge(PG_FUNCTION_ARGS)
2503 : : {
2504 : 7949 : Numeric num1 = PG_GETARG_NUMERIC(0);
2505 : 7949 : Numeric num2 = PG_GETARG_NUMERIC(1);
2506 : : bool result;
2507 : :
9340 2508 : 7949 : result = cmp_numerics(num1, num2) >= 0;
2509 : :
9618 2510 [ + + ]: 7949 : PG_FREE_IF_COPY(num1, 0);
2511 [ - + ]: 7949 : PG_FREE_IF_COPY(num2, 1);
2512 : :
2513 : 7949 : PG_RETURN_BOOL(result);
2514 : : }
2515 : :
2516 : : Datum
2517 : 250881 : numeric_lt(PG_FUNCTION_ARGS)
2518 : : {
2519 : 250881 : Numeric num1 = PG_GETARG_NUMERIC(0);
2520 : 250881 : Numeric num2 = PG_GETARG_NUMERIC(1);
2521 : : bool result;
2522 : :
9340 2523 : 250881 : result = cmp_numerics(num1, num2) < 0;
2524 : :
9618 2525 [ + + ]: 250881 : PG_FREE_IF_COPY(num1, 0);
2526 [ + + ]: 250881 : PG_FREE_IF_COPY(num2, 1);
2527 : :
2528 : 250881 : PG_RETURN_BOOL(result);
2529 : : }
2530 : :
2531 : : Datum
2532 : 10643 : numeric_le(PG_FUNCTION_ARGS)
2533 : : {
2534 : 10643 : Numeric num1 = PG_GETARG_NUMERIC(0);
2535 : 10643 : Numeric num2 = PG_GETARG_NUMERIC(1);
2536 : : bool result;
2537 : :
9340 2538 : 10643 : result = cmp_numerics(num1, num2) <= 0;
2539 : :
2540 [ + + ]: 10643 : PG_FREE_IF_COPY(num1, 0);
2541 [ + + ]: 10643 : PG_FREE_IF_COPY(num2, 1);
2542 : :
2543 : 10643 : PG_RETURN_BOOL(result);
2544 : : }
2545 : :
2546 : : static int
2547 : 18717853 : cmp_numerics(Numeric num1, Numeric num2)
2548 : : {
2549 : : int result;
2550 : :
2551 : : /*
2552 : : * We consider all NANs to be equal and larger than any non-NAN (including
2553 : : * Infinity). This is somewhat arbitrary; the important thing is to have
2554 : : * a consistent sort order.
2555 : : */
2320 2556 [ + + ]: 18717853 : if (NUMERIC_IS_SPECIAL(num1))
2557 : : {
2558 [ + + ]: 1956 : if (NUMERIC_IS_NAN(num1))
2559 : : {
2560 [ + + ]: 860 : if (NUMERIC_IS_NAN(num2))
2561 : 394 : result = 0; /* NAN = NAN */
2562 : : else
2563 : 466 : result = 1; /* NAN > non-NAN */
2564 : : }
2565 [ + + ]: 1096 : else if (NUMERIC_IS_PINF(num1))
2566 : : {
2567 [ + + ]: 92 : if (NUMERIC_IS_NAN(num2))
2568 : 15 : result = -1; /* PINF < NAN */
2569 [ + + ]: 77 : else if (NUMERIC_IS_PINF(num2))
2570 : 4 : result = 0; /* PINF = PINF */
2571 : : else
2572 : 73 : result = 1; /* PINF > anything else */
2573 : : }
2574 : : else /* num1 must be NINF */
2575 : : {
2576 [ + + ]: 1004 : if (NUMERIC_IS_NINF(num2))
2577 : 4 : result = 0; /* NINF = NINF */
2578 : : else
2579 : 1000 : result = -1; /* NINF < anything else */
2580 : : }
2581 : : }
2582 [ + + ]: 18715897 : else if (NUMERIC_IS_SPECIAL(num2))
2583 : : {
2584 [ + + ]: 7934 : if (NUMERIC_IS_NINF(num2))
2585 : 17 : result = 1; /* normal > NINF */
2586 : : else
2587 : 7917 : result = -1; /* normal < NAN or PINF */
2588 : : }
2589 : : else
2590 : : {
7599 bruce@momjian.us 2591 [ + + + + ]: 37416846 : result = cmp_var_common(NUMERIC_DIGITS(num1), NUMERIC_NDIGITS(num1),
5961 rhaas@postgresql.org 2592 [ + + - + : 18708294 : NUMERIC_WEIGHT(num1), NUMERIC_SIGN(num1),
+ + + + ]
7599 bruce@momjian.us 2593 [ + + + + ]: 18707963 : NUMERIC_DIGITS(num2), NUMERIC_NDIGITS(num2),
5961 rhaas@postgresql.org 2594 [ + + - + : 18708552 : NUMERIC_WEIGHT(num2), NUMERIC_SIGN(num2));
+ + + + ]
2595 : : }
2596 : :
9340 tgl@sss.pgh.pa.us 2597 : 18717853 : return result;
2598 : : }
2599 : :
2600 : : /*
2601 : : * in_range support function for numeric.
2602 : : */
2603 : : Datum
3199 2604 : 768 : in_range_numeric_numeric(PG_FUNCTION_ARGS)
2605 : : {
2606 : 768 : Numeric val = PG_GETARG_NUMERIC(0);
2607 : 768 : Numeric base = PG_GETARG_NUMERIC(1);
2608 : 768 : Numeric offset = PG_GETARG_NUMERIC(2);
2609 : 768 : bool sub = PG_GETARG_BOOL(3);
2610 : 768 : bool less = PG_GETARG_BOOL(4);
2611 : : bool result;
2612 : :
2613 : : /*
2614 : : * Reject negative (including -Inf) or NaN offset. Negative is per spec,
2615 : : * and NaN is because appropriate semantics for that seem non-obvious.
2616 : : */
2320 2617 [ + + ]: 768 : if (NUMERIC_IS_NAN(offset) ||
2618 [ + - ]: 764 : NUMERIC_IS_NINF(offset) ||
2619 [ + + - + : 764 : NUMERIC_SIGN(offset) == NUMERIC_NEG)
+ - - + -
- ]
3199 2620 [ + - ]: 4 : ereport(ERROR,
2621 : : (errcode(ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE),
2622 : : errmsg("invalid preceding or following size in window function")));
2623 : :
2624 : : /*
2625 : : * Deal with cases where val and/or base is NaN, following the rule that
2626 : : * NaN sorts after non-NaN (cf cmp_numerics). The offset cannot affect
2627 : : * the conclusion.
2628 : : */
2629 [ + + ]: 764 : if (NUMERIC_IS_NAN(val))
2630 : : {
2631 [ + + ]: 124 : if (NUMERIC_IS_NAN(base))
2632 : 40 : result = true; /* NAN = NAN */
2633 : : else
2634 : 84 : result = !less; /* NAN > non-NAN */
2635 : : }
2636 [ + + ]: 640 : else if (NUMERIC_IS_NAN(base))
2637 : : {
2638 : 84 : result = less; /* non-NAN < NAN */
2639 : : }
2640 : :
2641 : : /*
2642 : : * Deal with infinite offset (necessarily +Inf, at this point).
2643 : : */
2320 2644 [ + + ]: 556 : else if (NUMERIC_IS_SPECIAL(offset))
2645 : : {
2646 [ - + ]: 280 : Assert(NUMERIC_IS_PINF(offset));
2647 [ + + + + ]: 280 : if (sub ? NUMERIC_IS_PINF(base) : NUMERIC_IS_NINF(base))
2648 : : {
2649 : : /*
2650 : : * base +/- offset would produce NaN, so return true for any val
2651 : : * (see in_range_float8_float8() for reasoning).
2652 : : */
2653 : 116 : result = true;
2654 : : }
2655 [ + + ]: 164 : else if (sub)
2656 : : {
2657 : : /* base - offset must be -inf */
2658 [ + + ]: 100 : if (less)
2659 : 36 : result = NUMERIC_IS_NINF(val); /* only -inf is <= sum */
2660 : : else
2661 : 64 : result = true; /* any val is >= sum */
2662 : : }
2663 : : else
2664 : : {
2665 : : /* base + offset must be +inf */
2666 [ - + ]: 64 : if (less)
2320 tgl@sss.pgh.pa.us 2667 :UBC 0 : result = true; /* any val is <= sum */
2668 : : else
2320 tgl@sss.pgh.pa.us 2669 :CBC 64 : result = NUMERIC_IS_PINF(val); /* only +inf is >= sum */
2670 : : }
2671 : : }
2672 : :
2673 : : /*
2674 : : * Deal with cases where val and/or base is infinite. The offset, being
2675 : : * now known finite, cannot affect the conclusion.
2676 : : */
2677 [ + + ]: 276 : else if (NUMERIC_IS_SPECIAL(val))
2678 : : {
2679 [ + + ]: 52 : if (NUMERIC_IS_PINF(val))
2680 : : {
2681 [ + + ]: 24 : if (NUMERIC_IS_PINF(base))
2682 : 16 : result = true; /* PINF = PINF */
2683 : : else
2684 : 8 : result = !less; /* PINF > any other non-NAN */
2685 : : }
2686 : : else /* val must be NINF */
2687 : : {
2688 [ + + ]: 28 : if (NUMERIC_IS_NINF(base))
2689 : 20 : result = true; /* NINF = NINF */
2690 : : else
2691 : 8 : result = less; /* NINF < anything else */
2692 : : }
2693 : : }
2694 [ + + ]: 224 : else if (NUMERIC_IS_SPECIAL(base))
2695 : : {
2696 [ + + ]: 16 : if (NUMERIC_IS_NINF(base))
2697 : 8 : result = !less; /* normal > NINF */
2698 : : else
2699 : 8 : result = less; /* normal < PINF */
2700 : : }
2701 : : else
2702 : : {
2703 : : /*
2704 : : * Otherwise go ahead and compute base +/- offset. While it's
2705 : : * possible for this to overflow the numeric format, it's unlikely
2706 : : * enough that we don't take measures to prevent it.
2707 : : */
2708 : : NumericVar valv;
2709 : : NumericVar basev;
2710 : : NumericVar offsetv;
2711 : : NumericVar sum;
2712 : :
3199 2713 : 208 : init_var_from_num(val, &valv);
2714 : 208 : init_var_from_num(base, &basev);
2715 : 208 : init_var_from_num(offset, &offsetv);
2716 : 208 : init_var(&sum);
2717 : :
2718 [ + + ]: 208 : if (sub)
2719 : 104 : sub_var(&basev, &offsetv, &sum);
2720 : : else
2721 : 104 : add_var(&basev, &offsetv, &sum);
2722 : :
2723 [ + + ]: 208 : if (less)
2724 : 104 : result = (cmp_var(&valv, &sum) <= 0);
2725 : : else
2726 : 104 : result = (cmp_var(&valv, &sum) >= 0);
2727 : :
2728 : 208 : free_var(&sum);
2729 : : }
2730 : :
2731 [ + - ]: 764 : PG_FREE_IF_COPY(val, 0);
2732 [ + - ]: 764 : PG_FREE_IF_COPY(base, 1);
2733 [ - + ]: 764 : PG_FREE_IF_COPY(offset, 2);
2734 : :
2735 : 764 : PG_RETURN_BOOL(result);
2736 : : }
2737 : :
2738 : : Datum
7144 neilc@samurai.com 2739 : 410122 : hash_numeric(PG_FUNCTION_ARGS)
2740 : : {
6953 bruce@momjian.us 2741 : 410122 : Numeric key = PG_GETARG_NUMERIC(0);
2742 : : uint32 digit_hash;
2743 : : uint32 result;
2744 : : int weight;
2745 : : int start_offset;
2746 : : int end_offset;
2747 : : int i;
2748 : : int hash_len;
2749 : : NumericDigit *digits;
2750 : :
2751 : : /* If it's NaN or infinity, don't try to hash the rest of the fields */
2320 tgl@sss.pgh.pa.us 2752 [ - + ]: 410122 : if (NUMERIC_IS_SPECIAL(key))
7144 neilc@samurai.com 2753 :UBC 0 : PG_RETURN_UINT32(0);
2754 : :
5961 rhaas@postgresql.org 2755 [ + - + + ]:CBC 410122 : weight = NUMERIC_WEIGHT(key);
7144 neilc@samurai.com 2756 : 410122 : start_offset = 0;
6953 bruce@momjian.us 2757 : 410122 : end_offset = 0;
2758 : :
2759 : : /*
2760 : : * Omit any leading or trailing zeros from the input to the hash. The
2761 : : * numeric implementation *should* guarantee that leading and trailing
2762 : : * zeros are suppressed, but we're paranoid. Note that we measure the
2763 : : * starting and ending offsets in units of NumericDigits, not bytes.
2764 : : */
5961 rhaas@postgresql.org 2765 [ + - ]: 410122 : digits = NUMERIC_DIGITS(key);
7144 neilc@samurai.com 2766 [ + - + + ]: 410122 : for (i = 0; i < NUMERIC_NDIGITS(key); i++)
2767 : : {
5961 rhaas@postgresql.org 2768 [ + - ]: 408848 : if (digits[i] != (NumericDigit) 0)
7144 neilc@samurai.com 2769 : 408848 : break;
2770 : :
7144 neilc@samurai.com 2771 :UBC 0 : start_offset++;
2772 : :
2773 : : /*
2774 : : * The weight is effectively the # of digits before the decimal point,
2775 : : * so decrement it for each leading zero we skip.
2776 : : */
2777 : 0 : weight--;
2778 : : }
2779 : :
2780 : : /*
2781 : : * If there are no non-zero digits, then the value of the number is zero,
2782 : : * regardless of any other fields.
2783 : : */
7144 neilc@samurai.com 2784 [ + - + + ]:CBC 410122 : if (NUMERIC_NDIGITS(key) == start_offset)
2785 : 1274 : PG_RETURN_UINT32(-1);
2786 : :
2787 [ + - + - ]: 408848 : for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--)
2788 : : {
5961 rhaas@postgresql.org 2789 [ + - ]: 408848 : if (digits[i] != (NumericDigit) 0)
7144 neilc@samurai.com 2790 : 408848 : break;
2791 : :
7144 neilc@samurai.com 2792 :UBC 0 : end_offset++;
2793 : : }
2794 : :
2795 : : /* If we get here, there should be at least one non-zero digit */
7144 neilc@samurai.com 2796 [ + - - + ]:CBC 408848 : Assert(start_offset + end_offset < NUMERIC_NDIGITS(key));
2797 : :
2798 : : /*
2799 : : * Note that we don't hash on the Numeric's scale, since two numerics can
2800 : : * compare equal but have different scales. We also don't hash on the
2801 : : * sign, although we could: since a sign difference implies inequality,
2802 : : * this shouldn't affect correctness.
2803 : : */
2804 [ + - ]: 408848 : hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset;
66 john.naylor@postgres 2805 [ + - ]:GNC 408848 : digit_hash = hash_bytes((unsigned char *) (NUMERIC_DIGITS(key)
2806 : 408848 : + start_offset),
2807 : : hash_len * sizeof(NumericDigit));
2808 : :
2809 : : /* Mix in the weight, via XOR */
7144 neilc@samurai.com 2810 :CBC 408848 : result = digit_hash ^ weight;
2811 : :
66 john.naylor@postgres 2812 :GNC 408848 : PG_RETURN_UINT32(result);
2813 : : }
2814 : :
2815 : : /*
2816 : : * Returns 64-bit value by hashing a value to a 64-bit value, with a seed.
2817 : : * Otherwise, similar to hash_numeric.
2818 : : */
2819 : : Datum
3376 rhaas@postgresql.org 2820 :CBC 56 : hash_numeric_extended(PG_FUNCTION_ARGS)
2821 : : {
2822 : 56 : Numeric key = PG_GETARG_NUMERIC(0);
2823 : 56 : uint64 seed = PG_GETARG_INT64(1);
2824 : : uint64 digit_hash;
2825 : : uint64 result;
2826 : : int weight;
2827 : : int start_offset;
2828 : : int end_offset;
2829 : : int i;
2830 : : int hash_len;
2831 : : NumericDigit *digits;
2832 : :
2833 : : /* If it's NaN or infinity, don't try to hash the rest of the fields */
2320 tgl@sss.pgh.pa.us 2834 [ - + ]: 56 : if (NUMERIC_IS_SPECIAL(key))
3376 rhaas@postgresql.org 2835 :UBC 0 : PG_RETURN_UINT64(seed);
2836 : :
3376 rhaas@postgresql.org 2837 [ + - - + ]:CBC 56 : weight = NUMERIC_WEIGHT(key);
2838 : 56 : start_offset = 0;
2839 : 56 : end_offset = 0;
2840 : :
2841 [ + - ]: 56 : digits = NUMERIC_DIGITS(key);
2842 [ + - + + ]: 56 : for (i = 0; i < NUMERIC_NDIGITS(key); i++)
2843 : : {
2844 [ + - ]: 48 : if (digits[i] != (NumericDigit) 0)
2845 : 48 : break;
2846 : :
3376 rhaas@postgresql.org 2847 :UBC 0 : start_offset++;
2848 : :
2849 : 0 : weight--;
2850 : : }
2851 : :
3376 rhaas@postgresql.org 2852 [ + - + + ]:CBC 56 : if (NUMERIC_NDIGITS(key) == start_offset)
2853 : 8 : PG_RETURN_UINT64(seed - 1);
2854 : :
2855 [ + - + - ]: 48 : for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--)
2856 : : {
2857 [ + - ]: 48 : if (digits[i] != (NumericDigit) 0)
2858 : 48 : break;
2859 : :
3376 rhaas@postgresql.org 2860 :UBC 0 : end_offset++;
2861 : : }
2862 : :
3376 rhaas@postgresql.org 2863 [ + - - + ]:CBC 48 : Assert(start_offset + end_offset < NUMERIC_NDIGITS(key));
2864 : :
2865 [ + - ]: 48 : hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset;
66 john.naylor@postgres 2866 [ + - ]:GNC 48 : digit_hash = hash_bytes_extended((unsigned char *) (NUMERIC_DIGITS(key)
2867 : 48 : + start_offset),
2868 : : hash_len * sizeof(NumericDigit),
2869 : : seed);
2870 : :
2871 : 48 : result = digit_hash ^ weight;
2872 : :
2873 : 48 : PG_RETURN_UINT64(result);
2874 : : }
2875 : :
2876 : :
2877 : : /* ----------------------------------------------------------------------
2878 : : *
2879 : : * Basic arithmetic functions
2880 : : *
2881 : : * ----------------------------------------------------------------------
2882 : : */
2883 : :
2884 : :
2885 : : /*
2886 : : * numeric_add() -
2887 : : *
2888 : : * Add two numerics
2889 : : */
2890 : : Datum
9618 tgl@sss.pgh.pa.us 2891 :CBC 168462 : numeric_add(PG_FUNCTION_ARGS)
2892 : : {
2893 : 168462 : Numeric num1 = PG_GETARG_NUMERIC(0);
2894 : 168462 : Numeric num2 = PG_GETARG_NUMERIC(1);
2895 : : Numeric res;
2896 : :
449 michael@paquier.xyz 2897 : 168462 : res = numeric_add_safe(num1, num2, NULL);
2898 : :
2814 akorotkov@postgresql 2899 : 168462 : PG_RETURN_NUMERIC(res);
2900 : : }
2901 : :
2902 : : /*
2903 : : * numeric_add_safe() -
2904 : : *
2905 : : * Internal version of numeric_add() with support for soft error reporting.
2906 : : */
2907 : : Numeric
449 michael@paquier.xyz 2908 : 169156 : numeric_add_safe(Numeric num1, Numeric num2, Node *escontext)
2909 : : {
2910 : : NumericVar arg1;
2911 : : NumericVar arg2;
2912 : : NumericVar result;
2913 : : Numeric res;
2914 : :
2915 : : /*
2916 : : * Handle NaN and infinities
2917 : : */
2320 tgl@sss.pgh.pa.us 2918 [ + + + + ]: 169156 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
2919 : : {
2920 [ + + + + ]: 132 : if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2921 : 52 : return make_result(&const_nan);
2922 [ + + ]: 80 : if (NUMERIC_IS_PINF(num1))
2923 : : {
2924 [ + + ]: 24 : if (NUMERIC_IS_NINF(num2))
2925 : 4 : return make_result(&const_nan); /* Inf + -Inf */
2926 : : else
2927 : 20 : return make_result(&const_pinf);
2928 : : }
2929 [ + + ]: 56 : if (NUMERIC_IS_NINF(num1))
2930 : : {
2931 [ + + ]: 24 : if (NUMERIC_IS_PINF(num2))
2932 : 4 : return make_result(&const_nan); /* -Inf + Inf */
2933 : : else
2934 : 20 : return make_result(&const_ninf);
2935 : : }
2936 : : /* by here, num1 must be finite, so num2 is not */
2937 [ + + ]: 32 : if (NUMERIC_IS_PINF(num2))
2938 : 16 : return make_result(&const_pinf);
2939 [ - + ]: 16 : Assert(NUMERIC_IS_NINF(num2));
2940 : 16 : return make_result(&const_ninf);
2941 : : }
2942 : :
2943 : : /*
2944 : : * Unpack the values, let add_var() compute the result and return it.
2945 : : */
5120 heikki.linnakangas@i 2946 : 169024 : init_var_from_num(num1, &arg1);
2947 : 169024 : init_var_from_num(num2, &arg2);
2948 : :
2949 : 169024 : init_var(&result);
10195 JanWieck@Yahoo.com 2950 : 169024 : add_var(&arg1, &arg2, &result);
2951 : :
449 michael@paquier.xyz 2952 : 169024 : res = make_result_safe(&result, escontext);
2953 : :
10195 JanWieck@Yahoo.com 2954 : 169024 : free_var(&result);
2955 : :
2814 akorotkov@postgresql 2956 : 169024 : return res;
2957 : : }
2958 : :
2959 : :
2960 : : /*
2961 : : * numeric_sub() -
2962 : : *
2963 : : * Subtract one numeric from another
2964 : : */
2965 : : Datum
9618 tgl@sss.pgh.pa.us 2966 : 40584 : numeric_sub(PG_FUNCTION_ARGS)
2967 : : {
2968 : 40584 : Numeric num1 = PG_GETARG_NUMERIC(0);
2969 : 40584 : Numeric num2 = PG_GETARG_NUMERIC(1);
2970 : : Numeric res;
2971 : :
449 michael@paquier.xyz 2972 : 40584 : res = numeric_sub_safe(num1, num2, NULL);
2973 : :
2814 akorotkov@postgresql 2974 : 40584 : PG_RETURN_NUMERIC(res);
2975 : : }
2976 : :
2977 : :
2978 : : /*
2979 : : * numeric_sub_safe() -
2980 : : *
2981 : : * Internal version of numeric_sub() with support for soft error reporting.
2982 : : */
2983 : : Numeric
449 michael@paquier.xyz 2984 : 48688 : numeric_sub_safe(Numeric num1, Numeric num2, Node *escontext)
2985 : : {
2986 : : NumericVar arg1;
2987 : : NumericVar arg2;
2988 : : NumericVar result;
2989 : : Numeric res;
2990 : :
2991 : : /*
2992 : : * Handle NaN and infinities
2993 : : */
2320 tgl@sss.pgh.pa.us 2994 [ + + + + ]: 48688 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
2995 : : {
2996 [ + + + + ]: 142 : if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
2997 : 56 : return make_result(&const_nan);
2998 [ + + ]: 86 : if (NUMERIC_IS_PINF(num1))
2999 : : {
3000 [ + + ]: 29 : if (NUMERIC_IS_PINF(num2))
3001 : 4 : return make_result(&const_nan); /* Inf - Inf */
3002 : : else
3003 : 25 : return make_result(&const_pinf);
3004 : : }
3005 [ + + ]: 57 : if (NUMERIC_IS_NINF(num1))
3006 : : {
3007 [ + + ]: 24 : if (NUMERIC_IS_NINF(num2))
3008 : 4 : return make_result(&const_nan); /* -Inf - -Inf */
3009 : : else
3010 : 20 : return make_result(&const_ninf);
3011 : : }
3012 : : /* by here, num1 must be finite, so num2 is not */
3013 [ + + ]: 33 : if (NUMERIC_IS_PINF(num2))
3014 : 16 : return make_result(&const_ninf);
3015 [ - + ]: 17 : Assert(NUMERIC_IS_NINF(num2));
3016 : 17 : return make_result(&const_pinf);
3017 : : }
3018 : :
3019 : : /*
3020 : : * Unpack the values, let sub_var() compute the result and return it.
3021 : : */
5120 heikki.linnakangas@i 3022 : 48546 : init_var_from_num(num1, &arg1);
3023 : 48546 : init_var_from_num(num2, &arg2);
3024 : :
3025 : 48546 : init_var(&result);
10195 JanWieck@Yahoo.com 3026 : 48546 : sub_var(&arg1, &arg2, &result);
3027 : :
449 michael@paquier.xyz 3028 : 48546 : res = make_result_safe(&result, escontext);
3029 : :
10195 JanWieck@Yahoo.com 3030 : 48546 : free_var(&result);
3031 : :
2814 akorotkov@postgresql 3032 : 48546 : return res;
3033 : : }
3034 : :
3035 : :
3036 : : /*
3037 : : * numeric_mul() -
3038 : : *
3039 : : * Calculate the product of two numerics
3040 : : */
3041 : : Datum
9618 tgl@sss.pgh.pa.us 3042 : 326760 : numeric_mul(PG_FUNCTION_ARGS)
3043 : : {
3044 : 326760 : Numeric num1 = PG_GETARG_NUMERIC(0);
3045 : 326760 : Numeric num2 = PG_GETARG_NUMERIC(1);
3046 : : Numeric res;
3047 : :
249 peter@eisentraut.org 3048 : 326760 : res = numeric_mul_safe(num1, num2, fcinfo->context);
3049 : :
3050 [ - + - - : 326760 : if (unlikely(SOFT_ERROR_OCCURRED(fcinfo->context)))
- + - - -
+ ]
249 peter@eisentraut.org 3051 :UBC 0 : PG_RETURN_NULL();
3052 : :
2814 akorotkov@postgresql 3053 :CBC 326760 : PG_RETURN_NUMERIC(res);
3054 : : }
3055 : :
3056 : :
3057 : : /*
3058 : : * numeric_mul_safe() -
3059 : : *
3060 : : * Internal version of numeric_mul() with support for soft error reporting.
3061 : : */
3062 : : Numeric
449 michael@paquier.xyz 3063 : 326792 : numeric_mul_safe(Numeric num1, Numeric num2, Node *escontext)
3064 : : {
3065 : : NumericVar arg1;
3066 : : NumericVar arg2;
3067 : : NumericVar result;
3068 : : Numeric res;
3069 : :
3070 : : /*
3071 : : * Handle NaN and infinities
3072 : : */
2320 tgl@sss.pgh.pa.us 3073 [ + + + + ]: 326792 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3074 : : {
3075 [ + + + + ]: 132 : if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3076 : 52 : return make_result(&const_nan);
3077 [ + + ]: 80 : if (NUMERIC_IS_PINF(num1))
3078 : : {
3079 [ + + + - ]: 24 : switch (numeric_sign_internal(num2))
3080 : : {
3081 : 4 : case 0:
3082 : 4 : return make_result(&const_nan); /* Inf * 0 */
3083 : 12 : case 1:
3084 : 12 : return make_result(&const_pinf);
3085 : 8 : case -1:
3086 : 8 : return make_result(&const_ninf);
3087 : : }
2320 tgl@sss.pgh.pa.us 3088 :UBC 0 : Assert(false);
3089 : : }
2320 tgl@sss.pgh.pa.us 3090 [ + + ]:CBC 56 : if (NUMERIC_IS_NINF(num1))
3091 : : {
3092 [ + + + - ]: 24 : switch (numeric_sign_internal(num2))
3093 : : {
3094 : 4 : case 0:
3095 : 4 : return make_result(&const_nan); /* -Inf * 0 */
3096 : 12 : case 1:
3097 : 12 : return make_result(&const_ninf);
3098 : 8 : case -1:
3099 : 8 : return make_result(&const_pinf);
3100 : : }
2320 tgl@sss.pgh.pa.us 3101 :UBC 0 : Assert(false);
3102 : : }
3103 : : /* by here, num1 must be finite, so num2 is not */
2320 tgl@sss.pgh.pa.us 3104 [ + + ]:CBC 32 : if (NUMERIC_IS_PINF(num2))
3105 : : {
3106 [ + + + - ]: 16 : switch (numeric_sign_internal(num1))
3107 : : {
3108 : 4 : case 0:
3109 : 4 : return make_result(&const_nan); /* 0 * Inf */
3110 : 8 : case 1:
3111 : 8 : return make_result(&const_pinf);
3112 : 4 : case -1:
3113 : 4 : return make_result(&const_ninf);
3114 : : }
2320 tgl@sss.pgh.pa.us 3115 :UBC 0 : Assert(false);
3116 : : }
2320 tgl@sss.pgh.pa.us 3117 [ - + ]:CBC 16 : Assert(NUMERIC_IS_NINF(num2));
3118 [ + + + - ]: 16 : switch (numeric_sign_internal(num1))
3119 : : {
3120 : 4 : case 0:
3121 : 4 : return make_result(&const_nan); /* 0 * -Inf */
3122 : 8 : case 1:
3123 : 8 : return make_result(&const_ninf);
3124 : 4 : case -1:
3125 : 4 : return make_result(&const_pinf);
3126 : : }
2320 tgl@sss.pgh.pa.us 3127 :UBC 0 : Assert(false);
3128 : : }
3129 : :
3130 : : /*
3131 : : * Unpack the values, let mul_var() compute the result and return it.
3132 : : * Unlike add_var() and sub_var(), mul_var() will round its result. In the
3133 : : * case of numeric_mul(), which is invoked for the * operator on numerics,
3134 : : * we request exact representation for the product (rscale = sum(dscale of
3135 : : * arg1, dscale of arg2)). If the exact result has more digits after the
3136 : : * decimal point than can be stored in a numeric, we round it. Rounding
3137 : : * after computing the exact result ensures that the final result is
3138 : : * correctly rounded (rounding in mul_var() using a truncated product
3139 : : * would not guarantee this).
3140 : : */
5120 heikki.linnakangas@i 3141 :CBC 326660 : init_var_from_num(num1, &arg1);
3142 : 326660 : init_var_from_num(num2, &arg2);
3143 : :
3144 : 326660 : init_var(&result);
8653 tgl@sss.pgh.pa.us 3145 : 326660 : mul_var(&arg1, &arg2, &result, arg1.dscale + arg2.dscale);
3146 : :
1967 dean.a.rasheed@gmail 3147 [ + + ]: 326660 : if (result.dscale > NUMERIC_DSCALE_MAX)
3148 : 5 : round_var(&result, NUMERIC_DSCALE_MAX);
3149 : :
449 michael@paquier.xyz 3150 : 326660 : res = make_result_safe(&result, escontext);
3151 : :
10195 JanWieck@Yahoo.com 3152 : 326660 : free_var(&result);
3153 : :
2814 akorotkov@postgresql 3154 : 326660 : return res;
3155 : : }
3156 : :
3157 : :
3158 : : /*
3159 : : * numeric_div() -
3160 : : *
3161 : : * Divide one numeric into another
3162 : : */
3163 : : Datum
9618 tgl@sss.pgh.pa.us 3164 : 98481 : numeric_div(PG_FUNCTION_ARGS)
3165 : : {
3166 : 98481 : Numeric num1 = PG_GETARG_NUMERIC(0);
3167 : 98481 : Numeric num2 = PG_GETARG_NUMERIC(1);
3168 : : Numeric res;
3169 : :
449 michael@paquier.xyz 3170 : 98481 : res = numeric_div_safe(num1, num2, NULL);
3171 : :
2814 akorotkov@postgresql 3172 : 98460 : PG_RETURN_NUMERIC(res);
3173 : : }
3174 : :
3175 : :
3176 : : /*
3177 : : * numeric_div_safe() -
3178 : : *
3179 : : * Internal version of numeric_div() with support for soft error reporting.
3180 : : */
3181 : : Numeric
449 michael@paquier.xyz 3182 : 99042 : numeric_div_safe(Numeric num1, Numeric num2, Node *escontext)
3183 : : {
3184 : : NumericVar arg1;
3185 : : NumericVar arg2;
3186 : : NumericVar result;
3187 : : Numeric res;
3188 : : int rscale;
3189 : :
3190 : : /*
3191 : : * Handle NaN and infinities
3192 : : */
2320 tgl@sss.pgh.pa.us 3193 [ + + + + ]: 99042 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3194 : : {
3195 [ + + + + ]: 133 : if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3196 : 53 : return make_result(&const_nan);
3197 [ + + ]: 80 : if (NUMERIC_IS_PINF(num1))
3198 : : {
3199 [ + + ]: 24 : if (NUMERIC_IS_SPECIAL(num2))
3200 : 8 : return make_result(&const_nan); /* Inf / [-]Inf */
3201 [ + + + - ]: 16 : switch (numeric_sign_internal(num2))
3202 : : {
3203 : 4 : case 0:
449 michael@paquier.xyz 3204 : 4 : goto division_by_zero;
2320 tgl@sss.pgh.pa.us 3205 : 8 : case 1:
3206 : 8 : return make_result(&const_pinf);
3207 : 4 : case -1:
3208 : 4 : return make_result(&const_ninf);
3209 : : }
2320 tgl@sss.pgh.pa.us 3210 :UBC 0 : Assert(false);
3211 : : }
2320 tgl@sss.pgh.pa.us 3212 [ + + ]:CBC 56 : if (NUMERIC_IS_NINF(num1))
3213 : : {
3214 [ + + ]: 24 : if (NUMERIC_IS_SPECIAL(num2))
3215 : 8 : return make_result(&const_nan); /* -Inf / [-]Inf */
3216 [ + + + - ]: 16 : switch (numeric_sign_internal(num2))
3217 : : {
3218 : 4 : case 0:
449 michael@paquier.xyz 3219 : 4 : goto division_by_zero;
2320 tgl@sss.pgh.pa.us 3220 : 8 : case 1:
3221 : 8 : return make_result(&const_ninf);
3222 : 4 : case -1:
3223 : 4 : return make_result(&const_pinf);
3224 : : }
2320 tgl@sss.pgh.pa.us 3225 :UBC 0 : Assert(false);
3226 : : }
3227 : : /* by here, num1 must be finite, so num2 is not */
3228 : :
3229 : : /*
3230 : : * POSIX would have us return zero or minus zero if num1 is zero, and
3231 : : * otherwise throw an underflow error. But the numeric type doesn't
3232 : : * really do underflow, so let's just return zero.
3233 : : */
2320 tgl@sss.pgh.pa.us 3234 :CBC 32 : return make_result(&const_zero);
3235 : : }
3236 : :
3237 : : /*
3238 : : * Unpack the arguments
3239 : : */
5120 heikki.linnakangas@i 3240 : 98909 : init_var_from_num(num1, &arg1);
3241 : 98909 : init_var_from_num(num2, &arg2);
3242 : :
3243 : 98909 : init_var(&result);
3244 : :
3245 : : /*
3246 : : * Select scale for division result
3247 : : */
8653 tgl@sss.pgh.pa.us 3248 : 98909 : rscale = select_div_scale(&arg1, &arg2);
3249 : :
3250 : : /* Check for division by zero */
449 michael@paquier.xyz 3251 [ + + - + ]: 98909 : if (arg2.ndigits == 0 || arg2.digits[0] == 0)
3252 : 33 : goto division_by_zero;
3253 : :
3254 : : /*
3255 : : * Do the divide and return the result
3256 : : */
785 dean.a.rasheed@gmail 3257 : 98876 : div_var(&arg1, &arg2, &result, rscale, true, true);
3258 : :
449 michael@paquier.xyz 3259 : 98876 : res = make_result_safe(&result, escontext);
3260 : :
10195 JanWieck@Yahoo.com 3261 : 98876 : free_var(&result);
3262 : :
2814 akorotkov@postgresql 3263 : 98876 : return res;
3264 : :
449 michael@paquier.xyz 3265 : 41 : division_by_zero:
3266 [ + + ]: 41 : ereturn(escontext, NULL,
3267 : : errcode(ERRCODE_DIVISION_BY_ZERO),
3268 : : errmsg("division by zero"));
3269 : : }
3270 : :
3271 : :
3272 : : /*
3273 : : * numeric_div_trunc() -
3274 : : *
3275 : : * Divide one numeric into another, truncating the result to an integer
3276 : : */
3277 : : Datum
6812 tgl@sss.pgh.pa.us 3278 : 822 : numeric_div_trunc(PG_FUNCTION_ARGS)
3279 : : {
3280 : 822 : Numeric num1 = PG_GETARG_NUMERIC(0);
3281 : 822 : Numeric num2 = PG_GETARG_NUMERIC(1);
3282 : : NumericVar arg1;
3283 : : NumericVar arg2;
3284 : : NumericVar result;
3285 : : Numeric res;
3286 : :
3287 : : /*
3288 : : * Handle NaN and infinities
3289 : : */
2320 3290 [ + + + + ]: 822 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3291 : : {
3292 [ + + + + ]: 133 : if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3293 : 53 : PG_RETURN_NUMERIC(make_result(&const_nan));
3294 [ + + ]: 80 : if (NUMERIC_IS_PINF(num1))
3295 : : {
3296 [ + + ]: 24 : if (NUMERIC_IS_SPECIAL(num2))
3297 : 8 : PG_RETURN_NUMERIC(make_result(&const_nan)); /* Inf / [-]Inf */
3298 [ + + + - ]: 16 : switch (numeric_sign_internal(num2))
3299 : : {
3300 : 4 : case 0:
3301 [ + - ]: 4 : ereport(ERROR,
3302 : : (errcode(ERRCODE_DIVISION_BY_ZERO),
3303 : : errmsg("division by zero")));
3304 : : break;
3305 : 8 : case 1:
3306 : 8 : PG_RETURN_NUMERIC(make_result(&const_pinf));
3307 : 4 : case -1:
3308 : 4 : PG_RETURN_NUMERIC(make_result(&const_ninf));
3309 : : }
2320 tgl@sss.pgh.pa.us 3310 :UBC 0 : Assert(false);
3311 : : }
2320 tgl@sss.pgh.pa.us 3312 [ + + ]:CBC 56 : if (NUMERIC_IS_NINF(num1))
3313 : : {
3314 [ + + ]: 24 : if (NUMERIC_IS_SPECIAL(num2))
3315 : 8 : PG_RETURN_NUMERIC(make_result(&const_nan)); /* -Inf / [-]Inf */
3316 [ + + + - ]: 16 : switch (numeric_sign_internal(num2))
3317 : : {
3318 : 4 : case 0:
3319 [ + - ]: 4 : ereport(ERROR,
3320 : : (errcode(ERRCODE_DIVISION_BY_ZERO),
3321 : : errmsg("division by zero")));
3322 : : break;
3323 : 8 : case 1:
3324 : 8 : PG_RETURN_NUMERIC(make_result(&const_ninf));
3325 : 4 : case -1:
3326 : 4 : PG_RETURN_NUMERIC(make_result(&const_pinf));
3327 : : }
2320 tgl@sss.pgh.pa.us 3328 :UBC 0 : Assert(false);
3329 : : }
3330 : : /* by here, num1 must be finite, so num2 is not */
3331 : :
3332 : : /*
3333 : : * POSIX would have us return zero or minus zero if num1 is zero, and
3334 : : * otherwise throw an underflow error. But the numeric type doesn't
3335 : : * really do underflow, so let's just return zero.
3336 : : */
2320 tgl@sss.pgh.pa.us 3337 :CBC 32 : PG_RETURN_NUMERIC(make_result(&const_zero));
3338 : : }
3339 : :
3340 : : /*
3341 : : * Unpack the arguments
3342 : : */
5120 heikki.linnakangas@i 3343 : 689 : init_var_from_num(num1, &arg1);
3344 : 689 : init_var_from_num(num2, &arg2);
3345 : :
3346 : 689 : init_var(&result);
3347 : :
3348 : : /*
3349 : : * Do the divide and return the result
3350 : : */
785 dean.a.rasheed@gmail 3351 : 689 : div_var(&arg1, &arg2, &result, 0, false, true);
3352 : :
6812 tgl@sss.pgh.pa.us 3353 : 685 : res = make_result(&result);
3354 : :
3355 : 685 : free_var(&result);
3356 : :
3357 : 685 : PG_RETURN_NUMERIC(res);
3358 : : }
3359 : :
3360 : :
3361 : : /*
3362 : : * numeric_mod() -
3363 : : *
3364 : : * Calculate the modulo of two numerics
3365 : : */
3366 : : Datum
9618 3367 : 277247 : numeric_mod(PG_FUNCTION_ARGS)
3368 : : {
3369 : 277247 : Numeric num1 = PG_GETARG_NUMERIC(0);
3370 : 277247 : Numeric num2 = PG_GETARG_NUMERIC(1);
3371 : : Numeric res;
3372 : :
449 michael@paquier.xyz 3373 : 277247 : res = numeric_mod_safe(num1, num2, NULL);
3374 : :
2814 akorotkov@postgresql 3375 : 277235 : PG_RETURN_NUMERIC(res);
3376 : : }
3377 : :
3378 : :
3379 : : /*
3380 : : * numeric_mod_safe() -
3381 : : *
3382 : : * Internal version of numeric_mod() with support for soft error reporting.
3383 : : */
3384 : : Numeric
449 michael@paquier.xyz 3385 : 277255 : numeric_mod_safe(Numeric num1, Numeric num2, Node *escontext)
3386 : : {
3387 : : Numeric res;
3388 : : NumericVar arg1;
3389 : : NumericVar arg2;
3390 : : NumericVar result;
3391 : :
3392 : : /*
3393 : : * Handle NaN and infinities. We follow POSIX fmod() on this, except that
3394 : : * POSIX treats x-is-infinite and y-is-zero identically, raising EDOM and
3395 : : * returning NaN. We choose to throw error only for y-is-zero.
3396 : : */
2320 tgl@sss.pgh.pa.us 3397 [ + + + + ]: 277255 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3398 : : {
3399 [ + + + + ]: 133 : if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3400 : 53 : return make_result(&const_nan);
3401 [ + + ]: 80 : if (NUMERIC_IS_INF(num1))
3402 : : {
3403 [ + + ]: 48 : if (numeric_sign_internal(num2) == 0)
449 michael@paquier.xyz 3404 : 8 : goto division_by_zero;
3405 : :
3406 : : /* Inf % any nonzero = NaN */
2320 tgl@sss.pgh.pa.us 3407 : 40 : return make_result(&const_nan);
3408 : : }
3409 : : /* num2 must be [-]Inf; result is num1 regardless of sign of num2 */
3410 : 32 : return duplicate_numeric(num1);
3411 : : }
3412 : :
5120 heikki.linnakangas@i 3413 : 277122 : init_var_from_num(num1, &arg1);
3414 : 277122 : init_var_from_num(num2, &arg2);
3415 : :
3416 : 277122 : init_var(&result);
3417 : :
3418 : : /* Check for division by zero */
449 michael@paquier.xyz 3419 [ + + - + ]: 277122 : if (arg2.ndigits == 0 || arg2.digits[0] == 0)
3420 : 8 : goto division_by_zero;
3421 : :
10195 JanWieck@Yahoo.com 3422 : 277114 : mod_var(&arg1, &arg2, &result);
3423 : :
449 michael@paquier.xyz 3424 : 277114 : res = make_result_safe(&result, escontext);
3425 : :
10195 JanWieck@Yahoo.com 3426 : 277114 : free_var(&result);
3427 : :
2814 akorotkov@postgresql 3428 : 277114 : return res;
3429 : :
449 michael@paquier.xyz 3430 : 16 : division_by_zero:
3431 [ + - ]: 16 : ereturn(escontext, NULL,
3432 : : errcode(ERRCODE_DIVISION_BY_ZERO),
3433 : : errmsg("division by zero"));
3434 : : }
3435 : :
3436 : :
3437 : : /*
3438 : : * numeric_inc() -
3439 : : *
3440 : : * Increment a number by one
3441 : : */
3442 : : Datum
9618 tgl@sss.pgh.pa.us 3443 : 32 : numeric_inc(PG_FUNCTION_ARGS)
3444 : : {
3445 : 32 : Numeric num = PG_GETARG_NUMERIC(0);
3446 : : NumericVar arg;
3447 : : Numeric res;
3448 : :
3449 : : /*
3450 : : * Handle NaN and infinities
3451 : : */
2320 3452 [ + + ]: 32 : if (NUMERIC_IS_SPECIAL(num))
3453 : 12 : PG_RETURN_NUMERIC(duplicate_numeric(num));
3454 : :
3455 : : /*
3456 : : * Compute the result and return it
3457 : : */
5120 heikki.linnakangas@i 3458 : 20 : init_var_from_num(num, &arg);
3459 : :
10195 JanWieck@Yahoo.com 3460 : 20 : add_var(&arg, &const_one, &arg);
3461 : :
3462 : 20 : res = make_result(&arg);
3463 : :
3464 : 20 : free_var(&arg);
3465 : :
9618 tgl@sss.pgh.pa.us 3466 : 20 : PG_RETURN_NUMERIC(res);
3467 : : }
3468 : :
3469 : :
3470 : : /*
3471 : : * numeric_smaller() -
3472 : : *
3473 : : * Return the smaller of two numbers
3474 : : */
3475 : : Datum
3476 : 543 : numeric_smaller(PG_FUNCTION_ARGS)
3477 : : {
3478 : 543 : Numeric num1 = PG_GETARG_NUMERIC(0);
3479 : 543 : 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 : : */
8522 3485 [ + + ]: 543 : if (cmp_numerics(num1, num2) < 0)
3486 : 435 : PG_RETURN_NUMERIC(num1);
3487 : : else
3488 : 108 : PG_RETURN_NUMERIC(num2);
3489 : : }
3490 : :
3491 : :
3492 : : /*
3493 : : * numeric_larger() -
3494 : : *
3495 : : * Return the larger of two numbers
3496 : : */
3497 : : Datum
9618 3498 : 12657 : numeric_larger(PG_FUNCTION_ARGS)
3499 : : {
3500 : 12657 : Numeric num1 = PG_GETARG_NUMERIC(0);
3501 : 12657 : Numeric num2 = PG_GETARG_NUMERIC(1);
3502 : :
3503 : : /*
3504 : : * Use cmp_numerics so that this will agree with the comparison operators,
3505 : : * particularly as regards comparisons involving NaN.
3506 : : */
8522 3507 [ + + ]: 12657 : if (cmp_numerics(num1, num2) > 0)
3508 : 12092 : PG_RETURN_NUMERIC(num1);
3509 : : else
3510 : 565 : PG_RETURN_NUMERIC(num2);
3511 : : }
3512 : :
3513 : :
3514 : : /* ----------------------------------------------------------------------
3515 : : *
3516 : : * Advanced math functions
3517 : : *
3518 : : * ----------------------------------------------------------------------
3519 : : */
3520 : :
3521 : : /*
3522 : : * numeric_gcd() -
3523 : : *
3524 : : * Calculate the greatest common divisor of two numerics
3525 : : */
3526 : : Datum
2499 dean.a.rasheed@gmail 3527 : 144 : numeric_gcd(PG_FUNCTION_ARGS)
3528 : : {
3529 : 144 : Numeric num1 = PG_GETARG_NUMERIC(0);
3530 : 144 : Numeric num2 = PG_GETARG_NUMERIC(1);
3531 : : NumericVar arg1;
3532 : : NumericVar arg2;
3533 : : NumericVar result;
3534 : : Numeric res;
3535 : :
3536 : : /*
3537 : : * Handle NaN and infinities: we consider the result to be NaN in all such
3538 : : * cases.
3539 : : */
2320 tgl@sss.pgh.pa.us 3540 [ + + + + ]: 144 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
2499 dean.a.rasheed@gmail 3541 : 64 : PG_RETURN_NUMERIC(make_result(&const_nan));
3542 : :
3543 : : /*
3544 : : * Unpack the arguments
3545 : : */
3546 : 80 : init_var_from_num(num1, &arg1);
3547 : 80 : init_var_from_num(num2, &arg2);
3548 : :
3549 : 80 : init_var(&result);
3550 : :
3551 : : /*
3552 : : * Find the GCD and return the result
3553 : : */
3554 : 80 : gcd_var(&arg1, &arg2, &result);
3555 : :
3556 : 80 : res = make_result(&result);
3557 : :
3558 : 80 : free_var(&result);
3559 : :
3560 : 80 : PG_RETURN_NUMERIC(res);
3561 : : }
3562 : :
3563 : :
3564 : : /*
3565 : : * numeric_lcm() -
3566 : : *
3567 : : * Calculate the least common multiple of two numerics
3568 : : */
3569 : : Datum
3570 : 164 : numeric_lcm(PG_FUNCTION_ARGS)
3571 : : {
3572 : 164 : Numeric num1 = PG_GETARG_NUMERIC(0);
3573 : 164 : Numeric num2 = PG_GETARG_NUMERIC(1);
3574 : : NumericVar arg1;
3575 : : NumericVar arg2;
3576 : : NumericVar result;
3577 : : Numeric res;
3578 : :
3579 : : /*
3580 : : * Handle NaN and infinities: we consider the result to be NaN in all such
3581 : : * cases.
3582 : : */
2320 tgl@sss.pgh.pa.us 3583 [ + + + + ]: 164 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
2499 dean.a.rasheed@gmail 3584 : 64 : PG_RETURN_NUMERIC(make_result(&const_nan));
3585 : :
3586 : : /*
3587 : : * Unpack the arguments
3588 : : */
3589 : 100 : init_var_from_num(num1, &arg1);
3590 : 100 : init_var_from_num(num2, &arg2);
3591 : :
3592 : 100 : init_var(&result);
3593 : :
3594 : : /*
3595 : : * Compute the result using lcm(x, y) = abs(x / gcd(x, y) * y), returning
3596 : : * zero if either input is zero.
3597 : : *
3598 : : * Note that the division is guaranteed to be exact, returning an integer
3599 : : * result, so the LCM is an integral multiple of both x and y. A display
3600 : : * scale of Min(x.dscale, y.dscale) would be sufficient to represent it,
3601 : : * but as with other numeric functions, we choose to return a result whose
3602 : : * display scale is no smaller than either input.
3603 : : */
3604 [ + + + + ]: 100 : if (arg1.ndigits == 0 || arg2.ndigits == 0)
3605 : 32 : set_var_from_var(&const_zero, &result);
3606 : : else
3607 : : {
3608 : 68 : gcd_var(&arg1, &arg2, &result);
785 3609 : 68 : div_var(&arg1, &result, &result, 0, false, true);
2499 3610 : 68 : mul_var(&arg2, &result, &result, arg2.dscale);
3611 : 68 : result.sign = NUMERIC_POS;
3612 : : }
3613 : :
3614 : 100 : result.dscale = Max(arg1.dscale, arg2.dscale);
3615 : :
3616 : 100 : res = make_result(&result);
3617 : :
3618 : 96 : free_var(&result);
3619 : :
3620 : 96 : PG_RETURN_NUMERIC(res);
3621 : : }
3622 : :
3623 : :
3624 : : /*
3625 : : * numeric_fac()
3626 : : *
3627 : : * Compute factorial
3628 : : */
3629 : : Datum
8398 bruce@momjian.us 3630 : 33 : numeric_fac(PG_FUNCTION_ARGS)
3631 : : {
3632 : 33 : int64 num = PG_GETARG_INT64(0);
3633 : : Numeric res;
3634 : : NumericVar fact;
3635 : : NumericVar result;
3636 : :
2354 peter@eisentraut.org 3637 [ + + ]: 33 : if (num < 0)
3638 [ + - ]: 4 : ereport(ERROR,
3639 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
3640 : : errmsg("factorial of a negative number is undefined")));
8397 tgl@sss.pgh.pa.us 3641 [ + + ]: 29 : if (num <= 1)
3642 : : {
8398 bruce@momjian.us 3643 : 5 : res = make_result(&const_one);
3644 : 5 : PG_RETURN_NUMERIC(res);
3645 : : }
3646 : : /* Fail immediately if the result would overflow */
7112 tgl@sss.pgh.pa.us 3647 [ + + ]: 24 : if (num > 32177)
3648 [ + - ]: 4 : ereport(ERROR,
3649 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
3650 : : errmsg("value overflows numeric format")));
3651 : :
8398 bruce@momjian.us 3652 : 20 : init_var(&fact);
3653 : 20 : init_var(&result);
3654 : :
4271 andres@anarazel.de 3655 : 20 : int64_to_numericvar(num, &result);
3656 : :
8397 tgl@sss.pgh.pa.us 3657 [ + + ]: 245 : for (num = num - 1; num > 1; num--)
3658 : : {
3659 : : /* this loop can take awhile, so allow it to be interrupted */
7112 3660 [ - + ]: 225 : CHECK_FOR_INTERRUPTS();
3661 : :
4271 andres@anarazel.de 3662 : 225 : int64_to_numericvar(num, &fact);
3663 : :
8397 tgl@sss.pgh.pa.us 3664 : 225 : mul_var(&result, &fact, &result, 0);
3665 : : }
3666 : :
3667 : 20 : res = make_result(&result);
3668 : :
8398 bruce@momjian.us 3669 : 20 : free_var(&fact);
3670 : 20 : free_var(&result);
3671 : :
3672 : 20 : PG_RETURN_NUMERIC(res);
3673 : : }
3674 : :
3675 : :
3676 : : /*
3677 : : * numeric_sqrt() -
3678 : : *
3679 : : * Compute the square root of a numeric.
3680 : : */
3681 : : Datum
9618 tgl@sss.pgh.pa.us 3682 : 108 : numeric_sqrt(PG_FUNCTION_ARGS)
3683 : : {
3684 : 108 : Numeric num = PG_GETARG_NUMERIC(0);
3685 : : Numeric res;
3686 : : NumericVar arg;
3687 : : NumericVar result;
3688 : : int sweight;
3689 : : int rscale;
3690 : :
3691 : : /*
3692 : : * Handle NaN and infinities
3693 : : */
2320 3694 [ + + ]: 108 : if (NUMERIC_IS_SPECIAL(num))
3695 : : {
3696 : : /* error should match that in sqrt_var() */
3697 [ + + ]: 12 : if (NUMERIC_IS_NINF(num))
3698 [ + - ]: 4 : ereport(ERROR,
3699 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
3700 : : errmsg("cannot take square root of a negative number")));
3701 : : /* For NAN or PINF, just duplicate the input */
3702 : 8 : PG_RETURN_NUMERIC(duplicate_numeric(num));
3703 : : }
3704 : :
3705 : : /*
3706 : : * Unpack the argument and determine the result scale. We choose a scale
3707 : : * to give at least NUMERIC_MIN_SIG_DIGITS significant digits; but in any
3708 : : * case not less than the input's dscale.
3709 : : */
5120 heikki.linnakangas@i 3710 : 96 : init_var_from_num(num, &arg);
3711 : :
3712 : 96 : init_var(&result);
3713 : :
3714 : : /*
3715 : : * Assume the input was normalized, so arg.weight is accurate. The result
3716 : : * then has at least sweight = floor(arg.weight * DEC_DIGITS / 2 + 1)
3717 : : * digits before the decimal point. When DEC_DIGITS is even, we can save
3718 : : * a few cycles, since the division is exact and there is no need to round
3719 : : * towards negative infinity.
3720 : : */
3721 : : #if DEC_DIGITS == ((DEC_DIGITS / 2) * 2)
1395 dean.a.rasheed@gmail 3722 : 96 : sweight = arg.weight * DEC_DIGITS / 2 + 1;
3723 : : #else
3724 : : if (arg.weight >= 0)
3725 : : sweight = arg.weight * DEC_DIGITS / 2 + 1;
3726 : : else
3727 : : sweight = 1 - (1 - arg.weight * DEC_DIGITS) / 2;
3728 : : #endif
3729 : :
8653 tgl@sss.pgh.pa.us 3730 : 96 : rscale = NUMERIC_MIN_SIG_DIGITS - sweight;
3731 : 96 : rscale = Max(rscale, arg.dscale);
3732 : 96 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
3733 : 96 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
3734 : :
3735 : : /*
3736 : : * Let sqrt_var() do the calculation and return the result.
3737 : : */
3738 : 96 : sqrt_var(&arg, &result, rscale);
3739 : :
10195 JanWieck@Yahoo.com 3740 : 92 : res = make_result(&result);
3741 : :
3742 : 92 : free_var(&result);
3743 : :
9618 tgl@sss.pgh.pa.us 3744 : 92 : PG_RETURN_NUMERIC(res);
3745 : : }
3746 : :
3747 : :
3748 : : /*
3749 : : * numeric_exp() -
3750 : : *
3751 : : * Raise e to the power of x
3752 : : */
3753 : : Datum
3754 : 65 : numeric_exp(PG_FUNCTION_ARGS)
3755 : : {
3756 : 65 : Numeric num = PG_GETARG_NUMERIC(0);
3757 : : Numeric res;
3758 : : NumericVar arg;
3759 : : NumericVar result;
3760 : : int rscale;
3761 : : double val;
3762 : :
3763 : : /*
3764 : : * Handle NaN and infinities
3765 : : */
2320 3766 [ + + ]: 65 : if (NUMERIC_IS_SPECIAL(num))
3767 : : {
3768 : : /* Per POSIX, exp(-Inf) is zero */
3769 [ + + ]: 15 : if (NUMERIC_IS_NINF(num))
3770 : 5 : PG_RETURN_NUMERIC(make_result(&const_zero));
3771 : : /* For NAN or PINF, just duplicate the input */
3772 : 10 : PG_RETURN_NUMERIC(duplicate_numeric(num));
3773 : : }
3774 : :
3775 : : /*
3776 : : * Unpack the argument and determine the result scale. We choose a scale
3777 : : * to give at least NUMERIC_MIN_SIG_DIGITS significant digits; but in any
3778 : : * case not less than the input's dscale.
3779 : : */
5120 heikki.linnakangas@i 3780 : 50 : init_var_from_num(num, &arg);
3781 : :
3782 : 50 : init_var(&result);
3783 : :
3784 : : /* convert input to float8, ignoring overflow */
8653 tgl@sss.pgh.pa.us 3785 : 50 : val = numericvar_to_double_no_overflow(&arg);
3786 : :
3787 : : /*
3788 : : * log10(result) = num * log10(e), so this is approximately the decimal
3789 : : * weight of the result:
3790 : : */
8823 3791 : 50 : val *= 0.434294481903252;
3792 : :
3793 : : /* limit to something that won't cause integer overflow */
3794 [ + + ]: 50 : val = Max(val, -NUMERIC_MAX_RESULT_SCALE);
3795 [ + - ]: 50 : val = Min(val, NUMERIC_MAX_RESULT_SCALE);
3796 : :
8653 3797 : 50 : rscale = NUMERIC_MIN_SIG_DIGITS - (int) val;
3798 : 50 : rscale = Max(rscale, arg.dscale);
3799 : 50 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
3800 : 50 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
3801 : :
3802 : : /*
3803 : : * Let exp_var() do the calculation and return the result.
3804 : : */
3805 : 50 : exp_var(&arg, &result, rscale);
3806 : :
10195 JanWieck@Yahoo.com 3807 : 50 : res = make_result(&result);
3808 : :
3809 : 50 : free_var(&result);
3810 : :
9618 tgl@sss.pgh.pa.us 3811 : 50 : PG_RETURN_NUMERIC(res);
3812 : : }
3813 : :
3814 : :
3815 : : /*
3816 : : * numeric_ln() -
3817 : : *
3818 : : * Compute the natural logarithm of x
3819 : : */
3820 : : Datum
3821 : 140 : numeric_ln(PG_FUNCTION_ARGS)
3822 : : {
3823 : 140 : Numeric num = PG_GETARG_NUMERIC(0);
3824 : : Numeric res;
3825 : : NumericVar arg;
3826 : : NumericVar result;
3827 : : int ln_dweight;
3828 : : int rscale;
3829 : :
3830 : : /*
3831 : : * Handle NaN and infinities
3832 : : */
2320 3833 [ + + ]: 140 : if (NUMERIC_IS_SPECIAL(num))
3834 : : {
3835 [ + + ]: 12 : if (NUMERIC_IS_NINF(num))
3836 [ + - ]: 4 : ereport(ERROR,
3837 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
3838 : : errmsg("cannot take logarithm of a negative number")));
3839 : : /* For NAN or PINF, just duplicate the input */
3840 : 8 : PG_RETURN_NUMERIC(duplicate_numeric(num));
3841 : : }
3842 : :
5120 heikki.linnakangas@i 3843 : 128 : init_var_from_num(num, &arg);
10195 JanWieck@Yahoo.com 3844 : 128 : init_var(&result);
3845 : :
3846 : : /* Estimated dweight of logarithm */
4032 tgl@sss.pgh.pa.us 3847 : 128 : ln_dweight = estimate_ln_dweight(&arg);
3848 : :
3849 : 128 : rscale = NUMERIC_MIN_SIG_DIGITS - ln_dweight;
8653 3850 : 128 : rscale = Max(rscale, arg.dscale);
3851 : 128 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
3852 : 128 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
3853 : :
3854 : 128 : ln_var(&arg, &result, rscale);
3855 : :
10195 JanWieck@Yahoo.com 3856 : 112 : res = make_result(&result);
3857 : :
3858 : 112 : free_var(&result);
3859 : :
9618 tgl@sss.pgh.pa.us 3860 : 112 : PG_RETURN_NUMERIC(res);
3861 : : }
3862 : :
3863 : :
3864 : : /*
3865 : : * numeric_log() -
3866 : : *
3867 : : * Compute the logarithm of x in a given base
3868 : : */
3869 : : Datum
3870 : 249 : numeric_log(PG_FUNCTION_ARGS)
3871 : : {
3872 : 249 : Numeric num1 = PG_GETARG_NUMERIC(0);
3873 : 249 : Numeric num2 = PG_GETARG_NUMERIC(1);
3874 : : Numeric res;
3875 : : NumericVar arg1;
3876 : : NumericVar arg2;
3877 : : NumericVar result;
3878 : :
3879 : : /*
3880 : : * Handle NaN and infinities
3881 : : */
2320 3882 [ + + + + ]: 249 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3883 : : {
3884 : : int sign1,
3885 : : sign2;
3886 : :
3887 [ + + + + ]: 93 : if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
3888 : 36 : PG_RETURN_NUMERIC(make_result(&const_nan));
3889 : : /* fail on negative inputs including -Inf, as log_var would */
3890 : 57 : sign1 = numeric_sign_internal(num1);
3891 : 57 : sign2 = numeric_sign_internal(num2);
3892 [ + + + + ]: 57 : if (sign1 < 0 || sign2 < 0)
3893 [ + - ]: 16 : ereport(ERROR,
3894 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
3895 : : errmsg("cannot take logarithm of a negative number")));
3896 : : /* fail on zero inputs, as log_var would */
3897 [ + - + + ]: 41 : if (sign1 == 0 || sign2 == 0)
3898 [ + - ]: 4 : ereport(ERROR,
3899 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
3900 : : errmsg("cannot take logarithm of zero")));
3901 [ + + ]: 37 : if (NUMERIC_IS_PINF(num1))
3902 : : {
3903 : : /* log(Inf, Inf) reduces to Inf/Inf, so it's NaN */
3904 [ + + ]: 12 : if (NUMERIC_IS_PINF(num2))
3905 : 4 : PG_RETURN_NUMERIC(make_result(&const_nan));
3906 : : /* log(Inf, finite-positive) is zero (we don't throw underflow) */
3907 : 8 : PG_RETURN_NUMERIC(make_result(&const_zero));
3908 : : }
3909 [ - + ]: 25 : Assert(NUMERIC_IS_PINF(num2));
3910 : :
3911 : : /*
3912 : : * For a finite-positive base, log(base, Inf) = Inf / ln(base), so the
3913 : : * sign depends on whether base is more or less than 1. If base = 1,
3914 : : * fall through and let log_var report the error.
3915 : : */
44 tgl@sss.pgh.pa.us 3916 :GNC 25 : init_var_from_num(num1, &arg1);
3917 : 25 : sign1 = cmp_var(&arg1, &const_one);
3918 [ + + ]: 25 : if (sign1 < 0)
3919 : 5 : PG_RETURN_NUMERIC(make_result(&const_ninf));
3920 [ + + ]: 20 : if (sign1 > 0)
3921 : 16 : PG_RETURN_NUMERIC(make_result(&const_pinf));
3922 : : }
3923 : :
3924 : : /*
3925 : : * Initialize things
3926 : : */
5120 heikki.linnakangas@i 3927 :CBC 160 : init_var_from_num(num1, &arg1);
3928 : 160 : init_var_from_num(num2, &arg2);
10195 JanWieck@Yahoo.com 3929 : 160 : init_var(&result);
3930 : :
3931 : : /*
3932 : : * Call log_var() to compute and return the result; note it handles scale
3933 : : * selection itself.
3934 : : */
3935 : 160 : log_var(&arg1, &arg2, &result);
3936 : :
3937 : 116 : res = make_result(&result);
3938 : :
3939 : 116 : free_var(&result);
3940 : :
9618 tgl@sss.pgh.pa.us 3941 : 116 : PG_RETURN_NUMERIC(res);
3942 : : }
3943 : :
3944 : :
3945 : : /*
3946 : : * numeric_power() -
3947 : : *
3948 : : * Raise x to the power of y
3949 : : */
3950 : : Datum
3951 : 1149 : numeric_power(PG_FUNCTION_ARGS)
3952 : : {
3953 : 1149 : Numeric num1 = PG_GETARG_NUMERIC(0);
3954 : 1149 : Numeric num2 = PG_GETARG_NUMERIC(1);
3955 : : Numeric res;
3956 : : NumericVar arg1;
3957 : : NumericVar arg2;
3958 : : NumericVar result;
3959 : : int sign1,
3960 : : sign2;
3961 : :
3962 : : /*
3963 : : * Handle NaN and infinities
3964 : : */
2320 3965 [ + + + + ]: 1149 : if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
3966 : : {
3967 : : /*
3968 : : * We follow the POSIX spec for pow(3), which says that NaN ^ 0 = 1,
3969 : : * and 1 ^ NaN = 1, while all other cases with NaN inputs yield NaN
3970 : : * (with no error).
3971 : : */
3972 [ + + ]: 173 : if (NUMERIC_IS_NAN(num1))
3973 : : {
3974 [ + + ]: 39 : if (!NUMERIC_IS_SPECIAL(num2))
3975 : : {
3976 : 26 : init_var_from_num(num2, &arg2);
3977 [ + + ]: 26 : if (cmp_var(&arg2, &const_zero) == 0)
3978 : 9 : PG_RETURN_NUMERIC(make_result(&const_one));
3979 : : }
3980 : 30 : PG_RETURN_NUMERIC(make_result(&const_nan));
3981 : : }
3982 [ + + ]: 134 : if (NUMERIC_IS_NAN(num2))
3983 : : {
3984 [ + + ]: 30 : if (!NUMERIC_IS_SPECIAL(num1))
3985 : : {
3986 : 26 : init_var_from_num(num1, &arg1);
3987 [ + + ]: 26 : if (cmp_var(&arg1, &const_one) == 0)
3988 : 9 : PG_RETURN_NUMERIC(make_result(&const_one));
3989 : : }
3990 : 21 : PG_RETURN_NUMERIC(make_result(&const_nan));
3991 : : }
3992 : : /* At least one input is infinite, but error rules still apply */
3993 : 104 : sign1 = numeric_sign_internal(num1);
3994 : 104 : sign2 = numeric_sign_internal(num2);
3995 [ + + + + ]: 104 : if (sign1 == 0 && sign2 < 0)
3996 [ + - ]: 4 : ereport(ERROR,
3997 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
3998 : : errmsg("zero raised to a negative power is undefined")));
3999 [ + + + + ]: 100 : if (sign1 < 0 && !numeric_is_integral(num2))
4000 [ + - ]: 4 : ereport(ERROR,
4001 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
4002 : : errmsg("a negative number raised to a non-integer power yields a complex result")));
4003 : :
4004 : : /*
4005 : : * POSIX gives this series of rules for pow(3) with infinite inputs:
4006 : : *
4007 : : * For any value of y, if x is +1, 1.0 shall be returned.
4008 : : */
4009 [ + + ]: 96 : if (!NUMERIC_IS_SPECIAL(num1))
4010 : : {
4011 : 31 : init_var_from_num(num1, &arg1);
4012 [ + + ]: 31 : if (cmp_var(&arg1, &const_one) == 0)
3117 4013 : 4 : PG_RETURN_NUMERIC(make_result(&const_one));
4014 : : }
4015 : :
4016 : : /*
4017 : : * For any value of x, if y is [-]0, 1.0 shall be returned.
4018 : : */
2320 4019 [ + + ]: 92 : if (sign2 == 0)
3117 4020 : 9 : PG_RETURN_NUMERIC(make_result(&const_one));
4021 : :
4022 : : /*
4023 : : * For any odd integer value of y > 0, if x is [-]0, [-]0 shall be
4024 : : * returned. For y > 0 and not an odd integer, if x is [-]0, +0 shall
4025 : : * be returned. (Since we don't deal in minus zero, we need not
4026 : : * distinguish these two cases.)
4027 : : */
2320 4028 [ + + + - ]: 83 : if (sign1 == 0 && sign2 > 0)
4029 : 4 : PG_RETURN_NUMERIC(make_result(&const_zero));
4030 : :
4031 : : /*
4032 : : * If x is -1, and y is [-]Inf, 1.0 shall be returned.
4033 : : *
4034 : : * For |x| < 1, if y is -Inf, +Inf shall be returned.
4035 : : *
4036 : : * For |x| > 1, if y is -Inf, +0 shall be returned.
4037 : : *
4038 : : * For |x| < 1, if y is +Inf, +0 shall be returned.
4039 : : *
4040 : : * For |x| > 1, if y is +Inf, +Inf shall be returned.
4041 : : */
4042 [ + + ]: 79 : if (NUMERIC_IS_INF(num2))
4043 : : {
4044 : : bool abs_x_gt_one;
4045 : :
4046 [ + + ]: 42 : if (NUMERIC_IS_SPECIAL(num1))
4047 : 19 : abs_x_gt_one = true; /* x is either Inf or -Inf */
4048 : : else
4049 : : {
4050 : 23 : init_var_from_num(num1, &arg1);
4051 [ + + ]: 23 : if (cmp_var(&arg1, &const_minus_one) == 0)
4052 : 5 : PG_RETURN_NUMERIC(make_result(&const_one));
4053 : 18 : arg1.sign = NUMERIC_POS; /* now arg1 = abs(x) */
4054 : 18 : abs_x_gt_one = (cmp_var(&arg1, &const_one) > 0);
4055 : : }
4056 [ + + ]: 37 : if (abs_x_gt_one == (sign2 > 0))
4057 : 22 : PG_RETURN_NUMERIC(make_result(&const_pinf));
4058 : : else
4059 : 15 : PG_RETURN_NUMERIC(make_result(&const_zero));
4060 : : }
4061 : :
4062 : : /*
4063 : : * For y < 0, if x is +Inf, +0 shall be returned.
4064 : : *
4065 : : * For y > 0, if x is +Inf, +Inf shall be returned.
4066 : : */
4067 [ + + ]: 37 : if (NUMERIC_IS_PINF(num1))
4068 : : {
4069 [ + + ]: 17 : if (sign2 > 0)
4070 : 12 : PG_RETURN_NUMERIC(make_result(&const_pinf));
4071 : : else
4072 : 5 : PG_RETURN_NUMERIC(make_result(&const_zero));
4073 : : }
4074 : :
4075 [ - + ]: 20 : Assert(NUMERIC_IS_NINF(num1));
4076 : :
4077 : : /*
4078 : : * For y an odd integer < 0, if x is -Inf, -0 shall be returned. For
4079 : : * y < 0 and not an odd integer, if x is -Inf, +0 shall be returned.
4080 : : * (Again, we need not distinguish these two cases.)
4081 : : */
4082 [ + + ]: 20 : if (sign2 < 0)
4083 : 10 : PG_RETURN_NUMERIC(make_result(&const_zero));
4084 : :
4085 : : /*
4086 : : * For y an odd integer > 0, if x is -Inf, -Inf shall be returned. For
4087 : : * y > 0 and not an odd integer, if x is -Inf, +Inf shall be returned.
4088 : : */
4089 : 10 : init_var_from_num(num2, &arg2);
4090 [ + - + - ]: 10 : if (arg2.ndigits > 0 && arg2.ndigits == arg2.weight + 1 &&
4091 [ + + ]: 10 : (arg2.digits[arg2.ndigits - 1] & 1))
4092 : 5 : PG_RETURN_NUMERIC(make_result(&const_ninf));
4093 : : else
4094 : 5 : PG_RETURN_NUMERIC(make_result(&const_pinf));
4095 : : }
4096 : :
4097 : : /*
4098 : : * The SQL spec requires that we emit a particular SQLSTATE error code for
4099 : : * certain error conditions. Specifically, we don't return a
4100 : : * divide-by-zero error code for 0 ^ -1. Raising a negative number to a
4101 : : * non-integer power must produce the same error code, but that case is
4102 : : * handled in power_var().
4103 : : */
4104 : 976 : sign1 = numeric_sign_internal(num1);
4105 : 976 : sign2 = numeric_sign_internal(num2);
4106 : :
4107 [ + + + + ]: 976 : if (sign1 == 0 && sign2 < 0)
8231 neilc@samurai.com 4108 [ + - ]: 8 : ereport(ERROR,
4109 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
4110 : : errmsg("zero raised to a negative power is undefined")));
4111 : :
4112 : : /*
4113 : : * Initialize things
4114 : : */
2320 tgl@sss.pgh.pa.us 4115 : 968 : init_var(&result);
4116 : 968 : init_var_from_num(num1, &arg1);
4117 : 968 : init_var_from_num(num2, &arg2);
4118 : :
4119 : : /*
4120 : : * Call power_var() to compute and return the result; note it handles
4121 : : * scale selection itself.
4122 : : */
10195 JanWieck@Yahoo.com 4123 : 968 : power_var(&arg1, &arg2, &result);
4124 : :
4125 : 948 : res = make_result(&result);
4126 : :
4127 : 948 : free_var(&result);
4128 : :
9618 tgl@sss.pgh.pa.us 4129 : 948 : PG_RETURN_NUMERIC(res);
4130 : : }
4131 : :
4132 : : /*
4133 : : * numeric_scale() -
4134 : : *
4135 : : * Returns the scale, i.e. the count of decimal digits in the fractional part
4136 : : */
4137 : : Datum
3980 alvherre@alvh.no-ip. 4138 : 81 : numeric_scale(PG_FUNCTION_ARGS)
4139 : : {
4140 : 81 : Numeric num = PG_GETARG_NUMERIC(0);
4141 : :
2320 tgl@sss.pgh.pa.us 4142 [ + + ]: 81 : if (NUMERIC_IS_SPECIAL(num))
3980 alvherre@alvh.no-ip. 4143 : 14 : PG_RETURN_NULL();
4144 : :
4145 [ + - ]: 67 : PG_RETURN_INT32(NUMERIC_DSCALE(num));
4146 : : }
4147 : :
4148 : : /*
4149 : : * Calculate minimum scale for value.
4150 : : */
4151 : : static int
2518 tgl@sss.pgh.pa.us 4152 : 267 : get_min_scale(NumericVar *var)
4153 : : {
4154 : : int min_scale;
4155 : : int last_digit_pos;
4156 : :
4157 : : /*
4158 : : * Ordinarily, the input value will be "stripped" so that the last
4159 : : * NumericDigit is nonzero. But we don't want to get into an infinite
4160 : : * loop if it isn't, so explicitly find the last nonzero digit.
4161 : : */
4162 : 267 : last_digit_pos = var->ndigits - 1;
4163 [ + + ]: 267 : while (last_digit_pos >= 0 &&
4164 [ - + ]: 243 : var->digits[last_digit_pos] == 0)
2518 tgl@sss.pgh.pa.us 4165 :UBC 0 : last_digit_pos--;
4166 : :
2518 tgl@sss.pgh.pa.us 4167 [ + + ]:CBC 267 : if (last_digit_pos >= 0)
4168 : : {
4169 : : /* compute min_scale assuming that last ndigit has no zeroes */
4170 : 243 : min_scale = (last_digit_pos - var->weight) * DEC_DIGITS;
4171 : :
4172 : : /*
4173 : : * We could get a negative result if there are no digits after the
4174 : : * decimal point. In this case the min_scale must be zero.
4175 : : */
4176 [ + + ]: 243 : if (min_scale > 0)
4177 : : {
4178 : : /*
4179 : : * Reduce min_scale if trailing digit(s) in last NumericDigit are
4180 : : * zero.
4181 : : */
4182 : 135 : NumericDigit last_digit = var->digits[last_digit_pos];
4183 : :
4184 [ + + ]: 365 : while (last_digit % 10 == 0)
4185 : : {
4186 : 230 : min_scale--;
4187 : 230 : last_digit /= 10;
4188 : : }
4189 : : }
4190 : : else
4191 : 108 : min_scale = 0;
4192 : : }
4193 : : else
4194 : 24 : min_scale = 0; /* result if input is zero */
4195 : :
4196 : 267 : return min_scale;
4197 : : }
4198 : :
4199 : : /*
4200 : : * Returns minimum scale required to represent supplied value without loss.
4201 : : */
4202 : : Datum
4203 : 60 : numeric_min_scale(PG_FUNCTION_ARGS)
4204 : : {
4205 : 60 : Numeric num = PG_GETARG_NUMERIC(0);
4206 : : NumericVar arg;
4207 : : int min_scale;
4208 : :
2320 4209 [ + + ]: 60 : if (NUMERIC_IS_SPECIAL(num))
2518 4210 : 10 : PG_RETURN_NULL();
4211 : :
4212 : 50 : init_var_from_num(num, &arg);
4213 : 50 : min_scale = get_min_scale(&arg);
4214 : 50 : free_var(&arg);
4215 : :
4216 : 50 : PG_RETURN_INT32(min_scale);
4217 : : }
4218 : :
4219 : : /*
4220 : : * Reduce scale of numeric value to represent supplied value without loss.
4221 : : */
4222 : : Datum
4223 : 227 : numeric_trim_scale(PG_FUNCTION_ARGS)
4224 : : {
4225 : 227 : Numeric num = PG_GETARG_NUMERIC(0);
4226 : : Numeric res;
4227 : : NumericVar result;
4228 : :
2320 4229 [ + + ]: 227 : if (NUMERIC_IS_SPECIAL(num))
4230 : 10 : PG_RETURN_NUMERIC(duplicate_numeric(num));
4231 : :
2518 4232 : 217 : init_var_from_num(num, &result);
4233 : 217 : result.dscale = get_min_scale(&result);
4234 : 217 : res = make_result(&result);
4235 : 217 : free_var(&result);
4236 : :
4237 : 217 : PG_RETURN_NUMERIC(res);
4238 : : }
4239 : :
4240 : : /*
4241 : : * Return a random numeric value in the range [rmin, rmax].
4242 : : */
4243 : : Numeric
976 dean.a.rasheed@gmail 4244 : 22308 : random_numeric(pg_prng_state *state, Numeric rmin, Numeric rmax)
4245 : : {
4246 : : NumericVar rmin_var;
4247 : : NumericVar rmax_var;
4248 : : NumericVar result;
4249 : : Numeric res;
4250 : :
4251 : : /* Range bounds must not be NaN/infinity */
4252 [ + + ]: 22308 : if (NUMERIC_IS_SPECIAL(rmin))
4253 : : {
4254 [ + + ]: 8 : if (NUMERIC_IS_NAN(rmin))
4255 [ + - ]: 4 : ereport(ERROR,
4256 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4257 : : errmsg("lower bound cannot be NaN"));
4258 : : else
4259 [ + - ]: 4 : ereport(ERROR,
4260 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4261 : : errmsg("lower bound cannot be infinity"));
4262 : : }
4263 [ + + ]: 22300 : if (NUMERIC_IS_SPECIAL(rmax))
4264 : : {
4265 [ + + ]: 8 : if (NUMERIC_IS_NAN(rmax))
4266 [ + - ]: 4 : ereport(ERROR,
4267 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4268 : : errmsg("upper bound cannot be NaN"));
4269 : : else
4270 [ + - ]: 4 : ereport(ERROR,
4271 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4272 : : errmsg("upper bound cannot be infinity"));
4273 : : }
4274 : :
4275 : : /* Return a random value in the range [rmin, rmax] */
4276 : 22292 : init_var_from_num(rmin, &rmin_var);
4277 : 22292 : init_var_from_num(rmax, &rmax_var);
4278 : :
4279 : 22292 : init_var(&result);
4280 : :
4281 : 22292 : random_var(state, &rmin_var, &rmax_var, &result);
4282 : :
4283 : 22288 : res = make_result(&result);
4284 : :
4285 : 22288 : free_var(&result);
4286 : :
4287 : 22288 : return res;
4288 : : }
4289 : :
4290 : :
4291 : : /* ----------------------------------------------------------------------
4292 : : *
4293 : : * Type conversion functions
4294 : : *
4295 : : * ----------------------------------------------------------------------
4296 : : */
4297 : :
4298 : : Numeric
2271 peter@eisentraut.org 4299 : 1251624 : int64_to_numeric(int64 val)
4300 : : {
4301 : : Numeric res;
4302 : : NumericVar result;
4303 : :
10195 JanWieck@Yahoo.com 4304 : 1251624 : init_var(&result);
4305 : :
2271 peter@eisentraut.org 4306 : 1251624 : int64_to_numericvar(val, &result);
4307 : :
10195 JanWieck@Yahoo.com 4308 : 1251624 : res = make_result(&result);
4309 : :
4310 : 1251624 : free_var(&result);
4311 : :
2271 peter@eisentraut.org 4312 : 1251624 : return res;
4313 : : }
4314 : :
4315 : : /*
4316 : : * Convert val1/(10**log10val2) to numeric. This is much faster than normal
4317 : : * numeric division.
4318 : : */
4319 : : Numeric
2062 4320 : 15149 : int64_div_fast_to_numeric(int64 val1, int log10val2)
4321 : : {
4322 : : Numeric res;
4323 : : NumericVar result;
4324 : : int rscale;
4325 : : int w;
4326 : : int m;
4327 : :
1394 dean.a.rasheed@gmail 4328 : 15149 : init_var(&result);
4329 : :
4330 : : /* result scale */
4331 : 15149 : rscale = log10val2 < 0 ? 0 : log10val2;
4332 : :
4333 : : /* how much to decrease the weight by */
2062 peter@eisentraut.org 4334 : 15149 : w = log10val2 / DEC_DIGITS;
4335 : : /* how much is left to divide by */
4336 : 15149 : m = log10val2 % DEC_DIGITS;
1394 dean.a.rasheed@gmail 4337 [ - + ]: 15149 : if (m < 0)
4338 : : {
1394 dean.a.rasheed@gmail 4339 :UBC 0 : m += DEC_DIGITS;
4340 : 0 : w--;
4341 : : }
4342 : :
4343 : : /*
4344 : : * If there is anything left to divide by (10^m with 0 < m < DEC_DIGITS),
4345 : : * multiply the dividend by 10^(DEC_DIGITS - m), and shift the weight by
4346 : : * one more.
4347 : : */
2062 peter@eisentraut.org 4348 [ + - ]:CBC 15149 : if (m > 0)
4349 : : {
4350 : : #if DEC_DIGITS == 4
4351 : : static const int pow10[] = {1, 10, 100, 1000};
4352 : : #elif DEC_DIGITS == 2
4353 : : static const int pow10[] = {1, 10};
4354 : : #elif DEC_DIGITS == 1
4355 : : static const int pow10[] = {1};
4356 : : #else
4357 : : #error unsupported NBASE
4358 : : #endif
1394 dean.a.rasheed@gmail 4359 : 15149 : int64 factor = pow10[DEC_DIGITS - m];
4360 : : int64 new_val1;
4361 : :
4362 : : StaticAssertDecl(lengthof(pow10) == DEC_DIGITS, "mismatch with DEC_DIGITS");
4363 : :
4364 [ + + ]: 15149 : if (unlikely(pg_mul_s64_overflow(val1, factor, &new_val1)))
4365 : : {
4366 : : /* do the multiplication using 128-bit integers */
4367 : : INT128 tmp;
4368 : :
478 4369 : 9 : tmp = int64_to_int128(0);
4370 : 9 : int128_add_int64_mul_int64(&tmp, val1, factor);
4371 : :
1394 4372 : 9 : int128_to_numericvar(tmp, &result);
4373 : : }
4374 : : else
4375 : 15140 : int64_to_numericvar(new_val1, &result);
4376 : :
2062 peter@eisentraut.org 4377 : 15149 : w++;
4378 : : }
4379 : : else
1394 dean.a.rasheed@gmail 4380 :UBC 0 : int64_to_numericvar(val1, &result);
4381 : :
2062 peter@eisentraut.org 4382 :CBC 15149 : result.weight -= w;
1394 dean.a.rasheed@gmail 4383 : 15149 : result.dscale = rscale;
4384 : :
2062 peter@eisentraut.org 4385 : 15149 : res = make_result(&result);
4386 : :
4387 : 15149 : free_var(&result);
4388 : :
4389 : 15149 : return res;
4390 : : }
4391 : :
4392 : : Datum
2271 4393 : 1042852 : int4_numeric(PG_FUNCTION_ARGS)
4394 : : {
4395 : 1042852 : int32 val = PG_GETARG_INT32(0);
4396 : :
4397 : 1042852 : PG_RETURN_NUMERIC(int64_to_numeric(val));
4398 : : }
4399 : :
4400 : : /*
4401 : : * Internal version of numeric_int4() with support for soft error reporting.
4402 : : */
4403 : : int32
449 michael@paquier.xyz 4404 : 6925 : numeric_int4_safe(Numeric num, Node *escontext)
4405 : : {
4406 : : NumericVar x;
4407 : : int32 result;
4408 : :
2320 tgl@sss.pgh.pa.us 4409 [ + + ]: 6925 : if (NUMERIC_IS_SPECIAL(num))
4410 : : {
449 michael@paquier.xyz 4411 [ + + ]: 12 : if (NUMERIC_IS_NAN(num))
4412 [ + - ]: 4 : ereturn(escontext, 0,
4413 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4414 : : errmsg("cannot convert NaN to %s", "integer")));
4415 : : else
4416 [ + - ]: 8 : ereturn(escontext, 0,
4417 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4418 : : errmsg("cannot convert infinity to %s", "integer")));
4419 : : }
4420 : :
4421 : : /* Convert to variable format, then convert to int4 */
5120 heikki.linnakangas@i 4422 : 6913 : init_var_from_num(num, &x);
4423 : :
2814 akorotkov@postgresql 4424 [ + + ]: 6913 : if (!numericvar_to_int32(&x, &result))
449 michael@paquier.xyz 4425 [ + + ]: 70 : ereturn(escontext, 0,
4426 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4427 : : errmsg("integer out of range")));
4428 : :
2814 akorotkov@postgresql 4429 : 6843 : return result;
4430 : : }
4431 : :
4432 : : Datum
4433 : 5782 : numeric_int4(PG_FUNCTION_ARGS)
4434 : : {
4435 : 5782 : Numeric num = PG_GETARG_NUMERIC(0);
4436 : : int32 result;
4437 : :
249 peter@eisentraut.org 4438 : 5782 : result = numeric_int4_safe(num, fcinfo->context);
4439 : :
4440 [ - + - - : 5762 : if (unlikely(SOFT_ERROR_OCCURRED(fcinfo->context)))
- + - - -
+ ]
249 peter@eisentraut.org 4441 :UBC 0 : PG_RETURN_NULL();
4442 : :
249 peter@eisentraut.org 4443 :CBC 5762 : PG_RETURN_INT32(result);
4444 : : }
4445 : :
4446 : : /*
4447 : : * Given a NumericVar, convert it to an int32. If the NumericVar
4448 : : * exceeds the range of an int32, false is returned, otherwise true is returned.
4449 : : * The input NumericVar is *not* free'd.
4450 : : */
4451 : : static bool
2814 akorotkov@postgresql 4452 : 7414 : numericvar_to_int32(const NumericVar *var, int32 *result)
4453 : : {
4454 : : int64 val;
4455 : :
4271 andres@anarazel.de 4456 [ + + ]: 7414 : if (!numericvar_to_int64(var, &val))
2814 akorotkov@postgresql 4457 : 4 : return false;
4458 : :
1940 dean.a.rasheed@gmail 4459 [ + + + + ]: 7410 : if (unlikely(val < PG_INT32_MIN) || unlikely(val > PG_INT32_MAX))
4460 : 66 : return false;
4461 : :
4462 : : /* Down-convert to int4 */
2814 akorotkov@postgresql 4463 : 7344 : *result = (int32) val;
4464 : :
1940 dean.a.rasheed@gmail 4465 : 7344 : return true;
4466 : : }
4467 : :
4468 : : Datum
9630 tgl@sss.pgh.pa.us 4469 : 24605 : int8_numeric(PG_FUNCTION_ARGS)
4470 : : {
8653 4471 : 24605 : int64 val = PG_GETARG_INT64(0);
4472 : :
2271 peter@eisentraut.org 4473 : 24605 : PG_RETURN_NUMERIC(int64_to_numeric(val));
4474 : : }
4475 : :
4476 : : /*
4477 : : * Internal version of numeric_int8() with support for soft error reporting.
4478 : : */
4479 : : int64
449 michael@paquier.xyz 4480 : 388 : numeric_int8_safe(Numeric num, Node *escontext)
4481 : : {
4482 : : NumericVar x;
4483 : : int64 result;
4484 : :
2320 tgl@sss.pgh.pa.us 4485 [ + + ]: 388 : if (NUMERIC_IS_SPECIAL(num))
4486 : : {
449 michael@paquier.xyz 4487 [ + + ]: 12 : if (NUMERIC_IS_NAN(num))
4488 [ + - ]: 4 : ereturn(escontext, 0,
4489 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4490 : : errmsg("cannot convert NaN to %s", "bigint")));
4491 : : else
4492 [ + - ]: 8 : ereturn(escontext, 0,
4493 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4494 : : errmsg("cannot convert infinity to %s", "bigint")));
4495 : : }
4496 : :
4497 : : /* Convert to variable format, then convert to int8 */
5120 heikki.linnakangas@i 4498 : 376 : init_var_from_num(num, &x);
4499 : :
4271 andres@anarazel.de 4500 [ + + ]: 376 : if (!numericvar_to_int64(&x, &result))
449 michael@paquier.xyz 4501 [ + + ]: 40 : ereturn(escontext, 0,
4502 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4503 : : errmsg("bigint out of range")));
4504 : :
1060 peter@eisentraut.org 4505 : 336 : return result;
4506 : : }
4507 : :
4508 : : Datum
4509 : 348 : numeric_int8(PG_FUNCTION_ARGS)
4510 : : {
4511 : 348 : Numeric num = PG_GETARG_NUMERIC(0);
4512 : : int64 result;
4513 : :
249 4514 : 348 : result = numeric_int8_safe(num, fcinfo->context);
4515 : :
4516 [ - + - - : 304 : if (unlikely(SOFT_ERROR_OCCURRED(fcinfo->context)))
- + - - -
+ ]
249 peter@eisentraut.org 4517 :UBC 0 : PG_RETURN_NULL();
4518 : :
249 peter@eisentraut.org 4519 :CBC 304 : PG_RETURN_INT64(result);
4520 : : }
4521 : :
4522 : :
4523 : : Datum
9672 tgl@sss.pgh.pa.us 4524 : 5 : int2_numeric(PG_FUNCTION_ARGS)
4525 : : {
4526 : 5 : int16 val = PG_GETARG_INT16(0);
4527 : :
2271 peter@eisentraut.org 4528 : 5 : PG_RETURN_NUMERIC(int64_to_numeric(val));
4529 : : }
4530 : :
4531 : :
4532 : : Datum
9672 tgl@sss.pgh.pa.us 4533 : 73 : numeric_int2(PG_FUNCTION_ARGS)
4534 : : {
4535 : 73 : Numeric num = PG_GETARG_NUMERIC(0);
4536 : : NumericVar x;
4537 : : int64 val;
4538 : : int16 result;
4539 : :
2320 4540 [ + + ]: 73 : if (NUMERIC_IS_SPECIAL(num))
4541 : : {
4542 [ + + ]: 12 : if (NUMERIC_IS_NAN(num))
249 peter@eisentraut.org 4543 [ + - ]: 4 : ereturn(fcinfo->context, (Datum) 0,
4544 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4545 : : errmsg("cannot convert NaN to %s", "smallint")));
4546 : : else
4547 [ + - ]: 8 : ereturn(fcinfo->context, (Datum) 0,
4548 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4549 : : errmsg("cannot convert infinity to %s", "smallint")));
4550 : : }
4551 : :
4552 : : /* Convert to variable format and thence to int8 */
5120 heikki.linnakangas@i 4553 : 61 : init_var_from_num(num, &x);
4554 : :
4271 andres@anarazel.de 4555 [ - + ]: 61 : if (!numericvar_to_int64(&x, &val))
249 peter@eisentraut.org 4556 [ # # ]:UBC 0 : ereturn(fcinfo->context, (Datum) 0,
4557 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4558 : : errmsg("smallint out of range")));
4559 : :
1940 dean.a.rasheed@gmail 4560 [ + + + + ]:CBC 61 : if (unlikely(val < PG_INT16_MIN) || unlikely(val > PG_INT16_MAX))
249 peter@eisentraut.org 4561 [ + - ]: 8 : ereturn(fcinfo->context, (Datum) 0,
4562 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
4563 : : errmsg("smallint out of range")));
4564 : :
4565 : : /* Down-convert to int2 */
1940 dean.a.rasheed@gmail 4566 : 53 : result = (int16) val;
4567 : :
8653 tgl@sss.pgh.pa.us 4568 : 53 : PG_RETURN_INT16(result);
4569 : : }
4570 : :
4571 : :
4572 : : Datum
9618 4573 : 12798 : float8_numeric(PG_FUNCTION_ARGS)
4574 : : {
4575 : 12798 : float8 val = PG_GETARG_FLOAT8(0);
4576 : : Numeric res;
4577 : : NumericVar result;
4578 : : char buf[DBL_DIG + 100];
4579 : : const char *endptr;
4580 : :
4581 [ + + ]: 12798 : if (isnan(val))
4582 : 5 : PG_RETURN_NUMERIC(make_result(&const_nan));
4583 : :
3349 4584 [ + + ]: 12793 : if (isinf(val))
4585 : : {
2320 4586 [ + + ]: 10 : if (val < 0)
4587 : 5 : PG_RETURN_NUMERIC(make_result(&const_ninf));
4588 : : else
4589 : 5 : PG_RETURN_NUMERIC(make_result(&const_pinf));
4590 : : }
4591 : :
3349 4592 : 12783 : snprintf(buf, sizeof(buf), "%.*g", DBL_DIG, val);
4593 : :
10195 JanWieck@Yahoo.com 4594 : 12783 : init_var(&result);
4595 : :
4596 : : /* Assume we need not worry about leading/trailing spaces */
249 peter@eisentraut.org 4597 [ - + ]: 12783 : if (!set_var_from_str(buf, buf, &result, &endptr, fcinfo->context))
249 peter@eisentraut.org 4598 :UBC 0 : PG_RETURN_NULL();
4599 : :
10195 JanWieck@Yahoo.com 4600 :CBC 12783 : res = make_result(&result);
4601 : :
4602 : 12783 : free_var(&result);
4603 : :
9618 tgl@sss.pgh.pa.us 4604 : 12783 : PG_RETURN_NUMERIC(res);
4605 : : }
4606 : :
4607 : :
4608 : : Datum
4609 : 346821 : numeric_float8(PG_FUNCTION_ARGS)
4610 : : {
4611 : 346821 : Numeric num = PG_GETARG_NUMERIC(0);
4612 : : char *tmp;
4613 : : Datum result;
4614 : :
2320 4615 [ + + ]: 346821 : if (NUMERIC_IS_SPECIAL(num))
4616 : : {
4617 [ + + ]: 56 : if (NUMERIC_IS_PINF(num))
4618 : 17 : PG_RETURN_FLOAT8(get_float8_infinity());
4619 [ + + ]: 39 : else if (NUMERIC_IS_NINF(num))
4620 : 17 : PG_RETURN_FLOAT8(-get_float8_infinity());
4621 : : else
4622 : 22 : PG_RETURN_FLOAT8(get_float8_nan());
4623 : : }
4624 : :
9664 4625 : 346765 : tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
4626 : : NumericGetDatum(num)));
249 peter@eisentraut.org 4627 [ - + ]: 346765 : if (!DirectInputFunctionCallSafe(float8in, tmp,
4628 : : InvalidOid, -1,
4629 : : (Node *) fcinfo->context,
4630 : : &result))
4631 : : {
249 peter@eisentraut.org 4632 :UBC 0 : pfree(tmp);
4633 : 0 : PG_RETURN_NULL();
4634 : : }
4635 : :
9615 tgl@sss.pgh.pa.us 4636 :CBC 346765 : PG_RETURN_DATUM(result);
4637 : : }
4638 : :
4639 : :
4640 : : /*
4641 : : * Convert numeric to float8; if out of range, return +/- HUGE_VAL
4642 : : *
4643 : : * (internal helper function, not directly callable from SQL)
4644 : : */
4645 : : Datum
9177 4646 : 922 : numeric_float8_no_overflow(PG_FUNCTION_ARGS)
4647 : : {
4648 : 922 : Numeric num = PG_GETARG_NUMERIC(0);
4649 : : double val;
4650 : :
2320 4651 [ - + ]: 922 : if (NUMERIC_IS_SPECIAL(num))
4652 : : {
2320 tgl@sss.pgh.pa.us 4653 [ # # ]:UBC 0 : if (NUMERIC_IS_PINF(num))
4654 : 0 : val = HUGE_VAL;
4655 [ # # ]: 0 : else if (NUMERIC_IS_NINF(num))
4656 : 0 : val = -HUGE_VAL;
4657 : : else
4658 : 0 : val = get_float8_nan();
4659 : : }
4660 : : else
4661 : : {
4662 : : NumericVar x;
4663 : :
2320 tgl@sss.pgh.pa.us 4664 :CBC 922 : init_var_from_num(num, &x);
4665 : 922 : val = numericvar_to_double_no_overflow(&x);
4666 : : }
4667 : :
9177 4668 : 922 : PG_RETURN_FLOAT8(val);
4669 : : }
4670 : :
4671 : : Datum
9618 4672 : 15121 : float4_numeric(PG_FUNCTION_ARGS)
4673 : : {
4674 : 15121 : float4 val = PG_GETARG_FLOAT4(0);
4675 : : Numeric res;
4676 : : NumericVar result;
4677 : : char buf[FLT_DIG + 100];
4678 : : const char *endptr;
4679 : :
4680 [ + + ]: 15121 : if (isnan(val))
4681 : 5 : PG_RETURN_NUMERIC(make_result(&const_nan));
4682 : :
3349 4683 [ + + ]: 15116 : if (isinf(val))
4684 : : {
2320 4685 [ + + ]: 10 : if (val < 0)
4686 : 5 : PG_RETURN_NUMERIC(make_result(&const_ninf));
4687 : : else
4688 : 5 : PG_RETURN_NUMERIC(make_result(&const_pinf));
4689 : : }
4690 : :
3349 4691 : 15106 : snprintf(buf, sizeof(buf), "%.*g", FLT_DIG, val);
4692 : :
10195 JanWieck@Yahoo.com 4693 : 15106 : init_var(&result);
4694 : :
4695 : : /* Assume we need not worry about leading/trailing spaces */
249 peter@eisentraut.org 4696 [ - + ]: 15106 : if (!set_var_from_str(buf, buf, &result, &endptr, fcinfo->context))
249 peter@eisentraut.org 4697 :UBC 0 : PG_RETURN_NULL();
4698 : :
10195 JanWieck@Yahoo.com 4699 :CBC 15106 : res = make_result(&result);
4700 : :
4701 : 15106 : free_var(&result);
4702 : :
9618 tgl@sss.pgh.pa.us 4703 : 15106 : PG_RETURN_NUMERIC(res);
4704 : : }
4705 : :
4706 : :
4707 : : Datum
4708 : 1753 : numeric_float4(PG_FUNCTION_ARGS)
4709 : : {
4710 : 1753 : Numeric num = PG_GETARG_NUMERIC(0);
4711 : : char *tmp;
4712 : : Datum result;
4713 : :
2320 4714 [ + + ]: 1753 : if (NUMERIC_IS_SPECIAL(num))
4715 : : {
4716 [ + + ]: 56 : if (NUMERIC_IS_PINF(num))
4717 : 17 : PG_RETURN_FLOAT4(get_float4_infinity());
4718 [ + + ]: 39 : else if (NUMERIC_IS_NINF(num))
4719 : 17 : PG_RETURN_FLOAT4(-get_float4_infinity());
4720 : : else
4721 : 22 : PG_RETURN_FLOAT4(get_float4_nan());
4722 : : }
4723 : :
9664 4724 : 1697 : tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
4725 : : NumericGetDatum(num)));
4726 : :
249 peter@eisentraut.org 4727 [ - + ]: 1697 : if (!DirectInputFunctionCallSafe(float4in, tmp,
4728 : : InvalidOid, -1,
4729 : : (Node *) fcinfo->context,
4730 : : &result))
4731 : : {
249 peter@eisentraut.org 4732 :UBC 0 : pfree(tmp);
4733 : 0 : PG_RETURN_NULL();
4734 : : }
4735 : :
10195 JanWieck@Yahoo.com 4736 :CBC 1697 : pfree(tmp);
4737 : :
9615 tgl@sss.pgh.pa.us 4738 : 1697 : PG_RETURN_DATUM(result);
4739 : : }
4740 : :
4741 : :
4742 : : Datum
2342 fujii@postgresql.org 4743 : 105 : numeric_pg_lsn(PG_FUNCTION_ARGS)
4744 : : {
4745 : 105 : Numeric num = PG_GETARG_NUMERIC(0);
4746 : : NumericVar x;
4747 : : XLogRecPtr result;
4748 : :
2320 tgl@sss.pgh.pa.us 4749 [ + + ]: 105 : if (NUMERIC_IS_SPECIAL(num))
4750 : : {
4751 [ + - ]: 4 : if (NUMERIC_IS_NAN(num))
4752 [ + - ]: 4 : ereport(ERROR,
4753 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4754 : : errmsg("cannot convert NaN to %s", "pg_lsn")));
4755 : : else
2320 tgl@sss.pgh.pa.us 4756 [ # # ]:UBC 0 : ereport(ERROR,
4757 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4758 : : errmsg("cannot convert infinity to %s", "pg_lsn")));
4759 : : }
4760 : :
4761 : : /* Convert to variable format and thence to pg_lsn */
2342 fujii@postgresql.org 4762 :CBC 101 : init_var_from_num(num, &x);
4763 : :
4764 [ + + ]: 101 : if (!numericvar_to_uint64(&x, (uint64 *) &result))
4765 [ + - ]: 16 : ereport(ERROR,
4766 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4767 : : errmsg("pg_lsn out of range")));
4768 : :
4769 : 85 : PG_RETURN_LSN(result);
4770 : : }
4771 : :
4772 : :
4773 : : /* ----------------------------------------------------------------------
4774 : : *
4775 : : * Aggregate functions
4776 : : *
4777 : : * The transition datatype for all these aggregates is declared as INTERNAL.
4778 : : * Actually, it's a pointer to a NumericAggState allocated in the aggregate
4779 : : * context. The digit buffers for the NumericVars will be there too.
4780 : : *
4781 : : * For integer inputs, some aggregates use special-purpose 64-bit or 128-bit
4782 : : * integer based transition datatypes to speed up calculations.
4783 : : *
4784 : : * ----------------------------------------------------------------------
4785 : : */
4786 : :
4787 : : typedef struct NumericAggState
4788 : : {
4789 : : bool calcSumX2; /* if true, calculate sumX2 */
4790 : : MemoryContext agg_context; /* context we're calculating in */
4791 : : int64 N; /* count of processed numbers */
4792 : : NumericSumAccum sumX; /* sum of processed numbers */
4793 : : NumericSumAccum sumX2; /* sum of squares of processed numbers */
4794 : : int maxScale; /* maximum scale seen so far */
4795 : : int64 maxScaleCount; /* number of values seen with maximum scale */
4796 : : /* These counts are *not* included in N! Use NA_TOTAL_COUNT() as needed */
4797 : : int64 NaNcount; /* count of NaN values */
4798 : : int64 pInfcount; /* count of +Inf values */
4799 : : int64 nInfcount; /* count of -Inf values */
4800 : : } NumericAggState;
4801 : :
4802 : : #define NA_TOTAL_COUNT(na) \
4803 : : ((na)->N + (na)->NaNcount + (na)->pInfcount + (na)->nInfcount)
4804 : :
4805 : : /*
4806 : : * Prepare state data for a numeric aggregate function that needs to compute
4807 : : * sum, count and optionally sum of squares of the input.
4808 : : */
4809 : : static NumericAggState *
4760 tgl@sss.pgh.pa.us 4810 : 114082 : makeNumericAggState(FunctionCallInfo fcinfo, bool calcSumX2)
4811 : : {
4812 : : NumericAggState *state;
4813 : : MemoryContext agg_context;
4814 : : MemoryContext old_context;
4815 : :
4816 [ - + ]: 114082 : if (!AggCheckCallContext(fcinfo, &agg_context))
4760 tgl@sss.pgh.pa.us 4817 [ # # ]:UBC 0 : elog(ERROR, "aggregate function called in non-aggregate context");
4818 : :
4760 tgl@sss.pgh.pa.us 4819 :CBC 114082 : old_context = MemoryContextSwitchTo(agg_context);
4820 : :
353 michael@paquier.xyz 4821 : 114082 : state = palloc0_object(NumericAggState);
4760 tgl@sss.pgh.pa.us 4822 : 114082 : state->calcSumX2 = calcSumX2;
4823 : 114082 : state->agg_context = agg_context;
4824 : :
4825 : 114082 : MemoryContextSwitchTo(old_context);
4826 : :
4827 : 114082 : return state;
4828 : : }
4829 : :
4830 : : /*
4831 : : * Like makeNumericAggState(), but allocate the state in the current memory
4832 : : * context.
4833 : : */
4834 : : static NumericAggState *
3810 4835 : 56 : makeNumericAggStateCurrentContext(bool calcSumX2)
4836 : : {
4837 : : NumericAggState *state;
4838 : :
353 michael@paquier.xyz 4839 : 56 : state = palloc0_object(NumericAggState);
3810 tgl@sss.pgh.pa.us 4840 : 56 : state->calcSumX2 = calcSumX2;
4841 : 56 : state->agg_context = CurrentMemoryContext;
4842 : :
4843 : 56 : return state;
4844 : : }
4845 : :
4846 : : /*
4847 : : * Accumulate a new input value for numeric aggregate functions.
4848 : : */
4849 : : static void
4760 4850 : 1409012 : do_numeric_accum(NumericAggState *state, Numeric newval)
4851 : : {
4852 : : NumericVar X;
4853 : : NumericVar X2;
4854 : : MemoryContext old_context;
4855 : :
4856 : : /* Count NaN/infinity inputs separately from all else */
2320 4857 [ + + ]: 1409012 : if (NUMERIC_IS_SPECIAL(newval))
4858 : : {
4859 [ + + ]: 108 : if (NUMERIC_IS_PINF(newval))
4860 : 48 : state->pInfcount++;
4861 [ + + ]: 60 : else if (NUMERIC_IS_NINF(newval))
4862 : 24 : state->nInfcount++;
4863 : : else
4864 : 36 : state->NaNcount++;
4760 4865 : 108 : return;
4866 : : }
4867 : :
4868 : : /* load processed number in short-lived context */
4869 : 1408904 : init_var_from_num(newval, &X);
4870 : :
4871 : : /*
4872 : : * Track the highest input dscale that we've seen, to support inverse
4873 : : * transitions (see do_numeric_discard).
4874 : : */
4613 4875 [ + + ]: 1408904 : if (X.dscale > state->maxScale)
4876 : : {
4877 : 104 : state->maxScale = X.dscale;
4878 : 104 : state->maxScaleCount = 1;
4879 : : }
4880 [ + + ]: 1408800 : else if (X.dscale == state->maxScale)
4881 : 1408776 : state->maxScaleCount++;
4882 : :
4883 : : /* if we need X^2, calculate that in short-lived context */
4760 4884 [ + + ]: 1408904 : if (state->calcSumX2)
4885 : : {
4886 : 160488 : init_var(&X2);
4887 : 160488 : mul_var(&X, &X, &X2, X.dscale * 2);
4888 : : }
4889 : :
4890 : : /* The rest of this needs to work in the aggregate context */
4891 : 1408904 : old_context = MemoryContextSwitchTo(state->agg_context);
4892 : :
3739 heikki.linnakangas@i 4893 : 1408904 : state->N++;
4894 : :
4895 : : /* Accumulate sums */
4896 : 1408904 : accum_sum_add(&(state->sumX), &X);
4897 : :
4898 [ + + ]: 1408904 : if (state->calcSumX2)
4899 : 160488 : accum_sum_add(&(state->sumX2), &X2);
4900 : :
4760 tgl@sss.pgh.pa.us 4901 : 1408904 : MemoryContextSwitchTo(old_context);
4902 : : }
4903 : :
4904 : : /*
4905 : : * Attempt to remove an input value from the aggregated state.
4906 : : *
4907 : : * If the value cannot be removed then the function will return false; the
4908 : : * possible reasons for failing are described below.
4909 : : *
4910 : : * If we aggregate the values 1.01 and 2 then the result will be 3.01.
4911 : : * If we are then asked to un-aggregate the 1.01 then we must fail as we
4912 : : * won't be able to tell what the new aggregated value's dscale should be.
4913 : : * We don't want to return 2.00 (dscale = 2), since the sum's dscale would
4914 : : * have been zero if we'd really aggregated only 2.
4915 : : *
4916 : : * Note: alternatively, we could count the number of inputs with each possible
4917 : : * dscale (up to some sane limit). Not yet clear if it's worth the trouble.
4918 : : */
4919 : : static bool
4613 4920 : 228 : do_numeric_discard(NumericAggState *state, Numeric newval)
4921 : : {
4922 : : NumericVar X;
4923 : : NumericVar X2;
4924 : : MemoryContext old_context;
4925 : :
4926 : : /* Count NaN/infinity inputs separately from all else */
2320 4927 [ + + ]: 228 : if (NUMERIC_IS_SPECIAL(newval))
4928 : : {
4929 [ - + ]: 4 : if (NUMERIC_IS_PINF(newval))
2320 tgl@sss.pgh.pa.us 4930 :UBC 0 : state->pInfcount--;
2320 tgl@sss.pgh.pa.us 4931 [ - + ]:CBC 4 : else if (NUMERIC_IS_NINF(newval))
2320 tgl@sss.pgh.pa.us 4932 :UBC 0 : state->nInfcount--;
4933 : : else
2320 tgl@sss.pgh.pa.us 4934 :CBC 4 : state->NaNcount--;
4613 4935 : 4 : return true;
4936 : : }
4937 : :
4938 : : /* load processed number in short-lived context */
4939 : 224 : init_var_from_num(newval, &X);
4940 : :
4941 : : /*
4942 : : * state->sumX's dscale is the maximum dscale of any of the inputs.
4943 : : * Removing the last input with that dscale would require us to recompute
4944 : : * the maximum dscale of the *remaining* inputs, which we cannot do unless
4945 : : * no more non-NaN inputs remain at all. So we report a failure instead,
4946 : : * and force the aggregation to be redone from scratch.
4947 : : */
4948 [ + - ]: 224 : if (X.dscale == state->maxScale)
4949 : : {
4950 [ + + + + ]: 224 : if (state->maxScaleCount > 1 || state->maxScale == 0)
4951 : : {
4952 : : /*
4953 : : * Some remaining inputs have same dscale, or dscale hasn't gotten
4954 : : * above zero anyway
4955 : : */
4956 : 212 : state->maxScaleCount--;
4957 : : }
4958 [ + + ]: 12 : else if (state->N == 1)
4959 : : {
4960 : : /* No remaining non-NaN inputs at all, so reset maxScale */
4961 : 8 : state->maxScale = 0;
4962 : 8 : state->maxScaleCount = 0;
4963 : : }
4964 : : else
4965 : : {
4966 : : /* Correct new maxScale is uncertain, must fail */
4967 : 4 : return false;
4968 : : }
4969 : : }
4970 : :
4971 : : /* if we need X^2, calculate that in short-lived context */
4972 [ + + ]: 220 : if (state->calcSumX2)
4973 : : {
4974 : 192 : init_var(&X2);
4975 : 192 : mul_var(&X, &X, &X2, X.dscale * 2);
4976 : : }
4977 : :
4978 : : /* The rest of this needs to work in the aggregate context */
4979 : 220 : old_context = MemoryContextSwitchTo(state->agg_context);
4980 : :
4981 [ + + ]: 220 : if (state->N-- > 1)
4982 : : {
4983 : : /* Negate X, to subtract it from the sum */
3739 heikki.linnakangas@i 4984 [ + - ]: 208 : X.sign = (X.sign == NUMERIC_POS ? NUMERIC_NEG : NUMERIC_POS);
4985 : 208 : accum_sum_add(&(state->sumX), &X);
4986 : :
4613 tgl@sss.pgh.pa.us 4987 [ + + ]: 208 : if (state->calcSumX2)
4988 : : {
4989 : : /* Negate X^2. X^2 is always positive */
3739 heikki.linnakangas@i 4990 : 192 : X2.sign = NUMERIC_NEG;
4991 : 192 : accum_sum_add(&(state->sumX2), &X2);
4992 : : }
4993 : : }
4994 : : else
4995 : : {
4996 : : /* Zero the sums */
4613 tgl@sss.pgh.pa.us 4997 [ - + ]: 12 : Assert(state->N == 0);
4998 : :
3739 heikki.linnakangas@i 4999 : 12 : accum_sum_reset(&state->sumX);
5000 [ - + ]: 12 : if (state->calcSumX2)
3739 heikki.linnakangas@i 5001 :UBC 0 : accum_sum_reset(&state->sumX2);
5002 : : }
5003 : :
4613 tgl@sss.pgh.pa.us 5004 :CBC 220 : MemoryContextSwitchTo(old_context);
5005 : :
5006 : 220 : return true;
5007 : : }
5008 : :
5009 : : /*
5010 : : * Generic transition function for numeric aggregates that require sumX2.
5011 : : */
5012 : : Datum
9630 5013 : 428 : numeric_accum(PG_FUNCTION_ARGS)
5014 : : {
5015 : : NumericAggState *state;
5016 : :
4760 5017 [ + + ]: 428 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5018 : :
5019 : : /* Create the state data on the first call */
4613 5020 [ + + ]: 428 : if (state == NULL)
5021 : 116 : state = makeNumericAggState(fcinfo, true);
5022 : :
5023 [ + + ]: 428 : if (!PG_ARGISNULL(1))
4760 5024 : 416 : do_numeric_accum(state, PG_GETARG_NUMERIC(1));
5025 : :
5026 : 428 : PG_RETURN_POINTER(state);
5027 : : }
5028 : :
5029 : : /*
5030 : : * Generic combine function for numeric aggregates which require sumX2
5031 : : */
5032 : : Datum
3889 rhaas@postgresql.org 5033 : 24 : numeric_combine(PG_FUNCTION_ARGS)
5034 : : {
5035 : : NumericAggState *state1;
5036 : : NumericAggState *state2;
5037 : : MemoryContext agg_context;
5038 : : MemoryContext old_context;
5039 : :
5040 [ - + ]: 24 : if (!AggCheckCallContext(fcinfo, &agg_context))
3889 rhaas@postgresql.org 5041 [ # # ]:UBC 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5042 : :
3889 rhaas@postgresql.org 5043 [ + + ]:CBC 24 : state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5044 [ + - ]: 24 : state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
5045 : :
5046 [ - + ]: 24 : if (state2 == NULL)
5047 : : {
5048 : : /*
5049 : : * NULL state2 is easy, just return state1, which we know is already
5050 : : * in the agg_context
5051 : : */
110 tgl@sss.pgh.pa.us 5052 [ # # ]:UBC 0 : if (state1 == NULL)
5053 : 0 : PG_RETURN_NULL();
3889 rhaas@postgresql.org 5054 : 0 : PG_RETURN_POINTER(state1);
5055 : : }
5056 : :
5057 : : /* manually copy all fields from state2 to state1 */
3889 rhaas@postgresql.org 5058 [ + + ]:CBC 24 : if (state1 == NULL)
5059 : : {
5060 : 12 : old_context = MemoryContextSwitchTo(agg_context);
5061 : :
3810 tgl@sss.pgh.pa.us 5062 : 12 : state1 = makeNumericAggStateCurrentContext(true);
3889 rhaas@postgresql.org 5063 : 12 : state1->N = state2->N;
5064 : 12 : state1->NaNcount = state2->NaNcount;
2320 tgl@sss.pgh.pa.us 5065 : 12 : state1->pInfcount = state2->pInfcount;
5066 : 12 : state1->nInfcount = state2->nInfcount;
3889 rhaas@postgresql.org 5067 : 12 : state1->maxScale = state2->maxScale;
5068 : 12 : state1->maxScaleCount = state2->maxScaleCount;
5069 : :
3739 heikki.linnakangas@i 5070 : 12 : accum_sum_copy(&state1->sumX, &state2->sumX);
5071 : 12 : accum_sum_copy(&state1->sumX2, &state2->sumX2);
5072 : :
3889 rhaas@postgresql.org 5073 : 12 : MemoryContextSwitchTo(old_context);
5074 : :
5075 : 12 : PG_RETURN_POINTER(state1);
5076 : : }
5077 : :
2361 tgl@sss.pgh.pa.us 5078 : 12 : state1->N += state2->N;
5079 : 12 : state1->NaNcount += state2->NaNcount;
2320 5080 : 12 : state1->pInfcount += state2->pInfcount;
5081 : 12 : state1->nInfcount += state2->nInfcount;
5082 : :
3889 rhaas@postgresql.org 5083 [ + - ]: 12 : if (state2->N > 0)
5084 : : {
5085 : : /*
5086 : : * These are currently only needed for moving aggregates, but let's do
5087 : : * the right thing anyway...
5088 : : */
5089 [ - + ]: 12 : if (state2->maxScale > state1->maxScale)
5090 : : {
3889 rhaas@postgresql.org 5091 :UBC 0 : state1->maxScale = state2->maxScale;
5092 : 0 : state1->maxScaleCount = state2->maxScaleCount;
5093 : : }
3889 rhaas@postgresql.org 5094 [ + - ]:CBC 12 : else if (state2->maxScale == state1->maxScale)
5095 : 12 : state1->maxScaleCount += state2->maxScaleCount;
5096 : :
5097 : : /* The rest of this needs to work in the aggregate context */
5098 : 12 : old_context = MemoryContextSwitchTo(agg_context);
5099 : :
5100 : : /* Accumulate sums */
3739 heikki.linnakangas@i 5101 : 12 : accum_sum_combine(&state1->sumX, &state2->sumX);
5102 : 12 : accum_sum_combine(&state1->sumX2, &state2->sumX2);
5103 : :
3889 rhaas@postgresql.org 5104 : 12 : MemoryContextSwitchTo(old_context);
5105 : : }
5106 : 12 : PG_RETURN_POINTER(state1);
5107 : : }
5108 : :
5109 : : /*
5110 : : * Generic transition function for numeric aggregates that don't require sumX2.
5111 : : */
5112 : : Datum
7224 bruce@momjian.us 5113 : 1248516 : numeric_avg_accum(PG_FUNCTION_ARGS)
5114 : : {
5115 : : NumericAggState *state;
5116 : :
4760 tgl@sss.pgh.pa.us 5117 [ + + ]: 1248516 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5118 : :
5119 : : /* Create the state data on the first call */
4613 5120 [ + + ]: 1248516 : if (state == NULL)
5121 : 113926 : state = makeNumericAggState(fcinfo, false);
5122 : :
5123 [ + + ]: 1248516 : if (!PG_ARGISNULL(1))
4760 5124 : 1248476 : do_numeric_accum(state, PG_GETARG_NUMERIC(1));
5125 : :
4613 5126 : 1248516 : PG_RETURN_POINTER(state);
5127 : : }
5128 : :
5129 : : /*
5130 : : * Combine function for numeric aggregates which don't require sumX2
5131 : : */
5132 : : Datum
3889 rhaas@postgresql.org 5133 : 16 : numeric_avg_combine(PG_FUNCTION_ARGS)
5134 : : {
5135 : : NumericAggState *state1;
5136 : : NumericAggState *state2;
5137 : : MemoryContext agg_context;
5138 : : MemoryContext old_context;
5139 : :
5140 [ - + ]: 16 : if (!AggCheckCallContext(fcinfo, &agg_context))
3889 rhaas@postgresql.org 5141 [ # # ]:UBC 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5142 : :
3889 rhaas@postgresql.org 5143 [ + + ]:CBC 16 : state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5144 [ + - ]: 16 : state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
5145 : :
5146 [ - + ]: 16 : if (state2 == NULL)
5147 : : {
5148 : : /*
5149 : : * NULL state2 is easy, just return state1, which we know is already
5150 : : * in the agg_context
5151 : : */
110 tgl@sss.pgh.pa.us 5152 [ # # ]:UBC 0 : if (state1 == NULL)
5153 : 0 : PG_RETURN_NULL();
3889 rhaas@postgresql.org 5154 : 0 : PG_RETURN_POINTER(state1);
5155 : : }
5156 : :
5157 : : /* manually copy all fields from state2 to state1 */
3889 rhaas@postgresql.org 5158 [ + + ]:CBC 16 : if (state1 == NULL)
5159 : : {
5160 : 4 : old_context = MemoryContextSwitchTo(agg_context);
5161 : :
3810 tgl@sss.pgh.pa.us 5162 : 4 : state1 = makeNumericAggStateCurrentContext(false);
3889 rhaas@postgresql.org 5163 : 4 : state1->N = state2->N;
5164 : 4 : state1->NaNcount = state2->NaNcount;
2320 tgl@sss.pgh.pa.us 5165 : 4 : state1->pInfcount = state2->pInfcount;
5166 : 4 : state1->nInfcount = state2->nInfcount;
3889 rhaas@postgresql.org 5167 : 4 : state1->maxScale = state2->maxScale;
5168 : 4 : state1->maxScaleCount = state2->maxScaleCount;
5169 : :
3739 heikki.linnakangas@i 5170 : 4 : accum_sum_copy(&state1->sumX, &state2->sumX);
5171 : :
3889 rhaas@postgresql.org 5172 : 4 : MemoryContextSwitchTo(old_context);
5173 : :
5174 : 4 : PG_RETURN_POINTER(state1);
5175 : : }
5176 : :
2361 tgl@sss.pgh.pa.us 5177 : 12 : state1->N += state2->N;
5178 : 12 : state1->NaNcount += state2->NaNcount;
2320 5179 : 12 : state1->pInfcount += state2->pInfcount;
5180 : 12 : state1->nInfcount += state2->nInfcount;
5181 : :
3889 rhaas@postgresql.org 5182 [ + - ]: 12 : if (state2->N > 0)
5183 : : {
5184 : : /*
5185 : : * These are currently only needed for moving aggregates, but let's do
5186 : : * the right thing anyway...
5187 : : */
5188 [ - + ]: 12 : if (state2->maxScale > state1->maxScale)
5189 : : {
3889 rhaas@postgresql.org 5190 :UBC 0 : state1->maxScale = state2->maxScale;
5191 : 0 : state1->maxScaleCount = state2->maxScaleCount;
5192 : : }
3889 rhaas@postgresql.org 5193 [ + - ]:CBC 12 : else if (state2->maxScale == state1->maxScale)
5194 : 12 : state1->maxScaleCount += state2->maxScaleCount;
5195 : :
5196 : : /* The rest of this needs to work in the aggregate context */
5197 : 12 : old_context = MemoryContextSwitchTo(agg_context);
5198 : :
5199 : : /* Accumulate sums */
3739 heikki.linnakangas@i 5200 : 12 : accum_sum_combine(&state1->sumX, &state2->sumX);
5201 : :
3889 rhaas@postgresql.org 5202 : 12 : MemoryContextSwitchTo(old_context);
5203 : : }
5204 : 12 : PG_RETURN_POINTER(state1);
5205 : : }
5206 : :
5207 : : /*
5208 : : * numeric_avg_serialize
5209 : : * Serialize NumericAggState for numeric aggregates that don't require
5210 : : * sumX2.
5211 : : */
5212 : : Datum
5213 : 16 : numeric_avg_serialize(PG_FUNCTION_ARGS)
5214 : : {
5215 : : NumericAggState *state;
5216 : : StringInfoData buf;
5217 : : bytea *result;
5218 : : NumericVar tmp_var;
5219 : :
5220 : : /* Ensure we disallow calling when not in aggregate context */
5221 [ - + ]: 16 : if (!AggCheckCallContext(fcinfo, NULL))
3889 rhaas@postgresql.org 5222 [ # # ]:UBC 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5223 : :
3889 rhaas@postgresql.org 5224 :CBC 16 : state = (NumericAggState *) PG_GETARG_POINTER(0);
5225 : :
3739 heikki.linnakangas@i 5226 : 16 : init_var(&tmp_var);
5227 : :
3889 rhaas@postgresql.org 5228 : 16 : pq_begintypsend(&buf);
5229 : :
5230 : : /* N */
5231 : 16 : pq_sendint64(&buf, state->N);
5232 : :
5233 : : /* sumX */
1972 dean.a.rasheed@gmail 5234 : 16 : accum_sum_final(&state->sumX, &tmp_var);
5235 : 16 : numericvar_serialize(&buf, &tmp_var);
5236 : :
5237 : : /* maxScale */
3335 andres@anarazel.de 5238 : 16 : pq_sendint32(&buf, state->maxScale);
5239 : :
5240 : : /* maxScaleCount */
3889 rhaas@postgresql.org 5241 : 16 : pq_sendint64(&buf, state->maxScaleCount);
5242 : :
5243 : : /* NaNcount */
5244 : 16 : pq_sendint64(&buf, state->NaNcount);
5245 : :
5246 : : /* pInfcount */
2320 tgl@sss.pgh.pa.us 5247 : 16 : pq_sendint64(&buf, state->pInfcount);
5248 : :
5249 : : /* nInfcount */
5250 : 16 : pq_sendint64(&buf, state->nInfcount);
5251 : :
3889 rhaas@postgresql.org 5252 : 16 : result = pq_endtypsend(&buf);
5253 : :
1972 dean.a.rasheed@gmail 5254 : 16 : free_var(&tmp_var);
5255 : :
3889 rhaas@postgresql.org 5256 : 16 : PG_RETURN_BYTEA_P(result);
5257 : : }
5258 : :
5259 : : /*
5260 : : * numeric_avg_deserialize
5261 : : * Deserialize bytea into NumericAggState for numeric aggregates that
5262 : : * don't require sumX2.
5263 : : */
5264 : : Datum
5265 : 16 : numeric_avg_deserialize(PG_FUNCTION_ARGS)
5266 : : {
5267 : : bytea *sstate;
5268 : : NumericAggState *result;
5269 : : StringInfoData buf;
5270 : : NumericVar tmp_var;
5271 : :
5272 [ - + ]: 16 : if (!AggCheckCallContext(fcinfo, NULL))
3889 rhaas@postgresql.org 5273 [ # # ]:UBC 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5274 : :
3548 noah@leadboat.com 5275 :CBC 16 : sstate = PG_GETARG_BYTEA_PP(0);
5276 : :
1972 dean.a.rasheed@gmail 5277 : 16 : init_var(&tmp_var);
5278 : :
5279 : : /*
5280 : : * Initialize a StringInfo so that we can "receive" it using the standard
5281 : : * recv-function infrastructure.
5282 : : */
1128 drowley@postgresql.o 5283 : 16 : initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
5284 : 16 : VARSIZE_ANY_EXHDR(sstate));
5285 : :
3810 tgl@sss.pgh.pa.us 5286 : 16 : result = makeNumericAggStateCurrentContext(false);
5287 : :
5288 : : /* N */
3889 rhaas@postgresql.org 5289 : 16 : result->N = pq_getmsgint64(&buf);
5290 : :
5291 : : /* sumX */
1972 dean.a.rasheed@gmail 5292 : 16 : numericvar_deserialize(&buf, &tmp_var);
3739 heikki.linnakangas@i 5293 : 16 : accum_sum_add(&(result->sumX), &tmp_var);
5294 : :
5295 : : /* maxScale */
3889 rhaas@postgresql.org 5296 : 16 : result->maxScale = pq_getmsgint(&buf, 4);
5297 : :
5298 : : /* maxScaleCount */
5299 : 16 : result->maxScaleCount = pq_getmsgint64(&buf);
5300 : :
5301 : : /* NaNcount */
5302 : 16 : result->NaNcount = pq_getmsgint64(&buf);
5303 : :
5304 : : /* pInfcount */
2320 tgl@sss.pgh.pa.us 5305 : 16 : result->pInfcount = pq_getmsgint64(&buf);
5306 : :
5307 : : /* nInfcount */
5308 : 16 : result->nInfcount = pq_getmsgint64(&buf);
5309 : :
3889 rhaas@postgresql.org 5310 : 16 : pq_getmsgend(&buf);
5311 : :
1972 dean.a.rasheed@gmail 5312 : 16 : free_var(&tmp_var);
5313 : :
3889 rhaas@postgresql.org 5314 : 16 : PG_RETURN_POINTER(result);
5315 : : }
5316 : :
5317 : : /*
5318 : : * numeric_serialize
5319 : : * Serialization function for NumericAggState for numeric aggregates that
5320 : : * require sumX2.
5321 : : */
5322 : : Datum
5323 : 24 : numeric_serialize(PG_FUNCTION_ARGS)
5324 : : {
5325 : : NumericAggState *state;
5326 : : StringInfoData buf;
5327 : : bytea *result;
5328 : : NumericVar tmp_var;
5329 : :
5330 : : /* Ensure we disallow calling when not in aggregate context */
5331 [ - + ]: 24 : if (!AggCheckCallContext(fcinfo, NULL))
3889 rhaas@postgresql.org 5332 [ # # ]:UBC 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5333 : :
3889 rhaas@postgresql.org 5334 :CBC 24 : state = (NumericAggState *) PG_GETARG_POINTER(0);
5335 : :
3739 heikki.linnakangas@i 5336 : 24 : init_var(&tmp_var);
5337 : :
3889 rhaas@postgresql.org 5338 : 24 : pq_begintypsend(&buf);
5339 : :
5340 : : /* N */
5341 : 24 : pq_sendint64(&buf, state->N);
5342 : :
5343 : : /* sumX */
1972 dean.a.rasheed@gmail 5344 : 24 : accum_sum_final(&state->sumX, &tmp_var);
5345 : 24 : numericvar_serialize(&buf, &tmp_var);
5346 : :
5347 : : /* sumX2 */
5348 : 24 : accum_sum_final(&state->sumX2, &tmp_var);
5349 : 24 : numericvar_serialize(&buf, &tmp_var);
5350 : :
5351 : : /* maxScale */
3335 andres@anarazel.de 5352 : 24 : pq_sendint32(&buf, state->maxScale);
5353 : :
5354 : : /* maxScaleCount */
3889 rhaas@postgresql.org 5355 : 24 : pq_sendint64(&buf, state->maxScaleCount);
5356 : :
5357 : : /* NaNcount */
5358 : 24 : pq_sendint64(&buf, state->NaNcount);
5359 : :
5360 : : /* pInfcount */
2320 tgl@sss.pgh.pa.us 5361 : 24 : pq_sendint64(&buf, state->pInfcount);
5362 : :
5363 : : /* nInfcount */
5364 : 24 : pq_sendint64(&buf, state->nInfcount);
5365 : :
3889 rhaas@postgresql.org 5366 : 24 : result = pq_endtypsend(&buf);
5367 : :
1972 dean.a.rasheed@gmail 5368 : 24 : free_var(&tmp_var);
5369 : :
3889 rhaas@postgresql.org 5370 : 24 : PG_RETURN_BYTEA_P(result);
5371 : : }
5372 : :
5373 : : /*
5374 : : * numeric_deserialize
5375 : : * Deserialization function for NumericAggState for numeric aggregates that
5376 : : * require sumX2.
5377 : : */
5378 : : Datum
5379 : 24 : numeric_deserialize(PG_FUNCTION_ARGS)
5380 : : {
5381 : : bytea *sstate;
5382 : : NumericAggState *result;
5383 : : StringInfoData buf;
5384 : : NumericVar tmp_var;
5385 : :
5386 [ - + ]: 24 : if (!AggCheckCallContext(fcinfo, NULL))
3889 rhaas@postgresql.org 5387 [ # # ]:UBC 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5388 : :
3548 noah@leadboat.com 5389 :CBC 24 : sstate = PG_GETARG_BYTEA_PP(0);
5390 : :
1972 dean.a.rasheed@gmail 5391 : 24 : init_var(&tmp_var);
5392 : :
5393 : : /*
5394 : : * Initialize a StringInfo so that we can "receive" it using the standard
5395 : : * recv-function infrastructure.
5396 : : */
1128 drowley@postgresql.o 5397 : 24 : initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
5398 : 24 : VARSIZE_ANY_EXHDR(sstate));
5399 : :
60 5400 : 24 : result = makeNumericAggStateCurrentContext(true);
5401 : :
5402 : : /* N */
3889 rhaas@postgresql.org 5403 : 24 : result->N = pq_getmsgint64(&buf);
5404 : :
5405 : : /* sumX */
1972 dean.a.rasheed@gmail 5406 : 24 : numericvar_deserialize(&buf, &tmp_var);
5407 : 24 : accum_sum_add(&(result->sumX), &tmp_var);
5408 : :
5409 : : /* sumX2 */
5410 : 24 : numericvar_deserialize(&buf, &tmp_var);
5411 : 24 : accum_sum_add(&(result->sumX2), &tmp_var);
5412 : :
5413 : : /* maxScale */
3889 rhaas@postgresql.org 5414 : 24 : result->maxScale = pq_getmsgint(&buf, 4);
5415 : :
5416 : : /* maxScaleCount */
5417 : 24 : result->maxScaleCount = pq_getmsgint64(&buf);
5418 : :
5419 : : /* NaNcount */
5420 : 24 : result->NaNcount = pq_getmsgint64(&buf);
5421 : :
5422 : : /* pInfcount */
2320 tgl@sss.pgh.pa.us 5423 : 24 : result->pInfcount = pq_getmsgint64(&buf);
5424 : :
5425 : : /* nInfcount */
5426 : 24 : result->nInfcount = pq_getmsgint64(&buf);
5427 : :
3889 rhaas@postgresql.org 5428 : 24 : pq_getmsgend(&buf);
5429 : :
1972 dean.a.rasheed@gmail 5430 : 24 : free_var(&tmp_var);
5431 : :
3889 rhaas@postgresql.org 5432 : 24 : PG_RETURN_POINTER(result);
5433 : : }
5434 : :
5435 : : /*
5436 : : * Generic inverse transition function for numeric aggregates
5437 : : * (with or without requirement for X^2).
5438 : : */
5439 : : Datum
4613 tgl@sss.pgh.pa.us 5440 : 152 : numeric_accum_inv(PG_FUNCTION_ARGS)
5441 : : {
5442 : : NumericAggState *state;
5443 : :
5444 [ + - ]: 152 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5445 : :
5446 : : /* Should not get here with no state */
5447 [ - + ]: 152 : if (state == NULL)
4613 tgl@sss.pgh.pa.us 5448 [ # # ]:UBC 0 : elog(ERROR, "numeric_accum_inv called with NULL state");
5449 : :
4613 tgl@sss.pgh.pa.us 5450 [ + + ]:CBC 152 : if (!PG_ARGISNULL(1))
5451 : : {
5452 : : /* If we fail to perform the inverse transition, return NULL */
5453 [ + + ]: 132 : if (!do_numeric_discard(state, PG_GETARG_NUMERIC(1)))
5454 : 4 : PG_RETURN_NULL();
5455 : : }
5456 : :
4760 5457 : 148 : PG_RETURN_POINTER(state);
5458 : : }
5459 : :
5460 : :
5461 : : /*
5462 : : * Integer data types in general use Numeric accumulators to share code and
5463 : : * avoid risk of overflow. However for performance reasons optimized
5464 : : * special-purpose accumulator routines are used when possible:
5465 : : *
5466 : : * For 16-bit and 32-bit inputs, N and sum(X) fit into 64-bit, so 64-bit
5467 : : * accumulators are used for SUM and AVG of these data types.
5468 : : *
5469 : : * For 16-bit and 32-bit inputs, sum(X^2) fits into 128-bit, so 128-bit
5470 : : * accumulators are used for STDDEV_POP, STDDEV_SAMP, VAR_POP, and VAR_SAMP of
5471 : : * these data types.
5472 : : *
5473 : : * For 64-bit inputs, sum(X) fits into 128-bit, so a 128-bit accumulator is
5474 : : * used for SUM(int8) and AVG(int8).
5475 : : */
5476 : :
5477 : : typedef struct Int128AggState
5478 : : {
5479 : : bool calcSumX2; /* if true, calculate sumX2 */
5480 : : int64 N; /* count of processed numbers */
5481 : : INT128 sumX; /* sum of processed numbers */
5482 : : INT128 sumX2; /* sum of squares of processed numbers */
5483 : : } Int128AggState;
5484 : :
5485 : : /*
5486 : : * Prepare state data for a 128-bit aggregate function that needs to compute
5487 : : * sum, count and optionally sum of squares of the input.
5488 : : */
5489 : : static Int128AggState *
4271 andres@anarazel.de 5490 : 648 : makeInt128AggState(FunctionCallInfo fcinfo, bool calcSumX2)
5491 : : {
5492 : : Int128AggState *state;
5493 : : MemoryContext agg_context;
5494 : : MemoryContext old_context;
5495 : :
5496 [ - + ]: 648 : if (!AggCheckCallContext(fcinfo, &agg_context))
4271 andres@anarazel.de 5497 [ # # ]:UBC 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5498 : :
4271 andres@anarazel.de 5499 :CBC 648 : old_context = MemoryContextSwitchTo(agg_context);
5500 : :
353 michael@paquier.xyz 5501 : 648 : state = palloc0_object(Int128AggState);
4271 andres@anarazel.de 5502 : 648 : state->calcSumX2 = calcSumX2;
5503 : :
5504 : 648 : MemoryContextSwitchTo(old_context);
5505 : :
5506 : 648 : return state;
5507 : : }
5508 : :
5509 : : /*
5510 : : * Like makeInt128AggState(), but allocate the state in the current memory
5511 : : * context.
5512 : : */
5513 : : static Int128AggState *
3810 tgl@sss.pgh.pa.us 5514 : 41 : makeInt128AggStateCurrentContext(bool calcSumX2)
5515 : : {
5516 : : Int128AggState *state;
5517 : :
353 michael@paquier.xyz 5518 : 41 : state = palloc0_object(Int128AggState);
3810 tgl@sss.pgh.pa.us 5519 : 41 : state->calcSumX2 = calcSumX2;
5520 : :
5521 : 41 : return state;
5522 : : }
5523 : :
5524 : : /*
5525 : : * Accumulate a new input value for 128-bit aggregate functions.
5526 : : */
5527 : : static void
478 dean.a.rasheed@gmail 5528 : 371457 : do_int128_accum(Int128AggState *state, int64 newval)
5529 : : {
4271 andres@anarazel.de 5530 [ + + ]: 371457 : if (state->calcSumX2)
478 dean.a.rasheed@gmail 5531 : 161240 : int128_add_int64_mul_int64(&state->sumX2, newval, newval);
5532 : :
5533 : 371457 : int128_add_int64(&state->sumX, newval);
4271 andres@anarazel.de 5534 : 371457 : state->N++;
5535 : 371457 : }
5536 : :
5537 : : /*
5538 : : * Remove an input value from the aggregated state.
5539 : : */
5540 : : static void
478 dean.a.rasheed@gmail 5541 : 208 : do_int128_discard(Int128AggState *state, int64 newval)
5542 : : {
4271 andres@anarazel.de 5543 [ + + ]: 208 : if (state->calcSumX2)
478 dean.a.rasheed@gmail 5544 : 192 : int128_sub_int64_mul_int64(&state->sumX2, newval, newval);
5545 : :
5546 : 208 : int128_sub_int64(&state->sumX, newval);
4271 andres@anarazel.de 5547 : 208 : state->N--;
5548 : 208 : }
5549 : :
5550 : : Datum
9630 tgl@sss.pgh.pa.us 5551 : 132 : int2_accum(PG_FUNCTION_ARGS)
5552 : : {
5553 : : Int128AggState *state;
5554 : :
478 dean.a.rasheed@gmail 5555 [ + + ]: 132 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5556 : :
5557 : : /* Create the state data on the first call */
4613 tgl@sss.pgh.pa.us 5558 [ + + ]: 132 : if (state == NULL)
478 dean.a.rasheed@gmail 5559 : 24 : state = makeInt128AggState(fcinfo, true);
5560 : :
4760 tgl@sss.pgh.pa.us 5561 [ + + ]: 132 : if (!PG_ARGISNULL(1))
478 dean.a.rasheed@gmail 5562 : 120 : do_int128_accum(state, PG_GETARG_INT16(1));
5563 : :
4760 tgl@sss.pgh.pa.us 5564 : 132 : PG_RETURN_POINTER(state);
5565 : : }
5566 : :
5567 : : Datum
9630 5568 : 161132 : int4_accum(PG_FUNCTION_ARGS)
5569 : : {
5570 : : Int128AggState *state;
5571 : :
478 dean.a.rasheed@gmail 5572 [ + + ]: 161132 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5573 : :
5574 : : /* Create the state data on the first call */
4613 tgl@sss.pgh.pa.us 5575 [ + + ]: 161132 : if (state == NULL)
478 dean.a.rasheed@gmail 5576 : 50 : state = makeInt128AggState(fcinfo, true);
5577 : :
4760 tgl@sss.pgh.pa.us 5578 [ + + ]: 161132 : if (!PG_ARGISNULL(1))
478 dean.a.rasheed@gmail 5579 : 161120 : do_int128_accum(state, PG_GETARG_INT32(1));
5580 : :
4760 tgl@sss.pgh.pa.us 5581 : 161132 : PG_RETURN_POINTER(state);
5582 : : }
5583 : :
5584 : : Datum
9630 5585 : 160132 : int8_accum(PG_FUNCTION_ARGS)
5586 : : {
5587 : : NumericAggState *state;
5588 : :
4760 5589 [ + + ]: 160132 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5590 : :
5591 : : /* Create the state data on the first call */
4613 5592 [ + + ]: 160132 : if (state == NULL)
5593 : 40 : state = makeNumericAggState(fcinfo, true);
5594 : :
4760 5595 [ + + ]: 160132 : if (!PG_ARGISNULL(1))
2271 peter@eisentraut.org 5596 : 160120 : do_numeric_accum(state, int64_to_numeric(PG_GETARG_INT64(1)));
5597 : :
4760 tgl@sss.pgh.pa.us 5598 : 160132 : PG_RETURN_POINTER(state);
5599 : : }
5600 : :
5601 : : /*
5602 : : * Combine function for Int128AggState for aggregates which require sumX2
5603 : : */
5604 : : Datum
3889 rhaas@postgresql.org 5605 : 16 : numeric_poly_combine(PG_FUNCTION_ARGS)
5606 : : {
5607 : : Int128AggState *state1;
5608 : : Int128AggState *state2;
5609 : : MemoryContext agg_context;
5610 : : MemoryContext old_context;
5611 : :
5612 [ - + ]: 16 : if (!AggCheckCallContext(fcinfo, &agg_context))
3889 rhaas@postgresql.org 5613 [ # # ]:UBC 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5614 : :
478 dean.a.rasheed@gmail 5615 [ + + ]:CBC 16 : state1 = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5616 [ + - ]: 16 : state2 = PG_ARGISNULL(1) ? NULL : (Int128AggState *) PG_GETARG_POINTER(1);
5617 : :
3889 rhaas@postgresql.org 5618 [ - + ]: 16 : if (state2 == NULL)
5619 : : {
5620 : : /*
5621 : : * NULL state2 is easy, just return state1, which we know is already
5622 : : * in the agg_context
5623 : : */
110 tgl@sss.pgh.pa.us 5624 [ # # ]:UBC 0 : if (state1 == NULL)
5625 : 0 : PG_RETURN_NULL();
3889 rhaas@postgresql.org 5626 : 0 : PG_RETURN_POINTER(state1);
5627 : : }
5628 : :
5629 : : /* manually copy all fields from state2 to state1 */
3889 rhaas@postgresql.org 5630 [ + + ]:CBC 16 : if (state1 == NULL)
5631 : : {
5632 : 4 : old_context = MemoryContextSwitchTo(agg_context);
5633 : :
478 dean.a.rasheed@gmail 5634 : 4 : state1 = makeInt128AggState(fcinfo, true);
3889 rhaas@postgresql.org 5635 : 4 : state1->N = state2->N;
5636 : 4 : state1->sumX = state2->sumX;
5637 : 4 : state1->sumX2 = state2->sumX2;
5638 : :
5639 : 4 : MemoryContextSwitchTo(old_context);
5640 : :
5641 : 4 : PG_RETURN_POINTER(state1);
5642 : : }
5643 : :
5644 [ + - ]: 12 : if (state2->N > 0)
5645 : : {
5646 : 12 : state1->N += state2->N;
478 dean.a.rasheed@gmail 5647 : 12 : int128_add_int128(&state1->sumX, state2->sumX);
5648 : 12 : int128_add_int128(&state1->sumX2, state2->sumX2);
5649 : : }
5650 : 12 : PG_RETURN_POINTER(state1);
5651 : : }
5652 : :
5653 : : /*
5654 : : * int128_serialize - serialize a 128-bit integer to binary format
5655 : : */
5656 : : static inline void
5657 : 57 : int128_serialize(StringInfo buf, INT128 val)
5658 : : {
5659 : 57 : pq_sendint64(buf, PG_INT128_HI_INT64(val));
5660 : 57 : pq_sendint64(buf, PG_INT128_LO_UINT64(val));
5661 : 57 : }
5662 : :
5663 : : /*
5664 : : * int128_deserialize - deserialize binary format to a 128-bit integer.
5665 : : */
5666 : : static inline INT128
5667 : 57 : int128_deserialize(StringInfo buf)
5668 : : {
5669 : 57 : int64 hi = pq_getmsgint64(buf);
5670 : 57 : uint64 lo = pq_getmsgint64(buf);
5671 : :
5672 : 57 : return make_int128(hi, lo);
5673 : : }
5674 : :
5675 : : /*
5676 : : * numeric_poly_serialize
5677 : : * Serialize Int128AggState into bytea for aggregate functions which
5678 : : * require sumX2.
5679 : : */
5680 : : Datum
3889 rhaas@postgresql.org 5681 : 16 : numeric_poly_serialize(PG_FUNCTION_ARGS)
5682 : : {
5683 : : Int128AggState *state;
5684 : : StringInfoData buf;
5685 : : bytea *result;
5686 : :
5687 : : /* Ensure we disallow calling when not in aggregate context */
5688 [ - + ]: 16 : if (!AggCheckCallContext(fcinfo, NULL))
3889 rhaas@postgresql.org 5689 [ # # ]:UBC 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5690 : :
478 dean.a.rasheed@gmail 5691 :CBC 16 : state = (Int128AggState *) PG_GETARG_POINTER(0);
5692 : :
3889 rhaas@postgresql.org 5693 : 16 : pq_begintypsend(&buf);
5694 : :
5695 : : /* N */
5696 : 16 : pq_sendint64(&buf, state->N);
5697 : :
5698 : : /* sumX */
478 dean.a.rasheed@gmail 5699 : 16 : int128_serialize(&buf, state->sumX);
5700 : :
5701 : : /* sumX2 */
5702 : 16 : int128_serialize(&buf, state->sumX2);
5703 : :
3889 rhaas@postgresql.org 5704 : 16 : result = pq_endtypsend(&buf);
5705 : :
5706 : 16 : PG_RETURN_BYTEA_P(result);
5707 : : }
5708 : :
5709 : : /*
5710 : : * numeric_poly_deserialize
5711 : : * Deserialize Int128AggState from bytea for aggregate functions which
5712 : : * require sumX2.
5713 : : */
5714 : : Datum
5715 : 16 : numeric_poly_deserialize(PG_FUNCTION_ARGS)
5716 : : {
5717 : : bytea *sstate;
5718 : : Int128AggState *result;
5719 : : StringInfoData buf;
5720 : :
5721 [ - + ]: 16 : if (!AggCheckCallContext(fcinfo, NULL))
3889 rhaas@postgresql.org 5722 [ # # ]:UBC 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5723 : :
3548 noah@leadboat.com 5724 :CBC 16 : sstate = PG_GETARG_BYTEA_PP(0);
5725 : :
5726 : : /*
5727 : : * Initialize a StringInfo so that we can "receive" it using the standard
5728 : : * recv-function infrastructure.
5729 : : */
1128 drowley@postgresql.o 5730 : 16 : initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
5731 : 16 : VARSIZE_ANY_EXHDR(sstate));
5732 : :
60 5733 : 16 : result = makeInt128AggStateCurrentContext(true);
5734 : :
5735 : : /* N */
3889 rhaas@postgresql.org 5736 : 16 : result->N = pq_getmsgint64(&buf);
5737 : :
5738 : : /* sumX */
478 dean.a.rasheed@gmail 5739 : 16 : result->sumX = int128_deserialize(&buf);
5740 : :
5741 : : /* sumX2 */
5742 : 16 : result->sumX2 = int128_deserialize(&buf);
5743 : :
3889 rhaas@postgresql.org 5744 : 16 : pq_getmsgend(&buf);
5745 : :
5746 : 16 : PG_RETURN_POINTER(result);
5747 : : }
5748 : :
5749 : : /*
5750 : : * Transition function for int8 input when we don't need sumX2.
5751 : : */
5752 : : Datum
7224 bruce@momjian.us 5753 : 213245 : int8_avg_accum(PG_FUNCTION_ARGS)
5754 : : {
5755 : : Int128AggState *state;
5756 : :
478 dean.a.rasheed@gmail 5757 [ + + ]: 213245 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5758 : :
5759 : : /* Create the state data on the first call */
4613 tgl@sss.pgh.pa.us 5760 [ + + ]: 213245 : if (state == NULL)
478 dean.a.rasheed@gmail 5761 : 562 : state = makeInt128AggState(fcinfo, false);
5762 : :
4760 tgl@sss.pgh.pa.us 5763 [ + + ]: 213245 : if (!PG_ARGISNULL(1))
478 dean.a.rasheed@gmail 5764 : 210217 : do_int128_accum(state, PG_GETARG_INT64(1));
5765 : :
4613 tgl@sss.pgh.pa.us 5766 : 213245 : PG_RETURN_POINTER(state);
5767 : : }
5768 : :
5769 : : /*
5770 : : * Combine function for Int128AggState for aggregates which don't require
5771 : : * sumX2
5772 : : */
5773 : : Datum
3889 rhaas@postgresql.org 5774 : 25 : int8_avg_combine(PG_FUNCTION_ARGS)
5775 : : {
5776 : : Int128AggState *state1;
5777 : : Int128AggState *state2;
5778 : : MemoryContext agg_context;
5779 : : MemoryContext old_context;
5780 : :
5781 [ - + ]: 25 : if (!AggCheckCallContext(fcinfo, &agg_context))
3889 rhaas@postgresql.org 5782 [ # # ]:UBC 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5783 : :
478 dean.a.rasheed@gmail 5784 [ + + ]:CBC 25 : state1 = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5785 [ + - ]: 25 : state2 = PG_ARGISNULL(1) ? NULL : (Int128AggState *) PG_GETARG_POINTER(1);
5786 : :
3889 rhaas@postgresql.org 5787 [ - + ]: 25 : if (state2 == NULL)
5788 : : {
5789 : : /*
5790 : : * NULL state2 is easy, just return state1, which we know is already
5791 : : * in the agg_context
5792 : : */
110 tgl@sss.pgh.pa.us 5793 [ # # ]:UBC 0 : if (state1 == NULL)
5794 : 0 : PG_RETURN_NULL();
3889 rhaas@postgresql.org 5795 : 0 : PG_RETURN_POINTER(state1);
5796 : : }
5797 : :
5798 : : /* manually copy all fields from state2 to state1 */
3889 rhaas@postgresql.org 5799 [ + + ]:CBC 25 : if (state1 == NULL)
5800 : : {
5801 : 8 : old_context = MemoryContextSwitchTo(agg_context);
5802 : :
478 dean.a.rasheed@gmail 5803 : 8 : state1 = makeInt128AggState(fcinfo, false);
3889 rhaas@postgresql.org 5804 : 8 : state1->N = state2->N;
5805 : 8 : state1->sumX = state2->sumX;
5806 : :
5807 : 8 : MemoryContextSwitchTo(old_context);
5808 : :
5809 : 8 : PG_RETURN_POINTER(state1);
5810 : : }
5811 : :
5812 [ + - ]: 17 : if (state2->N > 0)
5813 : : {
5814 : 17 : state1->N += state2->N;
478 dean.a.rasheed@gmail 5815 : 17 : int128_add_int128(&state1->sumX, state2->sumX);
5816 : : }
3889 rhaas@postgresql.org 5817 : 17 : PG_RETURN_POINTER(state1);
5818 : : }
5819 : :
5820 : : /*
5821 : : * int8_avg_serialize
5822 : : * Serialize Int128AggState into bytea for aggregate functions which
5823 : : * don't require sumX2.
5824 : : */
5825 : : Datum
5826 : 25 : int8_avg_serialize(PG_FUNCTION_ARGS)
5827 : : {
5828 : : Int128AggState *state;
5829 : : StringInfoData buf;
5830 : : bytea *result;
5831 : :
5832 : : /* Ensure we disallow calling when not in aggregate context */
5833 [ - + ]: 25 : if (!AggCheckCallContext(fcinfo, NULL))
3889 rhaas@postgresql.org 5834 [ # # ]:UBC 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5835 : :
478 dean.a.rasheed@gmail 5836 :CBC 25 : state = (Int128AggState *) PG_GETARG_POINTER(0);
5837 : :
3889 rhaas@postgresql.org 5838 : 25 : pq_begintypsend(&buf);
5839 : :
5840 : : /* N */
5841 : 25 : pq_sendint64(&buf, state->N);
5842 : :
5843 : : /* sumX */
478 dean.a.rasheed@gmail 5844 : 25 : int128_serialize(&buf, state->sumX);
5845 : :
3889 rhaas@postgresql.org 5846 : 25 : result = pq_endtypsend(&buf);
5847 : :
5848 : 25 : PG_RETURN_BYTEA_P(result);
5849 : : }
5850 : :
5851 : : /*
5852 : : * int8_avg_deserialize
5853 : : * Deserialize Int128AggState from bytea for aggregate functions which
5854 : : * don't require sumX2.
5855 : : */
5856 : : Datum
5857 : 25 : int8_avg_deserialize(PG_FUNCTION_ARGS)
5858 : : {
5859 : : bytea *sstate;
5860 : : Int128AggState *result;
5861 : : StringInfoData buf;
5862 : :
5863 [ - + ]: 25 : if (!AggCheckCallContext(fcinfo, NULL))
3889 rhaas@postgresql.org 5864 [ # # ]:UBC 0 : elog(ERROR, "aggregate function called in non-aggregate context");
5865 : :
3548 noah@leadboat.com 5866 :CBC 25 : sstate = PG_GETARG_BYTEA_PP(0);
5867 : :
5868 : : /*
5869 : : * Initialize a StringInfo so that we can "receive" it using the standard
5870 : : * recv-function infrastructure.
5871 : : */
1128 drowley@postgresql.o 5872 : 25 : initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
5873 : 25 : VARSIZE_ANY_EXHDR(sstate));
5874 : :
478 dean.a.rasheed@gmail 5875 : 25 : result = makeInt128AggStateCurrentContext(false);
5876 : :
5877 : : /* N */
3889 rhaas@postgresql.org 5878 : 25 : result->N = pq_getmsgint64(&buf);
5879 : :
5880 : : /* sumX */
478 dean.a.rasheed@gmail 5881 : 25 : result->sumX = int128_deserialize(&buf);
5882 : :
3889 rhaas@postgresql.org 5883 : 25 : pq_getmsgend(&buf);
5884 : :
5885 : 25 : PG_RETURN_POINTER(result);
5886 : : }
5887 : :
5888 : : /*
5889 : : * Inverse transition functions to go with the above.
5890 : : */
5891 : :
5892 : : Datum
4613 tgl@sss.pgh.pa.us 5893 : 108 : int2_accum_inv(PG_FUNCTION_ARGS)
5894 : : {
5895 : : Int128AggState *state;
5896 : :
478 dean.a.rasheed@gmail 5897 [ + - ]: 108 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5898 : :
5899 : : /* Should not get here with no state */
4613 tgl@sss.pgh.pa.us 5900 [ - + ]: 108 : if (state == NULL)
4613 tgl@sss.pgh.pa.us 5901 [ # # ]:UBC 0 : elog(ERROR, "int2_accum_inv called with NULL state");
5902 : :
4613 tgl@sss.pgh.pa.us 5903 [ + + ]:CBC 108 : if (!PG_ARGISNULL(1))
478 dean.a.rasheed@gmail 5904 : 96 : do_int128_discard(state, PG_GETARG_INT16(1));
5905 : :
4760 tgl@sss.pgh.pa.us 5906 : 108 : PG_RETURN_POINTER(state);
5907 : : }
5908 : :
5909 : : Datum
4613 5910 : 108 : int4_accum_inv(PG_FUNCTION_ARGS)
5911 : : {
5912 : : Int128AggState *state;
5913 : :
478 dean.a.rasheed@gmail 5914 [ + - ]: 108 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5915 : :
5916 : : /* Should not get here with no state */
4613 tgl@sss.pgh.pa.us 5917 [ - + ]: 108 : if (state == NULL)
4613 tgl@sss.pgh.pa.us 5918 [ # # ]:UBC 0 : elog(ERROR, "int4_accum_inv called with NULL state");
5919 : :
4613 tgl@sss.pgh.pa.us 5920 [ + + ]:CBC 108 : if (!PG_ARGISNULL(1))
478 dean.a.rasheed@gmail 5921 : 96 : do_int128_discard(state, PG_GETARG_INT32(1));
5922 : :
4613 tgl@sss.pgh.pa.us 5923 : 108 : PG_RETURN_POINTER(state);
5924 : : }
5925 : :
5926 : : Datum
5927 : 108 : int8_accum_inv(PG_FUNCTION_ARGS)
5928 : : {
5929 : : NumericAggState *state;
5930 : :
5931 [ + - ]: 108 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5932 : :
5933 : : /* Should not get here with no state */
5934 [ - + ]: 108 : if (state == NULL)
4613 tgl@sss.pgh.pa.us 5935 [ # # ]:UBC 0 : elog(ERROR, "int8_accum_inv called with NULL state");
5936 : :
4613 tgl@sss.pgh.pa.us 5937 [ + + ]:CBC 108 : if (!PG_ARGISNULL(1))
5938 : : {
5939 : : /* Should never fail, all inputs have dscale 0 */
2271 peter@eisentraut.org 5940 [ - + ]: 96 : if (!do_numeric_discard(state, int64_to_numeric(PG_GETARG_INT64(1))))
4613 tgl@sss.pgh.pa.us 5941 [ # # ]:UBC 0 : elog(ERROR, "do_numeric_discard failed unexpectedly");
5942 : : }
5943 : :
4613 tgl@sss.pgh.pa.us 5944 :CBC 108 : PG_RETURN_POINTER(state);
5945 : : }
5946 : :
5947 : : Datum
4271 andres@anarazel.de 5948 : 24 : int8_avg_accum_inv(PG_FUNCTION_ARGS)
5949 : : {
5950 : : Int128AggState *state;
5951 : :
478 dean.a.rasheed@gmail 5952 [ + - ]: 24 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5953 : :
5954 : : /* Should not get here with no state */
4271 andres@anarazel.de 5955 [ - + ]: 24 : if (state == NULL)
4271 andres@anarazel.de 5956 [ # # ]:UBC 0 : elog(ERROR, "int8_avg_accum_inv called with NULL state");
5957 : :
4271 andres@anarazel.de 5958 [ + + ]:CBC 24 : if (!PG_ARGISNULL(1))
478 dean.a.rasheed@gmail 5959 : 16 : do_int128_discard(state, PG_GETARG_INT64(1));
5960 : :
4271 andres@anarazel.de 5961 : 24 : PG_RETURN_POINTER(state);
5962 : : }
5963 : :
5964 : : Datum
5965 : 701 : numeric_poly_sum(PG_FUNCTION_ARGS)
5966 : : {
5967 : : Int128AggState *state;
5968 : : Numeric res;
5969 : : NumericVar result;
5970 : :
478 dean.a.rasheed@gmail 5971 [ + + ]: 701 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5972 : :
5973 : : /* If there were no non-null inputs, return NULL */
4271 andres@anarazel.de 5974 [ + + + + ]: 701 : if (state == NULL || state->N == 0)
5975 : 16 : PG_RETURN_NULL();
5976 : :
5977 : 685 : init_var(&result);
5978 : :
5979 : 685 : int128_to_numericvar(state->sumX, &result);
5980 : :
5981 : 685 : res = make_result(&result);
5982 : :
5983 : 685 : free_var(&result);
5984 : :
5985 : 685 : PG_RETURN_NUMERIC(res);
5986 : : }
5987 : :
5988 : : Datum
5989 : 24 : numeric_poly_avg(PG_FUNCTION_ARGS)
5990 : : {
5991 : : Int128AggState *state;
5992 : : NumericVar result;
5993 : : Datum countd,
5994 : : sumd;
5995 : :
478 dean.a.rasheed@gmail 5996 [ + - ]: 24 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
5997 : :
5998 : : /* If there were no non-null inputs, return NULL */
4271 andres@anarazel.de 5999 [ + - + + ]: 24 : if (state == NULL || state->N == 0)
6000 : 12 : PG_RETURN_NULL();
6001 : :
6002 : 12 : init_var(&result);
6003 : :
6004 : 12 : int128_to_numericvar(state->sumX, &result);
6005 : :
2271 peter@eisentraut.org 6006 : 12 : countd = NumericGetDatum(int64_to_numeric(state->N));
4271 andres@anarazel.de 6007 : 12 : sumd = NumericGetDatum(make_result(&result));
6008 : :
6009 : 12 : free_var(&result);
6010 : :
6011 : 12 : PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumd, countd));
6012 : : }
6013 : :
6014 : : Datum
9630 tgl@sss.pgh.pa.us 6015 : 52 : numeric_avg(PG_FUNCTION_ARGS)
6016 : : {
6017 : : NumericAggState *state;
6018 : : Datum N_datum;
6019 : : Datum sumX_datum;
6020 : : NumericVar sumX_var;
6021 : :
4760 6022 [ + - ]: 52 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6023 : :
6024 : : /* If there were no non-null inputs, return NULL */
2320 6025 [ + - + + ]: 52 : if (state == NULL || NA_TOTAL_COUNT(state) == 0)
4760 6026 : 12 : PG_RETURN_NULL();
6027 : :
4589 bruce@momjian.us 6028 [ + + ]: 40 : if (state->NaNcount > 0) /* there was at least one NaN input */
4760 tgl@sss.pgh.pa.us 6029 : 4 : PG_RETURN_NUMERIC(make_result(&const_nan));
6030 : :
6031 : : /* adding plus and minus infinities gives NaN */
2320 6032 [ + + + + ]: 36 : if (state->pInfcount > 0 && state->nInfcount > 0)
6033 : 4 : PG_RETURN_NUMERIC(make_result(&const_nan));
6034 [ + + ]: 32 : if (state->pInfcount > 0)
6035 : 12 : PG_RETURN_NUMERIC(make_result(&const_pinf));
6036 [ + + ]: 20 : if (state->nInfcount > 0)
6037 : 4 : PG_RETURN_NUMERIC(make_result(&const_ninf));
6038 : :
2271 peter@eisentraut.org 6039 : 16 : N_datum = NumericGetDatum(int64_to_numeric(state->N));
6040 : :
3739 heikki.linnakangas@i 6041 : 16 : init_var(&sumX_var);
6042 : 16 : accum_sum_final(&state->sumX, &sumX_var);
6043 : 16 : sumX_datum = NumericGetDatum(make_result(&sumX_var));
6044 : 16 : free_var(&sumX_var);
6045 : :
4760 tgl@sss.pgh.pa.us 6046 : 16 : PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumX_datum, N_datum));
6047 : : }
6048 : :
6049 : : Datum
6050 : 113926 : numeric_sum(PG_FUNCTION_ARGS)
6051 : : {
6052 : : NumericAggState *state;
6053 : : NumericVar sumX_var;
6054 : : Numeric result;
6055 : :
6056 [ + - ]: 113926 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6057 : :
6058 : : /* If there were no non-null inputs, return NULL */
2320 6059 [ + - + + ]: 113926 : if (state == NULL || NA_TOTAL_COUNT(state) == 0)
9630 6060 : 12 : PG_RETURN_NULL();
6061 : :
4589 bruce@momjian.us 6062 [ + + ]: 113914 : if (state->NaNcount > 0) /* there was at least one NaN input */
4760 tgl@sss.pgh.pa.us 6063 : 12 : PG_RETURN_NUMERIC(make_result(&const_nan));
6064 : :
6065 : : /* adding plus and minus infinities gives NaN */
2320 6066 [ + + + + ]: 113902 : if (state->pInfcount > 0 && state->nInfcount > 0)
6067 : 4 : PG_RETURN_NUMERIC(make_result(&const_nan));
6068 [ + + ]: 113898 : if (state->pInfcount > 0)
6069 : 12 : PG_RETURN_NUMERIC(make_result(&const_pinf));
6070 [ + + ]: 113886 : if (state->nInfcount > 0)
6071 : 4 : PG_RETURN_NUMERIC(make_result(&const_ninf));
6072 : :
3739 heikki.linnakangas@i 6073 : 113882 : init_var(&sumX_var);
6074 : 113882 : accum_sum_final(&state->sumX, &sumX_var);
6075 : 113882 : result = make_result(&sumX_var);
6076 : 113882 : free_var(&sumX_var);
6077 : :
6078 : 113882 : PG_RETURN_NUMERIC(result);
6079 : : }
6080 : :
6081 : : /*
6082 : : * Workhorse routine for the standard deviance and variance
6083 : : * aggregates. 'state' is aggregate's transition state.
6084 : : * 'variance' specifies whether we should calculate the
6085 : : * variance or the standard deviation. 'sample' indicates whether the
6086 : : * caller is interested in the sample or the population
6087 : : * variance/stddev.
6088 : : *
6089 : : * If appropriate variance statistic is undefined for the input,
6090 : : * *is_null is set to true and NULL is returned.
6091 : : */
6092 : : static Numeric
4760 tgl@sss.pgh.pa.us 6093 : 654 : numeric_stddev_internal(NumericAggState *state,
6094 : : bool variance, bool sample,
6095 : : bool *is_null)
6096 : : {
6097 : : Numeric res;
6098 : : NumericVar vN,
6099 : : vsumX,
6100 : : vsumX2,
6101 : : vNminus1;
6102 : : int64 totCount;
6103 : : int rscale;
6104 : :
6105 : : /*
6106 : : * Sample stddev and variance are undefined when N <= 1; population stddev
6107 : : * is undefined when N == 0. Return NULL in either case (note that NaNs
6108 : : * and infinities count as normal inputs for this purpose).
6109 : : */
2320 6110 [ + - - + ]: 654 : if (state == NULL || (totCount = NA_TOTAL_COUNT(state)) == 0)
6111 : : {
2359 tgl@sss.pgh.pa.us 6112 :UBC 0 : *is_null = true;
6113 : 0 : return NULL;
6114 : : }
6115 : :
2359 tgl@sss.pgh.pa.us 6116 [ + + + + ]:CBC 654 : if (sample && totCount <= 1)
6117 : : {
4760 6118 : 88 : *is_null = true;
6119 : 88 : return NULL;
6120 : : }
6121 : :
7568 neilc@samurai.com 6122 : 566 : *is_null = false;
6123 : :
6124 : : /*
6125 : : * Deal with NaN and infinity cases. By analogy to the behavior of the
6126 : : * float8 functions, any infinity input produces NaN output.
6127 : : */
2320 tgl@sss.pgh.pa.us 6128 [ + + + + : 566 : if (state->NaNcount > 0 || state->pInfcount > 0 || state->nInfcount > 0)
+ + ]
7568 neilc@samurai.com 6129 : 36 : return make_result(&const_nan);
6130 : :
6131 : : /* OK, normal calculation applies */
4760 tgl@sss.pgh.pa.us 6132 : 530 : init_var(&vN);
6133 : 530 : init_var(&vsumX);
6134 : 530 : init_var(&vsumX2);
6135 : :
4271 andres@anarazel.de 6136 : 530 : int64_to_numericvar(state->N, &vN);
3739 heikki.linnakangas@i 6137 : 530 : accum_sum_final(&(state->sumX), &vsumX);
6138 : 530 : accum_sum_final(&(state->sumX2), &vsumX2);
6139 : :
8622 tgl@sss.pgh.pa.us 6140 : 530 : init_var(&vNminus1);
6141 : 530 : sub_var(&vN, &const_one, &vNminus1);
6142 : :
6143 : : /* compute rscale for mul_var calls */
8653 6144 : 530 : rscale = vsumX.dscale * 2;
6145 : :
6146 : 530 : mul_var(&vsumX, &vsumX, &vsumX, rscale); /* vsumX = sumX * sumX */
3447 6147 : 530 : mul_var(&vN, &vsumX2, &vsumX2, rscale); /* vsumX2 = N * sumX2 */
7360 bruce@momjian.us 6148 : 530 : sub_var(&vsumX2, &vsumX, &vsumX2); /* N * sumX2 - sumX * sumX */
6149 : :
9118 tgl@sss.pgh.pa.us 6150 [ + + ]: 530 : if (cmp_var(&vsumX2, &const_zero) <= 0)
6151 : : {
6152 : : /* Watch out for roundoff error producing a negative numerator */
6153 : 50 : res = make_result(&const_zero);
6154 : : }
6155 : : else
6156 : : {
7082 6157 [ + + ]: 480 : if (sample)
3447 6158 : 328 : mul_var(&vN, &vNminus1, &vNminus1, 0); /* N * (N - 1) */
6159 : : else
6953 bruce@momjian.us 6160 : 152 : mul_var(&vN, &vN, &vNminus1, 0); /* N * N */
8653 tgl@sss.pgh.pa.us 6161 : 480 : rscale = select_div_scale(&vsumX2, &vNminus1);
785 dean.a.rasheed@gmail 6162 : 480 : div_var(&vsumX2, &vNminus1, &vsumX, rscale, true, true); /* variance */
7568 neilc@samurai.com 6163 [ + + ]: 480 : if (!variance)
7360 bruce@momjian.us 6164 : 252 : sqrt_var(&vsumX, &vsumX, rscale); /* stddev */
6165 : :
9118 tgl@sss.pgh.pa.us 6166 : 480 : res = make_result(&vsumX);
6167 : : }
6168 : :
9630 6169 : 530 : free_var(&vNminus1);
6170 : 530 : free_var(&vsumX);
6171 : 530 : free_var(&vsumX2);
6172 : :
7568 neilc@samurai.com 6173 : 530 : return res;
6174 : : }
6175 : :
6176 : : Datum
6177 : 120 : numeric_var_samp(PG_FUNCTION_ARGS)
6178 : : {
6179 : : NumericAggState *state;
6180 : : Numeric res;
6181 : : bool is_null;
6182 : :
4760 tgl@sss.pgh.pa.us 6183 [ + - ]: 120 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6184 : :
6185 : 120 : res = numeric_stddev_internal(state, true, true, &is_null);
6186 : :
7568 neilc@samurai.com 6187 [ + + ]: 120 : if (is_null)
8622 tgl@sss.pgh.pa.us 6188 : 28 : PG_RETURN_NULL();
6189 : : else
7568 neilc@samurai.com 6190 : 92 : PG_RETURN_NUMERIC(res);
6191 : : }
6192 : :
6193 : : Datum
6194 : 116 : numeric_stddev_samp(PG_FUNCTION_ARGS)
6195 : : {
6196 : : NumericAggState *state;
6197 : : Numeric res;
6198 : : bool is_null;
6199 : :
4760 tgl@sss.pgh.pa.us 6200 [ + - ]: 116 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6201 : :
6202 : 116 : res = numeric_stddev_internal(state, false, true, &is_null);
6203 : :
7568 neilc@samurai.com 6204 [ + + ]: 116 : if (is_null)
6205 : 28 : PG_RETURN_NULL();
6206 : : else
6207 : 88 : PG_RETURN_NUMERIC(res);
6208 : : }
6209 : :
6210 : : Datum
6211 : 76 : numeric_var_pop(PG_FUNCTION_ARGS)
6212 : : {
6213 : : NumericAggState *state;
6214 : : Numeric res;
6215 : : bool is_null;
6216 : :
4760 tgl@sss.pgh.pa.us 6217 [ + - ]: 76 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6218 : :
6219 : 76 : res = numeric_stddev_internal(state, true, false, &is_null);
6220 : :
7568 neilc@samurai.com 6221 [ - + ]: 76 : if (is_null)
7568 neilc@samurai.com 6222 :UBC 0 : PG_RETURN_NULL();
6223 : : else
7568 neilc@samurai.com 6224 :CBC 76 : PG_RETURN_NUMERIC(res);
6225 : : }
6226 : :
6227 : : Datum
6228 : 64 : numeric_stddev_pop(PG_FUNCTION_ARGS)
6229 : : {
6230 : : NumericAggState *state;
6231 : : Numeric res;
6232 : : bool is_null;
6233 : :
4760 tgl@sss.pgh.pa.us 6234 [ + - ]: 64 : state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
6235 : :
6236 : 64 : res = numeric_stddev_internal(state, false, false, &is_null);
6237 : :
7568 neilc@samurai.com 6238 [ - + ]: 64 : if (is_null)
7568 neilc@samurai.com 6239 :UBC 0 : PG_RETURN_NULL();
6240 : : else
7568 neilc@samurai.com 6241 :CBC 64 : PG_RETURN_NUMERIC(res);
6242 : : }
6243 : :
6244 : : static Numeric
4271 andres@anarazel.de 6245 : 278 : numeric_poly_stddev_internal(Int128AggState *state,
6246 : : bool variance, bool sample,
6247 : : bool *is_null)
6248 : : {
6249 : : NumericAggState numstate;
6250 : : Numeric res;
6251 : :
6252 : : /* Initialize an empty agg state */
3739 heikki.linnakangas@i 6253 : 278 : memset(&numstate, 0, sizeof(NumericAggState));
6254 : :
4271 andres@anarazel.de 6255 [ + - ]: 278 : if (state)
6256 : : {
6257 : : NumericVar tmp_var;
6258 : :
6259 : 278 : numstate.N = state->N;
6260 : :
3739 heikki.linnakangas@i 6261 : 278 : init_var(&tmp_var);
6262 : :
6263 : 278 : int128_to_numericvar(state->sumX, &tmp_var);
6264 : 278 : accum_sum_add(&numstate.sumX, &tmp_var);
6265 : :
6266 : 278 : int128_to_numericvar(state->sumX2, &tmp_var);
6267 : 278 : accum_sum_add(&numstate.sumX2, &tmp_var);
6268 : :
6269 : 278 : free_var(&tmp_var);
6270 : : }
6271 : :
4271 andres@anarazel.de 6272 : 278 : res = numeric_stddev_internal(&numstate, variance, sample, is_null);
6273 : :
3739 heikki.linnakangas@i 6274 [ + - ]: 278 : if (numstate.sumX.ndigits > 0)
6275 : : {
6276 : 278 : pfree(numstate.sumX.pos_digits);
6277 : 278 : pfree(numstate.sumX.neg_digits);
6278 : : }
6279 [ + - ]: 278 : if (numstate.sumX2.ndigits > 0)
6280 : : {
6281 : 278 : pfree(numstate.sumX2.pos_digits);
6282 : 278 : pfree(numstate.sumX2.neg_digits);
6283 : : }
6284 : :
4271 andres@anarazel.de 6285 : 278 : return res;
6286 : : }
6287 : :
6288 : : Datum
6289 : 84 : numeric_poly_var_samp(PG_FUNCTION_ARGS)
6290 : : {
6291 : : Int128AggState *state;
6292 : : Numeric res;
6293 : : bool is_null;
6294 : :
478 dean.a.rasheed@gmail 6295 [ + - ]: 84 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
6296 : :
4271 andres@anarazel.de 6297 : 84 : res = numeric_poly_stddev_internal(state, true, true, &is_null);
6298 : :
6299 [ + + ]: 84 : if (is_null)
6300 : 16 : PG_RETURN_NULL();
6301 : : else
6302 : 68 : PG_RETURN_NUMERIC(res);
6303 : : }
6304 : :
6305 : : Datum
6306 : 106 : numeric_poly_stddev_samp(PG_FUNCTION_ARGS)
6307 : : {
6308 : : Int128AggState *state;
6309 : : Numeric res;
6310 : : bool is_null;
6311 : :
478 dean.a.rasheed@gmail 6312 [ + - ]: 106 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
6313 : :
4271 andres@anarazel.de 6314 : 106 : res = numeric_poly_stddev_internal(state, false, true, &is_null);
6315 : :
6316 [ + + ]: 106 : if (is_null)
6317 : 16 : PG_RETURN_NULL();
6318 : : else
6319 : 90 : PG_RETURN_NUMERIC(res);
6320 : : }
6321 : :
6322 : : Datum
6323 : 40 : numeric_poly_var_pop(PG_FUNCTION_ARGS)
6324 : : {
6325 : : Int128AggState *state;
6326 : : Numeric res;
6327 : : bool is_null;
6328 : :
478 dean.a.rasheed@gmail 6329 [ + - ]: 40 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
6330 : :
4271 andres@anarazel.de 6331 : 40 : res = numeric_poly_stddev_internal(state, true, false, &is_null);
6332 : :
6333 [ - + ]: 40 : if (is_null)
4271 andres@anarazel.de 6334 :UBC 0 : PG_RETURN_NULL();
6335 : : else
4271 andres@anarazel.de 6336 :CBC 40 : PG_RETURN_NUMERIC(res);
6337 : : }
6338 : :
6339 : : Datum
6340 : 48 : numeric_poly_stddev_pop(PG_FUNCTION_ARGS)
6341 : : {
6342 : : Int128AggState *state;
6343 : : Numeric res;
6344 : : bool is_null;
6345 : :
478 dean.a.rasheed@gmail 6346 [ + - ]: 48 : state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
6347 : :
4271 andres@anarazel.de 6348 : 48 : res = numeric_poly_stddev_internal(state, false, false, &is_null);
6349 : :
6350 [ - + ]: 48 : if (is_null)
4271 andres@anarazel.de 6351 :UBC 0 : PG_RETURN_NULL();
6352 : : else
4271 andres@anarazel.de 6353 :CBC 48 : PG_RETURN_NUMERIC(res);
6354 : : }
6355 : :
6356 : : /*
6357 : : * SUM transition functions for integer datatypes.
6358 : : *
6359 : : * To avoid overflow, we use accumulators wider than the input datatype.
6360 : : * A Numeric accumulator is needed for int8 input; for int4 and int2
6361 : : * inputs, we use int8 accumulators which should be sufficient for practical
6362 : : * purposes. (The latter two therefore don't really belong in this file,
6363 : : * but we keep them here anyway.)
6364 : : *
6365 : : * Because SQL defines the SUM() of no values to be NULL, not zero,
6366 : : * the initial condition of the transition data value needs to be NULL. This
6367 : : * means we can't rely on ExecAgg to automatically insert the first non-null
6368 : : * data value into the transition data: it doesn't know how to do the type
6369 : : * conversion. The upshot is that these routines have to be marked non-strict
6370 : : * and handle substitution of the first non-null input themselves.
6371 : : *
6372 : : * Note: these functions are used only in plain aggregation mode.
6373 : : * In moving-aggregate mode, we use intX_avg_accum and intX_avg_accum_inv.
6374 : : */
6375 : :
6376 : : Datum
9630 tgl@sss.pgh.pa.us 6377 : 16 : int2_sum(PG_FUNCTION_ARGS)
6378 : : {
6379 : : int64 oldsum;
6380 : : int64 newval;
6381 : :
31 drowley@postgresql.o 6382 [ - + ]:GNC 16 : if (PG_ARGISNULL(1))
6383 : : {
6384 : : /* NULL value being aggregated, so return state unchanged */
31 drowley@postgresql.o 6385 :UNC 0 : PG_RETURN_ARG(0);
6386 : : }
6387 : :
9630 tgl@sss.pgh.pa.us 6388 [ + + ]:CBC 16 : if (PG_ARGISNULL(0))
6389 : : {
6390 : : /* This is the first non-null input. */
31 drowley@postgresql.o 6391 :GNC 4 : PG_RETURN_INT64((int64) PG_GETARG_INT16(1));
6392 : : }
6393 : :
472 tgl@sss.pgh.pa.us 6394 :CBC 12 : oldsum = PG_GETARG_INT64(0);
6395 : :
6396 : : /* OK to do the addition. */
31 drowley@postgresql.o 6397 [ - + ]:GNC 12 : if (unlikely(pg_add_s64_overflow(oldsum, (int64) PG_GETARG_INT16(1),
6398 : : &newval)))
31 drowley@postgresql.o 6399 [ # # ]:UNC 0 : ereport(ERROR,
6400 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
6401 : : errmsg("bigint out of range")));
6402 : :
472 tgl@sss.pgh.pa.us 6403 :CBC 12 : PG_RETURN_INT64(newval);
6404 : : }
6405 : :
6406 : : Datum
9630 6407 : 3416740 : int4_sum(PG_FUNCTION_ARGS)
6408 : : {
6409 : : int64 oldsum;
6410 : : int64 newval;
6411 : :
31 drowley@postgresql.o 6412 [ + + ]:GNC 3416740 : if (PG_ARGISNULL(1))
6413 : : {
6414 : : /* NULL value being aggregated, so return state unchanged */
6415 : 21260 : PG_RETURN_ARG(0);
6416 : : }
6417 : :
9630 tgl@sss.pgh.pa.us 6418 [ + + ]:CBC 3395480 : if (PG_ARGISNULL(0))
6419 : : {
6420 : : /* This is the first non-null input. */
31 drowley@postgresql.o 6421 :GNC 128905 : PG_RETURN_INT64((int64) PG_GETARG_INT32(1));
6422 : : }
6423 : :
472 tgl@sss.pgh.pa.us 6424 :CBC 3266575 : oldsum = PG_GETARG_INT64(0);
6425 : :
6426 : : /* OK to do the addition. */
31 drowley@postgresql.o 6427 [ - + ]:GNC 3266575 : if (unlikely(pg_add_s64_overflow(oldsum, (int64) PG_GETARG_INT32(1),
6428 : : &newval)))
31 drowley@postgresql.o 6429 [ # # ]:UNC 0 : ereport(ERROR,
6430 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
6431 : : errmsg("bigint out of range")));
6432 : :
472 tgl@sss.pgh.pa.us 6433 :CBC 3266575 : PG_RETURN_INT64(newval);
6434 : : }
6435 : :
6436 : : /*
6437 : : * Note: this function is obsolete, it's no longer used for SUM(int8).
6438 : : */
6439 : : Datum
9630 tgl@sss.pgh.pa.us 6440 :UBC 0 : int8_sum(PG_FUNCTION_ARGS)
6441 : : {
6442 : : Numeric oldsum;
6443 : :
6444 [ # # ]: 0 : if (PG_ARGISNULL(0))
6445 : : {
6446 : : /* No non-null input seen so far... */
6447 [ # # ]: 0 : if (PG_ARGISNULL(1))
6448 : 0 : PG_RETURN_NULL(); /* still no non-null */
6449 : : /* This is the first non-null input. */
2271 peter@eisentraut.org 6450 : 0 : PG_RETURN_NUMERIC(int64_to_numeric(PG_GETARG_INT64(1)));
6451 : : }
6452 : :
9630 tgl@sss.pgh.pa.us 6453 : 0 : oldsum = PG_GETARG_NUMERIC(0);
6454 : :
6455 : : /* Leave sum unchanged if new input is null. */
6456 [ # # ]: 0 : if (PG_ARGISNULL(1))
6457 : 0 : PG_RETURN_NUMERIC(oldsum);
6458 : :
6459 : : /* OK to do the addition. */
9618 6460 : 0 : PG_RETURN_DATUM(DirectFunctionCall2(numeric_add,
6461 : : NumericGetDatum(oldsum),
6462 : : NumericGetDatum(int64_to_numeric(PG_GETARG_INT64(1)))));
6463 : : }
6464 : :
6465 : :
6466 : : /*
6467 : : * Routines for avg(int2) and avg(int4). The transition datatype
6468 : : * is a two-element int8 array, holding count and sum.
6469 : : *
6470 : : * These functions are also used for sum(int2) and sum(int4) when
6471 : : * operating in moving-aggregate mode, since for correct inverse transitions
6472 : : * we need to count the inputs.
6473 : : */
6474 : :
6475 : : typedef struct Int8TransTypeData
6476 : : {
6477 : : int64 count;
6478 : : int64 sum;
6479 : : } Int8TransTypeData;
6480 : :
6481 : : Datum
9237 tgl@sss.pgh.pa.us 6482 :CBC 28 : int2_avg_accum(PG_FUNCTION_ARGS)
6483 : : {
6484 : : ArrayType *transarray;
6485 : 28 : int16 newval = PG_GETARG_INT16(1);
6486 : : Int8TransTypeData *transdata;
6487 : : int64 newsum;
6488 : :
6489 : : /*
6490 : : * If we're invoked as an aggregate, we can cheat and modify our first
6491 : : * parameter in-place to reduce palloc overhead. Otherwise we need to make
6492 : : * a copy of it before scribbling on it.
6493 : : */
6137 6494 [ + - ]: 28 : if (AggCheckCallContext(fcinfo, NULL))
7908 neilc@samurai.com 6495 : 28 : transarray = PG_GETARG_ARRAYTYPE_P(0);
6496 : : else
7908 neilc@samurai.com 6497 :UBC 0 : transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6498 : :
7681 tgl@sss.pgh.pa.us 6499 [ + - - + ]:CBC 56 : if (ARR_HASNULL(transarray) ||
6500 : 28 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
8525 tgl@sss.pgh.pa.us 6501 [ # # ]:UBC 0 : elog(ERROR, "expected 2-element int8 array");
6502 : :
7908 neilc@samurai.com 6503 [ - + ]:CBC 28 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6504 : :
31 drowley@postgresql.o 6505 [ - + ]:GNC 28 : if (unlikely(pg_add_s64_overflow(transdata->sum, (int64) newval, &newsum)))
31 drowley@postgresql.o 6506 [ # # ]:UNC 0 : ereport(ERROR,
6507 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
6508 : : errmsg("bigint out of range")));
6509 : :
9237 tgl@sss.pgh.pa.us 6510 :CBC 28 : transdata->count++;
31 drowley@postgresql.o 6511 :GNC 28 : transdata->sum = newsum;
6512 : :
9237 tgl@sss.pgh.pa.us 6513 :CBC 28 : PG_RETURN_ARRAYTYPE_P(transarray);
6514 : : }
6515 : :
6516 : : Datum
6517 : 1744070 : int4_avg_accum(PG_FUNCTION_ARGS)
6518 : : {
6519 : : ArrayType *transarray;
6520 : 1744070 : int32 newval = PG_GETARG_INT32(1);
6521 : : Int8TransTypeData *transdata;
6522 : : int64 newsum;
6523 : :
6524 : : /*
6525 : : * If we're invoked as an aggregate, we can cheat and modify our first
6526 : : * parameter in-place to reduce palloc overhead. Otherwise we need to make
6527 : : * a copy of it before scribbling on it.
6528 : : */
6137 6529 [ + - ]: 1744070 : if (AggCheckCallContext(fcinfo, NULL))
7908 neilc@samurai.com 6530 : 1744070 : transarray = PG_GETARG_ARRAYTYPE_P(0);
6531 : : else
7908 neilc@samurai.com 6532 :UBC 0 : transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6533 : :
7681 tgl@sss.pgh.pa.us 6534 [ + - - + ]:CBC 3488140 : if (ARR_HASNULL(transarray) ||
6535 : 1744070 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
8525 tgl@sss.pgh.pa.us 6536 [ # # ]:UBC 0 : elog(ERROR, "expected 2-element int8 array");
6537 : :
7908 neilc@samurai.com 6538 [ - + ]:CBC 1744070 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6539 : :
31 drowley@postgresql.o 6540 [ - + ]:GNC 1744070 : if (unlikely(pg_add_s64_overflow(transdata->sum, (int64) newval, &newsum)))
31 drowley@postgresql.o 6541 [ # # ]:UNC 0 : ereport(ERROR,
6542 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
6543 : : errmsg("bigint out of range")));
6544 : :
9237 tgl@sss.pgh.pa.us 6545 :CBC 1744070 : transdata->count++;
31 drowley@postgresql.o 6546 :GNC 1744070 : transdata->sum = newsum;
6547 : :
9237 tgl@sss.pgh.pa.us 6548 :CBC 1744070 : PG_RETURN_ARRAYTYPE_P(transarray);
6549 : : }
6550 : :
6551 : : Datum
3889 rhaas@postgresql.org 6552 : 6903 : int4_avg_combine(PG_FUNCTION_ARGS)
6553 : : {
6554 : : ArrayType *transarray1;
6555 : : ArrayType *transarray2;
6556 : : Int8TransTypeData *state1;
6557 : : Int8TransTypeData *state2;
6558 : : int64 newsum;
6559 : :
6560 [ - + ]: 6903 : if (!AggCheckCallContext(fcinfo, NULL))
3889 rhaas@postgresql.org 6561 [ # # ]:UBC 0 : elog(ERROR, "aggregate function called in non-aggregate context");
6562 : :
3889 rhaas@postgresql.org 6563 :CBC 6903 : transarray1 = PG_GETARG_ARRAYTYPE_P(0);
6564 : 6903 : transarray2 = PG_GETARG_ARRAYTYPE_P(1);
6565 : :
6566 [ + - - + ]: 13806 : if (ARR_HASNULL(transarray1) ||
6567 : 6903 : ARR_SIZE(transarray1) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
3889 rhaas@postgresql.org 6568 [ # # ]:UBC 0 : elog(ERROR, "expected 2-element int8 array");
6569 : :
3889 rhaas@postgresql.org 6570 [ + - - + ]:CBC 13806 : if (ARR_HASNULL(transarray2) ||
6571 : 6903 : ARR_SIZE(transarray2) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
3889 rhaas@postgresql.org 6572 [ # # ]:UBC 0 : elog(ERROR, "expected 2-element int8 array");
6573 : :
3889 rhaas@postgresql.org 6574 [ - + ]:CBC 6903 : state1 = (Int8TransTypeData *) ARR_DATA_PTR(transarray1);
6575 [ - + ]: 6903 : state2 = (Int8TransTypeData *) ARR_DATA_PTR(transarray2);
6576 : :
31 drowley@postgresql.o 6577 [ - + ]:GNC 6903 : if (unlikely(pg_add_s64_overflow(state1->sum, state2->sum, &newsum)))
31 drowley@postgresql.o 6578 [ # # ]:UNC 0 : ereport(ERROR,
6579 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
6580 : : errmsg("bigint out of range")));
6581 : :
3889 rhaas@postgresql.org 6582 :CBC 6903 : state1->count += state2->count;
31 drowley@postgresql.o 6583 :GNC 6903 : state1->sum = newsum;
6584 : :
3889 rhaas@postgresql.org 6585 :CBC 6903 : PG_RETURN_ARRAYTYPE_P(transarray1);
6586 : : }
6587 : :
6588 : : Datum
4613 tgl@sss.pgh.pa.us 6589 : 8 : int2_avg_accum_inv(PG_FUNCTION_ARGS)
6590 : : {
6591 : : ArrayType *transarray;
6592 : 8 : int16 newval = PG_GETARG_INT16(1);
6593 : : Int8TransTypeData *transdata;
6594 : :
6595 : : /*
6596 : : * If we're invoked as an aggregate, we can cheat and modify our first
6597 : : * parameter in-place to reduce palloc overhead. Otherwise we need to make
6598 : : * a copy of it before scribbling on it.
6599 : : */
6600 [ + - ]: 8 : if (AggCheckCallContext(fcinfo, NULL))
6601 : 8 : transarray = PG_GETARG_ARRAYTYPE_P(0);
6602 : : else
4613 tgl@sss.pgh.pa.us 6603 :UBC 0 : transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6604 : :
4613 tgl@sss.pgh.pa.us 6605 [ + - - + ]:CBC 16 : if (ARR_HASNULL(transarray) ||
6606 : 8 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
4613 tgl@sss.pgh.pa.us 6607 [ # # ]:UBC 0 : elog(ERROR, "expected 2-element int8 array");
6608 : :
4613 tgl@sss.pgh.pa.us 6609 [ - + ]:CBC 8 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6610 : 8 : transdata->count--;
6611 : 8 : transdata->sum -= newval;
6612 : :
6613 : 8 : PG_RETURN_ARRAYTYPE_P(transarray);
6614 : : }
6615 : :
6616 : : Datum
6617 : 1000 : int4_avg_accum_inv(PG_FUNCTION_ARGS)
6618 : : {
6619 : : ArrayType *transarray;
6620 : 1000 : int32 newval = PG_GETARG_INT32(1);
6621 : : Int8TransTypeData *transdata;
6622 : :
6623 : : /*
6624 : : * If we're invoked as an aggregate, we can cheat and modify our first
6625 : : * parameter in-place to reduce palloc overhead. Otherwise we need to make
6626 : : * a copy of it before scribbling on it.
6627 : : */
6628 [ + - ]: 1000 : if (AggCheckCallContext(fcinfo, NULL))
6629 : 1000 : transarray = PG_GETARG_ARRAYTYPE_P(0);
6630 : : else
4613 tgl@sss.pgh.pa.us 6631 :UBC 0 : transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6632 : :
4613 tgl@sss.pgh.pa.us 6633 [ + - - + ]:CBC 2000 : if (ARR_HASNULL(transarray) ||
6634 : 1000 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
4613 tgl@sss.pgh.pa.us 6635 [ # # ]:UBC 0 : elog(ERROR, "expected 2-element int8 array");
6636 : :
4613 tgl@sss.pgh.pa.us 6637 [ - + ]:CBC 1000 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6638 : 1000 : transdata->count--;
6639 : 1000 : transdata->sum -= newval;
6640 : :
6641 : 1000 : PG_RETURN_ARRAYTYPE_P(transarray);
6642 : : }
6643 : :
6644 : : Datum
9237 6645 : 6817 : int8_avg(PG_FUNCTION_ARGS)
6646 : : {
6647 : 6817 : ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
6648 : : Int8TransTypeData *transdata;
6649 : : Datum countd,
6650 : : sumd;
6651 : :
7681 6652 [ + - - + ]: 13634 : if (ARR_HASNULL(transarray) ||
6653 : 6817 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
8525 tgl@sss.pgh.pa.us 6654 [ # # ]:UBC 0 : elog(ERROR, "expected 2-element int8 array");
9237 tgl@sss.pgh.pa.us 6655 [ - + ]:CBC 6817 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6656 : :
6657 : : /* SQL defines AVG of no values to be NULL */
6658 [ + + ]: 6817 : if (transdata->count == 0)
6659 : 73 : PG_RETURN_NULL();
6660 : :
2271 peter@eisentraut.org 6661 : 6744 : countd = NumericGetDatum(int64_to_numeric(transdata->count));
6662 : 6744 : sumd = NumericGetDatum(int64_to_numeric(transdata->sum));
6663 : :
9237 tgl@sss.pgh.pa.us 6664 : 6744 : PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumd, countd));
6665 : : }
6666 : :
6667 : : /*
6668 : : * SUM(int2) and SUM(int4) both return int8, so we can use this
6669 : : * final function for both.
6670 : : */
6671 : : Datum
4613 6672 : 2716 : int2int4_sum(PG_FUNCTION_ARGS)
6673 : : {
6674 : 2716 : ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
6675 : : Int8TransTypeData *transdata;
6676 : :
6677 [ + - - + ]: 5432 : if (ARR_HASNULL(transarray) ||
6678 : 2716 : ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
4613 tgl@sss.pgh.pa.us 6679 [ # # ]:UBC 0 : elog(ERROR, "expected 2-element int8 array");
4613 tgl@sss.pgh.pa.us 6680 [ - + ]:CBC 2716 : transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6681 : :
6682 : : /* SQL defines SUM of no values to be NULL */
6683 [ + + ]: 2716 : if (transdata->count == 0)
6684 : 404 : PG_RETURN_NULL();
6685 : :
6686 : 2312 : PG_RETURN_DATUM(Int64GetDatumFast(transdata->sum));
6687 : : }
6688 : :
6689 : :
6690 : : /* ----------------------------------------------------------------------
6691 : : *
6692 : : * Debug support
6693 : : *
6694 : : * ----------------------------------------------------------------------
6695 : : */
6696 : :
6697 : : #ifdef NUMERIC_DEBUG
6698 : :
6699 : : /*
6700 : : * dump_numeric() - Dump a value in the db storage format for debugging
6701 : : */
6702 : : static void
6703 : : dump_numeric(const char *str, Numeric num)
6704 : : {
6705 : : NumericDigit *digits = NUMERIC_DIGITS(num);
6706 : : int ndigits;
6707 : : int i;
6708 : :
6709 : : ndigits = NUMERIC_NDIGITS(num);
6710 : :
6711 : : printf("%s: NUMERIC w=%d d=%d ", str,
6712 : : NUMERIC_WEIGHT(num), NUMERIC_DSCALE(num));
6713 : : switch (NUMERIC_SIGN(num))
6714 : : {
6715 : : case NUMERIC_POS:
6716 : : printf("POS");
6717 : : break;
6718 : : case NUMERIC_NEG:
6719 : : printf("NEG");
6720 : : break;
6721 : : case NUMERIC_NAN:
6722 : : printf("NaN");
6723 : : break;
6724 : : case NUMERIC_PINF:
6725 : : printf("Infinity");
6726 : : break;
6727 : : case NUMERIC_NINF:
6728 : : printf("-Infinity");
6729 : : break;
6730 : : default:
6731 : : printf("SIGN=0x%x", NUMERIC_SIGN(num));
6732 : : break;
6733 : : }
6734 : :
6735 : : for (i = 0; i < ndigits; i++)
6736 : : printf(" %0*d", DEC_DIGITS, digits[i]);
6737 : : printf("\n");
6738 : : }
6739 : :
6740 : :
6741 : : /*
6742 : : * dump_var() - Dump a value in the variable format for debugging
6743 : : */
6744 : : static void
6745 : : dump_var(const char *str, NumericVar *var)
6746 : : {
6747 : : int i;
6748 : :
6749 : : printf("%s: VAR w=%d d=%d ", str, var->weight, var->dscale);
6750 : : switch (var->sign)
6751 : : {
6752 : : case NUMERIC_POS:
6753 : : printf("POS");
6754 : : break;
6755 : : case NUMERIC_NEG:
6756 : : printf("NEG");
6757 : : break;
6758 : : case NUMERIC_NAN:
6759 : : printf("NaN");
6760 : : break;
6761 : : case NUMERIC_PINF:
6762 : : printf("Infinity");
6763 : : break;
6764 : : case NUMERIC_NINF:
6765 : : printf("-Infinity");
6766 : : break;
6767 : : default:
6768 : : printf("SIGN=0x%x", var->sign);
6769 : : break;
6770 : : }
6771 : :
6772 : : for (i = 0; i < var->ndigits; i++)
6773 : : printf(" %0*d", DEC_DIGITS, var->digits[i]);
6774 : :
6775 : : printf("\n");
6776 : : }
6777 : : #endif /* NUMERIC_DEBUG */
6778 : :
6779 : :
6780 : : /* ----------------------------------------------------------------------
6781 : : *
6782 : : * Local functions follow
6783 : : *
6784 : : * In general, these do not support "special" (NaN or infinity) inputs;
6785 : : * callers should handle those possibilities first.
6786 : : * (There are one or two exceptions, noted in their header comments.)
6787 : : *
6788 : : * ----------------------------------------------------------------------
6789 : : */
6790 : :
6791 : :
6792 : : /*
6793 : : * alloc_var() -
6794 : : *
6795 : : * Allocate a digit buffer of ndigits digits (plus a spare digit for rounding)
6796 : : */
6797 : : static void
9811 6798 : 1492891 : alloc_var(NumericVar *var, int ndigits)
6799 : : {
6800 [ + + ]: 1492891 : digitbuf_free(var->buf);
6801 : 1492891 : var->buf = digitbuf_alloc(ndigits + 1);
8517 bruce@momjian.us 6802 : 1492891 : var->buf[0] = 0; /* spare digit for rounding */
9811 tgl@sss.pgh.pa.us 6803 : 1492891 : var->digits = var->buf + 1;
6804 : 1492891 : var->ndigits = ndigits;
10195 JanWieck@Yahoo.com 6805 : 1492891 : }
6806 : :
6807 : :
6808 : : /*
6809 : : * free_var() -
6810 : : *
6811 : : * Return the digit buffer of a variable to the free pool
6812 : : */
6813 : : static void
10049 bruce@momjian.us 6814 : 2837493 : free_var(NumericVar *var)
6815 : : {
9811 tgl@sss.pgh.pa.us 6816 [ + + ]: 2837493 : digitbuf_free(var->buf);
6817 : 2837493 : var->buf = NULL;
6818 : 2837493 : var->digits = NULL;
10195 JanWieck@Yahoo.com 6819 : 2837493 : var->sign = NUMERIC_NAN;
6820 : 2837493 : }
6821 : :
6822 : :
6823 : : /*
6824 : : * zero_var() -
6825 : : *
6826 : : * Set a variable to ZERO.
6827 : : * Note: its dscale is not touched.
6828 : : */
6829 : : static void
9811 tgl@sss.pgh.pa.us 6830 : 37868 : zero_var(NumericVar *var)
6831 : : {
6832 [ + + ]: 37868 : digitbuf_free(var->buf);
6833 : 37868 : var->buf = NULL;
6834 : 37868 : var->digits = NULL;
6835 : 37868 : var->ndigits = 0;
6836 : 37868 : var->weight = 0; /* by convention; doesn't really matter */
6837 : 37868 : var->sign = NUMERIC_POS; /* anything but NAN... */
10195 JanWieck@Yahoo.com 6838 : 37868 : }
6839 : :
6840 : :
6841 : : /*
6842 : : * set_var_from_str()
6843 : : *
6844 : : * Parse a string and put the number into a variable
6845 : : *
6846 : : * This function does not handle leading or trailing spaces. It returns
6847 : : * the end+1 position parsed into *endptr, so that caller can check for
6848 : : * trailing spaces/garbage if deemed necessary.
6849 : : *
6850 : : * cp is the place to actually start parsing; str is what to use in error
6851 : : * reports. (Typically cp would be the same except advanced over spaces.)
6852 : : *
6853 : : * Returns true on success, false on failure (if escontext points to an
6854 : : * ErrorSaveContext; otherwise errors are thrown).
6855 : : */
6856 : : static bool
1450 tgl@sss.pgh.pa.us 6857 : 160400 : set_var_from_str(const char *str, const char *cp,
6858 : : NumericVar *dest, const char **endptr,
6859 : : Node *escontext)
6860 : : {
3391 peter_e@gmx.net 6861 : 160400 : bool have_dp = false;
6862 : : int i;
6863 : : unsigned char *decdigits;
8653 tgl@sss.pgh.pa.us 6864 : 160400 : int sign = NUMERIC_POS;
6865 : 160400 : int dweight = -1;
6866 : : int ddigits;
6867 : 160400 : int dscale = 0;
6868 : : int weight;
6869 : : int ndigits;
6870 : : int offset;
6871 : : NumericDigit *digits;
6872 : :
6873 : : /*
6874 : : * We first parse the string to extract decimal digits and determine the
6875 : : * correct decimal weight. Then convert to NBASE representation.
6876 : : */
10195 JanWieck@Yahoo.com 6877 [ - + + ]: 160400 : switch (*cp)
6878 : : {
10049 bruce@momjian.us 6879 :UBC 0 : case '+':
8653 tgl@sss.pgh.pa.us 6880 : 0 : sign = NUMERIC_POS;
10049 bruce@momjian.us 6881 : 0 : cp++;
6882 : 0 : break;
6883 : :
10049 bruce@momjian.us 6884 :CBC 183 : case '-':
8653 tgl@sss.pgh.pa.us 6885 : 183 : sign = NUMERIC_NEG;
10049 bruce@momjian.us 6886 : 183 : cp++;
6887 : 183 : break;
6888 : : }
6889 : :
10195 JanWieck@Yahoo.com 6890 [ + + ]: 160400 : if (*cp == '.')
6891 : : {
3391 peter_e@gmx.net 6892 : 253 : have_dp = true;
10195 JanWieck@Yahoo.com 6893 : 253 : cp++;
6894 : : }
6895 : :
9491 tgl@sss.pgh.pa.us 6896 [ - + ]: 160400 : if (!isdigit((unsigned char) *cp))
1393 dean.a.rasheed@gmail 6897 :UBC 0 : goto invalid_syntax;
6898 : :
8517 bruce@momjian.us 6899 :CBC 160400 : decdigits = (unsigned char *) palloc(strlen(cp) + DEC_DIGITS * 2);
6900 : :
6901 : : /* leading padding for digit alignment later */
8653 tgl@sss.pgh.pa.us 6902 : 160400 : memset(decdigits, 0, DEC_DIGITS);
6903 : 160400 : i = DEC_DIGITS;
6904 : :
10195 JanWieck@Yahoo.com 6905 [ + + ]: 2389601 : while (*cp)
6906 : : {
9491 tgl@sss.pgh.pa.us 6907 [ + + ]: 2230313 : if (isdigit((unsigned char) *cp))
6908 : : {
8653 6909 : 2217107 : decdigits[i++] = *cp++ - '0';
9811 6910 [ + + ]: 2217107 : if (!have_dp)
8653 6911 : 2155109 : dweight++;
6912 : : else
6913 : 61998 : dscale++;
6914 : : }
9811 6915 [ + + ]: 13206 : else if (*cp == '.')
6916 : : {
6917 [ - + ]: 11986 : if (have_dp)
1393 dean.a.rasheed@gmail 6918 :UBC 0 : goto invalid_syntax;
3391 peter_e@gmx.net 6919 :CBC 11986 : have_dp = true;
9811 tgl@sss.pgh.pa.us 6920 : 11986 : cp++;
6921 : : /* decimal point must not be followed by underscore */
1393 dean.a.rasheed@gmail 6922 [ + + ]: 11986 : if (*cp == '_')
6923 : 4 : goto invalid_syntax;
6924 : : }
6925 [ + + ]: 1220 : else if (*cp == '_')
6926 : : {
6927 : : /* underscore must be followed by more digits */
6928 : 124 : cp++;
6929 [ + + ]: 124 : if (!isdigit((unsigned char) *cp))
6930 : 12 : goto invalid_syntax;
6931 : : }
6932 : : else
9811 tgl@sss.pgh.pa.us 6933 : 1096 : break;
6934 : : }
6935 : :
8653 6936 : 160384 : ddigits = i - DEC_DIGITS;
6937 : : /* trailing padding for digit alignment later */
8517 bruce@momjian.us 6938 : 160384 : memset(decdigits + i, 0, DEC_DIGITS - 1);
6939 : :
6940 : : /* Handle exponent, if any */
10195 JanWieck@Yahoo.com 6941 [ + + + + ]: 160384 : if (*cp == 'e' || *cp == 'E')
6942 : : {
1393 dean.a.rasheed@gmail 6943 : 1064 : int64 exponent = 0;
6944 : 1064 : bool neg = false;
6945 : :
6946 : : /*
6947 : : * At this point, dweight and dscale can't be more than about
6948 : : * INT_MAX/2 due to the MaxAllocSize limit on string length, so
6949 : : * constraining the exponent similarly should be enough to prevent
6950 : : * integer overflow in this function. If the value is too large to
6951 : : * fit in storage format, make_result() will complain about it later;
6952 : : * for consistency use the same ereport errcode/text as make_result().
6953 : : */
6954 : :
6955 : : /* exponent sign */
6956 : 1064 : cp++;
6957 [ + + ]: 1064 : if (*cp == '+')
6958 : 102 : cp++;
6959 [ + + ]: 962 : else if (*cp == '-')
6960 : : {
6961 : 461 : neg = true;
6962 : 461 : cp++;
6963 : : }
6964 : :
6965 : : /* exponent digits */
6966 [ + + ]: 1064 : if (!isdigit((unsigned char) *cp))
6967 : 4 : goto invalid_syntax;
6968 : :
6969 [ + + ]: 3733 : while (*cp)
6970 : : {
6971 [ + + ]: 2685 : if (isdigit((unsigned char) *cp))
6972 : : {
6973 : 2657 : exponent = exponent * 10 + (*cp++ - '0');
6974 [ + + ]: 2657 : if (exponent > PG_INT32_MAX / 2)
6975 : 4 : goto out_of_range;
6976 : : }
6977 [ + - ]: 28 : else if (*cp == '_')
6978 : : {
6979 : : /* underscore must be followed by more digits */
6980 : 28 : cp++;
6981 [ + + ]: 28 : if (!isdigit((unsigned char) *cp))
6982 : 8 : goto invalid_syntax;
6983 : : }
6984 : : else
1393 dean.a.rasheed@gmail 6985 :UBC 0 : break;
6986 : : }
6987 : :
1393 dean.a.rasheed@gmail 6988 [ + + ]:CBC 1048 : if (neg)
6989 : 461 : exponent = -exponent;
6990 : :
8653 tgl@sss.pgh.pa.us 6991 : 1048 : dweight += (int) exponent;
6992 : 1048 : dscale -= (int) exponent;
6993 [ + + ]: 1048 : if (dscale < 0)
6994 : 451 : dscale = 0;
6995 : : }
6996 : :
6997 : : /*
6998 : : * Okay, convert pure-decimal representation to base NBASE. First we need
6999 : : * to determine the converted weight and ndigits. offset is the number of
7000 : : * decimal zeroes to insert before the first given digit to have a
7001 : : * correctly aligned first NBASE digit.
7002 : : */
7003 [ + + ]: 160368 : if (dweight >= 0)
8517 bruce@momjian.us 7004 : 159723 : weight = (dweight + 1 + DEC_DIGITS - 1) / DEC_DIGITS - 1;
7005 : : else
7006 : 645 : weight = -((-dweight - 1) / DEC_DIGITS + 1);
8653 tgl@sss.pgh.pa.us 7007 : 160368 : offset = (weight + 1) * DEC_DIGITS - (dweight + 1);
8517 bruce@momjian.us 7008 : 160368 : ndigits = (ddigits + offset + DEC_DIGITS - 1) / DEC_DIGITS;
7009 : :
8653 tgl@sss.pgh.pa.us 7010 : 160368 : alloc_var(dest, ndigits);
7011 : 160368 : dest->sign = sign;
7012 : 160368 : dest->weight = weight;
7013 : 160368 : dest->dscale = dscale;
7014 : :
7015 : 160368 : i = DEC_DIGITS - offset;
7016 : 160368 : digits = dest->digits;
7017 : :
7018 [ + + ]: 801562 : while (ndigits-- > 0)
7019 : : {
7020 : : #if DEC_DIGITS == 4
8517 bruce@momjian.us 7021 : 641194 : *digits++ = ((decdigits[i] * 10 + decdigits[i + 1]) * 10 +
7022 : 641194 : decdigits[i + 2]) * 10 + decdigits[i + 3];
7023 : : #elif DEC_DIGITS == 2
7024 : : *digits++ = decdigits[i] * 10 + decdigits[i + 1];
7025 : : #elif DEC_DIGITS == 1
7026 : : *digits++ = decdigits[i];
7027 : : #else
7028 : : #error unsupported NBASE
7029 : : #endif
8653 tgl@sss.pgh.pa.us 7030 : 641194 : i += DEC_DIGITS;
7031 : : }
7032 : :
7033 : 160368 : pfree(decdigits);
7034 : :
7035 : : /* Strip any leading/trailing zeroes, and normalize weight if zero */
7036 : 160368 : strip_var(dest);
7037 : :
7038 : : /* Return end+1 position for caller */
1450 7039 : 160368 : *endptr = cp;
7040 : :
7041 : 160368 : return true;
7042 : :
1393 dean.a.rasheed@gmail 7043 : 4 : out_of_range:
7044 [ + - ]: 4 : ereturn(escontext, false,
7045 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7046 : : errmsg("value overflows numeric format")));
7047 : :
7048 : 28 : invalid_syntax:
7049 [ + - ]: 28 : ereturn(escontext, false,
7050 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
7051 : : errmsg("invalid input syntax for type %s: \"%s\"",
7052 : : "numeric", str)));
7053 : : }
7054 : :
7055 : :
7056 : : /*
7057 : : * Return the numeric value of a single hex digit.
7058 : : */
7059 : : static inline int
1405 7060 : 472 : xdigit_value(char dig)
7061 : : {
7062 [ + - + + ]: 596 : return dig >= '0' && dig <= '9' ? dig - '0' :
7063 [ + + + - ]: 196 : dig >= 'a' && dig <= 'f' ? dig - 'a' + 10 :
7064 [ + - + - ]: 72 : dig >= 'A' && dig <= 'F' ? dig - 'A' + 10 : -1;
7065 : : }
7066 : :
7067 : : /*
7068 : : * set_var_from_non_decimal_integer_str()
7069 : : *
7070 : : * Parse a string containing a non-decimal integer
7071 : : *
7072 : : * This function does not handle leading or trailing spaces. It returns
7073 : : * the end+1 position parsed into *endptr, so that caller can check for
7074 : : * trailing spaces/garbage if deemed necessary.
7075 : : *
7076 : : * cp is the place to actually start parsing; str is what to use in error
7077 : : * reports. The number's sign and base prefix indicator (e.g., "0x") are
7078 : : * assumed to have already been parsed, so cp should point to the number's
7079 : : * first digit in the base specified.
7080 : : *
7081 : : * base is expected to be 2, 8 or 16.
7082 : : *
7083 : : * Returns true on success, false on failure (if escontext points to an
7084 : : * ErrorSaveContext; otherwise errors are thrown).
7085 : : */
7086 : : static bool
7087 : 104 : set_var_from_non_decimal_integer_str(const char *str, const char *cp, int sign,
7088 : : int base, NumericVar *dest,
7089 : : const char **endptr, Node *escontext)
7090 : : {
7091 : 104 : const char *firstdigit = cp;
7092 : : int64 tmp;
7093 : : int64 mul;
7094 : : NumericVar tmp_var;
7095 : :
7096 : 104 : init_var(&tmp_var);
7097 : :
7098 : 104 : zero_var(dest);
7099 : :
7100 : : /*
7101 : : * Process input digits in groups that fit in int64. Here "tmp" is the
7102 : : * value of the digits in the group, and "mul" is base^n, where n is the
7103 : : * number of digits in the group. Thus tmp < mul, and we must start a new
7104 : : * group when mul * base threatens to overflow PG_INT64_MAX.
7105 : : */
7106 : 104 : tmp = 0;
7107 : 104 : mul = 1;
7108 : :
7109 [ + + ]: 104 : if (base == 16)
7110 : : {
7111 [ + + ]: 552 : while (*cp)
7112 : : {
7113 [ + + ]: 532 : if (isxdigit((unsigned char) *cp))
7114 : : {
7115 [ + + ]: 472 : if (mul > PG_INT64_MAX / 16)
7116 : : {
7117 : : /* Add the contribution from this group of digits */
7118 : 20 : int64_to_numericvar(mul, &tmp_var);
7119 : 20 : mul_var(dest, &tmp_var, dest, 0);
7120 : 20 : int64_to_numericvar(tmp, &tmp_var);
7121 : 20 : add_var(dest, &tmp_var, dest);
7122 : :
7123 : : /* Result will overflow if weight overflows int16 */
873 7124 [ - + ]: 20 : if (dest->weight > NUMERIC_WEIGHT_MAX)
1405 dean.a.rasheed@gmail 7125 :UBC 0 : goto out_of_range;
7126 : :
7127 : : /* Begin a new group */
1405 dean.a.rasheed@gmail 7128 :CBC 20 : tmp = 0;
7129 : 20 : mul = 1;
7130 : : }
7131 : :
7132 : 472 : tmp = tmp * 16 + xdigit_value(*cp++);
7133 : 472 : mul = mul * 16;
7134 : : }
1393 7135 [ + + ]: 60 : else if (*cp == '_')
7136 : : {
7137 : : /* Underscore must be followed by more digits */
7138 : 44 : cp++;
7139 [ + + ]: 44 : if (!isxdigit((unsigned char) *cp))
7140 : 12 : goto invalid_syntax;
7141 : : }
7142 : : else
1405 7143 : 16 : break;
7144 : : }
7145 : : }
7146 [ + + ]: 56 : else if (base == 8)
7147 : : {
7148 [ + + ]: 424 : while (*cp)
7149 : : {
7150 [ + + + + ]: 404 : if (*cp >= '0' && *cp <= '7')
7151 : : {
7152 [ + + ]: 372 : if (mul > PG_INT64_MAX / 8)
7153 : : {
7154 : : /* Add the contribution from this group of digits */
7155 : 12 : int64_to_numericvar(mul, &tmp_var);
7156 : 12 : mul_var(dest, &tmp_var, dest, 0);
7157 : 12 : int64_to_numericvar(tmp, &tmp_var);
7158 : 12 : add_var(dest, &tmp_var, dest);
7159 : :
7160 : : /* Result will overflow if weight overflows int16 */
873 7161 [ - + ]: 12 : if (dest->weight > NUMERIC_WEIGHT_MAX)
1405 dean.a.rasheed@gmail 7162 :UBC 0 : goto out_of_range;
7163 : :
7164 : : /* Begin a new group */
1405 dean.a.rasheed@gmail 7165 :CBC 12 : tmp = 0;
7166 : 12 : mul = 1;
7167 : : }
7168 : :
7169 : 372 : tmp = tmp * 8 + (*cp++ - '0');
7170 : 372 : mul = mul * 8;
7171 : : }
1393 7172 [ + + ]: 32 : else if (*cp == '_')
7173 : : {
7174 : : /* Underscore must be followed by more digits */
7175 : 24 : cp++;
7176 [ + - - + ]: 24 : if (*cp < '0' || *cp > '7')
1393 dean.a.rasheed@gmail 7177 :UBC 0 : goto invalid_syntax;
7178 : : }
7179 : : else
1405 dean.a.rasheed@gmail 7180 :CBC 8 : break;
7181 : : }
7182 : : }
7183 [ + - ]: 28 : else if (base == 2)
7184 : : {
7185 [ + + ]: 1040 : while (*cp)
7186 : : {
7187 [ + + + + ]: 1020 : if (*cp >= '0' && *cp <= '1')
7188 : : {
7189 [ + + ]: 944 : if (mul > PG_INT64_MAX / 2)
7190 : : {
7191 : : /* Add the contribution from this group of digits */
7192 : 12 : int64_to_numericvar(mul, &tmp_var);
7193 : 12 : mul_var(dest, &tmp_var, dest, 0);
7194 : 12 : int64_to_numericvar(tmp, &tmp_var);
7195 : 12 : add_var(dest, &tmp_var, dest);
7196 : :
7197 : : /* Result will overflow if weight overflows int16 */
873 7198 [ - + ]: 12 : if (dest->weight > NUMERIC_WEIGHT_MAX)
1405 dean.a.rasheed@gmail 7199 :UBC 0 : goto out_of_range;
7200 : :
7201 : : /* Begin a new group */
1405 dean.a.rasheed@gmail 7202 :CBC 12 : tmp = 0;
7203 : 12 : mul = 1;
7204 : : }
7205 : :
7206 : 944 : tmp = tmp * 2 + (*cp++ - '0');
7207 : 944 : mul = mul * 2;
7208 : : }
1393 7209 [ + + ]: 76 : else if (*cp == '_')
7210 : : {
7211 : : /* Underscore must be followed by more digits */
7212 : 68 : cp++;
7213 [ + - - + ]: 68 : if (*cp < '0' || *cp > '1')
1393 dean.a.rasheed@gmail 7214 :UBC 0 : goto invalid_syntax;
7215 : : }
7216 : : else
1405 dean.a.rasheed@gmail 7217 :CBC 8 : break;
7218 : : }
7219 : : }
7220 : : else
7221 : : /* Should never happen; treat as invalid input */
1405 dean.a.rasheed@gmail 7222 :UBC 0 : goto invalid_syntax;
7223 : :
7224 : : /* Check that we got at least one digit */
1405 dean.a.rasheed@gmail 7225 [ - + ]:CBC 92 : if (unlikely(cp == firstdigit))
1405 dean.a.rasheed@gmail 7226 :UBC 0 : goto invalid_syntax;
7227 : :
7228 : : /* Add the contribution from the final group of digits */
1405 dean.a.rasheed@gmail 7229 :CBC 92 : int64_to_numericvar(mul, &tmp_var);
7230 : 92 : mul_var(dest, &tmp_var, dest, 0);
7231 : 92 : int64_to_numericvar(tmp, &tmp_var);
7232 : 92 : add_var(dest, &tmp_var, dest);
7233 : :
873 7234 [ - + ]: 92 : if (dest->weight > NUMERIC_WEIGHT_MAX)
1405 dean.a.rasheed@gmail 7235 :UBC 0 : goto out_of_range;
7236 : :
1405 dean.a.rasheed@gmail 7237 :CBC 92 : dest->sign = sign;
7238 : :
7239 : 92 : free_var(&tmp_var);
7240 : :
7241 : : /* Return end+1 position for caller */
7242 : 92 : *endptr = cp;
7243 : :
7244 : 92 : return true;
7245 : :
1405 dean.a.rasheed@gmail 7246 :UBC 0 : out_of_range:
7247 [ # # ]: 0 : ereturn(escontext, false,
7248 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7249 : : errmsg("value overflows numeric format")));
7250 : :
1405 dean.a.rasheed@gmail 7251 :CBC 12 : invalid_syntax:
7252 [ + - ]: 12 : ereturn(escontext, false,
7253 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
7254 : : errmsg("invalid input syntax for type %s: \"%s\"",
7255 : : "numeric", str)));
7256 : : }
7257 : :
7258 : :
7259 : : /*
7260 : : * set_var_from_num() -
7261 : : *
7262 : : * Convert the packed db format into a variable
7263 : : */
7264 : : static void
10049 bruce@momjian.us 7265 : 8819 : set_var_from_num(Numeric num, NumericVar *dest)
7266 : : {
7267 : : int ndigits;
7268 : :
7599 7269 [ + + ]: 8819 : ndigits = NUMERIC_NDIGITS(num);
7270 : :
8653 tgl@sss.pgh.pa.us 7271 : 8819 : alloc_var(dest, ndigits);
7272 : :
5961 rhaas@postgresql.org 7273 [ + + + + ]: 8819 : dest->weight = NUMERIC_WEIGHT(num);
10049 bruce@momjian.us 7274 [ + + - + ]: 8819 : dest->sign = NUMERIC_SIGN(num);
8653 tgl@sss.pgh.pa.us 7275 [ + + ]: 8819 : dest->dscale = NUMERIC_DSCALE(num);
7276 : :
5961 rhaas@postgresql.org 7277 [ + + ]: 8819 : memcpy(dest->digits, NUMERIC_DIGITS(num), ndigits * sizeof(NumericDigit));
10195 JanWieck@Yahoo.com 7278 : 8819 : }
7279 : :
7280 : :
7281 : : /*
7282 : : * init_var_from_num() -
7283 : : *
7284 : : * Initialize a variable from packed db format. The digits array is not
7285 : : * copied, which saves some cycles when the resulting var is not modified.
7286 : : * Also, there's no need to call free_var(), as long as you don't assign any
7287 : : * other value to it (with set_var_* functions, or by using the var as the
7288 : : * destination of a function like add_var())
7289 : : *
7290 : : * CAUTION: Do not modify the digits buffer of a var initialized with this
7291 : : * function, e.g by calling round_var() or trunc_var(), as the changes will
7292 : : * propagate to the original Numeric! It's OK to use it as the destination
7293 : : * argument of one of the calculational functions, though.
7294 : : */
7295 : : static void
5120 heikki.linnakangas@i 7296 : 3905493 : init_var_from_num(Numeric num, NumericVar *dest)
7297 : : {
7298 [ + + ]: 3905493 : dest->ndigits = NUMERIC_NDIGITS(num);
7299 [ + + + + ]: 3905493 : dest->weight = NUMERIC_WEIGHT(num);
7300 [ + + + + ]: 3905493 : dest->sign = NUMERIC_SIGN(num);
7301 [ + + ]: 3905493 : dest->dscale = NUMERIC_DSCALE(num);
7302 [ + + ]: 3905493 : dest->digits = NUMERIC_DIGITS(num);
4931 bruce@momjian.us 7303 : 3905493 : dest->buf = NULL; /* digits array is not palloc'd */
5120 heikki.linnakangas@i 7304 : 3905493 : }
7305 : :
7306 : :
7307 : : /*
7308 : : * set_var_from_var() -
7309 : : *
7310 : : * Copy one variable into another
7311 : : */
7312 : : static void
3366 andres@anarazel.de 7313 : 26599 : set_var_from_var(const NumericVar *value, NumericVar *dest)
7314 : : {
7315 : : NumericDigit *newbuf;
7316 : :
9811 tgl@sss.pgh.pa.us 7317 : 26599 : newbuf = digitbuf_alloc(value->ndigits + 1);
7318 : 26599 : newbuf[0] = 0; /* spare digit for rounding */
4136 7319 [ + + ]: 26599 : if (value->ndigits > 0) /* else value->digits might be null */
7320 : 25927 : memcpy(newbuf + 1, value->digits,
7321 : 25927 : value->ndigits * sizeof(NumericDigit));
7322 : :
10195 JanWieck@Yahoo.com 7323 [ + + ]: 26599 : digitbuf_free(dest->buf);
7324 : :
8333 neilc@samurai.com 7325 : 26599 : memmove(dest, value, sizeof(NumericVar));
10049 bruce@momjian.us 7326 : 26599 : dest->buf = newbuf;
9811 tgl@sss.pgh.pa.us 7327 : 26599 : dest->digits = newbuf + 1;
7328 : 26599 : }
7329 : :
7330 : :
7331 : : /*
7332 : : * get_str_from_var() -
7333 : : *
7334 : : * Convert a var to text representation (guts of numeric_out).
7335 : : * The var is displayed to the number of digits indicated by its dscale.
7336 : : * Returns a palloc'd string.
7337 : : */
7338 : : static char *
3366 andres@anarazel.de 7339 : 584704 : get_str_from_var(const NumericVar *var)
7340 : : {
7341 : : int dscale;
7342 : : char *str;
7343 : : char *cp;
7344 : : char *endcp;
7345 : : int i;
7346 : : int d;
7347 : : NumericDigit dig;
7348 : :
7349 : : #if DEC_DIGITS > 1
7350 : : NumericDigit d1;
7351 : : #endif
7352 : :
5120 heikki.linnakangas@i 7353 : 584704 : dscale = var->dscale;
7354 : :
7355 : : /*
7356 : : * Allocate space for the result.
7357 : : *
7358 : : * i is set to the # of decimal digits before decimal point. dscale is the
7359 : : * # of decimal digits we will print after decimal point. We may generate
7360 : : * as many as DEC_DIGITS-1 excess digits at the end, and in addition we
7361 : : * need room for sign, decimal point, null terminator.
7362 : : */
8653 tgl@sss.pgh.pa.us 7363 : 584704 : i = (var->weight + 1) * DEC_DIGITS;
7364 [ + + ]: 584704 : if (i <= 0)
7365 : 72498 : i = 1;
7366 : :
7367 : 584704 : str = palloc(i + dscale + DEC_DIGITS + 2);
9811 7368 : 584704 : cp = str;
7369 : :
7370 : : /*
7371 : : * Output a dash for negative values
7372 : : */
7373 [ + + ]: 584704 : if (var->sign == NUMERIC_NEG)
7374 : 4354 : *cp++ = '-';
7375 : :
7376 : : /*
7377 : : * Output all digits before the decimal point
7378 : : */
8653 7379 [ + + ]: 584704 : if (var->weight < 0)
7380 : : {
7381 : 72498 : d = var->weight + 1;
7382 : 72498 : *cp++ = '0';
7383 : : }
7384 : : else
7385 : : {
7386 [ + + ]: 1124066 : for (d = 0; d <= var->weight; d++)
7387 : : {
7388 [ + + ]: 611860 : dig = (d < var->ndigits) ? var->digits[d] : 0;
7389 : : /* In the first digit, suppress extra leading decimal zeroes */
7390 : : #if DEC_DIGITS == 4
7391 : : {
8517 bruce@momjian.us 7392 : 611860 : bool putit = (d > 0);
7393 : :
8653 tgl@sss.pgh.pa.us 7394 : 611860 : d1 = dig / 1000;
7395 : 611860 : dig -= d1 * 1000;
7396 : 611860 : putit |= (d1 > 0);
7397 [ + + ]: 611860 : if (putit)
7398 : 153204 : *cp++ = d1 + '0';
7399 : 611860 : d1 = dig / 100;
7400 : 611860 : dig -= d1 * 100;
7401 : 611860 : putit |= (d1 > 0);
7402 [ + + ]: 611860 : if (putit)
7403 : 427817 : *cp++ = d1 + '0';
7404 : 611860 : d1 = dig / 10;
7405 : 611860 : dig -= d1 * 10;
7406 : 611860 : putit |= (d1 > 0);
7407 [ + + ]: 611860 : if (putit)
7408 : 512971 : *cp++ = d1 + '0';
7409 : 611860 : *cp++ = dig + '0';
7410 : : }
7411 : : #elif DEC_DIGITS == 2
7412 : : d1 = dig / 10;
7413 : : dig -= d1 * 10;
7414 : : if (d1 > 0 || d > 0)
7415 : : *cp++ = d1 + '0';
7416 : : *cp++ = dig + '0';
7417 : : #elif DEC_DIGITS == 1
7418 : : *cp++ = dig + '0';
7419 : : #else
7420 : : #error unsupported NBASE
7421 : : #endif
7422 : : }
7423 : : }
7424 : :
7425 : : /*
7426 : : * If requested, output a decimal point and all the digits that follow it.
7427 : : * We initially put out a multiple of DEC_DIGITS digits, then truncate if
7428 : : * needed.
7429 : : */
9811 7430 [ + + ]: 584704 : if (dscale > 0)
7431 : : {
7432 : 409333 : *cp++ = '.';
8653 7433 : 409333 : endcp = cp + dscale;
7434 [ + + ]: 1150259 : for (i = 0; i < dscale; d++, i += DEC_DIGITS)
7435 : : {
7436 [ + + + + ]: 740926 : dig = (d >= 0 && d < var->ndigits) ? var->digits[d] : 0;
7437 : : #if DEC_DIGITS == 4
7438 : 740926 : d1 = dig / 1000;
7439 : 740926 : dig -= d1 * 1000;
7440 : 740926 : *cp++ = d1 + '0';
7441 : 740926 : d1 = dig / 100;
7442 : 740926 : dig -= d1 * 100;
7443 : 740926 : *cp++ = d1 + '0';
7444 : 740926 : d1 = dig / 10;
7445 : 740926 : dig -= d1 * 10;
7446 : 740926 : *cp++ = d1 + '0';
7447 : 740926 : *cp++ = dig + '0';
7448 : : #elif DEC_DIGITS == 2
7449 : : d1 = dig / 10;
7450 : : dig -= d1 * 10;
7451 : : *cp++ = d1 + '0';
7452 : : *cp++ = dig + '0';
7453 : : #elif DEC_DIGITS == 1
7454 : : *cp++ = dig + '0';
7455 : : #else
7456 : : #error unsupported NBASE
7457 : : #endif
7458 : : }
7459 : 409333 : cp = endcp;
7460 : : }
7461 : :
7462 : : /*
7463 : : * terminate the string and return it
7464 : : */
9811 7465 : 584704 : *cp = '\0';
7466 : 584704 : return str;
7467 : : }
7468 : :
7469 : : /*
7470 : : * get_str_from_var_sci() -
7471 : : *
7472 : : * Convert a var to a normalised scientific notation text representation.
7473 : : * This function does the heavy lifting for numeric_out_sci().
7474 : : *
7475 : : * This notation has the general form a * 10^b, where a is known as the
7476 : : * "significand" and b is known as the "exponent".
7477 : : *
7478 : : * Because we can't do superscript in ASCII (and because we want to copy
7479 : : * printf's behaviour) we display the exponent using E notation, with a
7480 : : * minimum of two exponent digits.
7481 : : *
7482 : : * For example, the value 1234 could be output as 1.2e+03.
7483 : : *
7484 : : * We assume that the exponent can fit into an int32.
7485 : : *
7486 : : * rscale is the number of decimal digits desired after the decimal point in
7487 : : * the output, negative values will be treated as meaning zero.
7488 : : *
7489 : : * Returns a palloc'd string.
7490 : : */
7491 : : static char *
3366 andres@anarazel.de 7492 : 184 : get_str_from_var_sci(const NumericVar *var, int rscale)
7493 : : {
7494 : : int32 exponent;
7495 : : NumericVar tmp_var;
7496 : : size_t len;
7497 : : char *str;
7498 : : char *sig_out;
7499 : :
6319 tgl@sss.pgh.pa.us 7500 [ - + ]: 184 : if (rscale < 0)
6319 tgl@sss.pgh.pa.us 7501 :UBC 0 : rscale = 0;
7502 : :
7503 : : /*
7504 : : * Determine the exponent of this number in normalised form.
7505 : : *
7506 : : * This is the exponent required to represent the number with only one
7507 : : * significant digit before the decimal place.
7508 : : */
6319 tgl@sss.pgh.pa.us 7509 [ + + ]:CBC 184 : if (var->ndigits > 0)
7510 : : {
7511 : 168 : exponent = (var->weight + 1) * DEC_DIGITS;
7512 : :
7513 : : /*
7514 : : * Compensate for leading decimal zeroes in the first numeric digit by
7515 : : * decrementing the exponent.
7516 : : */
7517 : 168 : exponent -= DEC_DIGITS - (int) log10(var->digits[0]);
7518 : : }
7519 : : else
7520 : : {
7521 : : /*
7522 : : * If var has no digits, then it must be zero.
7523 : : *
7524 : : * Zero doesn't technically have a meaningful exponent in normalised
7525 : : * notation, but we just display the exponent as zero for consistency
7526 : : * of output.
7527 : : */
7528 : 16 : exponent = 0;
7529 : : }
7530 : :
7531 : : /*
7532 : : * Divide var by 10^exponent to get the significand, rounding to rscale
7533 : : * decimal digits in the process.
7534 : : */
1941 dean.a.rasheed@gmail 7535 : 184 : init_var(&tmp_var);
7536 : :
7537 : 184 : power_ten_int(exponent, &tmp_var);
785 7538 : 184 : div_var(var, &tmp_var, &tmp_var, rscale, true, true);
7539 : :
7540 : : /*
7541 : : * Rounding can increase the significand from, say, 9.999 to 10.00,
7542 : : * breaking our intended formatting. If that has happened, increase the
7543 : : * exponent and recompute the significand. (This is a rare edge case, so
7544 : : * it doesn't seem worth working harder.)
7545 : : */
10 tgl@sss.pgh.pa.us 7546 [ + + ]: 184 : if (tmp_var.ndigits > 0 &&
7547 [ + - ]: 168 : (tmp_var.weight > 0 ||
7548 [ + - + + ]: 168 : (tmp_var.weight == 0 && tmp_var.digits[0] >= 10)))
7549 : : {
7550 : 16 : exponent++;
7551 : 16 : power_ten_int(exponent, &tmp_var);
7552 : 16 : div_var(var, &tmp_var, &tmp_var, rscale, true, true);
7553 : : }
7554 : :
1941 dean.a.rasheed@gmail 7555 : 184 : sig_out = get_str_from_var(&tmp_var);
7556 : :
7557 : 184 : free_var(&tmp_var);
7558 : :
7559 : : /*
7560 : : * Allocate space for the result.
7561 : : *
7562 : : * In addition to the significand, we need room for the exponent
7563 : : * decoration ("e"), the sign of the exponent, up to 10 digits for the
7564 : : * exponent itself, and of course the null terminator.
7565 : : */
6319 tgl@sss.pgh.pa.us 7566 : 184 : len = strlen(sig_out) + 13;
7567 : 184 : str = palloc(len);
7568 : 184 : snprintf(str, len, "%se%+03d", sig_out, exponent);
7569 : :
7570 : 184 : pfree(sig_out);
7571 : :
7572 : 184 : return str;
7573 : : }
7574 : :
7575 : :
7576 : : /*
7577 : : * numericvar_serialize - serialize NumericVar to binary format
7578 : : *
7579 : : * At variable level, no checks are performed on the weight or dscale, allowing
7580 : : * us to pass around intermediate values with higher precision than supported
7581 : : * by the numeric type. Note: this is incompatible with numeric_send/recv(),
7582 : : * which use 16-bit integers for these fields.
7583 : : */
7584 : : static void
1972 dean.a.rasheed@gmail 7585 : 64 : numericvar_serialize(StringInfo buf, const NumericVar *var)
7586 : : {
7587 : : int i;
7588 : :
7589 : 64 : pq_sendint32(buf, var->ndigits);
7590 : 64 : pq_sendint32(buf, var->weight);
7591 : 64 : pq_sendint32(buf, var->sign);
7592 : 64 : pq_sendint32(buf, var->dscale);
7593 [ + + ]: 425172 : for (i = 0; i < var->ndigits; i++)
7594 : 425108 : pq_sendint16(buf, var->digits[i]);
7595 : 64 : }
7596 : :
7597 : : /*
7598 : : * numericvar_deserialize - deserialize binary format to NumericVar
7599 : : */
7600 : : static void
7601 : 64 : numericvar_deserialize(StringInfo buf, NumericVar *var)
7602 : : {
7603 : : int len,
7604 : : i;
7605 : :
7606 : 64 : len = pq_getmsgint(buf, sizeof(int32));
7607 : :
7608 : 64 : alloc_var(var, len); /* sets var->ndigits */
7609 : :
7610 : 64 : var->weight = pq_getmsgint(buf, sizeof(int32));
7611 : 64 : var->sign = pq_getmsgint(buf, sizeof(int32));
7612 : 64 : var->dscale = pq_getmsgint(buf, sizeof(int32));
7613 [ + + ]: 425172 : for (i = 0; i < len; i++)
7614 : 425108 : var->digits[i] = pq_getmsgint(buf, sizeof(int16));
7615 : 64 : }
7616 : :
7617 : :
7618 : : /*
7619 : : * duplicate_numeric() - copy a packed-format Numeric
7620 : : *
7621 : : * This will handle NaN and Infinity cases.
7622 : : */
7623 : : static Numeric
2320 tgl@sss.pgh.pa.us 7624 : 18829 : duplicate_numeric(Numeric num)
7625 : : {
7626 : : Numeric res;
7627 : :
7628 : 18829 : res = (Numeric) palloc(VARSIZE(num));
7629 : 18829 : memcpy(res, num, VARSIZE(num));
7630 : 18829 : return res;
7631 : : }
7632 : :
7633 : : /*
7634 : : * make_result_safe() -
7635 : : *
7636 : : * Create the packed db numeric format in palloc()'d memory from
7637 : : * a variable. This will handle NaN and Infinity cases.
7638 : : */
7639 : : static Numeric
449 michael@paquier.xyz 7640 : 2578965 : make_result_safe(const NumericVar *var, Node *escontext)
7641 : : {
7642 : : Numeric result;
8653 tgl@sss.pgh.pa.us 7643 : 2578965 : NumericDigit *digits = var->digits;
10049 bruce@momjian.us 7644 : 2578965 : int weight = var->weight;
7645 : 2578965 : int sign = var->sign;
7646 : : int n;
7647 : : Size len;
7648 : :
2320 tgl@sss.pgh.pa.us 7649 [ + + ]: 2578965 : if ((sign & NUMERIC_SIGN_MASK) == NUMERIC_SPECIAL)
7650 : : {
7651 : : /*
7652 : : * Verify valid special value. This could be just an Assert, perhaps,
7653 : : * but it seems worthwhile to expend a few cycles to ensure that we
7654 : : * never write any nonzero reserved bits to disk.
7655 : : */
7656 [ + + + + : 2249 : if (!(sign == NUMERIC_NAN ||
- + ]
7657 : : sign == NUMERIC_PINF ||
7658 : : sign == NUMERIC_NINF))
2320 tgl@sss.pgh.pa.us 7659 [ # # ]:UBC 0 : elog(ERROR, "invalid numeric sign value 0x%x", sign);
7660 : :
5961 rhaas@postgresql.org 7661 :CBC 2249 : result = (Numeric) palloc(NUMERIC_HDRSZ_SHORT);
7662 : :
7663 : 2249 : SET_VARSIZE(result, NUMERIC_HDRSZ_SHORT);
2320 tgl@sss.pgh.pa.us 7664 : 2249 : result->choice.n_header = sign;
7665 : : /* the header word is all we need */
7666 : :
7667 : : dump_numeric("make_result()", result);
10195 JanWieck@Yahoo.com 7668 : 2249 : return result;
7669 : : }
7670 : :
8653 tgl@sss.pgh.pa.us 7671 : 2576716 : n = var->ndigits;
7672 : :
7673 : : /* truncate leading zeroes */
7674 [ + + + + ]: 2576746 : while (n > 0 && *digits == 0)
7675 : : {
7676 : 30 : digits++;
10195 JanWieck@Yahoo.com 7677 : 30 : weight--;
7678 : 30 : n--;
7679 : : }
7680 : : /* truncate trailing zeroes */
8653 tgl@sss.pgh.pa.us 7681 [ + + + + ]: 2628846 : while (n > 0 && digits[n - 1] == 0)
10195 JanWieck@Yahoo.com 7682 : 52130 : n--;
7683 : :
7684 : : /* If zero result, force to weight=0 and positive sign */
7685 [ + + ]: 2576716 : if (n == 0)
7686 : : {
7687 : 85529 : weight = 0;
10049 bruce@momjian.us 7688 : 85529 : sign = NUMERIC_POS;
7689 : : }
7690 : :
7691 : : /* Build the result */
5961 rhaas@postgresql.org 7692 [ + + + + : 2576716 : if (NUMERIC_CAN_BE_SHORT(var->dscale, weight))
+ - ]
7693 : : {
7694 : 2574715 : len = NUMERIC_HDRSZ_SHORT + n * sizeof(NumericDigit);
7695 : 2574715 : result = (Numeric) palloc(len);
7696 : 2574715 : SET_VARSIZE(result, len);
5849 peter_e@gmx.net 7697 : 2574715 : result->choice.n_short.n_header =
7698 : : (sign == NUMERIC_NEG ? (NUMERIC_SHORT | NUMERIC_SHORT_SIGN_MASK)
7699 : : : NUMERIC_SHORT)
5961 rhaas@postgresql.org 7700 [ + + ]: 2574715 : | (var->dscale << NUMERIC_SHORT_DSCALE_SHIFT)
7701 : 2574715 : | (weight < 0 ? NUMERIC_SHORT_WEIGHT_SIGN_MASK : 0)
7702 : 2574715 : | (weight & NUMERIC_SHORT_WEIGHT_MASK);
7703 : : }
7704 : : else
7705 : : {
7706 : 2001 : len = NUMERIC_HDRSZ + n * sizeof(NumericDigit);
7707 : 2001 : result = (Numeric) palloc(len);
7708 : 2001 : SET_VARSIZE(result, len);
7709 : 2001 : result->choice.n_long.n_sign_dscale =
7710 : 2001 : sign | (var->dscale & NUMERIC_DSCALE_MASK);
7711 : 2001 : result->choice.n_long.n_weight = weight;
7712 : : }
7713 : :
7714 [ + + - + ]: 2576716 : Assert(NUMERIC_NDIGITS(result) == n);
4136 tgl@sss.pgh.pa.us 7715 [ + + ]: 2576716 : if (n > 0)
7716 [ + + ]: 2491187 : memcpy(NUMERIC_DIGITS(result), digits, n * sizeof(NumericDigit));
7717 : :
7718 : : /* Check for overflow of int16 fields */
5961 rhaas@postgresql.org 7719 [ + + + + : 2576716 : if (NUMERIC_WEIGHT(result) != weight ||
+ + ]
8653 tgl@sss.pgh.pa.us 7720 [ + + - + ]: 2576683 : NUMERIC_DSCALE(result) != var->dscale)
449 michael@paquier.xyz 7721 [ + + ]: 33 : ereturn(escontext, NULL,
7722 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7723 : : errmsg("value overflows numeric format")));
7724 : :
7725 : : dump_numeric("make_result()", result);
10195 JanWieck@Yahoo.com 7726 : 2576683 : return result;
7727 : : }
7728 : :
7729 : :
7730 : : /*
7731 : : * make_result() -
7732 : : *
7733 : : * An interface to make_result_safe() without "escontext" argument.
7734 : : */
7735 : : static Numeric
2814 akorotkov@postgresql 7736 : 1523218 : make_result(const NumericVar *var)
7737 : : {
449 michael@paquier.xyz 7738 : 1523218 : return make_result_safe(var, NULL);
7739 : : }
7740 : :
7741 : :
7742 : : /*
7743 : : * apply_typmod() -
7744 : : *
7745 : : * Do bounds checking and rounding according to the specified typmod.
7746 : : * Note that this is only applied to normal finite values.
7747 : : *
7748 : : * Returns true on success, false on failure (if escontext points to an
7749 : : * ErrorSaveContext; otherwise errors are thrown).
7750 : : */
7751 : : static bool
1450 tgl@sss.pgh.pa.us 7752 : 135642 : apply_typmod(NumericVar *var, int32 typmod, Node *escontext)
7753 : : {
7754 : : int precision;
7755 : : int scale;
7756 : : int maxdigits;
7757 : : int ddigits;
7758 : : int i;
7759 : :
7760 : : /* Do nothing if we have an invalid typmod */
1951 dean.a.rasheed@gmail 7761 [ + + ]: 135642 : if (!is_valid_numeric_typmod(typmod))
1450 tgl@sss.pgh.pa.us 7762 : 116138 : return true;
7763 : :
1951 dean.a.rasheed@gmail 7764 : 19504 : precision = numeric_typmod_precision(typmod);
7765 : 19504 : scale = numeric_typmod_scale(typmod);
8653 tgl@sss.pgh.pa.us 7766 : 19504 : maxdigits = precision - scale;
7767 : :
7768 : : /* Round to target scale (and set var->dscale) */
7769 : 19504 : round_var(var, scale);
7770 : :
7771 : : /* but don't allow var->dscale to be negative */
1951 dean.a.rasheed@gmail 7772 [ + + ]: 19504 : if (var->dscale < 0)
7773 : 100 : var->dscale = 0;
7774 : :
7775 : : /*
7776 : : * Check for overflow - note we can't do this before rounding, because
7777 : : * rounding could raise the weight. Also note that the var's weight could
7778 : : * be inflated by leading zeroes, which will be stripped before storage
7779 : : * but perhaps might not have been yet. In any case, we must recognize a
7780 : : * true zero, whose weight doesn't mean anything.
7781 : : */
8653 tgl@sss.pgh.pa.us 7782 : 19504 : ddigits = (var->weight + 1) * DEC_DIGITS;
7783 [ + + ]: 19504 : if (ddigits > maxdigits)
7784 : : {
7785 : : /* Determine true weight; and check for all-zero result */
9814 7786 [ + + ]: 4286 : for (i = 0; i < var->ndigits; i++)
7787 : : {
8653 7788 : 4276 : NumericDigit dig = var->digits[i];
7789 : :
7790 [ + - ]: 4276 : if (dig)
7791 : : {
7792 : : /* Adjust for any high-order decimal zero digits */
7793 : : #if DEC_DIGITS == 4
7794 [ + + ]: 4276 : if (dig < 10)
7795 : 197 : ddigits -= 3;
7796 [ + + ]: 4079 : else if (dig < 100)
7797 : 428 : ddigits -= 2;
7798 [ + + ]: 3651 : else if (dig < 1000)
7799 : 3639 : ddigits -= 1;
7800 : : #elif DEC_DIGITS == 2
7801 : : if (dig < 10)
7802 : : ddigits -= 1;
7803 : : #elif DEC_DIGITS == 1
7804 : : /* no adjustment */
7805 : : #else
7806 : : #error unsupported NBASE
7807 : : #endif
7808 [ + + ]: 4276 : if (ddigits > maxdigits)
1450 7809 [ + + + + : 64 : ereturn(escontext, false,
+ + ]
7810 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7811 : : errmsg("numeric field overflow"),
7812 : : errdetail("A field with precision %d, scale %d must round to an absolute value less than %s%d.",
7813 : : precision, scale,
7814 : : /* Display 10^0 as 1 */
7815 : : maxdigits ? "10^" : "",
7816 : : maxdigits ? maxdigits : 1
7817 : : )));
9814 7818 : 4212 : break;
7819 : : }
8653 tgl@sss.pgh.pa.us 7820 :UBC 0 : ddigits -= DEC_DIGITS;
7821 : : }
7822 : : }
7823 : :
1450 tgl@sss.pgh.pa.us 7824 :CBC 19440 : return true;
7825 : : }
7826 : :
7827 : : /*
7828 : : * apply_typmod_special() -
7829 : : *
7830 : : * Do bounds checking according to the specified typmod, for an Inf or NaN.
7831 : : * For convenience of most callers, the value is presented in packed form.
7832 : : *
7833 : : * Returns true on success, false on failure (if escontext points to an
7834 : : * ErrorSaveContext; otherwise errors are thrown).
7835 : : */
7836 : : static bool
7837 : 1321 : apply_typmod_special(Numeric num, int32 typmod, Node *escontext)
7838 : : {
7839 : : int precision;
7840 : : int scale;
7841 : :
2320 7842 [ - + ]: 1321 : Assert(NUMERIC_IS_SPECIAL(num)); /* caller error if not */
7843 : :
7844 : : /*
7845 : : * NaN is allowed regardless of the typmod; that's rather dubious perhaps,
7846 : : * but it's a longstanding behavior. Inf is rejected if we have any
7847 : : * typmod restriction, since an infinity shouldn't be claimed to fit in
7848 : : * any finite number of digits.
7849 : : */
7850 [ + + ]: 1321 : if (NUMERIC_IS_NAN(num))
1450 7851 : 568 : return true;
7852 : :
7853 : : /* Do nothing if we have a default typmod (-1) */
1951 dean.a.rasheed@gmail 7854 [ + + ]: 753 : if (!is_valid_numeric_typmod(typmod))
1450 tgl@sss.pgh.pa.us 7855 : 741 : return true;
7856 : :
1951 dean.a.rasheed@gmail 7857 : 12 : precision = numeric_typmod_precision(typmod);
7858 : 12 : scale = numeric_typmod_scale(typmod);
7859 : :
1450 tgl@sss.pgh.pa.us 7860 [ + - ]: 12 : ereturn(escontext, false,
7861 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7862 : : errmsg("numeric field overflow"),
7863 : : errdetail("A field with precision %d, scale %d cannot hold an infinite value.",
7864 : : precision, scale)));
7865 : : }
7866 : :
7867 : :
7868 : : /*
7869 : : * Convert numeric to int8, rounding if needed.
7870 : : *
7871 : : * If overflow, return false (no error is raised). Return true if okay.
7872 : : */
7873 : : static bool
3366 andres@anarazel.de 7874 : 8729 : numericvar_to_int64(const NumericVar *var, int64 *result)
7875 : : {
7876 : : NumericDigit *digits;
7877 : : int ndigits;
7878 : : int weight;
7879 : : int i;
7880 : : int64 val;
7881 : : bool neg;
7882 : : NumericVar rounded;
7883 : :
7884 : : /* Round to nearest integer */
5120 heikki.linnakangas@i 7885 : 8729 : init_var(&rounded);
7886 : 8729 : set_var_from_var(var, &rounded);
7887 : 8729 : round_var(&rounded, 0);
7888 : :
7889 : : /* Check for zero input */
7890 : 8729 : strip_var(&rounded);
7891 : 8729 : ndigits = rounded.ndigits;
8653 tgl@sss.pgh.pa.us 7892 [ + + ]: 8729 : if (ndigits == 0)
7893 : : {
7894 : 348 : *result = 0;
5120 heikki.linnakangas@i 7895 : 348 : free_var(&rounded);
8653 tgl@sss.pgh.pa.us 7896 : 348 : return true;
7897 : : }
7898 : :
7899 : : /*
7900 : : * For input like 10000000000, we must treat stripped digits as real. So
7901 : : * the loop assumes there are weight+1 digits before the decimal point.
7902 : : */
5120 heikki.linnakangas@i 7903 : 8381 : weight = rounded.weight;
8517 bruce@momjian.us 7904 [ + - - + ]: 8381 : Assert(weight >= 0 && ndigits <= weight + 1);
7905 : :
7906 : : /*
7907 : : * Construct the result. To avoid issues with converting a value
7908 : : * corresponding to INT64_MIN (which can't be represented as a positive 64
7909 : : * bit two's complement integer), accumulate value as a negative number.
7910 : : */
5120 heikki.linnakangas@i 7911 : 8381 : digits = rounded.digits;
7912 : 8381 : neg = (rounded.sign == NUMERIC_NEG);
3273 andres@anarazel.de 7913 : 8381 : val = -digits[0];
8549 tgl@sss.pgh.pa.us 7914 [ + + ]: 12922 : for (i = 1; i <= weight; i++)
7915 : : {
3273 andres@anarazel.de 7916 [ + + ]: 4574 : if (unlikely(pg_mul_s64_overflow(val, NBASE, &val)))
7917 : : {
7918 : 21 : free_var(&rounded);
7919 : 21 : return false;
7920 : : }
7921 : :
7922 [ + + ]: 4553 : if (i < ndigits)
7923 : : {
7924 [ + + ]: 4347 : if (unlikely(pg_sub_s64_overflow(val, digits[i], &val)))
7925 : : {
5120 heikki.linnakangas@i 7926 : 12 : free_var(&rounded);
8653 tgl@sss.pgh.pa.us 7927 : 12 : return false;
7928 : : }
7929 : : }
7930 : : }
7931 : :
5120 heikki.linnakangas@i 7932 : 8348 : free_var(&rounded);
7933 : :
3273 andres@anarazel.de 7934 [ + + ]: 8348 : if (!neg)
7935 : : {
88 michael@paquier.xyz 7936 [ + + ]:GNC 7798 : if (unlikely(pg_neg_s64_overflow(val, &val)))
3273 andres@anarazel.de 7937 :CBC 16 : return false;
7938 : : }
7939 : 8332 : *result = val;
7940 : :
8653 tgl@sss.pgh.pa.us 7941 : 8332 : return true;
7942 : : }
7943 : :
7944 : : /*
7945 : : * Convert int8 value to numeric.
7946 : : */
7947 : : static void
4271 andres@anarazel.de 7948 : 1268316 : int64_to_numericvar(int64 val, NumericVar *var)
7949 : : {
7950 : : uint64 uval,
7951 : : newuval;
7952 : : NumericDigit *ptr;
7953 : : int ndigits;
7954 : :
7955 : : /* int64 can require at most 19 decimal digits; add one for safety */
8517 bruce@momjian.us 7956 : 1268316 : alloc_var(var, 20 / DEC_DIGITS);
8653 tgl@sss.pgh.pa.us 7957 [ + + ]: 1268316 : if (val < 0)
7958 : : {
7959 : 1271 : var->sign = NUMERIC_NEG;
835 nathan@postgresql.or 7960 : 1271 : uval = pg_abs_s64(val);
7961 : : }
7962 : : else
7963 : : {
8653 tgl@sss.pgh.pa.us 7964 : 1267045 : var->sign = NUMERIC_POS;
7965 : 1267045 : uval = val;
7966 : : }
7967 : 1268316 : var->dscale = 0;
7968 [ + + ]: 1268316 : if (val == 0)
7969 : : {
7970 : 19427 : var->ndigits = 0;
7971 : 19427 : var->weight = 0;
7972 : 19427 : return;
7973 : : }
7974 : 1248889 : ptr = var->digits + var->ndigits;
7975 : 1248889 : ndigits = 0;
7976 : : do
7977 : : {
7978 : 1450298 : ptr--;
7979 : 1450298 : ndigits++;
7980 : 1450298 : newuval = uval / NBASE;
7981 : 1450298 : *ptr = uval - newuval * NBASE;
7982 : 1450298 : uval = newuval;
7983 [ + + ]: 1450298 : } while (uval);
7984 : 1248889 : var->digits = ptr;
7985 : 1248889 : var->ndigits = ndigits;
7986 : 1248889 : var->weight = ndigits - 1;
7987 : : }
7988 : :
7989 : : /*
7990 : : * Convert numeric to uint64, rounding if needed.
7991 : : *
7992 : : * If overflow, return false (no error is raised). Return true if okay.
7993 : : */
7994 : : static bool
2342 fujii@postgresql.org 7995 : 101 : numericvar_to_uint64(const NumericVar *var, uint64 *result)
7996 : : {
7997 : : NumericDigit *digits;
7998 : : int ndigits;
7999 : : int weight;
8000 : : int i;
8001 : : uint64 val;
8002 : : NumericVar rounded;
8003 : :
8004 : : /* Round to nearest integer */
8005 : 101 : init_var(&rounded);
8006 : 101 : set_var_from_var(var, &rounded);
8007 : 101 : round_var(&rounded, 0);
8008 : :
8009 : : /* Check for zero input */
8010 : 101 : strip_var(&rounded);
8011 : 101 : ndigits = rounded.ndigits;
8012 [ + + ]: 101 : if (ndigits == 0)
8013 : : {
8014 : 15 : *result = 0;
8015 : 15 : free_var(&rounded);
8016 : 15 : return true;
8017 : : }
8018 : :
8019 : : /* Check for negative input */
8020 [ + + ]: 86 : if (rounded.sign == NUMERIC_NEG)
8021 : : {
8022 : 8 : free_var(&rounded);
8023 : 8 : return false;
8024 : : }
8025 : :
8026 : : /*
8027 : : * For input like 10000000000, we must treat stripped digits as real. So
8028 : : * the loop assumes there are weight+1 digits before the decimal point.
8029 : : */
8030 : 78 : weight = rounded.weight;
8031 [ + - - + ]: 78 : Assert(weight >= 0 && ndigits <= weight + 1);
8032 : :
8033 : : /* Construct the result */
8034 : 78 : digits = rounded.digits;
8035 : 78 : val = digits[0];
8036 [ + + ]: 220 : for (i = 1; i <= weight; i++)
8037 : : {
8038 [ - + ]: 150 : if (unlikely(pg_mul_u64_overflow(val, NBASE, &val)))
8039 : : {
2342 fujii@postgresql.org 8040 :UBC 0 : free_var(&rounded);
8041 : 0 : return false;
8042 : : }
8043 : :
2342 fujii@postgresql.org 8044 [ + - ]:CBC 150 : if (i < ndigits)
8045 : : {
8046 [ + + ]: 150 : if (unlikely(pg_add_u64_overflow(val, digits[i], &val)))
8047 : : {
8048 : 8 : free_var(&rounded);
8049 : 8 : return false;
8050 : : }
8051 : : }
8052 : : }
8053 : :
8054 : 70 : free_var(&rounded);
8055 : :
8056 : 70 : *result = val;
8057 : :
8058 : 70 : return true;
8059 : : }
8060 : :
8061 : : /*
8062 : : * Convert 128 bit integer to numeric.
8063 : : */
8064 : : static void
478 dean.a.rasheed@gmail 8065 : 6262 : int128_to_numericvar(INT128 val, NumericVar *var)
8066 : : {
8067 : : int sign;
8068 : : NumericDigit *ptr;
8069 : : int ndigits;
8070 : : int32 dig;
8071 : :
8072 : : /* int128 can require at most 39 decimal digits; add one for safety */
4271 andres@anarazel.de 8073 : 6262 : alloc_var(var, 40 / DEC_DIGITS);
478 dean.a.rasheed@gmail 8074 : 6262 : sign = int128_sign(val);
8075 : 6262 : var->sign = sign < 0 ? NUMERIC_NEG : NUMERIC_POS;
4271 andres@anarazel.de 8076 : 6262 : var->dscale = 0;
478 dean.a.rasheed@gmail 8077 [ + + ]: 6262 : if (sign == 0)
8078 : : {
4271 andres@anarazel.de 8079 : 137 : var->ndigits = 0;
8080 : 137 : var->weight = 0;
8081 : 137 : return;
8082 : : }
8083 : 6125 : ptr = var->digits + var->ndigits;
8084 : 6125 : ndigits = 0;
8085 : : do
8086 : : {
8087 : 32839 : ptr--;
8088 : 32839 : ndigits++;
478 dean.a.rasheed@gmail 8089 : 32839 : int128_div_mod_int32(&val, NBASE, &dig);
8090 : 32839 : *ptr = (NumericDigit) abs(dig);
8091 [ + + ]: 32839 : } while (!int128_is_zero(val));
4271 andres@anarazel.de 8092 : 6125 : var->digits = ptr;
8093 : 6125 : var->ndigits = ndigits;
8094 : 6125 : var->weight = ndigits - 1;
8095 : : }
8096 : :
8097 : : /*
8098 : : * Convert a NumericVar to float8; if out of range, return +/- HUGE_VAL
8099 : : */
8100 : : static double
3366 8101 : 1265 : numericvar_to_double_no_overflow(const NumericVar *var)
8102 : : {
8103 : : char *tmp;
8104 : : double val;
8105 : : char *endptr;
8106 : :
5120 heikki.linnakangas@i 8107 : 1265 : tmp = get_str_from_var(var);
8108 : :
8109 : : /* unlike float8in, we ignore ERANGE from strtod */
8823 tgl@sss.pgh.pa.us 8110 : 1265 : val = strtod(tmp, &endptr);
8111 [ - + ]: 1265 : if (*endptr != '\0')
8112 : : {
8113 : : /* shouldn't happen ... */
8525 tgl@sss.pgh.pa.us 8114 [ # # ]:UBC 0 : ereport(ERROR,
8115 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
8116 : : errmsg("invalid input syntax for type %s: \"%s\"",
8117 : : "double precision", tmp)));
8118 : : }
8119 : :
8823 tgl@sss.pgh.pa.us 8120 :CBC 1265 : pfree(tmp);
8121 : :
8122 : 1265 : return val;
8123 : : }
8124 : :
8125 : :
8126 : : /*
8127 : : * cmp_var() -
8128 : : *
8129 : : * Compare two values on variable level. We assume zeroes have been
8130 : : * truncated to no digits.
8131 : : */
8132 : : static int
3366 andres@anarazel.de 8133 : 114524 : cmp_var(const NumericVar *var1, const NumericVar *var2)
8134 : : {
7599 bruce@momjian.us 8135 : 229048 : return cmp_var_common(var1->digits, var1->ndigits,
8136 : 114524 : var1->weight, var1->sign,
8137 : 114524 : var2->digits, var2->ndigits,
8138 : 114524 : var2->weight, var2->sign);
8139 : : }
8140 : :
8141 : : /*
8142 : : * cmp_var_common() -
8143 : : *
8144 : : * Main routine of cmp_var(). This function can be used by both
8145 : : * NumericVar and Numeric.
8146 : : */
8147 : : static int
8148 : 18822487 : cmp_var_common(const NumericDigit *var1digits, int var1ndigits,
8149 : : int var1weight, int var1sign,
8150 : : const NumericDigit *var2digits, int var2ndigits,
8151 : : int var2weight, int var2sign)
8152 : : {
8153 [ + + ]: 18822487 : if (var1ndigits == 0)
8154 : : {
8155 [ + + ]: 428734 : if (var2ndigits == 0)
10195 JanWieck@Yahoo.com 8156 : 340754 : return 0;
7599 bruce@momjian.us 8157 [ + + ]: 87980 : if (var2sign == NUMERIC_NEG)
10195 JanWieck@Yahoo.com 8158 : 302 : return 1;
8159 : 87678 : return -1;
8160 : : }
7599 bruce@momjian.us 8161 [ + + ]: 18393753 : if (var2ndigits == 0)
8162 : : {
8163 [ + + ]: 70154 : if (var1sign == NUMERIC_POS)
10195 JanWieck@Yahoo.com 8164 : 64763 : return 1;
8165 : 5391 : return -1;
8166 : : }
8167 : :
7599 bruce@momjian.us 8168 [ + + ]: 18323599 : if (var1sign == NUMERIC_POS)
8169 : : {
8170 [ + + ]: 18276208 : if (var2sign == NUMERIC_NEG)
10195 JanWieck@Yahoo.com 8171 : 15320 : return 1;
7599 bruce@momjian.us 8172 : 18260888 : return cmp_abs_common(var1digits, var1ndigits, var1weight,
8173 : : var2digits, var2ndigits, var2weight);
8174 : : }
8175 : :
8176 [ + + ]: 47391 : if (var2sign == NUMERIC_POS)
10195 JanWieck@Yahoo.com 8177 : 13957 : return -1;
8178 : :
7599 bruce@momjian.us 8179 : 33434 : return cmp_abs_common(var2digits, var2ndigits, var2weight,
8180 : : var1digits, var1ndigits, var1weight);
8181 : : }
8182 : :
8183 : :
8184 : : /*
8185 : : * add_var() -
8186 : : *
8187 : : * Full version of add functionality on variable level (handling signs).
8188 : : * result might point to one of the operands too without danger.
8189 : : */
8190 : : static void
3366 andres@anarazel.de 8191 : 414388 : add_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
8192 : : {
8193 : : /*
8194 : : * Decide on the signs of the two variables what to do
8195 : : */
10195 JanWieck@Yahoo.com 8196 [ + + ]: 414388 : if (var1->sign == NUMERIC_POS)
8197 : : {
8198 [ + + ]: 413133 : if (var2->sign == NUMERIC_POS)
8199 : : {
8200 : : /*
8201 : : * Both are positive result = +(ABS(var1) + ABS(var2))
8202 : : */
8203 : 279532 : add_abs(var1, var2, result);
8204 : 279532 : result->sign = NUMERIC_POS;
8205 : : }
8206 : : else
8207 : : {
8208 : : /*
8209 : : * var1 is positive, var2 is negative Must compare absolute values
8210 : : */
8211 [ + + + - ]: 133601 : switch (cmp_abs(var1, var2))
8212 : : {
9630 tgl@sss.pgh.pa.us 8213 : 150 : case 0:
8214 : : /* ----------
8215 : : * ABS(var1) == ABS(var2)
8216 : : * result = ZERO
8217 : : * ----------
8218 : : */
9811 8219 : 150 : zero_var(result);
9049 bruce@momjian.us 8220 : 150 : result->dscale = Max(var1->dscale, var2->dscale);
10049 8221 : 150 : break;
8222 : :
9630 tgl@sss.pgh.pa.us 8223 : 124193 : case 1:
8224 : : /* ----------
8225 : : * ABS(var1) > ABS(var2)
8226 : : * result = +(ABS(var1) - ABS(var2))
8227 : : * ----------
8228 : : */
10049 bruce@momjian.us 8229 : 124193 : sub_abs(var1, var2, result);
8230 : 124193 : result->sign = NUMERIC_POS;
8231 : 124193 : break;
8232 : :
9630 tgl@sss.pgh.pa.us 8233 : 9258 : case -1:
8234 : : /* ----------
8235 : : * ABS(var1) < ABS(var2)
8236 : : * result = -(ABS(var2) - ABS(var1))
8237 : : * ----------
8238 : : */
10049 bruce@momjian.us 8239 : 9258 : sub_abs(var2, var1, result);
8240 : 9258 : result->sign = NUMERIC_NEG;
8241 : 9258 : break;
8242 : : }
8243 : : }
8244 : : }
8245 : : else
8246 : : {
10195 JanWieck@Yahoo.com 8247 [ + + ]: 1255 : if (var2->sign == NUMERIC_POS)
8248 : : {
8249 : : /* ----------
8250 : : * var1 is negative, var2 is positive
8251 : : * Must compare absolute values
8252 : : * ----------
8253 : : */
8254 [ + + + - ]: 318 : switch (cmp_abs(var1, var2))
8255 : : {
9630 tgl@sss.pgh.pa.us 8256 : 20 : case 0:
8257 : : /* ----------
8258 : : * ABS(var1) == ABS(var2)
8259 : : * result = ZERO
8260 : : * ----------
8261 : : */
9811 8262 : 20 : zero_var(result);
9049 bruce@momjian.us 8263 : 20 : result->dscale = Max(var1->dscale, var2->dscale);
10049 8264 : 20 : break;
8265 : :
9630 tgl@sss.pgh.pa.us 8266 : 197 : case 1:
8267 : : /* ----------
8268 : : * ABS(var1) > ABS(var2)
8269 : : * result = -(ABS(var1) - ABS(var2))
8270 : : * ----------
8271 : : */
10049 bruce@momjian.us 8272 : 197 : sub_abs(var1, var2, result);
8273 : 197 : result->sign = NUMERIC_NEG;
8274 : 197 : break;
8275 : :
9630 tgl@sss.pgh.pa.us 8276 : 101 : case -1:
8277 : : /* ----------
8278 : : * ABS(var1) < ABS(var2)
8279 : : * result = +(ABS(var2) - ABS(var1))
8280 : : * ----------
8281 : : */
10049 bruce@momjian.us 8282 : 101 : sub_abs(var2, var1, result);
8283 : 101 : result->sign = NUMERIC_POS;
8284 : 101 : break;
8285 : : }
8286 : : }
8287 : : else
8288 : : {
8289 : : /* ----------
8290 : : * Both are negative
8291 : : * result = -(ABS(var1) + ABS(var2))
8292 : : * ----------
8293 : : */
10195 JanWieck@Yahoo.com 8294 : 937 : add_abs(var1, var2, result);
8295 : 937 : result->sign = NUMERIC_NEG;
8296 : : }
8297 : : }
8298 : 414388 : }
8299 : :
8300 : :
8301 : : /*
8302 : : * sub_var() -
8303 : : *
8304 : : * Full version of sub functionality on variable level (handling signs).
8305 : : * result might point to one of the operands too without danger.
8306 : : */
8307 : : static void
3366 andres@anarazel.de 8308 : 355524 : sub_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
8309 : : {
8310 : : /*
8311 : : * Decide on the signs of the two variables what to do
8312 : : */
10195 JanWieck@Yahoo.com 8313 [ + + ]: 355524 : if (var1->sign == NUMERIC_POS)
8314 : : {
8315 [ + + ]: 354915 : if (var2->sign == NUMERIC_NEG)
8316 : : {
8317 : : /* ----------
8318 : : * var1 is positive, var2 is negative
8319 : : * result = +(ABS(var1) + ABS(var2))
8320 : : * ----------
8321 : : */
8322 : 18814 : add_abs(var1, var2, result);
8323 : 18814 : result->sign = NUMERIC_POS;
8324 : : }
8325 : : else
8326 : : {
8327 : : /* ----------
8328 : : * Both are positive
8329 : : * Must compare absolute values
8330 : : * ----------
8331 : : */
8332 [ + + + - ]: 336101 : switch (cmp_abs(var1, var2))
8333 : : {
9630 tgl@sss.pgh.pa.us 8334 : 29454 : case 0:
8335 : : /* ----------
8336 : : * ABS(var1) == ABS(var2)
8337 : : * result = ZERO
8338 : : * ----------
8339 : : */
9811 8340 : 29454 : zero_var(result);
9049 bruce@momjian.us 8341 : 29454 : result->dscale = Max(var1->dscale, var2->dscale);
10049 8342 : 29454 : break;
8343 : :
9630 tgl@sss.pgh.pa.us 8344 : 301678 : case 1:
8345 : : /* ----------
8346 : : * ABS(var1) > ABS(var2)
8347 : : * result = +(ABS(var1) - ABS(var2))
8348 : : * ----------
8349 : : */
10049 bruce@momjian.us 8350 : 301678 : sub_abs(var1, var2, result);
8351 : 301678 : result->sign = NUMERIC_POS;
8352 : 301678 : break;
8353 : :
9630 tgl@sss.pgh.pa.us 8354 : 4969 : case -1:
8355 : : /* ----------
8356 : : * ABS(var1) < ABS(var2)
8357 : : * result = -(ABS(var2) - ABS(var1))
8358 : : * ----------
8359 : : */
10049 bruce@momjian.us 8360 : 4969 : sub_abs(var2, var1, result);
8361 : 4969 : result->sign = NUMERIC_NEG;
8362 : 4969 : break;
8363 : : }
8364 : : }
8365 : : }
8366 : : else
8367 : : {
10195 JanWieck@Yahoo.com 8368 [ + + ]: 609 : if (var2->sign == NUMERIC_NEG)
8369 : : {
8370 : : /* ----------
8371 : : * Both are negative
8372 : : * Must compare absolute values
8373 : : * ----------
8374 : : */
8375 [ + + + - ]: 304 : switch (cmp_abs(var1, var2))
8376 : : {
9630 tgl@sss.pgh.pa.us 8377 : 110 : case 0:
8378 : : /* ----------
8379 : : * ABS(var1) == ABS(var2)
8380 : : * result = ZERO
8381 : : * ----------
8382 : : */
9811 8383 : 110 : zero_var(result);
9049 bruce@momjian.us 8384 : 110 : result->dscale = Max(var1->dscale, var2->dscale);
10049 8385 : 110 : break;
8386 : :
9630 tgl@sss.pgh.pa.us 8387 : 162 : case 1:
8388 : : /* ----------
8389 : : * ABS(var1) > ABS(var2)
8390 : : * result = -(ABS(var1) - ABS(var2))
8391 : : * ----------
8392 : : */
10049 bruce@momjian.us 8393 : 162 : sub_abs(var1, var2, result);
8394 : 162 : result->sign = NUMERIC_NEG;
8395 : 162 : break;
8396 : :
9630 tgl@sss.pgh.pa.us 8397 : 32 : case -1:
8398 : : /* ----------
8399 : : * ABS(var1) < ABS(var2)
8400 : : * result = +(ABS(var2) - ABS(var1))
8401 : : * ----------
8402 : : */
10049 bruce@momjian.us 8403 : 32 : sub_abs(var2, var1, result);
8404 : 32 : result->sign = NUMERIC_POS;
8405 : 32 : break;
8406 : : }
8407 : : }
8408 : : else
8409 : : {
8410 : : /* ----------
8411 : : * var1 is negative, var2 is positive
8412 : : * result = -(ABS(var1) + ABS(var2))
8413 : : * ----------
8414 : : */
10195 JanWieck@Yahoo.com 8415 : 305 : add_abs(var1, var2, result);
8416 : 305 : result->sign = NUMERIC_NEG;
8417 : : }
8418 : : }
8419 : 355524 : }
8420 : :
8421 : :
8422 : : /*
8423 : : * mul_var() -
8424 : : *
8425 : : * Multiplication on variable level. Product of var1 * var2 is stored
8426 : : * in result. Result is rounded to no more than rscale fractional digits.
8427 : : */
8428 : : static void
3366 andres@anarazel.de 8429 : 797543 : mul_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result,
8430 : : int rscale)
8431 : : {
8432 : : int res_ndigits;
8433 : : int res_ndigitpairs;
8434 : : int res_sign;
8435 : : int res_weight;
8436 : : int pair_offset;
8437 : : int maxdigits;
8438 : : int maxdigitpairs;
8439 : : uint64 *dig,
8440 : : *dig_i1_off;
8441 : : uint64 maxdig;
8442 : : uint64 carry;
8443 : : uint64 newdig;
8444 : : int var1ndigits;
8445 : : int var2ndigits;
8446 : : int var1ndigitpairs;
8447 : : int var2ndigitpairs;
8448 : : NumericDigit *var1digits;
8449 : : NumericDigit *var2digits;
8450 : : uint32 var1digitpair;
8451 : : uint32 *var2digitpairs;
8452 : : NumericDigit *res_digits;
8453 : : int i,
8454 : : i1,
8455 : : i2,
8456 : : i2limit;
8457 : :
8458 : : /*
8459 : : * Arrange for var1 to be the shorter of the two numbers. This improves
8460 : : * performance because the inner multiplication loop is much simpler than
8461 : : * the outer loop, so it's better to have a smaller number of iterations
8462 : : * of the outer loop. This also reduces the number of times that the
8463 : : * accumulator array needs to be normalized.
8464 : : */
4032 tgl@sss.pgh.pa.us 8465 [ + + ]: 797543 : if (var1->ndigits > var2->ndigits)
8466 : : {
3366 andres@anarazel.de 8467 : 12408 : const NumericVar *tmp = var1;
8468 : :
4032 tgl@sss.pgh.pa.us 8469 : 12408 : var1 = var2;
8470 : 12408 : var2 = tmp;
8471 : : }
8472 : :
8473 : : /* copy these values into local vars for speed in inner loop */
8474 : 797543 : var1ndigits = var1->ndigits;
8475 : 797543 : var2ndigits = var2->ndigits;
8476 : 797543 : var1digits = var1->digits;
8477 : 797543 : var2digits = var2->digits;
8478 : :
872 dean.a.rasheed@gmail 8479 [ + + ]: 797543 : if (var1ndigits == 0)
8480 : : {
8481 : : /* one or both inputs is zero; so is result */
8653 tgl@sss.pgh.pa.us 8482 : 1947 : zero_var(result);
8483 : 1947 : result->dscale = rscale;
8484 : 1947 : return;
8485 : : }
8486 : :
8487 : : /*
8488 : : * If var1 has 1-6 digits and the exact result was requested, delegate to
8489 : : * mul_var_short() which uses a faster direct multiplication algorithm.
8490 : : */
835 dean.a.rasheed@gmail 8491 [ + + + + ]: 795596 : if (var1ndigits <= 6 && rscale == var1->dscale + var2->dscale)
8492 : : {
872 8493 : 774979 : mul_var_short(var1, var2, result);
8494 : 774979 : return;
8495 : : }
8496 : :
8497 : : /* Determine result sign */
10195 JanWieck@Yahoo.com 8498 [ + + ]: 20617 : if (var1->sign == var2->sign)
8499 : 19338 : res_sign = NUMERIC_POS;
8500 : : else
8501 : 1279 : res_sign = NUMERIC_NEG;
8502 : :
8503 : : /*
8504 : : * Determine the number of result digits to compute and the (maximum
8505 : : * possible) result weight. If the exact result would have more than
8506 : : * rscale fractional digits, truncate the computation with
8507 : : * MUL_GUARD_DIGITS guard digits, i.e., ignore input digits that would
8508 : : * only contribute to the right of that. (This will give the exact
8509 : : * rounded-to-rscale answer unless carries out of the ignored positions
8510 : : * would have propagated through more than MUL_GUARD_DIGITS digits.)
8511 : : *
8512 : : * Note: an exact computation could not produce more than var1ndigits +
8513 : : * var2ndigits digits, but we allocate at least one extra output digit in
8514 : : * case rscale-driven rounding produces a carry out of the highest exact
8515 : : * digit.
8516 : : *
8517 : : * The computation itself is done using base-NBASE^2 arithmetic, so we
8518 : : * actually process the input digits in pairs, producing a base-NBASE^2
8519 : : * intermediate result. This significantly improves performance, since
8520 : : * schoolbook multiplication is O(N^2) in the number of input digits, and
8521 : : * working in base NBASE^2 effectively halves "N".
8522 : : *
8523 : : * Note: in a truncated computation, we must compute at least one extra
8524 : : * output digit to ensure that all the guard digits are fully computed.
8525 : : */
8526 : : /* digit pairs in each input */
835 dean.a.rasheed@gmail 8527 : 20617 : var1ndigitpairs = (var1ndigits + 1) / 2;
8528 : 20617 : var2ndigitpairs = (var2ndigits + 1) / 2;
8529 : :
8530 : : /* digits in exact result */
8531 : 20617 : res_ndigits = var1ndigits + var2ndigits;
8532 : :
8533 : : /* digit pairs in exact result with at least one extra output digit */
8534 : 20617 : res_ndigitpairs = res_ndigits / 2 + 1;
8535 : :
8536 : : /* pair offset to align result to end of dig[] */
8537 : 20617 : pair_offset = res_ndigitpairs - var1ndigitpairs - var2ndigitpairs + 1;
8538 : :
8539 : : /* maximum possible result weight (odd-length inputs shifted up below) */
8540 : 20617 : res_weight = var1->weight + var2->weight + 1 + 2 * res_ndigitpairs -
8541 : 20617 : res_ndigits - (var1ndigits & 1) - (var2ndigits & 1);
8542 : :
8543 : : /* rscale-based truncation with at least one extra output digit */
4032 tgl@sss.pgh.pa.us 8544 : 20617 : maxdigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS +
8545 : : MUL_GUARD_DIGITS;
835 dean.a.rasheed@gmail 8546 : 20617 : maxdigitpairs = maxdigits / 2 + 1;
8547 : :
8548 : 20617 : res_ndigitpairs = Min(res_ndigitpairs, maxdigitpairs);
8549 : 20617 : res_ndigits = 2 * res_ndigitpairs;
8550 : :
8551 : : /*
8552 : : * In the computation below, digit pair i1 of var1 and digit pair i2 of
8553 : : * var2 are multiplied and added to digit i1+i2+pair_offset of dig[]. Thus
8554 : : * input digit pairs with index >= res_ndigitpairs - pair_offset don't
8555 : : * contribute to the result, and can be ignored.
8556 : : */
8557 [ + + ]: 20617 : if (res_ndigitpairs <= pair_offset)
8558 : : {
8559 : : /* All input digits will be ignored; so result is zero */
4032 tgl@sss.pgh.pa.us 8560 : 10 : zero_var(result);
8561 : 10 : result->dscale = rscale;
8562 : 10 : return;
8563 : : }
835 dean.a.rasheed@gmail 8564 : 20607 : var1ndigitpairs = Min(var1ndigitpairs, res_ndigitpairs - pair_offset);
8565 : 20607 : var2ndigitpairs = Min(var2ndigitpairs, res_ndigitpairs - pair_offset);
8566 : :
8567 : : /*
8568 : : * We do the arithmetic in an array "dig[]" of unsigned 64-bit integers.
8569 : : * Since PG_UINT64_MAX is much larger than NBASE^4, this gives us a lot of
8570 : : * headroom to avoid normalizing carries immediately.
8571 : : *
8572 : : * maxdig tracks the maximum possible value of any dig[] entry; when this
8573 : : * threatens to exceed PG_UINT64_MAX, we take the time to propagate
8574 : : * carries. Furthermore, we need to ensure that overflow doesn't occur
8575 : : * during the carry propagation passes either. The carry values could be
8576 : : * as much as PG_UINT64_MAX / NBASE^2, so really we must normalize when
8577 : : * digits threaten to exceed PG_UINT64_MAX - PG_UINT64_MAX / NBASE^2.
8578 : : *
8579 : : * To avoid overflow in maxdig itself, it actually represents the maximum
8580 : : * possible value divided by NBASE^2-1, i.e., at the top of the loop it is
8581 : : * known that no dig[] entry exceeds maxdig * (NBASE^2-1).
8582 : : *
8583 : : * The conversion of var1 to base NBASE^2 is done on the fly, as each new
8584 : : * digit is required. The digits of var2 are converted upfront, and
8585 : : * stored at the end of dig[]. To avoid loss of precision, the input
8586 : : * digits are aligned with the start of digit pair array, effectively
8587 : : * shifting them up (multiplying by NBASE) if the inputs have an odd
8588 : : * number of NBASE digits.
8589 : : */
8590 : 20607 : dig = (uint64 *) palloc(res_ndigitpairs * sizeof(uint64) +
8591 : : var2ndigitpairs * sizeof(uint32));
8592 : :
8593 : : /* convert var2 to base NBASE^2, shifting up if its length is odd */
8594 : 20607 : var2digitpairs = (uint32 *) (dig + res_ndigitpairs);
8595 : :
8596 [ + + ]: 1048193 : for (i2 = 0; i2 < var2ndigitpairs - 1; i2++)
8597 : 1027586 : var2digitpairs[i2] = var2digits[2 * i2] * NBASE + var2digits[2 * i2 + 1];
8598 : :
8599 [ + + ]: 20607 : if (2 * i2 + 1 < var2ndigits)
8600 : 14623 : var2digitpairs[i2] = var2digits[2 * i2] * NBASE + var2digits[2 * i2 + 1];
8601 : : else
8602 : 5984 : var2digitpairs[i2] = var2digits[2 * i2] * NBASE;
8603 : :
8604 : : /*
8605 : : * Start by multiplying var2 by the least significant contributing digit
8606 : : * pair from var1, storing the results at the end of dig[], and filling
8607 : : * the leading digits with zeros.
8608 : : *
8609 : : * The loop here is the same as the inner loop below, except that we set
8610 : : * the results in dig[], rather than adding to them. This is the
8611 : : * performance bottleneck for multiplication, so we want to keep it simple
8612 : : * enough so that it can be auto-vectorized. Accordingly, process the
8613 : : * digits left-to-right even though schoolbook multiplication would
8614 : : * suggest right-to-left. Since we aren't propagating carries in this
8615 : : * loop, the order does not matter.
8616 : : */
8617 : 20607 : i1 = var1ndigitpairs - 1;
8618 [ + + ]: 20607 : if (2 * i1 + 1 < var1ndigits)
8619 : 9155 : var1digitpair = var1digits[2 * i1] * NBASE + var1digits[2 * i1 + 1];
8620 : : else
8621 : 11452 : var1digitpair = var1digits[2 * i1] * NBASE;
8622 : 20607 : maxdig = var1digitpair;
8623 : :
8624 : 20607 : i2limit = Min(var2ndigitpairs, res_ndigitpairs - i1 - pair_offset);
8625 : 20607 : dig_i1_off = &dig[i1 + pair_offset];
8626 : :
8627 : 20607 : memset(dig, 0, (i1 + pair_offset) * sizeof(uint64));
8628 [ + + ]: 930395 : for (i2 = 0; i2 < i2limit; i2++)
8629 : 909788 : dig_i1_off[i2] = (uint64) var1digitpair * var2digitpairs[i2];
8630 : :
8631 : : /*
8632 : : * Next, multiply var2 by the remaining digit pairs from var1, adding the
8633 : : * results to dig[] at the appropriate offsets, and normalizing whenever
8634 : : * there is a risk of any dig[] entry overflowing.
8635 : : */
8636 [ + + ]: 1012280 : for (i1 = i1 - 1; i1 >= 0; i1--)
8637 : : {
8638 : 991673 : var1digitpair = var1digits[2 * i1] * NBASE + var1digits[2 * i1 + 1];
8639 [ + + ]: 991673 : if (var1digitpair == 0)
8653 tgl@sss.pgh.pa.us 8640 : 786344 : continue;
8641 : :
8642 : : /* Time to normalize? */
835 dean.a.rasheed@gmail 8643 : 205329 : maxdig += var1digitpair;
8644 [ + + ]: 205329 : if (maxdig > (PG_UINT64_MAX - PG_UINT64_MAX / NBASE_SQR) / (NBASE_SQR - 1))
8645 : : {
8646 : : /* Yes, do it (to base NBASE^2) */
8653 tgl@sss.pgh.pa.us 8647 : 21 : carry = 0;
835 dean.a.rasheed@gmail 8648 [ + + ]: 84074 : for (i = res_ndigitpairs - 1; i >= 0; i--)
8649 : : {
8653 tgl@sss.pgh.pa.us 8650 : 84053 : newdig = dig[i] + carry;
835 dean.a.rasheed@gmail 8651 [ + + ]: 84053 : if (newdig >= NBASE_SQR)
8652 : : {
8653 : 80719 : carry = newdig / NBASE_SQR;
8654 : 80719 : newdig -= carry * NBASE_SQR;
8655 : : }
8656 : : else
8653 tgl@sss.pgh.pa.us 8657 : 3334 : carry = 0;
8658 : 84053 : dig[i] = newdig;
8659 : : }
8660 [ - + ]: 21 : Assert(carry == 0);
8661 : : /* Reset maxdig to indicate new worst-case */
835 dean.a.rasheed@gmail 8662 : 21 : maxdig = 1 + var1digitpair;
8663 : : }
8664 : :
8665 : : /* Multiply and add */
8666 : 205329 : i2limit = Min(var2ndigitpairs, res_ndigitpairs - i1 - pair_offset);
8667 : 205329 : dig_i1_off = &dig[i1 + pair_offset];
8668 : :
8669 [ + + ]: 87004803 : for (i2 = 0; i2 < i2limit; i2++)
8670 : 86799474 : dig_i1_off[i2] += (uint64) var1digitpair * var2digitpairs[i2];
8671 : : }
8672 : :
8673 : : /*
8674 : : * Now we do a final carry propagation pass to normalize back to base
8675 : : * NBASE^2, and construct the base-NBASE result digits. Note that this is
8676 : : * still done at full precision w/guard digits.
8677 : : */
8653 tgl@sss.pgh.pa.us 8678 : 20607 : alloc_var(result, res_ndigits);
8679 : 20607 : res_digits = result->digits;
8680 : 20607 : carry = 0;
835 dean.a.rasheed@gmail 8681 [ + + ]: 1946024 : for (i = res_ndigitpairs - 1; i >= 0; i--)
8682 : : {
8653 tgl@sss.pgh.pa.us 8683 : 1925417 : newdig = dig[i] + carry;
835 dean.a.rasheed@gmail 8684 [ + + ]: 1925417 : if (newdig >= NBASE_SQR)
8685 : : {
8686 : 289944 : carry = newdig / NBASE_SQR;
8687 : 289944 : newdig -= carry * NBASE_SQR;
8688 : : }
8689 : : else
8653 tgl@sss.pgh.pa.us 8690 : 1635473 : carry = 0;
835 dean.a.rasheed@gmail 8691 : 1925417 : res_digits[2 * i + 1] = (NumericDigit) ((uint32) newdig % NBASE);
8692 : 1925417 : res_digits[2 * i] = (NumericDigit) ((uint32) newdig / NBASE);
8693 : : }
8653 tgl@sss.pgh.pa.us 8694 [ - + ]: 20607 : Assert(carry == 0);
8695 : :
8696 : 20607 : pfree(dig);
8697 : :
8698 : : /*
8699 : : * Finally, round the result to the requested precision.
8700 : : */
10049 bruce@momjian.us 8701 : 20607 : result->weight = res_weight;
8702 : 20607 : result->sign = res_sign;
8703 : :
8704 : : /* Round to target rscale (and set result->dscale) */
8653 tgl@sss.pgh.pa.us 8705 : 20607 : round_var(result, rscale);
8706 : :
8707 : : /* Strip leading and trailing zeroes */
8708 : 20607 : strip_var(result);
8709 : : }
8710 : :
8711 : :
8712 : : /*
8713 : : * mul_var_short() -
8714 : : *
8715 : : * Special-case multiplication function used when var1 has 1-6 digits, var2
8716 : : * has at least as many digits as var1, and the exact product var1 * var2 is
8717 : : * requested.
8718 : : */
8719 : : static void
872 dean.a.rasheed@gmail 8720 : 774979 : mul_var_short(const NumericVar *var1, const NumericVar *var2,
8721 : : NumericVar *result)
8722 : : {
8723 : 774979 : int var1ndigits = var1->ndigits;
8724 : 774979 : int var2ndigits = var2->ndigits;
8725 : 774979 : NumericDigit *var1digits = var1->digits;
8726 : 774979 : NumericDigit *var2digits = var2->digits;
8727 : : int res_sign;
8728 : : int res_weight;
8729 : : int res_ndigits;
8730 : : NumericDigit *res_buf;
8731 : : NumericDigit *res_digits;
824 8732 : 774979 : uint32 carry = 0;
8733 : : uint32 term;
8734 : :
8735 : : /* Check preconditions */
872 8736 [ - + ]: 774979 : Assert(var1ndigits >= 1);
835 8737 [ - + ]: 774979 : Assert(var1ndigits <= 6);
872 8738 [ - + ]: 774979 : Assert(var2ndigits >= var1ndigits);
8739 : :
8740 : : /*
8741 : : * Determine the result sign, weight, and number of digits to calculate.
8742 : : * The weight figured here is correct if the product has no leading zero
8743 : : * digits; otherwise strip_var() will fix things up. Note that, unlike
8744 : : * mul_var(), we do not need to allocate an extra output digit, because we
8745 : : * are not rounding here.
8746 : : */
8747 [ + + ]: 774979 : if (var1->sign == var2->sign)
8748 : 774172 : res_sign = NUMERIC_POS;
8749 : : else
8750 : 807 : res_sign = NUMERIC_NEG;
8751 : 774979 : res_weight = var1->weight + var2->weight + 1;
8752 : 774979 : res_ndigits = var1ndigits + var2ndigits;
8753 : :
8754 : : /* Allocate result digit array */
8755 : 774979 : res_buf = digitbuf_alloc(res_ndigits + 1);
8756 : 774979 : res_buf[0] = 0; /* spare digit for later rounding */
8757 : 774979 : res_digits = res_buf + 1;
8758 : :
8759 : : /*
8760 : : * Compute the result digits in reverse, in one pass, propagating the
8761 : : * carry up as we go. The i'th result digit consists of the sum of the
8762 : : * products var1digits[i1] * var2digits[i2] for which i = i1 + i2 + 1.
8763 : : */
8764 : : #define PRODSUM1(v1,i1,v2,i2) ((v1)[(i1)] * (v2)[(i2)])
8765 : : #define PRODSUM2(v1,i1,v2,i2) (PRODSUM1(v1,i1,v2,i2) + (v1)[(i1)+1] * (v2)[(i2)-1])
8766 : : #define PRODSUM3(v1,i1,v2,i2) (PRODSUM2(v1,i1,v2,i2) + (v1)[(i1)+2] * (v2)[(i2)-2])
8767 : : #define PRODSUM4(v1,i1,v2,i2) (PRODSUM3(v1,i1,v2,i2) + (v1)[(i1)+3] * (v2)[(i2)-3])
8768 : : #define PRODSUM5(v1,i1,v2,i2) (PRODSUM4(v1,i1,v2,i2) + (v1)[(i1)+4] * (v2)[(i2)-4])
8769 : : #define PRODSUM6(v1,i1,v2,i2) (PRODSUM5(v1,i1,v2,i2) + (v1)[(i1)+5] * (v2)[(i2)-5])
8770 : :
8771 [ + + + + : 774979 : switch (var1ndigits)
+ + - ]
8772 : : {
8773 : 770874 : case 1:
8774 : : /* ---------
8775 : : * 1-digit case:
8776 : : * var1ndigits = 1
8777 : : * var2ndigits >= 1
8778 : : * res_ndigits = var2ndigits + 1
8779 : : * ----------
8780 : : */
835 8781 [ + + ]: 2412356 : for (int i = var2ndigits - 1; i >= 0; i--)
8782 : : {
8783 : 1641482 : term = PRODSUM1(var1digits, 0, var2digits, i) + carry;
872 8784 : 1641482 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8785 : 1641482 : carry = term / NBASE;
8786 : : }
8787 : 770874 : res_digits[0] = (NumericDigit) carry;
8788 : 770874 : break;
8789 : :
8790 : 519 : case 2:
8791 : : /* ---------
8792 : : * 2-digit case:
8793 : : * var1ndigits = 2
8794 : : * var2ndigits >= 2
8795 : : * res_ndigits = var2ndigits + 2
8796 : : * ----------
8797 : : */
8798 : : /* last result digit and carry */
835 8799 : 519 : term = PRODSUM1(var1digits, 1, var2digits, var2ndigits - 1);
872 8800 : 519 : res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
8801 : 519 : carry = term / NBASE;
8802 : :
8803 : : /* remaining digits, except for the first two */
835 8804 [ + + ]: 1573 : for (int i = var2ndigits - 1; i >= 1; i--)
8805 : : {
8806 : 1054 : term = PRODSUM2(var1digits, 0, var2digits, i) + carry;
872 8807 : 1054 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8808 : 1054 : carry = term / NBASE;
8809 : : }
8810 : 519 : break;
8811 : :
8812 : 146 : case 3:
8813 : : /* ---------
8814 : : * 3-digit case:
8815 : : * var1ndigits = 3
8816 : : * var2ndigits >= 3
8817 : : * res_ndigits = var2ndigits + 3
8818 : : * ----------
8819 : : */
8820 : : /* last two result digits */
835 8821 : 146 : term = PRODSUM1(var1digits, 2, var2digits, var2ndigits - 1);
872 8822 : 146 : res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
8823 : 146 : carry = term / NBASE;
8824 : :
835 8825 : 146 : term = PRODSUM2(var1digits, 1, var2digits, var2ndigits - 1) + carry;
872 8826 : 146 : res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
8827 : 146 : carry = term / NBASE;
8828 : :
8829 : : /* remaining digits, except for the first three */
835 8830 [ + + ]: 387 : for (int i = var2ndigits - 1; i >= 2; i--)
8831 : : {
8832 : 241 : term = PRODSUM3(var1digits, 0, var2digits, i) + carry;
872 8833 : 241 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8834 : 241 : carry = term / NBASE;
8835 : : }
8836 : 146 : break;
8837 : :
8838 : 2848 : case 4:
8839 : : /* ---------
8840 : : * 4-digit case:
8841 : : * var1ndigits = 4
8842 : : * var2ndigits >= 4
8843 : : * res_ndigits = var2ndigits + 4
8844 : : * ----------
8845 : : */
8846 : : /* last three result digits */
835 8847 : 2848 : term = PRODSUM1(var1digits, 3, var2digits, var2ndigits - 1);
872 8848 : 2848 : res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
8849 : 2848 : carry = term / NBASE;
8850 : :
835 8851 : 2848 : term = PRODSUM2(var1digits, 2, var2digits, var2ndigits - 1) + carry;
872 8852 : 2848 : res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
8853 : 2848 : carry = term / NBASE;
8854 : :
835 8855 : 2848 : term = PRODSUM3(var1digits, 1, var2digits, var2ndigits - 1) + carry;
872 8856 : 2848 : res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
8857 : 2848 : carry = term / NBASE;
8858 : :
8859 : : /* remaining digits, except for the first four */
835 8860 [ + + ]: 7938 : for (int i = var2ndigits - 1; i >= 3; i--)
8861 : : {
8862 : 5090 : term = PRODSUM4(var1digits, 0, var2digits, i) + carry;
872 8863 : 5090 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8864 : 5090 : carry = term / NBASE;
8865 : : }
835 8866 : 2848 : break;
8867 : :
8868 : 91 : case 5:
8869 : : /* ---------
8870 : : * 5-digit case:
8871 : : * var1ndigits = 5
8872 : : * var2ndigits >= 5
8873 : : * res_ndigits = var2ndigits + 5
8874 : : * ----------
8875 : : */
8876 : : /* last four result digits */
8877 : 91 : term = PRODSUM1(var1digits, 4, var2digits, var2ndigits - 1);
8878 : 91 : res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
872 8879 : 91 : carry = term / NBASE;
8880 : :
835 8881 : 91 : term = PRODSUM2(var1digits, 3, var2digits, var2ndigits - 1) + carry;
8882 : 91 : res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
8883 : 91 : carry = term / NBASE;
8884 : :
8885 : 91 : term = PRODSUM3(var1digits, 2, var2digits, var2ndigits - 1) + carry;
8886 : 91 : res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
872 8887 : 91 : carry = term / NBASE;
8888 : :
835 8889 : 91 : term = PRODSUM4(var1digits, 1, var2digits, var2ndigits - 1) + carry;
8890 : 91 : res_digits[res_ndigits - 4] = (NumericDigit) (term % NBASE);
8891 : 91 : carry = term / NBASE;
8892 : :
8893 : : /* remaining digits, except for the first five */
8894 [ + + ]: 242 : for (int i = var2ndigits - 1; i >= 4; i--)
8895 : : {
8896 : 151 : term = PRODSUM5(var1digits, 0, var2digits, i) + carry;
8897 : 151 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8898 : 151 : carry = term / NBASE;
8899 : : }
8900 : 91 : break;
8901 : :
8902 : 501 : case 6:
8903 : : /* ---------
8904 : : * 6-digit case:
8905 : : * var1ndigits = 6
8906 : : * var2ndigits >= 6
8907 : : * res_ndigits = var2ndigits + 6
8908 : : * ----------
8909 : : */
8910 : : /* last five result digits */
8911 : 501 : term = PRODSUM1(var1digits, 5, var2digits, var2ndigits - 1);
8912 : 501 : res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
8913 : 501 : carry = term / NBASE;
8914 : :
8915 : 501 : term = PRODSUM2(var1digits, 4, var2digits, var2ndigits - 1) + carry;
8916 : 501 : res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
8917 : 501 : carry = term / NBASE;
8918 : :
8919 : 501 : term = PRODSUM3(var1digits, 3, var2digits, var2ndigits - 1) + carry;
8920 : 501 : res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
8921 : 501 : carry = term / NBASE;
8922 : :
8923 : 501 : term = PRODSUM4(var1digits, 2, var2digits, var2ndigits - 1) + carry;
8924 : 501 : res_digits[res_ndigits - 4] = (NumericDigit) (term % NBASE);
8925 : 501 : carry = term / NBASE;
8926 : :
8927 : 501 : term = PRODSUM5(var1digits, 1, var2digits, var2ndigits - 1) + carry;
8928 : 501 : res_digits[res_ndigits - 5] = (NumericDigit) (term % NBASE);
8929 : 501 : carry = term / NBASE;
8930 : :
8931 : : /* remaining digits, except for the first six */
8932 [ + + ]: 1400 : for (int i = var2ndigits - 1; i >= 5; i--)
8933 : : {
8934 : 899 : term = PRODSUM6(var1digits, 0, var2digits, i) + carry;
8935 : 899 : res_digits[i + 1] = (NumericDigit) (term % NBASE);
8936 : 899 : carry = term / NBASE;
8937 : : }
8938 : 501 : break;
8939 : : }
8940 : :
8941 : : /*
8942 : : * Finally, for var1ndigits > 1, compute the remaining var1ndigits most
8943 : : * significant result digits.
8944 : : */
8945 [ + + + + : 774979 : switch (var1ndigits)
+ + ]
8946 : : {
8947 : 501 : case 6:
8948 : 501 : term = PRODSUM5(var1digits, 0, var2digits, 4) + carry;
8949 : 501 : res_digits[5] = (NumericDigit) (term % NBASE);
8950 : 501 : carry = term / NBASE;
8951 : : pg_fallthrough;
8952 : 592 : case 5:
8953 : 592 : term = PRODSUM4(var1digits, 0, var2digits, 3) + carry;
8954 : 592 : res_digits[4] = (NumericDigit) (term % NBASE);
8955 : 592 : carry = term / NBASE;
8956 : : pg_fallthrough;
8957 : 3440 : case 4:
8958 : 3440 : term = PRODSUM3(var1digits, 0, var2digits, 2) + carry;
8959 : 3440 : res_digits[3] = (NumericDigit) (term % NBASE);
8960 : 3440 : carry = term / NBASE;
8961 : : pg_fallthrough;
8962 : 3586 : case 3:
8963 : 3586 : term = PRODSUM2(var1digits, 0, var2digits, 1) + carry;
8964 : 3586 : res_digits[2] = (NumericDigit) (term % NBASE);
8965 : 3586 : carry = term / NBASE;
8966 : : pg_fallthrough;
8967 : 4105 : case 2:
8968 : 4105 : term = PRODSUM1(var1digits, 0, var2digits, 0) + carry;
872 8969 : 4105 : res_digits[1] = (NumericDigit) (term % NBASE);
8970 : 4105 : res_digits[0] = (NumericDigit) (term / NBASE);
8971 : 4105 : break;
8972 : : }
8973 : :
8974 : : /* Store the product in result */
8975 [ + + ]: 774979 : digitbuf_free(result->buf);
8976 : 774979 : result->ndigits = res_ndigits;
8977 : 774979 : result->buf = res_buf;
8978 : 774979 : result->digits = res_digits;
8979 : 774979 : result->weight = res_weight;
8980 : 774979 : result->sign = res_sign;
8981 : 774979 : result->dscale = var1->dscale + var2->dscale;
8982 : :
8983 : : /* Strip leading and trailing zeroes */
8984 : 774979 : strip_var(result);
8985 : 774979 : }
8986 : :
8987 : :
8988 : : /*
8989 : : * div_var() -
8990 : : *
8991 : : * Compute the quotient var1 / var2 to rscale fractional digits.
8992 : : *
8993 : : * If "round" is true, the result is rounded at the rscale'th digit; if
8994 : : * false, it is truncated (towards zero) at that digit.
8995 : : *
8996 : : * If "exact" is true, the exact result is computed to the specified rscale;
8997 : : * if false, successive quotient digits are approximated up to rscale plus
8998 : : * DIV_GUARD_DIGITS extra digits, ignoring all contributions from digits to
8999 : : * the right of that, before rounding or truncating to the specified rscale.
9000 : : * This can be significantly faster, and usually gives the same result as the
9001 : : * exact computation, but it may occasionally be off by one in the final
9002 : : * digit, if contributions from the ignored digits would have propagated
9003 : : * through the guard digits. This is good enough for the transcendental
9004 : : * functions, where small errors are acceptable.
9005 : : */
9006 : : static void
3366 andres@anarazel.de 9007 : 382453 : div_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result,
9008 : : int rscale, bool round, bool exact)
9009 : : {
785 dean.a.rasheed@gmail 9010 : 382453 : int var1ndigits = var1->ndigits;
9011 : 382453 : int var2ndigits = var2->ndigits;
9012 : : int res_sign;
9013 : : int res_weight;
9014 : : int res_ndigits;
9015 : : int var1ndigitpairs;
9016 : : int var2ndigitpairs;
9017 : : int res_ndigitpairs;
9018 : : int div_ndigitpairs;
9019 : : int64 *dividend;
9020 : : int32 *divisor;
9021 : : double fdivisor,
9022 : : fdivisorinverse,
9023 : : fdividend,
9024 : : fquotient;
9025 : : int64 maxdiv;
9026 : : int qi;
9027 : : int32 qdigit;
9028 : : int64 carry;
9029 : : int64 newdig;
9030 : : int64 *remainder;
9031 : : NumericDigit *res_digits;
9032 : : int i;
9033 : :
9034 : : /*
9035 : : * First of all division by zero check; we must not be handed an
9036 : : * unnormalized divisor.
9037 : : */
6812 tgl@sss.pgh.pa.us 9038 [ + + - + ]: 382453 : if (var2ndigits == 0 || var2->digits[0] == 0)
9039 [ + - ]: 4 : ereport(ERROR,
9040 : : (errcode(ERRCODE_DIVISION_BY_ZERO),
9041 : : errmsg("division by zero")));
9042 : :
9043 : : /*
9044 : : * If the divisor has just one or two digits, delegate to div_var_int(),
9045 : : * which uses fast short division.
9046 : : *
9047 : : * Similarly, on platforms with 128-bit integer support, delegate to
9048 : : * div_var_int64() for divisors with three or four digits.
9049 : : */
1735 dean.a.rasheed@gmail 9050 [ + + ]: 382449 : if (var2ndigits <= 2)
9051 : : {
9052 : : int idivisor;
9053 : : int idivisor_weight;
9054 : :
9055 : 378117 : idivisor = var2->digits[0];
9056 : 378117 : idivisor_weight = var2->weight;
9057 [ + + ]: 378117 : if (var2ndigits == 2)
9058 : : {
9059 : 4276 : idivisor = idivisor * NBASE + var2->digits[1];
9060 : 4276 : idivisor_weight--;
9061 : : }
9062 [ + + ]: 378117 : if (var2->sign == NUMERIC_NEG)
9063 : 440 : idivisor = -idivisor;
9064 : :
9065 : 378117 : div_var_int(var1, idivisor, idivisor_weight, result, rscale, round);
9066 : 378117 : return;
9067 : : }
9068 : : #ifdef HAVE_INT128
1405 9069 [ + + ]: 4332 : if (var2ndigits <= 4)
9070 : : {
9071 : : int64 idivisor;
9072 : : int idivisor_weight;
9073 : :
9074 : 360 : idivisor = var2->digits[0];
9075 : 360 : idivisor_weight = var2->weight;
9076 [ + + ]: 1340 : for (i = 1; i < var2ndigits; i++)
9077 : : {
9078 : 980 : idivisor = idivisor * NBASE + var2->digits[i];
9079 : 980 : idivisor_weight--;
9080 : : }
9081 [ + + ]: 360 : if (var2->sign == NUMERIC_NEG)
9082 : 80 : idivisor = -idivisor;
9083 : :
9084 : 360 : div_var_int64(var1, idivisor, idivisor_weight, result, rscale, round);
9085 : 360 : return;
9086 : : }
9087 : : #endif
9088 : :
9089 : : /*
9090 : : * Otherwise, perform full long division.
9091 : : */
9092 : :
9093 : : /* Result zero check */
6812 tgl@sss.pgh.pa.us 9094 [ + + ]: 3972 : if (var1ndigits == 0)
9095 : : {
9096 : 24 : zero_var(result);
9097 : 24 : result->dscale = rscale;
9098 : 24 : return;
9099 : : }
9100 : :
9101 : : /*
9102 : : * The approximate computation can be significantly faster than the exact
9103 : : * one, since the working dividend is var2ndigitpairs base-NBASE^2 digits
9104 : : * shorter below. However, that comes with the tradeoff of computing
9105 : : * DIV_GUARD_DIGITS extra base-NBASE result digits. Ignoring all other
9106 : : * overheads, that suggests that, in theory, the approximate computation
9107 : : * will only be faster than the exact one when var2ndigits is greater than
9108 : : * 2 * (DIV_GUARD_DIGITS + 1), independent of the size of var1.
9109 : : *
9110 : : * Thus, we're better off doing an exact computation when var2 is shorter
9111 : : * than this. Empirically, it has been found that the exact threshold is
9112 : : * a little higher, due to other overheads in the outer division loop.
9113 : : */
785 dean.a.rasheed@gmail 9114 [ + + ]: 3948 : if (var2ndigits <= 2 * (DIV_GUARD_DIGITS + 2))
9115 : 2688 : exact = true;
9116 : :
9117 : : /*
9118 : : * Determine the result sign, weight and number of digits to calculate.
9119 : : * The weight figured here is correct if the emitted quotient has no
9120 : : * leading zero digits; otherwise strip_var() will fix things up.
9121 : : */
6812 tgl@sss.pgh.pa.us 9122 [ + + ]: 3948 : if (var1->sign == var2->sign)
9123 : 3846 : res_sign = NUMERIC_POS;
9124 : : else
9125 : 102 : res_sign = NUMERIC_NEG;
785 dean.a.rasheed@gmail 9126 : 3948 : res_weight = var1->weight - var2->weight + 1;
9127 : : /* The number of accurate result digits we need to produce: */
6812 tgl@sss.pgh.pa.us 9128 : 3948 : res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
9129 : : /* ... but always at least 1 */
9130 : 3948 : res_ndigits = Max(res_ndigits, 1);
9131 : : /* If rounding needed, figure one more digit to ensure correct result */
9132 [ + + ]: 3948 : if (round)
9133 : 658 : res_ndigits++;
9134 : : /* Add guard digits for roundoff error when producing approx result */
785 dean.a.rasheed@gmail 9135 [ + + ]: 3948 : if (!exact)
9136 : 1246 : res_ndigits += DIV_GUARD_DIGITS;
9137 : :
9138 : : /*
9139 : : * The computation itself is done using base-NBASE^2 arithmetic, so we
9140 : : * actually process the input digits in pairs, producing a base-NBASE^2
9141 : : * intermediate result. This significantly improves performance, since
9142 : : * the computation is O(N^2) in the number of input digits, and working in
9143 : : * base NBASE^2 effectively halves "N".
9144 : : */
9145 : 3948 : var1ndigitpairs = (var1ndigits + 1) / 2;
9146 : 3948 : var2ndigitpairs = (var2ndigits + 1) / 2;
9147 : 3948 : res_ndigitpairs = (res_ndigits + 1) / 2;
9148 : 3948 : res_ndigits = 2 * res_ndigitpairs;
9149 : :
9150 : : /*
9151 : : * We do the arithmetic in an array "dividend[]" of signed 64-bit
9152 : : * integers. Since PG_INT64_MAX is much larger than NBASE^4, this gives
9153 : : * us a lot of headroom to avoid normalizing carries immediately.
9154 : : *
9155 : : * When performing an exact computation, the working dividend requires
9156 : : * res_ndigitpairs + var2ndigitpairs digits. If var1 is larger than that,
9157 : : * the extra digits do not contribute to the result, and are ignored.
9158 : : *
9159 : : * When performing an approximate computation, the working dividend only
9160 : : * requires res_ndigitpairs digits (which includes the extra guard
9161 : : * digits). All input digits beyond that are ignored.
9162 : : */
9163 [ + + ]: 3948 : if (exact)
9164 : : {
9165 : 2702 : div_ndigitpairs = res_ndigitpairs + var2ndigitpairs;
9166 : 2702 : var1ndigitpairs = Min(var1ndigitpairs, div_ndigitpairs);
9167 : : }
9168 : : else
9169 : : {
9170 : 1246 : div_ndigitpairs = res_ndigitpairs;
9171 : 1246 : var1ndigitpairs = Min(var1ndigitpairs, div_ndigitpairs);
9172 : 1246 : var2ndigitpairs = Min(var2ndigitpairs, div_ndigitpairs);
9173 : : }
9174 : :
9175 : : /*
9176 : : * Allocate room for the working dividend (div_ndigitpairs 64-bit digits)
9177 : : * plus the divisor (var2ndigitpairs 32-bit base-NBASE^2 digits).
9178 : : *
9179 : : * For convenience, we allocate one extra dividend digit, which is set to
9180 : : * zero and not counted in div_ndigitpairs, so that the main loop below
9181 : : * can safely read and write the (qi+1)'th digit in the approximate case.
9182 : : */
9183 : 3948 : dividend = (int64 *) palloc((div_ndigitpairs + 1) * sizeof(int64) +
9184 : : var2ndigitpairs * sizeof(int32));
9185 : 3948 : divisor = (int32 *) (dividend + div_ndigitpairs + 1);
9186 : :
9187 : : /* load var1 into dividend[0 .. var1ndigitpairs-1], zeroing the rest */
9188 [ + + ]: 102588 : for (i = 0; i < var1ndigitpairs - 1; i++)
9189 : 98640 : dividend[i] = var1->digits[2 * i] * NBASE + var1->digits[2 * i + 1];
9190 : :
9191 [ + + ]: 3948 : if (2 * i + 1 < var1ndigits)
9192 : 2321 : dividend[i] = var1->digits[2 * i] * NBASE + var1->digits[2 * i + 1];
9193 : : else
9194 : 1627 : dividend[i] = var1->digits[2 * i] * NBASE;
9195 : :
9196 : 3948 : memset(dividend + i + 1, 0, (div_ndigitpairs - i) * sizeof(int64));
9197 : :
9198 : : /* load var2 into divisor[0 .. var2ndigitpairs-1] */
9199 [ + + ]: 94880 : for (i = 0; i < var2ndigitpairs - 1; i++)
9200 : 90932 : divisor[i] = var2->digits[2 * i] * NBASE + var2->digits[2 * i + 1];
9201 : :
9202 [ + + ]: 3948 : if (2 * i + 1 < var2ndigits)
9203 : 2122 : divisor[i] = var2->digits[2 * i] * NBASE + var2->digits[2 * i + 1];
9204 : : else
9205 : 1826 : divisor[i] = var2->digits[2 * i] * NBASE;
9206 : :
9207 : : /*
9208 : : * We estimate each quotient digit using floating-point arithmetic, taking
9209 : : * the first 2 base-NBASE^2 digits of the (current) dividend and divisor.
9210 : : * This must be float to avoid overflow.
9211 : : *
9212 : : * Since the floating-point dividend and divisor use 4 base-NBASE input
9213 : : * digits, they include roughly 40-53 bits of information from their
9214 : : * respective inputs (assuming NBASE is 10000), which fits well in IEEE
9215 : : * double-precision variables. The relative error in the floating-point
9216 : : * quotient digit will then be less than around 2/NBASE^3, so the
9217 : : * estimated base-NBASE^2 quotient digit will typically be correct, and
9218 : : * should not be off by more than one from the correct value.
9219 : : */
9220 : 3948 : fdivisor = (double) divisor[0] * NBASE_SQR;
9221 [ + - ]: 3948 : if (var2ndigitpairs > 1)
9222 : 3948 : fdivisor += (double) divisor[1];
8653 tgl@sss.pgh.pa.us 9223 : 3948 : fdivisorinverse = 1.0 / fdivisor;
9224 : :
9225 : : /*
9226 : : * maxdiv tracks the maximum possible absolute value of any dividend[]
9227 : : * entry; when this threatens to exceed PG_INT64_MAX, we take the time to
9228 : : * propagate carries. Furthermore, we need to ensure that overflow
9229 : : * doesn't occur during the carry propagation passes either. The carry
9230 : : * values may have an absolute value as high as PG_INT64_MAX/NBASE^2 + 1,
9231 : : * so really we must normalize when digits threaten to exceed PG_INT64_MAX
9232 : : * - PG_INT64_MAX/NBASE^2 - 1.
9233 : : *
9234 : : * To avoid overflow in maxdiv itself, it represents the max absolute
9235 : : * value divided by NBASE^2-1, i.e., at the top of the loop it is known
9236 : : * that no dividend[] entry has an absolute value exceeding maxdiv *
9237 : : * (NBASE^2-1).
9238 : : *
9239 : : * Actually, though, that holds good only for dividend[] entries after
9240 : : * dividend[qi]; the adjustment done at the bottom of the loop may cause
9241 : : * dividend[qi + 1] to exceed the maxdiv limit, so that dividend[qi] in
9242 : : * the next iteration is beyond the limit. This does not cause problems,
9243 : : * as explained below.
9244 : : */
9245 : 3948 : maxdiv = 1;
9246 : :
9247 : : /*
9248 : : * Outer loop computes next quotient digit, which goes in dividend[qi].
9249 : : */
785 dean.a.rasheed@gmail 9250 [ + + ]: 36376 : for (qi = 0; qi < res_ndigitpairs; qi++)
9251 : : {
9252 : : /* Approximate the current dividend value */
9253 : 32428 : fdividend = (double) dividend[qi] * NBASE_SQR;
9254 : 32428 : fdividend += (double) dividend[qi + 1];
9255 : :
9256 : : /* Compute the (approximate) quotient digit */
8653 tgl@sss.pgh.pa.us 9257 : 32428 : fquotient = fdividend * fdivisorinverse;
785 dean.a.rasheed@gmail 9258 [ + + ]: 32428 : qdigit = (fquotient >= 0.0) ? ((int32) fquotient) :
9259 : 5 : (((int32) fquotient) - 1); /* truncate towards -infinity */
9260 : :
8653 tgl@sss.pgh.pa.us 9261 [ + + ]: 32428 : if (qdigit != 0)
9262 : : {
9263 : : /* Do we need to normalize now? */
785 dean.a.rasheed@gmail 9264 : 29803 : maxdiv += i64abs(qdigit);
9265 [ + + ]: 29803 : if (maxdiv > (PG_INT64_MAX - PG_INT64_MAX / NBASE_SQR - 1) / (NBASE_SQR - 1))
9266 : : {
9267 : : /*
9268 : : * Yes, do it. Note that if var2ndigitpairs is much smaller
9269 : : * than div_ndigitpairs, we can save a significant amount of
9270 : : * effort here by noting that we only need to normalise those
9271 : : * dividend[] entries touched where prior iterations
9272 : : * subtracted multiples of the divisor.
9273 : : */
8653 tgl@sss.pgh.pa.us 9274 : 5 : carry = 0;
785 dean.a.rasheed@gmail 9275 [ + + ]: 5625 : for (i = Min(qi + var2ndigitpairs - 2, div_ndigitpairs - 1); i > qi; i--)
9276 : : {
9277 : 5620 : newdig = dividend[i] + carry;
8653 tgl@sss.pgh.pa.us 9278 [ + - ]: 5620 : if (newdig < 0)
9279 : : {
785 dean.a.rasheed@gmail 9280 : 5620 : carry = -((-newdig - 1) / NBASE_SQR) - 1;
9281 : 5620 : newdig -= carry * NBASE_SQR;
9282 : : }
785 dean.a.rasheed@gmail 9283 [ # # ]:UBC 0 : else if (newdig >= NBASE_SQR)
9284 : : {
9285 : 0 : carry = newdig / NBASE_SQR;
9286 : 0 : newdig -= carry * NBASE_SQR;
9287 : : }
9288 : : else
8653 tgl@sss.pgh.pa.us 9289 : 0 : carry = 0;
785 dean.a.rasheed@gmail 9290 :CBC 5620 : dividend[i] = newdig;
9291 : : }
9292 : 5 : dividend[qi] += carry;
9293 : :
9294 : : /*
9295 : : * All the dividend[] digits except possibly dividend[qi] are
9296 : : * now in the range 0..NBASE^2-1. We do not need to consider
9297 : : * dividend[qi] in the maxdiv value anymore, so we can reset
9298 : : * maxdiv to 1.
9299 : : */
4021 tgl@sss.pgh.pa.us 9300 : 5 : maxdiv = 1;
9301 : :
9302 : : /*
9303 : : * Recompute the quotient digit since new info may have
9304 : : * propagated into the top two dividend digits.
9305 : : */
785 dean.a.rasheed@gmail 9306 : 5 : fdividend = (double) dividend[qi] * NBASE_SQR;
9307 : 5 : fdividend += (double) dividend[qi + 1];
8653 tgl@sss.pgh.pa.us 9308 : 5 : fquotient = fdividend * fdivisorinverse;
785 dean.a.rasheed@gmail 9309 [ + - ]: 5 : qdigit = (fquotient >= 0.0) ? ((int32) fquotient) :
785 dean.a.rasheed@gmail 9310 :UBC 0 : (((int32) fquotient) - 1); /* truncate towards -infinity */
9311 : :
785 dean.a.rasheed@gmail 9312 :CBC 5 : maxdiv += i64abs(qdigit);
9313 : : }
9314 : :
9315 : : /*
9316 : : * Subtract off the appropriate multiple of the divisor.
9317 : : *
9318 : : * The digits beyond dividend[qi] cannot overflow, because we know
9319 : : * they will fall within the maxdiv limit. As for dividend[qi]
9320 : : * itself, note that qdigit is approximately trunc(dividend[qi] /
9321 : : * divisor[0]), which would make the new value simply dividend[qi]
9322 : : * mod divisor[0]. The lower-order terms in qdigit can change
9323 : : * this result by not more than about twice PG_INT64_MAX/NBASE^2,
9324 : : * so overflow is impossible.
9325 : : *
9326 : : * This inner loop is the performance bottleneck for division, so
9327 : : * code it in the same way as the inner loop of mul_var() so that
9328 : : * it can be auto-vectorized.
9329 : : */
8653 tgl@sss.pgh.pa.us 9330 [ + - ]: 29803 : if (qdigit != 0)
9331 : : {
785 dean.a.rasheed@gmail 9332 : 29803 : int istop = Min(var2ndigitpairs, div_ndigitpairs - qi);
9333 : 29803 : int64 *dividend_qi = ÷nd[qi];
9334 : :
8653 tgl@sss.pgh.pa.us 9335 [ + + ]: 6584109 : for (i = 0; i < istop; i++)
785 dean.a.rasheed@gmail 9336 : 6554306 : dividend_qi[i] -= (int64) qdigit * divisor[i];
9337 : : }
9338 : : }
9339 : :
9340 : : /*
9341 : : * The dividend digit we are about to replace might still be nonzero.
9342 : : * Fold it into the next digit position.
9343 : : *
9344 : : * There is no risk of overflow here, although proving that requires
9345 : : * some care. Much as with the argument for dividend[qi] not
9346 : : * overflowing, if we consider the first two terms in the numerator
9347 : : * and denominator of qdigit, we can see that the final value of
9348 : : * dividend[qi + 1] will be approximately a remainder mod
9349 : : * (divisor[0]*NBASE^2 + divisor[1]). Accounting for the lower-order
9350 : : * terms is a bit complicated but ends up adding not much more than
9351 : : * PG_INT64_MAX/NBASE^2 to the possible range. Thus, dividend[qi + 1]
9352 : : * cannot overflow here, and in its role as dividend[qi] in the next
9353 : : * loop iteration, it can't be large enough to cause overflow in the
9354 : : * carry propagation step (if any), either.
9355 : : *
9356 : : * But having said that: dividend[qi] can be more than
9357 : : * PG_INT64_MAX/NBASE^2, as noted above, which means that the product
9358 : : * dividend[qi] * NBASE^2 *can* overflow. When that happens, adding
9359 : : * it to dividend[qi + 1] will always cause a canceling overflow so
9360 : : * that the end result is correct. We could avoid the intermediate
9361 : : * overflow by doing the multiplication and addition using unsigned
9362 : : * int64 arithmetic, which is modulo 2^64, but so far there appears no
9363 : : * need.
9364 : : */
9365 : 32428 : dividend[qi + 1] += dividend[qi] * NBASE_SQR;
9366 : :
9367 : 32428 : dividend[qi] = qdigit;
9368 : : }
9369 : :
9370 : : /*
9371 : : * If an exact result was requested, use the remainder to correct the
9372 : : * approximate quotient. The remainder is in dividend[], immediately
9373 : : * after the quotient digits. Note, however, that although the remainder
9374 : : * starts at dividend[qi = res_ndigitpairs], the first digit is the result
9375 : : * of folding two remainder digits into one above, and the remainder
9376 : : * currently only occupies var2ndigitpairs - 1 digits (the last digit of
9377 : : * the working dividend was untouched by the computation above). Thus we
9378 : : * expand the remainder down by one base-NBASE^2 digit when we normalize
9379 : : * it, so that it completely fills the last var2ndigitpairs digits of the
9380 : : * dividend array.
9381 : : */
9382 [ + + ]: 3948 : if (exact)
9383 : : {
9384 : : /* Normalize the remainder, expanding it down by one digit */
9385 : 2702 : remainder = ÷nd[qi];
9386 : 2702 : carry = 0;
9387 [ + + ]: 80974 : for (i = var2ndigitpairs - 2; i >= 0; i--)
9388 : : {
9389 : 78272 : newdig = remainder[i] + carry;
9390 [ + + ]: 78272 : if (newdig < 0)
9391 : : {
9392 : 75532 : carry = -((-newdig - 1) / NBASE_SQR) - 1;
9393 : 75532 : newdig -= carry * NBASE_SQR;
9394 : : }
9395 [ + + ]: 2740 : else if (newdig >= NBASE_SQR)
9396 : : {
9397 : 2672 : carry = newdig / NBASE_SQR;
9398 : 2672 : newdig -= carry * NBASE_SQR;
9399 : : }
9400 : : else
9401 : 68 : carry = 0;
9402 : 78272 : remainder[i + 1] = newdig;
9403 : : }
9404 : 2702 : remainder[0] = carry;
9405 : :
9406 [ + + ]: 2702 : if (remainder[0] < 0)
9407 : : {
9408 : : /*
9409 : : * The remainder is negative, so the approximate quotient is too
9410 : : * large. Correct by reducing the quotient by one and adding the
9411 : : * divisor to the remainder until the remainder is positive. We
9412 : : * expect the quotient to be off by at most one, which has been
9413 : : * borne out in all testing, but not conclusively proven, so we
9414 : : * allow for larger corrections, just in case.
9415 : : */
9416 : : do
9417 : : {
9418 : : /* Add the divisor to the remainder */
9419 : 9 : carry = 0;
9420 [ + + ]: 65601 : for (i = var2ndigitpairs - 1; i > 0; i--)
9421 : : {
9422 : 65592 : newdig = remainder[i] + divisor[i] + carry;
9423 [ + + ]: 65592 : if (newdig >= NBASE_SQR)
9424 : : {
9425 : 65520 : remainder[i] = newdig - NBASE_SQR;
9426 : 65520 : carry = 1;
9427 : : }
9428 : : else
9429 : : {
9430 : 72 : remainder[i] = newdig;
9431 : 72 : carry = 0;
9432 : : }
9433 : : }
9434 : 9 : remainder[0] += divisor[0] + carry;
9435 : :
9436 : : /* Subtract 1 from the quotient (propagating carries later) */
9437 : 9 : dividend[qi - 1]--;
9438 : :
9439 [ - + ]: 9 : } while (remainder[0] < 0);
9440 : : }
9441 : : else
9442 : : {
9443 : : /*
9444 : : * The remainder is nonnegative. If it's greater than or equal to
9445 : : * the divisor, then the approximate quotient is too small and
9446 : : * must be corrected. As above, we don't expect to have to apply
9447 : : * more than one correction, but allow for it just in case.
9448 : : */
9449 : : while (true)
9450 : 5 : {
9451 : 2698 : bool less = false;
9452 : :
9453 : : /* Is remainder < divisor? */
9454 [ + + ]: 2713 : for (i = 0; i < var2ndigitpairs; i++)
9455 : : {
9456 [ + + ]: 2708 : if (remainder[i] < divisor[i])
9457 : : {
9458 : 2693 : less = true;
9459 : 2693 : break;
9460 : : }
9461 [ - + ]: 15 : if (remainder[i] > divisor[i])
785 dean.a.rasheed@gmail 9462 :UBC 0 : break; /* remainder > divisor */
9463 : : }
785 dean.a.rasheed@gmail 9464 [ + + ]:CBC 2698 : if (less)
9465 : 2693 : break; /* quotient is correct */
9466 : :
9467 : : /* Subtract the divisor from the remainder */
9468 : 5 : carry = 0;
9469 [ + + ]: 15 : for (i = var2ndigitpairs - 1; i > 0; i--)
9470 : : {
9471 : 10 : newdig = remainder[i] - divisor[i] + carry;
9472 [ - + ]: 10 : if (newdig < 0)
9473 : : {
785 dean.a.rasheed@gmail 9474 :UBC 0 : remainder[i] = newdig + NBASE_SQR;
9475 : 0 : carry = -1;
9476 : : }
9477 : : else
9478 : : {
785 dean.a.rasheed@gmail 9479 :CBC 10 : remainder[i] = newdig;
9480 : 10 : carry = 0;
9481 : : }
9482 : : }
9483 : 5 : remainder[0] = remainder[0] - divisor[0] + carry;
9484 : :
9485 : : /* Add 1 to the quotient (propagating carries later) */
9486 : 5 : dividend[qi - 1]++;
9487 : : }
9488 : : }
9489 : : }
9490 : :
9491 : : /*
9492 : : * Because the quotient digits were estimates that might have been off by
9493 : : * one (and we didn't bother propagating carries when adjusting the
9494 : : * quotient above), some quotient digits might be out of range, so do a
9495 : : * final carry propagation pass to normalize back to base NBASE^2, and
9496 : : * construct the base-NBASE result digits. Note that this is still done
9497 : : * at full precision w/guard digits.
9498 : : */
9499 : 3948 : alloc_var(result, res_ndigits);
8653 tgl@sss.pgh.pa.us 9500 : 3948 : res_digits = result->digits;
9501 : 3948 : carry = 0;
785 dean.a.rasheed@gmail 9502 [ + + ]: 36376 : for (i = res_ndigitpairs - 1; i >= 0; i--)
9503 : : {
9504 : 32428 : newdig = dividend[i] + carry;
8653 tgl@sss.pgh.pa.us 9505 [ + + ]: 32428 : if (newdig < 0)
9506 : : {
785 dean.a.rasheed@gmail 9507 : 17 : carry = -((-newdig - 1) / NBASE_SQR) - 1;
9508 : 17 : newdig -= carry * NBASE_SQR;
9509 : : }
9510 [ - + ]: 32411 : else if (newdig >= NBASE_SQR)
9511 : : {
785 dean.a.rasheed@gmail 9512 :UBC 0 : carry = newdig / NBASE_SQR;
9513 : 0 : newdig -= carry * NBASE_SQR;
9514 : : }
9515 : : else
8653 tgl@sss.pgh.pa.us 9516 :CBC 32411 : carry = 0;
785 dean.a.rasheed@gmail 9517 : 32428 : res_digits[2 * i + 1] = (NumericDigit) ((uint32) newdig % NBASE);
9518 : 32428 : res_digits[2 * i] = (NumericDigit) ((uint32) newdig / NBASE);
9519 : : }
8653 tgl@sss.pgh.pa.us 9520 [ - + ]: 3948 : Assert(carry == 0);
9521 : :
785 dean.a.rasheed@gmail 9522 : 3948 : pfree(dividend);
9523 : :
9524 : : /*
9525 : : * Finally, round or truncate the result to the requested precision.
9526 : : */
8653 tgl@sss.pgh.pa.us 9527 : 3948 : result->weight = res_weight;
9528 : 3948 : result->sign = res_sign;
9529 : :
9530 : : /* Round or truncate to target rscale (and set result->dscale) */
7847 bruce@momjian.us 9531 [ + + ]: 3948 : if (round)
9532 : 658 : round_var(result, rscale);
9533 : : else
9534 : 3290 : trunc_var(result, rscale);
9535 : :
9536 : : /* Strip leading and trailing zeroes */
8653 tgl@sss.pgh.pa.us 9537 : 3948 : strip_var(result);
9538 : : }
9539 : :
9540 : :
9541 : : /*
9542 : : * div_var_int() -
9543 : : *
9544 : : * Divide a numeric variable by a 32-bit integer with the specified weight.
9545 : : * The quotient var / (ival * NBASE^ival_weight) is stored in result.
9546 : : */
9547 : : static void
1735 dean.a.rasheed@gmail 9548 : 391827 : div_var_int(const NumericVar *var, int ival, int ival_weight,
9549 : : NumericVar *result, int rscale, bool round)
9550 : : {
9551 : 391827 : NumericDigit *var_digits = var->digits;
9552 : 391827 : int var_ndigits = var->ndigits;
9553 : : int res_sign;
9554 : : int res_weight;
9555 : : int res_ndigits;
9556 : : NumericDigit *res_buf;
9557 : : NumericDigit *res_digits;
9558 : : uint32 divisor;
9559 : : int i;
9560 : :
9561 : : /* Guard against division by zero */
9562 [ - + ]: 391827 : if (ival == 0)
1735 dean.a.rasheed@gmail 9563 [ # # ]:UBC 0 : ereport(ERROR,
9564 : : errcode(ERRCODE_DIVISION_BY_ZERO),
9565 : : errmsg("division by zero"));
9566 : :
9567 : : /* Result zero check */
1735 dean.a.rasheed@gmail 9568 [ + + ]:CBC 391827 : if (var_ndigits == 0)
9569 : : {
9570 : 1579 : zero_var(result);
9571 : 1579 : result->dscale = rscale;
9572 : 1579 : return;
9573 : : }
9574 : :
9575 : : /*
9576 : : * Determine the result sign, weight and number of digits to calculate.
9577 : : * The weight figured here is correct if the emitted quotient has no
9578 : : * leading zero digits; otherwise strip_var() will fix things up.
9579 : : */
9580 [ + + ]: 390248 : if (var->sign == NUMERIC_POS)
9581 [ + + ]: 387984 : res_sign = ival > 0 ? NUMERIC_POS : NUMERIC_NEG;
9582 : : else
9583 [ + + ]: 2264 : res_sign = ival > 0 ? NUMERIC_NEG : NUMERIC_POS;
9584 : 390248 : res_weight = var->weight - ival_weight;
9585 : : /* The number of accurate result digits we need to produce: */
9586 : 390248 : res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
9587 : : /* ... but always at least 1 */
9588 : 390248 : res_ndigits = Max(res_ndigits, 1);
9589 : : /* If rounding needed, figure one more digit to ensure correct result */
9590 [ + + ]: 390248 : if (round)
9591 : 111706 : res_ndigits++;
9592 : :
9593 : 390248 : res_buf = digitbuf_alloc(res_ndigits + 1);
9594 : 390248 : res_buf[0] = 0; /* spare digit for later rounding */
9595 : 390248 : res_digits = res_buf + 1;
9596 : :
9597 : : /*
9598 : : * Now compute the quotient digits. This is the short division algorithm
9599 : : * described in Knuth volume 2, section 4.3.1 exercise 16, except that we
9600 : : * allow the divisor to exceed the internal base.
9601 : : *
9602 : : * In this algorithm, the carry from one digit to the next is at most
9603 : : * divisor - 1. Therefore, while processing the next digit, carry may
9604 : : * become as large as divisor * NBASE - 1, and so it requires a 64-bit
9605 : : * integer if this exceeds UINT_MAX.
9606 : : */
1513 peter@eisentraut.org 9607 : 390248 : divisor = abs(ival);
9608 : :
1735 dean.a.rasheed@gmail 9609 [ + + ]: 390248 : if (divisor <= UINT_MAX / NBASE)
9610 : : {
9611 : : /* carry cannot overflow 32 bits */
9612 : 386383 : uint32 carry = 0;
9613 : :
9614 [ + + ]: 1914183 : for (i = 0; i < res_ndigits; i++)
9615 : : {
9616 [ + + ]: 1527800 : carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
9617 : 1527800 : res_digits[i] = (NumericDigit) (carry / divisor);
9618 : 1527800 : carry = carry % divisor;
9619 : : }
9620 : : }
9621 : : else
9622 : : {
9623 : : /* carry may exceed 32 bits */
9624 : 3865 : uint64 carry = 0;
9625 : :
9626 [ + + ]: 12044 : for (i = 0; i < res_ndigits; i++)
9627 : : {
9628 [ + + ]: 8179 : carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
9629 : 8179 : res_digits[i] = (NumericDigit) (carry / divisor);
9630 : 8179 : carry = carry % divisor;
9631 : : }
9632 : : }
9633 : :
9634 : : /* Store the quotient in result */
9635 [ + + ]: 390248 : digitbuf_free(result->buf);
9636 : 390248 : result->ndigits = res_ndigits;
9637 : 390248 : result->buf = res_buf;
9638 : 390248 : result->digits = res_digits;
9639 : 390248 : result->weight = res_weight;
9640 : 390248 : result->sign = res_sign;
9641 : :
9642 : : /* Round or truncate to target rscale (and set result->dscale) */
9643 [ + + ]: 390248 : if (round)
9644 : 111706 : round_var(result, rscale);
9645 : : else
9646 : 278542 : trunc_var(result, rscale);
9647 : :
9648 : : /* Strip leading/trailing zeroes */
9649 : 390248 : strip_var(result);
9650 : : }
9651 : :
9652 : :
9653 : : #ifdef HAVE_INT128
9654 : : /*
9655 : : * div_var_int64() -
9656 : : *
9657 : : * Divide a numeric variable by a 64-bit integer with the specified weight.
9658 : : * The quotient var / (ival * NBASE^ival_weight) is stored in result.
9659 : : *
9660 : : * This duplicates the logic in div_var_int(), so any changes made there
9661 : : * should be made here too.
9662 : : */
9663 : : static void
1405 9664 : 360 : div_var_int64(const NumericVar *var, int64 ival, int ival_weight,
9665 : : NumericVar *result, int rscale, bool round)
9666 : : {
9667 : 360 : NumericDigit *var_digits = var->digits;
9668 : 360 : int var_ndigits = var->ndigits;
9669 : : int res_sign;
9670 : : int res_weight;
9671 : : int res_ndigits;
9672 : : NumericDigit *res_buf;
9673 : : NumericDigit *res_digits;
9674 : : uint64 divisor;
9675 : : int i;
9676 : :
9677 : : /* Guard against division by zero */
9678 [ - + ]: 360 : if (ival == 0)
1405 dean.a.rasheed@gmail 9679 [ # # ]:UBC 0 : ereport(ERROR,
9680 : : errcode(ERRCODE_DIVISION_BY_ZERO),
9681 : : errmsg("division by zero"));
9682 : :
9683 : : /* Result zero check */
1405 dean.a.rasheed@gmail 9684 [ + + ]:CBC 360 : if (var_ndigits == 0)
9685 : : {
9686 : 64 : zero_var(result);
9687 : 64 : result->dscale = rscale;
9688 : 64 : return;
9689 : : }
9690 : :
9691 : : /*
9692 : : * Determine the result sign, weight and number of digits to calculate.
9693 : : * The weight figured here is correct if the emitted quotient has no
9694 : : * leading zero digits; otherwise strip_var() will fix things up.
9695 : : */
9696 [ + + ]: 296 : if (var->sign == NUMERIC_POS)
9697 [ + + ]: 175 : res_sign = ival > 0 ? NUMERIC_POS : NUMERIC_NEG;
9698 : : else
9699 [ + + ]: 121 : res_sign = ival > 0 ? NUMERIC_NEG : NUMERIC_POS;
9700 : 296 : res_weight = var->weight - ival_weight;
9701 : : /* The number of accurate result digits we need to produce: */
9702 : 296 : res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
9703 : : /* ... but always at least 1 */
9704 : 296 : res_ndigits = Max(res_ndigits, 1);
9705 : : /* If rounding needed, figure one more digit to ensure correct result */
9706 [ + + ]: 296 : if (round)
9707 : 291 : res_ndigits++;
9708 : :
9709 : 296 : res_buf = digitbuf_alloc(res_ndigits + 1);
9710 : 296 : res_buf[0] = 0; /* spare digit for later rounding */
9711 : 296 : res_digits = res_buf + 1;
9712 : :
9713 : : /*
9714 : : * Now compute the quotient digits. This is the short division algorithm
9715 : : * described in Knuth volume 2, section 4.3.1 exercise 16, except that we
9716 : : * allow the divisor to exceed the internal base.
9717 : : *
9718 : : * In this algorithm, the carry from one digit to the next is at most
9719 : : * divisor - 1. Therefore, while processing the next digit, carry may
9720 : : * become as large as divisor * NBASE - 1, and so it requires a 128-bit
9721 : : * integer if this exceeds PG_UINT64_MAX.
9722 : : */
9723 : 296 : divisor = i64abs(ival);
9724 : :
9725 [ + + ]: 296 : if (divisor <= PG_UINT64_MAX / NBASE)
9726 : : {
9727 : : /* carry cannot overflow 64 bits */
9728 : 232 : uint64 carry = 0;
9729 : :
9730 [ + + ]: 2361 : for (i = 0; i < res_ndigits; i++)
9731 : : {
9732 [ + + ]: 2129 : carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
9733 : 2129 : res_digits[i] = (NumericDigit) (carry / divisor);
9734 : 2129 : carry = carry % divisor;
9735 : : }
9736 : : }
9737 : : else
9738 : : {
9739 : : /* carry may exceed 64 bits */
9740 : 64 : uint128 carry = 0;
9741 : :
9742 [ + + ]: 688 : for (i = 0; i < res_ndigits; i++)
9743 : : {
9744 [ + + ]: 624 : carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
9745 : 624 : res_digits[i] = (NumericDigit) (carry / divisor);
9746 : 624 : carry = carry % divisor;
9747 : : }
9748 : : }
9749 : :
9750 : : /* Store the quotient in result */
9751 [ + + ]: 296 : digitbuf_free(result->buf);
9752 : 296 : result->ndigits = res_ndigits;
9753 : 296 : result->buf = res_buf;
9754 : 296 : result->digits = res_digits;
9755 : 296 : result->weight = res_weight;
9756 : 296 : result->sign = res_sign;
9757 : :
9758 : : /* Round or truncate to target rscale (and set result->dscale) */
9759 [ + + ]: 296 : if (round)
9760 : 291 : round_var(result, rscale);
9761 : : else
9762 : 5 : trunc_var(result, rscale);
9763 : :
9764 : : /* Strip leading/trailing zeroes */
9765 : 296 : strip_var(result);
9766 : : }
9767 : : #endif
9768 : :
9769 : :
9770 : : /*
9771 : : * Default scale selection for division
9772 : : *
9773 : : * Returns the appropriate result scale for the division result.
9774 : : */
9775 : : static int
3366 andres@anarazel.de 9776 : 99389 : select_div_scale(const NumericVar *var1, const NumericVar *var2)
9777 : : {
9778 : : int weight1,
9779 : : weight2,
9780 : : qweight,
9781 : : i;
9782 : : NumericDigit firstdigit1,
9783 : : firstdigit2;
9784 : : int rscale;
9785 : :
9786 : : /*
9787 : : * The result scale of a division isn't specified in any SQL standard. For
9788 : : * PostgreSQL we select a result scale that will give at least
9789 : : * NUMERIC_MIN_SIG_DIGITS significant digits, so that numeric gives a
9790 : : * result no less accurate than float8; but use a scale not less than
9791 : : * either input's display scale.
9792 : : */
9793 : :
9794 : : /* Get the actual (normalized) weight and first digit of each input */
9795 : :
8823 tgl@sss.pgh.pa.us 9796 : 99389 : weight1 = 0; /* values to use if var1 is zero */
9797 : 99389 : firstdigit1 = 0;
9798 [ + + ]: 99389 : for (i = 0; i < var1->ndigits; i++)
9799 : : {
9800 : 98256 : firstdigit1 = var1->digits[i];
9801 [ + - ]: 98256 : if (firstdigit1 != 0)
9802 : : {
9803 : 98256 : weight1 = var1->weight - i;
9804 : 98256 : break;
9805 : : }
9806 : : }
9807 : :
9808 : 99389 : weight2 = 0; /* values to use if var2 is zero */
9809 : 99389 : firstdigit2 = 0;
9810 [ + + ]: 99389 : for (i = 0; i < var2->ndigits; i++)
9811 : : {
9812 : 99356 : firstdigit2 = var2->digits[i];
9813 [ + - ]: 99356 : if (firstdigit2 != 0)
9814 : : {
9815 : 99356 : weight2 = var2->weight - i;
9816 : 99356 : break;
9817 : : }
9818 : : }
9819 : :
9820 : : /*
9821 : : * Estimate weight of quotient. If the two first digits are equal, we
9822 : : * can't be sure, but assume that var1 is less than var2.
9823 : : */
9824 : 99389 : qweight = weight1 - weight2;
9825 [ + + ]: 99389 : if (firstdigit1 <= firstdigit2)
9826 : 88555 : qweight--;
9827 : :
9828 : : /* Select result scale */
8653 9829 : 99389 : rscale = NUMERIC_MIN_SIG_DIGITS - qweight * DEC_DIGITS;
9830 : 99389 : rscale = Max(rscale, var1->dscale);
9831 : 99389 : rscale = Max(rscale, var2->dscale);
9832 : 99389 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
9833 : 99389 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
9834 : :
9835 : 99389 : return rscale;
9836 : : }
9837 : :
9838 : :
9839 : : /*
9840 : : * mod_var() -
9841 : : *
9842 : : * Calculate the modulo of two numerics at variable level
9843 : : */
9844 : : static void
3366 andres@anarazel.de 9845 : 277506 : mod_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
9846 : : {
9847 : : NumericVar tmp;
9848 : :
10195 JanWieck@Yahoo.com 9849 : 277506 : init_var(&tmp);
9850 : :
9851 : : /* ---------
9852 : : * We do this using the equation
9853 : : * mod(x,y) = x - trunc(x/y)*y
9854 : : * div_var can be persuaded to give us trunc(x/y) directly.
9855 : : * ----------
9856 : : */
785 dean.a.rasheed@gmail 9857 : 277506 : div_var(var1, var2, &tmp, 0, false, true);
9858 : :
6812 tgl@sss.pgh.pa.us 9859 : 277506 : mul_var(var2, &tmp, &tmp, var2->dscale);
9860 : :
10195 JanWieck@Yahoo.com 9861 : 277506 : sub_var(var1, &tmp, result);
9862 : :
9863 : 277506 : free_var(&tmp);
9864 : 277506 : }
9865 : :
9866 : :
9867 : : /*
9868 : : * div_mod_var() -
9869 : : *
9870 : : * Calculate the truncated integer quotient and numeric remainder of two
9871 : : * numeric variables. The remainder is precise to var2's dscale.
9872 : : */
9873 : : static void
2436 dean.a.rasheed@gmail 9874 : 3275 : div_mod_var(const NumericVar *var1, const NumericVar *var2,
9875 : : NumericVar *quot, NumericVar *rem)
9876 : : {
9877 : : NumericVar q;
9878 : : NumericVar r;
9879 : :
9880 : 3275 : init_var(&q);
9881 : 3275 : init_var(&r);
9882 : :
9883 : : /*
9884 : : * Use div_var() with exact = false to get an initial estimate for the
9885 : : * integer quotient (truncated towards zero). This might be slightly
9886 : : * inaccurate, but we correct it below.
9887 : : */
785 9888 : 3275 : div_var(var1, var2, &q, 0, false, false);
9889 : :
9890 : : /* Compute initial estimate of remainder using the quotient estimate. */
2436 9891 : 3275 : mul_var(var2, &q, &r, var2->dscale);
9892 : 3275 : sub_var(var1, &r, &r);
9893 : :
9894 : : /*
9895 : : * Adjust the results if necessary --- the remainder should have the same
9896 : : * sign as var1, and its absolute value should be less than the absolute
9897 : : * value of var2.
9898 : : */
9899 [ + - - + ]: 3275 : while (r.ndigits != 0 && r.sign != var1->sign)
9900 : : {
9901 : : /* The absolute value of the quotient is too large */
2436 dean.a.rasheed@gmail 9902 [ # # ]:UBC 0 : if (var1->sign == var2->sign)
9903 : : {
9904 : 0 : sub_var(&q, &const_one, &q);
9905 : 0 : add_var(&r, var2, &r);
9906 : : }
9907 : : else
9908 : : {
9909 : 0 : add_var(&q, &const_one, &q);
9910 : 0 : sub_var(&r, var2, &r);
9911 : : }
9912 : : }
9913 : :
2436 dean.a.rasheed@gmail 9914 [ - + ]:CBC 3275 : while (cmp_abs(&r, var2) >= 0)
9915 : : {
9916 : : /* The absolute value of the quotient is too small */
2436 dean.a.rasheed@gmail 9917 [ # # ]:UBC 0 : if (var1->sign == var2->sign)
9918 : : {
9919 : 0 : add_var(&q, &const_one, &q);
9920 : 0 : sub_var(&r, var2, &r);
9921 : : }
9922 : : else
9923 : : {
9924 : 0 : sub_var(&q, &const_one, &q);
9925 : 0 : add_var(&r, var2, &r);
9926 : : }
9927 : : }
9928 : :
2436 dean.a.rasheed@gmail 9929 :CBC 3275 : set_var_from_var(&q, quot);
9930 : 3275 : set_var_from_var(&r, rem);
9931 : :
9932 : 3275 : free_var(&q);
9933 : 3275 : free_var(&r);
9934 : 3275 : }
9935 : :
9936 : :
9937 : : /*
9938 : : * ceil_var() -
9939 : : *
9940 : : * Return the smallest integer greater than or equal to the argument
9941 : : * on variable level
9942 : : */
9943 : : static void
3366 andres@anarazel.de 9944 : 136 : ceil_var(const NumericVar *var, NumericVar *result)
9945 : : {
9946 : : NumericVar tmp;
9947 : :
10195 JanWieck@Yahoo.com 9948 : 136 : init_var(&tmp);
9949 : 136 : set_var_from_var(var, &tmp);
9950 : :
8653 tgl@sss.pgh.pa.us 9951 : 136 : trunc_var(&tmp, 0);
9952 : :
9953 [ + + + + ]: 136 : if (var->sign == NUMERIC_POS && cmp_var(var, &tmp) != 0)
10195 JanWieck@Yahoo.com 9954 : 40 : add_var(&tmp, &const_one, &tmp);
9955 : :
9956 : 136 : set_var_from_var(&tmp, result);
9957 : 136 : free_var(&tmp);
9958 : 136 : }
9959 : :
9960 : :
9961 : : /*
9962 : : * floor_var() -
9963 : : *
9964 : : * Return the largest integer equal to or less than the argument
9965 : : * on variable level
9966 : : */
9967 : : static void
3366 andres@anarazel.de 9968 : 72 : floor_var(const NumericVar *var, NumericVar *result)
9969 : : {
9970 : : NumericVar tmp;
9971 : :
10195 JanWieck@Yahoo.com 9972 : 72 : init_var(&tmp);
9973 : 72 : set_var_from_var(var, &tmp);
9974 : :
8653 tgl@sss.pgh.pa.us 9975 : 72 : trunc_var(&tmp, 0);
9976 : :
9977 [ + + + + ]: 72 : if (var->sign == NUMERIC_NEG && cmp_var(var, &tmp) != 0)
10195 JanWieck@Yahoo.com 9978 : 20 : sub_var(&tmp, &const_one, &tmp);
9979 : :
9980 : 72 : set_var_from_var(&tmp, result);
9981 : 72 : free_var(&tmp);
9982 : 72 : }
9983 : :
9984 : :
9985 : : /*
9986 : : * gcd_var() -
9987 : : *
9988 : : * Calculate the greatest common divisor of two numerics at variable level
9989 : : */
9990 : : static void
2499 dean.a.rasheed@gmail 9991 : 148 : gcd_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
9992 : : {
9993 : : int res_dscale;
9994 : : int cmp;
9995 : : NumericVar tmp_arg;
9996 : : NumericVar mod;
9997 : :
9998 : 148 : res_dscale = Max(var1->dscale, var2->dscale);
9999 : :
10000 : : /*
10001 : : * Arrange for var1 to be the number with the greater absolute value.
10002 : : *
10003 : : * This would happen automatically in the loop below, but avoids an
10004 : : * expensive modulo operation.
10005 : : */
10006 : 148 : cmp = cmp_abs(var1, var2);
10007 [ + + ]: 148 : if (cmp < 0)
10008 : : {
10009 : 56 : const NumericVar *tmp = var1;
10010 : :
10011 : 56 : var1 = var2;
10012 : 56 : var2 = tmp;
10013 : : }
10014 : :
10015 : : /*
10016 : : * Also avoid the taking the modulo if the inputs have the same absolute
10017 : : * value, or if the smaller input is zero.
10018 : : */
10019 [ + + + + ]: 148 : if (cmp == 0 || var2->ndigits == 0)
10020 : : {
10021 : 48 : set_var_from_var(var1, result);
10022 : 48 : result->sign = NUMERIC_POS;
10023 : 48 : result->dscale = res_dscale;
10024 : 48 : return;
10025 : : }
10026 : :
10027 : 100 : init_var(&tmp_arg);
10028 : 100 : init_var(&mod);
10029 : :
10030 : : /* Use the Euclidean algorithm to find the GCD */
10031 : 100 : set_var_from_var(var1, &tmp_arg);
10032 : 100 : set_var_from_var(var2, result);
10033 : :
10034 : : for (;;)
10035 : : {
10036 : : /* this loop can take a while, so allow it to be interrupted */
10037 [ - + ]: 392 : CHECK_FOR_INTERRUPTS();
10038 : :
10039 : 392 : mod_var(&tmp_arg, result, &mod);
10040 [ + + ]: 392 : if (mod.ndigits == 0)
10041 : 100 : break;
10042 : 292 : set_var_from_var(result, &tmp_arg);
10043 : 292 : set_var_from_var(&mod, result);
10044 : : }
10045 : 100 : result->sign = NUMERIC_POS;
10046 : 100 : result->dscale = res_dscale;
10047 : :
10048 : 100 : free_var(&tmp_arg);
10049 : 100 : free_var(&mod);
10050 : : }
10051 : :
10052 : :
10053 : : /*
10054 : : * sqrt_var() -
10055 : : *
10056 : : * Compute the square root of x using the Karatsuba Square Root algorithm.
10057 : : * NOTE: we allow rscale < 0 here, implying rounding before the decimal
10058 : : * point.
10059 : : */
10060 : : static void
3366 andres@anarazel.de 10061 : 3028 : sqrt_var(const NumericVar *arg, NumericVar *result, int rscale)
10062 : : {
10063 : : int stat;
10064 : : int res_weight;
10065 : : int res_ndigits;
10066 : : int src_ndigits;
10067 : : int step;
10068 : : int ndigits[32];
10069 : : int blen;
10070 : : int64 arg_int64;
10071 : : int src_idx;
10072 : : int64 s_int64;
10073 : : int64 r_int64;
10074 : : NumericVar s_var;
10075 : : NumericVar r_var;
10076 : : NumericVar a0_var;
10077 : : NumericVar a1_var;
10078 : : NumericVar q_var;
10079 : : NumericVar u_var;
10080 : :
10195 JanWieck@Yahoo.com 10081 : 3028 : stat = cmp_var(arg, &const_zero);
10082 [ + + ]: 3028 : if (stat == 0)
10083 : : {
8653 tgl@sss.pgh.pa.us 10084 : 12 : zero_var(result);
10085 : 12 : result->dscale = rscale;
10195 JanWieck@Yahoo.com 10086 : 12 : return;
10087 : : }
10088 : :
10089 : : /*
10090 : : * SQL2003 defines sqrt() in terms of power, so we need to emit the right
10091 : : * SQLSTATE error code if the operand is negative.
10092 : : */
10093 [ + + ]: 3016 : if (stat < 0)
8525 tgl@sss.pgh.pa.us 10094 [ + - ]: 4 : ereport(ERROR,
10095 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
10096 : : errmsg("cannot take square root of a negative number")));
10097 : :
2436 dean.a.rasheed@gmail 10098 : 3012 : init_var(&s_var);
10099 : 3012 : init_var(&r_var);
10100 : 3012 : init_var(&a0_var);
10101 : 3012 : init_var(&a1_var);
10102 : 3012 : init_var(&q_var);
10103 : 3012 : init_var(&u_var);
10104 : :
10105 : : /*
10106 : : * The result weight is half the input weight, rounded towards minus
10107 : : * infinity --- res_weight = floor(arg->weight / 2).
10108 : : */
10109 [ + + ]: 3012 : if (arg->weight >= 0)
10110 : 2741 : res_weight = arg->weight / 2;
10111 : : else
10112 : 271 : res_weight = -((-arg->weight - 1) / 2 + 1);
10113 : :
10114 : : /*
10115 : : * Number of NBASE digits to compute. To ensure correct rounding, compute
10116 : : * at least 1 extra decimal digit. We explicitly allow rscale to be
10117 : : * negative here, but must always compute at least 1 NBASE digit. Thus
10118 : : * res_ndigits = res_weight + 1 + ceil((rscale + 1) / DEC_DIGITS) or 1.
10119 : : */
10120 [ + - ]: 3012 : if (rscale + 1 >= 0)
10121 : 3012 : res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS) / DEC_DIGITS;
10122 : : else
2436 dean.a.rasheed@gmail 10123 :UBC 0 : res_ndigits = res_weight + 1 - (-rscale - 1) / DEC_DIGITS;
2436 dean.a.rasheed@gmail 10124 :CBC 3012 : res_ndigits = Max(res_ndigits, 1);
10125 : :
10126 : : /*
10127 : : * Number of source NBASE digits logically required to produce a result
10128 : : * with this precision --- every digit before the decimal point, plus 2
10129 : : * for each result digit after the decimal point (or minus 2 for each
10130 : : * result digit we round before the decimal point).
10131 : : */
10132 : 3012 : src_ndigits = arg->weight + 1 + (res_ndigits - res_weight - 1) * 2;
10133 : 3012 : src_ndigits = Max(src_ndigits, 1);
10134 : :
10135 : : /* ----------
10136 : : * From this point on, we treat the input and the result as integers and
10137 : : * compute the integer square root and remainder using the Karatsuba
10138 : : * Square Root algorithm, which may be written recursively as follows:
10139 : : *
10140 : : * SqrtRem(n = a3*b^3 + a2*b^2 + a1*b + a0):
10141 : : * [ for some base b, and coefficients a0,a1,a2,a3 chosen so that
10142 : : * 0 <= a0,a1,a2 < b and a3 >= b/4 ]
10143 : : * Let (s,r) = SqrtRem(a3*b + a2)
10144 : : * Let (q,u) = DivRem(r*b + a1, 2*s)
10145 : : * Let s = s*b + q
10146 : : * Let r = u*b + a0 - q^2
10147 : : * If r < 0 Then
10148 : : * Let r = r + s
10149 : : * Let s = s - 1
10150 : : * Let r = r + s
10151 : : * Return (s,r)
10152 : : *
10153 : : * See "Karatsuba Square Root", Paul Zimmermann, INRIA Research Report
10154 : : * RR-3805, November 1999. At the time of writing this was available
10155 : : * on the net at <https://hal.inria.fr/inria-00072854>.
10156 : : *
10157 : : * The way to read the assumption "n = a3*b^3 + a2*b^2 + a1*b + a0" is
10158 : : * "choose a base b such that n requires at least four base-b digits to
10159 : : * express; then those digits are a3,a2,a1,a0, with a3 possibly larger
10160 : : * than b". For optimal performance, b should have approximately a
10161 : : * quarter the number of digits in the input, so that the outer square
10162 : : * root computes roughly twice as many digits as the inner one. For
10163 : : * simplicity, we choose b = NBASE^blen, an integer power of NBASE.
10164 : : *
10165 : : * We implement the algorithm iteratively rather than recursively, to
10166 : : * allow the working variables to be reused. With this approach, each
10167 : : * digit of the input is read precisely once --- src_idx tracks the number
10168 : : * of input digits used so far.
10169 : : *
10170 : : * The array ndigits[] holds the number of NBASE digits of the input that
10171 : : * will have been used at the end of each iteration, which roughly doubles
10172 : : * each time. Note that the array elements are stored in reverse order,
10173 : : * so if the final iteration requires src_ndigits = 37 input digits, the
10174 : : * array will contain [37,19,11,7,5,3], and we would start by computing
10175 : : * the square root of the 3 most significant NBASE digits.
10176 : : *
10177 : : * In each iteration, we choose blen to be the largest integer for which
10178 : : * the input number has a3 >= b/4, when written in the form above. In
10179 : : * general, this means blen = src_ndigits / 4 (truncated), but if
10180 : : * src_ndigits is a multiple of 4, that might lead to the coefficient a3
10181 : : * being less than b/4 (if the first input digit is less than NBASE/4), in
10182 : : * which case we choose blen = src_ndigits / 4 - 1. The number of digits
10183 : : * in the inner square root is then src_ndigits - 2*blen. So, for
10184 : : * example, if we have src_ndigits = 26 initially, the array ndigits[]
10185 : : * will be either [26,14,8,4] or [26,14,8,6,4], depending on the size of
10186 : : * the first input digit.
10187 : : *
10188 : : * Additionally, we can put an upper bound on the number of steps required
10189 : : * as follows --- suppose that the number of source digits is an n-bit
10190 : : * number in the range [2^(n-1), 2^n-1], then blen will be in the range
10191 : : * [2^(n-3)-1, 2^(n-2)-1] and the number of digits in the inner square
10192 : : * root will be in the range [2^(n-2), 2^(n-1)+1]. In the next step, blen
10193 : : * will be in the range [2^(n-4)-1, 2^(n-3)] and the number of digits in
10194 : : * the next inner square root will be in the range [2^(n-3), 2^(n-2)+1].
10195 : : * This pattern repeats, and in the worst case the array ndigits[] will
10196 : : * contain [2^n-1, 2^(n-1)+1, 2^(n-2)+1, ... 9, 5, 3], and the computation
10197 : : * will require n steps. Therefore, since all digit array sizes are
10198 : : * signed 32-bit integers, the number of steps required is guaranteed to
10199 : : * be less than 32.
10200 : : * ----------
10201 : : */
10202 : 3012 : step = 0;
10203 [ + + ]: 14431 : while ((ndigits[step] = src_ndigits) > 4)
10204 : : {
10205 : : /* Choose b so that a3 >= b/4, as described above */
10206 : 11419 : blen = src_ndigits / 4;
10207 [ + + + + ]: 11419 : if (blen * 4 == src_ndigits && arg->digits[0] < NBASE / 4)
10208 : 259 : blen--;
10209 : :
10210 : : /* Number of digits in the next step (inner square root) */
10211 : 11419 : src_ndigits -= 2 * blen;
10212 : 11419 : step++;
10213 : : }
10214 : :
10215 : : /*
10216 : : * First iteration (innermost square root and remainder):
10217 : : *
10218 : : * Here src_ndigits <= 4, and the input fits in an int64. Its square root
10219 : : * has at most 9 decimal digits, so estimate it using double precision
10220 : : * arithmetic, which will in fact almost certainly return the correct
10221 : : * result with no further correction required.
10222 : : */
10223 : 3012 : arg_int64 = arg->digits[0];
10224 [ + + ]: 9635 : for (src_idx = 1; src_idx < src_ndigits; src_idx++)
10225 : : {
10226 : 6623 : arg_int64 *= NBASE;
10227 [ + + ]: 6623 : if (src_idx < arg->ndigits)
10228 : 5611 : arg_int64 += arg->digits[src_idx];
10229 : : }
10230 : :
10231 : 3012 : s_int64 = (int64) sqrt((double) arg_int64);
10232 : 3012 : r_int64 = arg_int64 - s_int64 * s_int64;
10233 : :
10234 : : /*
10235 : : * Use Newton's method to correct the result, if necessary.
10236 : : *
10237 : : * This uses integer division with truncation to compute the truncated
10238 : : * integer square root by iterating using the formula x -> (x + n/x) / 2.
10239 : : * This is known to converge to isqrt(n), unless n+1 is a perfect square.
10240 : : * If n+1 is a perfect square, the sequence will oscillate between the two
10241 : : * values isqrt(n) and isqrt(n)+1, so we can be assured of convergence by
10242 : : * checking the remainder.
10243 : : */
10244 [ - + - + ]: 3012 : while (r_int64 < 0 || r_int64 > 2 * s_int64)
10245 : : {
2436 dean.a.rasheed@gmail 10246 :UBC 0 : s_int64 = (s_int64 + arg_int64 / s_int64) / 2;
10247 : 0 : r_int64 = arg_int64 - s_int64 * s_int64;
10248 : : }
10249 : :
10250 : : /*
10251 : : * Iterations with src_ndigits <= 8:
10252 : : *
10253 : : * The next 1 or 2 iterations compute larger (outer) square roots with
10254 : : * src_ndigits <= 8, so the result still fits in an int64 (even though the
10255 : : * input no longer does) and we can continue to compute using int64
10256 : : * variables to avoid more expensive numeric computations.
10257 : : *
10258 : : * It is fairly easy to see that there is no risk of the intermediate
10259 : : * values below overflowing 64-bit integers. In the worst case, the
10260 : : * previous iteration will have computed a 3-digit square root (of a
10261 : : * 6-digit input less than NBASE^6 / 4), so at the start of this
10262 : : * iteration, s will be less than NBASE^3 / 2 = 10^12 / 2, and r will be
10263 : : * less than 10^12. In this case, blen will be 1, so numer will be less
10264 : : * than 10^17, and denom will be less than 10^12 (and hence u will also be
10265 : : * less than 10^12). Finally, since q^2 = u*b + a0 - r, we can also be
10266 : : * sure that q^2 < 10^17. Therefore all these quantities fit comfortably
10267 : : * in 64-bit integers.
10268 : : */
2436 dean.a.rasheed@gmail 10269 :CBC 3012 : step--;
10270 [ + - + + ]: 7612 : while (step >= 0 && (src_ndigits = ndigits[step]) <= 8)
10271 : : {
10272 : : int b;
10273 : : int a0;
10274 : : int a1;
10275 : : int i;
10276 : : int64 numer;
10277 : : int64 denom;
10278 : : int64 q;
10279 : : int64 u;
10280 : :
10281 : 4600 : blen = (src_ndigits - src_idx) / 2;
10282 : :
10283 : : /* Extract a1 and a0, and compute b */
10284 : 4600 : a0 = 0;
10285 : 4600 : a1 = 0;
10286 : 4600 : b = 1;
10287 : :
10288 [ + + ]: 9319 : for (i = 0; i < blen; i++, src_idx++)
10289 : : {
10290 : 4719 : b *= NBASE;
10291 : 4719 : a1 *= NBASE;
10292 [ + + ]: 4719 : if (src_idx < arg->ndigits)
10293 : 3500 : a1 += arg->digits[src_idx];
10294 : : }
10295 : :
10296 [ + + ]: 9319 : for (i = 0; i < blen; i++, src_idx++)
10297 : : {
10298 : 4719 : a0 *= NBASE;
10299 [ + + ]: 4719 : if (src_idx < arg->ndigits)
10300 : 3388 : a0 += arg->digits[src_idx];
10301 : : }
10302 : :
10303 : : /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
10304 : 4600 : numer = r_int64 * b + a1;
10305 : 4600 : denom = 2 * s_int64;
10306 : 4600 : q = numer / denom;
10307 : 4600 : u = numer - q * denom;
10308 : :
10309 : : /* Compute s = s*b + q and r = u*b + a0 - q^2 */
10310 : 4600 : s_int64 = s_int64 * b + q;
10311 : 4600 : r_int64 = u * b + a0 - q * q;
10312 : :
10313 [ + + ]: 4600 : if (r_int64 < 0)
10314 : : {
10315 : : /* s is too large by 1; set r += s, s--, r += s */
10316 : 161 : r_int64 += s_int64;
10317 : 161 : s_int64--;
10318 : 161 : r_int64 += s_int64;
10319 : : }
10320 : :
10321 [ - + ]: 4600 : Assert(src_idx == src_ndigits); /* All input digits consumed */
10322 : 4600 : step--;
10323 : : }
10324 : :
10325 : : /*
10326 : : * On platforms with 128-bit integer support, we can further delay the
10327 : : * need to use numeric variables.
10328 : : */
10329 : : #ifdef HAVE_INT128
10330 [ + - ]: 3012 : if (step >= 0)
10331 : : {
10332 : : int128 s_int128;
10333 : : int128 r_int128;
10334 : :
10335 : 3012 : s_int128 = s_int64;
10336 : 3012 : r_int128 = r_int64;
10337 : :
10338 : : /*
10339 : : * Iterations with src_ndigits <= 16:
10340 : : *
10341 : : * The result fits in an int128 (even though the input doesn't) so we
10342 : : * use int128 variables to avoid more expensive numeric computations.
10343 : : */
10344 [ + + + + ]: 6556 : while (step >= 0 && (src_ndigits = ndigits[step]) <= 16)
10345 : : {
10346 : : int64 b;
10347 : : int64 a0;
10348 : : int64 a1;
10349 : : int64 i;
10350 : : int128 numer;
10351 : : int128 denom;
10352 : : int128 q;
10353 : : int128 u;
10354 : :
10355 : 3544 : blen = (src_ndigits - src_idx) / 2;
10356 : :
10357 : : /* Extract a1 and a0, and compute b */
10358 : 3544 : a0 = 0;
10359 : 3544 : a1 = 0;
10360 : 3544 : b = 1;
10361 : :
10362 [ + + ]: 11736 : for (i = 0; i < blen; i++, src_idx++)
10363 : : {
10364 : 8192 : b *= NBASE;
10365 : 8192 : a1 *= NBASE;
10366 [ + + ]: 8192 : if (src_idx < arg->ndigits)
10367 : 4915 : a1 += arg->digits[src_idx];
10368 : : }
10369 : :
10370 [ + + ]: 11736 : for (i = 0; i < blen; i++, src_idx++)
10371 : : {
10372 : 8192 : a0 *= NBASE;
10373 [ + + ]: 8192 : if (src_idx < arg->ndigits)
10374 : 3407 : a0 += arg->digits[src_idx];
10375 : : }
10376 : :
10377 : : /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
10378 : 3544 : numer = r_int128 * b + a1;
10379 : 3544 : denom = 2 * s_int128;
10380 : 3544 : q = numer / denom;
10381 : 3544 : u = numer - q * denom;
10382 : :
10383 : : /* Compute s = s*b + q and r = u*b + a0 - q^2 */
10384 : 3544 : s_int128 = s_int128 * b + q;
10385 : 3544 : r_int128 = u * b + a0 - q * q;
10386 : :
10387 [ + + ]: 3544 : if (r_int128 < 0)
10388 : : {
10389 : : /* s is too large by 1; set r += s, s--, r += s */
10390 : 146 : r_int128 += s_int128;
10391 : 146 : s_int128--;
10392 : 146 : r_int128 += s_int128;
10393 : : }
10394 : :
10395 [ - + ]: 3544 : Assert(src_idx == src_ndigits); /* All input digits consumed */
10396 : 3544 : step--;
10397 : : }
10398 : :
10399 : : /*
10400 : : * All remaining iterations require numeric variables. Convert the
10401 : : * integer values to NumericVar and continue. Note that in the final
10402 : : * iteration we don't need the remainder, so we can save a few cycles
10403 : : * there by not fully computing it.
10404 : : */
10405 : 3012 : int128_to_numericvar(s_int128, &s_var);
10406 [ + + ]: 3012 : if (step >= 0)
10407 : 1988 : int128_to_numericvar(r_int128, &r_var);
10408 : : }
10409 : : else
10410 : : {
2436 dean.a.rasheed@gmail 10411 :UBC 0 : int64_to_numericvar(s_int64, &s_var);
10412 : : /* step < 0, so we certainly don't need r */
10413 : : }
10414 : : #else /* !HAVE_INT128 */
10415 : : int64_to_numericvar(s_int64, &s_var);
10416 : : if (step >= 0)
10417 : : int64_to_numericvar(r_int64, &r_var);
10418 : : #endif /* HAVE_INT128 */
10419 : :
10420 : : /*
10421 : : * The remaining iterations with src_ndigits > 8 (or 16, if have int128)
10422 : : * use numeric variables.
10423 : : */
2436 dean.a.rasheed@gmail 10424 [ + + ]:CBC 6287 : while (step >= 0)
10425 : : {
10426 : : int tmp_len;
10427 : :
10428 : 3275 : src_ndigits = ndigits[step];
10429 : 3275 : blen = (src_ndigits - src_idx) / 2;
10430 : :
10431 : : /* Extract a1 and a0 */
10432 [ + + ]: 3275 : if (src_idx < arg->ndigits)
10433 : : {
10434 : 1088 : tmp_len = Min(blen, arg->ndigits - src_idx);
10435 : 1088 : alloc_var(&a1_var, tmp_len);
10436 : 1088 : memcpy(a1_var.digits, arg->digits + src_idx,
10437 : : tmp_len * sizeof(NumericDigit));
10438 : 1088 : a1_var.weight = blen - 1;
10439 : 1088 : a1_var.sign = NUMERIC_POS;
10440 : 1088 : a1_var.dscale = 0;
10441 : 1088 : strip_var(&a1_var);
10442 : : }
10443 : : else
10444 : : {
10445 : 2187 : zero_var(&a1_var);
10446 : 2187 : a1_var.dscale = 0;
10447 : : }
10448 : 3275 : src_idx += blen;
10449 : :
10450 [ + + ]: 3275 : if (src_idx < arg->ndigits)
10451 : : {
10452 : 1088 : tmp_len = Min(blen, arg->ndigits - src_idx);
10453 : 1088 : alloc_var(&a0_var, tmp_len);
10454 : 1088 : memcpy(a0_var.digits, arg->digits + src_idx,
10455 : : tmp_len * sizeof(NumericDigit));
10456 : 1088 : a0_var.weight = blen - 1;
10457 : 1088 : a0_var.sign = NUMERIC_POS;
10458 : 1088 : a0_var.dscale = 0;
10459 : 1088 : strip_var(&a0_var);
10460 : : }
10461 : : else
10462 : : {
10463 : 2187 : zero_var(&a0_var);
10464 : 2187 : a0_var.dscale = 0;
10465 : : }
10466 : 3275 : src_idx += blen;
10467 : :
10468 : : /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
10469 : 3275 : set_var_from_var(&r_var, &q_var);
10470 : 3275 : q_var.weight += blen;
10471 : 3275 : add_var(&q_var, &a1_var, &q_var);
10472 : 3275 : add_var(&s_var, &s_var, &u_var);
10473 : 3275 : div_mod_var(&q_var, &u_var, &q_var, &u_var);
10474 : :
10475 : : /* Compute s = s*b + q */
10476 : 3275 : s_var.weight += blen;
10477 : 3275 : add_var(&s_var, &q_var, &s_var);
10478 : :
10479 : : /*
10480 : : * Compute r = u*b + a0 - q^2.
10481 : : *
10482 : : * In the final iteration, we don't actually need r; we just need to
10483 : : * know whether it is negative, so that we know whether to adjust s.
10484 : : * So instead of the final subtraction we can just compare.
10485 : : */
10486 : 3275 : u_var.weight += blen;
10487 : 3275 : add_var(&u_var, &a0_var, &u_var);
10488 : 3275 : mul_var(&q_var, &q_var, &q_var, 0);
10489 : :
10490 [ + + ]: 3275 : if (step > 0)
10491 : : {
10492 : : /* Need r for later iterations */
10493 : 1287 : sub_var(&u_var, &q_var, &r_var);
10494 [ + + ]: 1287 : if (r_var.sign == NUMERIC_NEG)
10495 : : {
10496 : : /* s is too large by 1; set r += s, s--, r += s */
10497 : 85 : add_var(&r_var, &s_var, &r_var);
10498 : 85 : sub_var(&s_var, &const_one, &s_var);
10499 : 85 : add_var(&r_var, &s_var, &r_var);
10500 : : }
10501 : : }
10502 : : else
10503 : : {
10504 : : /* Don't need r anymore, except to test if s is too large by 1 */
10505 [ + + ]: 1988 : if (cmp_var(&u_var, &q_var) < 0)
10506 : 27 : sub_var(&s_var, &const_one, &s_var);
10507 : : }
10508 : :
10509 [ - + ]: 3275 : Assert(src_idx == src_ndigits); /* All input digits consumed */
10510 : 3275 : step--;
10511 : : }
10512 : :
10513 : : /*
10514 : : * Construct the final result, rounding it to the requested precision.
10515 : : */
10516 : 3012 : set_var_from_var(&s_var, result);
10517 : 3012 : result->weight = res_weight;
10518 : 3012 : result->sign = NUMERIC_POS;
10519 : :
10520 : : /* Round to target rscale (and set result->dscale) */
8653 tgl@sss.pgh.pa.us 10521 : 3012 : round_var(result, rscale);
10522 : :
10523 : : /* Strip leading and trailing zeroes */
2436 dean.a.rasheed@gmail 10524 : 3012 : strip_var(result);
10525 : :
10526 : 3012 : free_var(&s_var);
10527 : 3012 : free_var(&r_var);
10528 : 3012 : free_var(&a0_var);
10529 : 3012 : free_var(&a1_var);
10530 : 3012 : free_var(&q_var);
10531 : 3012 : free_var(&u_var);
10532 : : }
10533 : :
10534 : :
10535 : : /*
10536 : : * exp_var() -
10537 : : *
10538 : : * Raise e to the power of x, computed to rscale fractional digits
10539 : : */
10540 : : static void
3366 andres@anarazel.de 10541 : 139 : exp_var(const NumericVar *arg, NumericVar *result, int rscale)
10542 : : {
10543 : : NumericVar x;
10544 : : NumericVar elem;
10545 : : int ni;
10546 : : double val;
10547 : : int dweight;
10548 : : int ndiv2;
10549 : : int sig_digits;
10550 : : int local_rscale;
10551 : :
10195 JanWieck@Yahoo.com 10552 : 139 : init_var(&x);
4032 tgl@sss.pgh.pa.us 10553 : 139 : init_var(&elem);
10554 : :
10195 JanWieck@Yahoo.com 10555 : 139 : set_var_from_var(arg, &x);
10556 : :
10557 : : /*
10558 : : * Estimate the dweight of the result using floating point arithmetic, so
10559 : : * that we can choose an appropriate local rscale for the calculation.
10560 : : */
4032 tgl@sss.pgh.pa.us 10561 : 139 : val = numericvar_to_double_no_overflow(&x);
10562 : :
10563 : : /* Guard against overflow/underflow */
10564 : : /* If you change this limit, see also power_var()'s limit */
1513 peter@eisentraut.org 10565 [ + + ]: 139 : if (fabs(val) >= NUMERIC_MAX_RESULT_SCALE * 3)
10566 : : {
1946 dean.a.rasheed@gmail 10567 [ - + ]: 5 : if (val > 0)
1946 dean.a.rasheed@gmail 10568 [ # # ]:UBC 0 : ereport(ERROR,
10569 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
10570 : : errmsg("value overflows numeric format")));
1946 dean.a.rasheed@gmail 10571 :CBC 5 : zero_var(result);
10572 : 5 : result->dscale = rscale;
10573 : 5 : return;
10574 : : }
10575 : :
10576 : : /* decimal weight = log10(e^x) = x * log10(e) */
4032 tgl@sss.pgh.pa.us 10577 : 134 : dweight = (int) (val * 0.434294481903252);
10578 : :
10579 : : /*
10580 : : * Reduce x to the range -0.01 <= x <= 0.01 (approximately) by dividing by
10581 : : * 2^ndiv2, to improve the convergence rate of the Taylor series.
10582 : : *
10583 : : * Note that the overflow check above ensures that fabs(x) < 6000, which
10584 : : * means that ndiv2 <= 20 here.
10585 : : */
1513 peter@eisentraut.org 10586 [ + + ]: 134 : if (fabs(val) > 0.01)
10587 : : {
4032 tgl@sss.pgh.pa.us 10588 : 110 : ndiv2 = 1;
10589 : 110 : val /= 2;
10590 : :
1513 peter@eisentraut.org 10591 [ + + ]: 1402 : while (fabs(val) > 0.01)
10592 : : {
4032 tgl@sss.pgh.pa.us 10593 : 1292 : ndiv2++;
10594 : 1292 : val /= 2;
10595 : : }
10596 : :
10597 : 110 : local_rscale = x.dscale + ndiv2;
1735 dean.a.rasheed@gmail 10598 : 110 : div_var_int(&x, 1 << ndiv2, 0, &x, local_rscale, true);
10599 : : }
10600 : : else
4032 tgl@sss.pgh.pa.us 10601 : 24 : ndiv2 = 0;
10602 : :
10603 : : /*
10604 : : * Set the scale for the Taylor series expansion. The final result has
10605 : : * (dweight + rscale + 1) significant digits. In addition, we have to
10606 : : * raise the Taylor series result to the power 2^ndiv2, which introduces
10607 : : * an error of up to around log10(2^ndiv2) digits, so work with this many
10608 : : * extra digits of precision (plus a few more for good measure).
10609 : : */
10610 : 134 : sig_digits = 1 + dweight + rscale + (int) (ndiv2 * 0.301029995663981);
10611 : 134 : sig_digits = Max(sig_digits, 0) + 8;
10612 : :
10613 : 134 : local_rscale = sig_digits - 1;
10614 : :
10615 : : /*
10616 : : * Use the Taylor series
10617 : : *
10618 : : * exp(x) = 1 + x + x^2/2! + x^3/3! + ...
10619 : : *
10620 : : * Given the limited range of x, this should converge reasonably quickly.
10621 : : * We run the series until the terms fall below the local_rscale limit.
10622 : : */
10195 JanWieck@Yahoo.com 10623 : 134 : add_var(&const_one, &x, result);
10624 : :
4032 tgl@sss.pgh.pa.us 10625 : 134 : mul_var(&x, &x, &elem, local_rscale);
1735 dean.a.rasheed@gmail 10626 : 134 : ni = 2;
10627 : 134 : div_var_int(&elem, ni, 0, &elem, local_rscale, true);
10628 : :
4032 tgl@sss.pgh.pa.us 10629 [ + + ]: 3639 : while (elem.ndigits != 0)
10630 : : {
10195 JanWieck@Yahoo.com 10631 : 3505 : add_var(result, &elem, result);
10632 : :
4032 tgl@sss.pgh.pa.us 10633 : 3505 : mul_var(&elem, &x, &elem, local_rscale);
1735 dean.a.rasheed@gmail 10634 : 3505 : ni++;
10635 : 3505 : div_var_int(&elem, ni, 0, &elem, local_rscale, true);
10636 : : }
10637 : :
10638 : : /*
10639 : : * Compensate for the argument range reduction. Since the weight of the
10640 : : * result doubles with each multiplication, we can reduce the local rscale
10641 : : * as we proceed.
10642 : : */
10195 JanWieck@Yahoo.com 10643 [ + + ]: 1536 : while (ndiv2-- > 0)
10644 : : {
4032 tgl@sss.pgh.pa.us 10645 : 1402 : local_rscale = sig_digits - result->weight * 2 * DEC_DIGITS;
10646 : 1402 : local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
8653 10647 : 1402 : mul_var(result, result, result, local_rscale);
10648 : : }
10649 : :
10650 : : /* Round to requested rscale */
4032 10651 : 134 : round_var(result, rscale);
10652 : :
10195 JanWieck@Yahoo.com 10653 : 134 : free_var(&x);
10654 : 134 : free_var(&elem);
10655 : : }
10656 : :
10657 : :
10658 : : /*
10659 : : * Estimate the dweight of the most significant decimal digit of the natural
10660 : : * logarithm of a number.
10661 : : *
10662 : : * Essentially, we're approximating log10(abs(ln(var))). This is used to
10663 : : * determine the appropriate rscale when computing natural logarithms.
10664 : : *
10665 : : * Note: many callers call this before range-checking the input. Therefore,
10666 : : * we must be robust against values that are invalid to apply ln() to.
10667 : : * We don't wish to throw an error here, so just return zero in such cases.
10668 : : */
10669 : : static int
3366 andres@anarazel.de 10670 : 526 : estimate_ln_dweight(const NumericVar *var)
10671 : : {
10672 : : int ln_dweight;
10673 : :
10674 : : /* Caller should fail on ln(negative), but for the moment return zero */
1731 tgl@sss.pgh.pa.us 10675 [ + + ]: 526 : if (var->sign != NUMERIC_POS)
10676 : 28 : return 0;
10677 : :
4032 10678 [ + + + + ]: 937 : if (cmp_var(var, &const_zero_point_nine) >= 0 &&
10679 : 439 : cmp_var(var, &const_one_point_one) <= 0)
10680 : 66 : {
10681 : : /*
10682 : : * 0.9 <= var <= 1.1
10683 : : *
10684 : : * ln(var) has a negative weight (possibly very large). To get a
10685 : : * reasonably accurate result, estimate it using ln(1+x) ~= x.
10686 : : */
10687 : : NumericVar x;
10688 : :
10689 : 66 : init_var(&x);
10690 : 66 : sub_var(var, &const_one, &x);
10691 : :
10692 [ + + ]: 66 : if (x.ndigits > 0)
10693 : : {
10694 : : /* Use weight of most significant decimal digit of x */
10695 : 35 : ln_dweight = x.weight * DEC_DIGITS + (int) log10(x.digits[0]);
10696 : : }
10697 : : else
10698 : : {
10699 : : /* x = 0. Since ln(1) = 0 exactly, we don't need extra digits */
10700 : 31 : ln_dweight = 0;
10701 : : }
10702 : :
10703 : 66 : free_var(&x);
10704 : : }
10705 : : else
10706 : : {
10707 : : /*
10708 : : * Estimate the logarithm using the first couple of digits from the
10709 : : * input number. This will give an accurate result whenever the input
10710 : : * is not too close to 1.
10711 : : */
10712 [ + + ]: 432 : if (var->ndigits > 0)
10713 : : {
10714 : : int digits;
10715 : : int dweight;
10716 : : double ln_var;
10717 : :
10718 : 404 : digits = var->digits[0];
10719 : 404 : dweight = var->weight * DEC_DIGITS;
10720 : :
10721 [ + + ]: 404 : if (var->ndigits > 1)
10722 : : {
10723 : 246 : digits = digits * NBASE + var->digits[1];
10724 : 246 : dweight -= DEC_DIGITS;
10725 : : }
10726 : :
10727 : : /*----------
10728 : : * We have var ~= digits * 10^dweight
10729 : : * so ln(var) ~= ln(digits) + dweight * ln(10)
10730 : : *----------
10731 : : */
10732 : 404 : ln_var = log((double) digits) + dweight * 2.302585092994046;
1513 peter@eisentraut.org 10733 : 404 : ln_dweight = (int) log10(fabs(ln_var));
10734 : : }
10735 : : else
10736 : : {
10737 : : /* Caller should fail on ln(0), but for the moment return zero */
4032 tgl@sss.pgh.pa.us 10738 : 28 : ln_dweight = 0;
10739 : : }
10740 : : }
10741 : :
10742 : 498 : return ln_dweight;
10743 : : }
10744 : :
10745 : :
10746 : : /*
10747 : : * ln_var() -
10748 : : *
10749 : : * Compute the natural log of x
10750 : : */
10751 : : static void
3366 andres@anarazel.de 10752 : 599 : ln_var(const NumericVar *arg, NumericVar *result, int rscale)
10753 : : {
10754 : : NumericVar x;
10755 : : NumericVar xx;
10756 : : int ni;
10757 : : NumericVar elem;
10758 : : NumericVar fact;
10759 : : int nsqrt;
10760 : : int local_rscale;
10761 : : int cmp;
10762 : :
8231 neilc@samurai.com 10763 : 599 : cmp = cmp_var(arg, &const_zero);
10764 [ + + ]: 599 : if (cmp == 0)
8525 tgl@sss.pgh.pa.us 10765 [ + - ]: 28 : ereport(ERROR,
10766 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
10767 : : errmsg("cannot take logarithm of zero")));
8231 neilc@samurai.com 10768 [ + + ]: 571 : else if (cmp < 0)
10769 [ + - ]: 24 : ereport(ERROR,
10770 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
10771 : : errmsg("cannot take logarithm of a negative number")));
10772 : :
10195 JanWieck@Yahoo.com 10773 : 547 : init_var(&x);
10774 : 547 : init_var(&xx);
10775 : 547 : init_var(&elem);
10776 : 547 : init_var(&fact);
10777 : :
10778 : 547 : set_var_from_var(arg, &x);
8653 tgl@sss.pgh.pa.us 10779 : 547 : set_var_from_var(&const_two, &fact);
10780 : :
10781 : : /*
10782 : : * Reduce input into range 0.9 < x < 1.1 with repeated sqrt() operations.
10783 : : *
10784 : : * The final logarithm will have up to around rscale+6 significant digits.
10785 : : * Each sqrt() will roughly halve the weight of x, so adjust the local
10786 : : * rscale as we work so that we keep this many significant digits at each
10787 : : * step (plus a few more for good measure).
10788 : : *
10789 : : * Note that we allow local_rscale < 0 during this input reduction
10790 : : * process, which implies rounding before the decimal point. sqrt_var()
10791 : : * explicitly supports this, and it significantly reduces the work
10792 : : * required to reduce very large inputs to the required range. Once the
10793 : : * input reduction is complete, x.weight will be 0 and its display scale
10794 : : * will be non-negative again.
10795 : : */
2463 dean.a.rasheed@gmail 10796 : 547 : nsqrt = 0;
8823 tgl@sss.pgh.pa.us 10797 [ + + ]: 818 : while (cmp_var(&x, &const_zero_point_nine) <= 0)
10798 : : {
4032 10799 : 271 : local_rscale = rscale - x.weight * DEC_DIGITS / 2 + 8;
8653 10800 : 271 : sqrt_var(&x, &x, local_rscale);
10801 : 271 : mul_var(&fact, &const_two, &fact, 0);
2463 dean.a.rasheed@gmail 10802 : 271 : nsqrt++;
10803 : : }
8823 tgl@sss.pgh.pa.us 10804 [ + + ]: 2956 : while (cmp_var(&x, &const_one_point_one) >= 0)
10805 : : {
4032 10806 : 2409 : local_rscale = rscale - x.weight * DEC_DIGITS / 2 + 8;
8653 10807 : 2409 : sqrt_var(&x, &x, local_rscale);
10808 : 2409 : mul_var(&fact, &const_two, &fact, 0);
2463 dean.a.rasheed@gmail 10809 : 2409 : nsqrt++;
10810 : : }
10811 : :
10812 : : /*
10813 : : * We use the Taylor series for 0.5 * ln((1+z)/(1-z)),
10814 : : *
10815 : : * z + z^3/3 + z^5/5 + ...
10816 : : *
10817 : : * where z = (x-1)/(x+1) is in the range (approximately) -0.053 .. 0.048
10818 : : * due to the above range-reduction of x.
10819 : : *
10820 : : * The convergence of this is not as fast as one would like, but is
10821 : : * tolerable given that z is small.
10822 : : *
10823 : : * The Taylor series result will be multiplied by 2^(nsqrt+1), which has a
10824 : : * decimal weight of (nsqrt+1) * log10(2), so work with this many extra
10825 : : * digits of precision (plus a few more for good measure).
10826 : : */
10827 : 547 : local_rscale = rscale + (int) ((nsqrt + 1) * 0.301029995663981) + 8;
10828 : :
10195 JanWieck@Yahoo.com 10829 : 547 : sub_var(&x, &const_one, result);
10830 : 547 : add_var(&x, &const_one, &elem);
785 dean.a.rasheed@gmail 10831 : 547 : div_var(result, &elem, result, local_rscale, true, false);
10195 JanWieck@Yahoo.com 10832 : 547 : set_var_from_var(result, &xx);
8653 tgl@sss.pgh.pa.us 10833 : 547 : mul_var(result, result, &x, local_rscale);
10834 : :
1735 dean.a.rasheed@gmail 10835 : 547 : ni = 1;
10836 : :
10837 : : for (;;)
10838 : : {
10839 : 9961 : ni += 2;
8653 tgl@sss.pgh.pa.us 10840 : 9961 : mul_var(&xx, &x, &xx, local_rscale);
1735 dean.a.rasheed@gmail 10841 : 9961 : div_var_int(&xx, ni, 0, &elem, local_rscale, true);
10842 : :
8823 tgl@sss.pgh.pa.us 10843 [ + + ]: 9961 : if (elem.ndigits == 0)
10195 JanWieck@Yahoo.com 10844 : 547 : break;
10845 : :
10846 : 9414 : add_var(result, &elem, result);
10847 : :
8517 bruce@momjian.us 10848 [ - + ]: 9414 : if (elem.weight < (result->weight - local_rscale * 2 / DEC_DIGITS))
8660 tgl@sss.pgh.pa.us 10849 :UBC 0 : break;
10850 : : }
10851 : :
10852 : : /* Compensate for argument range reduction, round to requested rscale */
8653 tgl@sss.pgh.pa.us 10853 :CBC 547 : mul_var(result, &fact, result, rscale);
10854 : :
10195 JanWieck@Yahoo.com 10855 : 547 : free_var(&x);
10856 : 547 : free_var(&xx);
10857 : 547 : free_var(&elem);
10858 : 547 : free_var(&fact);
10859 : 547 : }
10860 : :
10861 : :
10862 : : /*
10863 : : * log_var() -
10864 : : *
10865 : : * Compute the logarithm of num in a given base.
10866 : : *
10867 : : * Note: this routine chooses dscale of the result.
10868 : : */
10869 : : static void
3366 andres@anarazel.de 10870 : 160 : log_var(const NumericVar *base, const NumericVar *num, NumericVar *result)
10871 : : {
10872 : : NumericVar ln_base;
10873 : : NumericVar ln_num;
10874 : : int ln_base_dweight;
10875 : : int ln_num_dweight;
10876 : : int result_dweight;
10877 : : int rscale;
10878 : : int ln_base_rscale;
10879 : : int ln_num_rscale;
10880 : :
10881 : : /*
10882 : : * ln_var will throw a suitable error for most invalid-input cases, but we
10883 : : * need a special case for base == 1, else we'd report "division by zero"
10884 : : * which is a bit confusing.
10885 : : */
44 tgl@sss.pgh.pa.us 10886 [ + + ]:GNC 160 : if (cmp_var(base, &const_one) == 0)
10887 [ + - ]: 8 : ereport(ERROR,
10888 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
10889 : : errmsg("cannot take logarithm using base one")));
10890 : :
10195 JanWieck@Yahoo.com 10891 :CBC 152 : init_var(&ln_base);
10892 : 152 : init_var(&ln_num);
10893 : :
10894 : : /* Estimated dweights of ln(base), ln(num) and the final result */
4032 tgl@sss.pgh.pa.us 10895 : 152 : ln_base_dweight = estimate_ln_dweight(base);
10896 : 152 : ln_num_dweight = estimate_ln_dweight(num);
10897 : 152 : result_dweight = ln_num_dweight - ln_base_dweight;
10898 : :
10899 : : /*
10900 : : * Select the scale of the result so that it will have at least
10901 : : * NUMERIC_MIN_SIG_DIGITS significant digits and is not less than either
10902 : : * input's display scale.
10903 : : */
10904 : 152 : rscale = NUMERIC_MIN_SIG_DIGITS - result_dweight;
8653 10905 : 152 : rscale = Max(rscale, base->dscale);
10906 : 152 : rscale = Max(rscale, num->dscale);
10907 : 152 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
10908 : 152 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
10909 : :
10910 : : /*
10911 : : * Set the scales for ln(base) and ln(num) so that they each have more
10912 : : * significant digits than the final result.
10913 : : */
4032 10914 : 152 : ln_base_rscale = rscale + result_dweight - ln_base_dweight + 8;
10915 : 152 : ln_base_rscale = Max(ln_base_rscale, NUMERIC_MIN_DISPLAY_SCALE);
10916 : :
10917 : 152 : ln_num_rscale = rscale + result_dweight - ln_num_dweight + 8;
10918 : 152 : ln_num_rscale = Max(ln_num_rscale, NUMERIC_MIN_DISPLAY_SCALE);
10919 : :
10920 : : /* Form natural logarithms */
10921 : 152 : ln_var(base, &ln_base, ln_base_rscale);
10922 : 136 : ln_var(num, &ln_num, ln_num_rscale);
10923 : :
10924 : : /* Divide and round to the required scale */
785 dean.a.rasheed@gmail 10925 : 116 : div_var(&ln_num, &ln_base, result, rscale, true, false);
10926 : :
10195 JanWieck@Yahoo.com 10927 : 116 : free_var(&ln_num);
10928 : 116 : free_var(&ln_base);
10929 : 116 : }
10930 : :
10931 : :
10932 : : /*
10933 : : * power_var() -
10934 : : *
10935 : : * Raise base to the power of exp
10936 : : *
10937 : : * Note: this routine chooses dscale of the result.
10938 : : */
10939 : : static void
3366 andres@anarazel.de 10940 : 968 : power_var(const NumericVar *base, const NumericVar *exp, NumericVar *result)
10941 : : {
10942 : : int res_sign;
10943 : : NumericVar abs_base;
10944 : : NumericVar ln_base;
10945 : : NumericVar ln_num;
10946 : : int ln_dweight;
10947 : : int rscale;
10948 : : int sig_digits;
10949 : : int local_rscale;
10950 : : double val;
10951 : :
10952 : : /* If exp can be represented as an integer, use power_var_int */
8653 tgl@sss.pgh.pa.us 10953 [ + + + + ]: 968 : if (exp->ndigits == 0 || exp->ndigits <= exp->weight + 1)
10954 : : {
10955 : : /* exact integer, but does it fit in int? */
10956 : : int64 expval64;
10957 : :
4271 andres@anarazel.de 10958 [ + + ]: 878 : if (numericvar_to_int64(exp, &expval64))
10959 : : {
1940 dean.a.rasheed@gmail 10960 [ + - + + ]: 873 : if (expval64 >= PG_INT32_MIN && expval64 <= PG_INT32_MAX)
10961 : : {
10962 : : /* Okay, use power_var_int */
1500 10963 : 848 : power_var_int(base, (int) expval64, exp->dscale, result);
8653 tgl@sss.pgh.pa.us 10964 : 840 : return;
10965 : : }
10966 : : }
10967 : : }
10968 : :
10969 : : /*
10970 : : * This avoids log(0) for cases of 0 raised to a non-integer. 0 ^ 0 is
10971 : : * handled by power_var_int().
10972 : : */
6778 bruce@momjian.us 10973 [ + + ]: 120 : if (cmp_var(base, &const_zero) == 0)
10974 : : {
10975 : 14 : set_var_from_var(&const_zero, result);
3447 tgl@sss.pgh.pa.us 10976 : 14 : result->dscale = NUMERIC_MIN_SIG_DIGITS; /* no need to round */
6778 bruce@momjian.us 10977 : 14 : return;
10978 : : }
10979 : :
1946 dean.a.rasheed@gmail 10980 : 106 : init_var(&abs_base);
10195 JanWieck@Yahoo.com 10981 : 106 : init_var(&ln_base);
10982 : 106 : init_var(&ln_num);
10983 : :
10984 : : /*
10985 : : * If base is negative, insist that exp be an integer. The result is then
10986 : : * positive if exp is even and negative if exp is odd.
10987 : : */
1946 dean.a.rasheed@gmail 10988 [ + + ]: 106 : if (base->sign == NUMERIC_NEG)
10989 : : {
10990 : : /*
10991 : : * Check that exp is an integer. This error code is defined by the
10992 : : * SQL standard, and matches other errors in numeric_power().
10993 : : */
10994 [ + - + + ]: 27 : if (exp->ndigits > 0 && exp->ndigits > exp->weight + 1)
10995 [ + - ]: 12 : ereport(ERROR,
10996 : : (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
10997 : : errmsg("a negative number raised to a non-integer power yields a complex result")));
10998 : :
10999 : : /* Test if exp is odd or even */
11000 [ + - + + ]: 15 : if (exp->ndigits > 0 && exp->ndigits == exp->weight + 1 &&
11001 [ + + ]: 10 : (exp->digits[exp->ndigits - 1] & 1))
11002 : 5 : res_sign = NUMERIC_NEG;
11003 : : else
11004 : 10 : res_sign = NUMERIC_POS;
11005 : :
11006 : : /* Then work with abs(base) below */
11007 : 15 : set_var_from_var(base, &abs_base);
11008 : 15 : abs_base.sign = NUMERIC_POS;
11009 : 15 : base = &abs_base;
11010 : : }
11011 : : else
11012 : 79 : res_sign = NUMERIC_POS;
11013 : :
11014 : : /*----------
11015 : : * Decide on the scale for the ln() calculation. For this we need an
11016 : : * estimate of the weight of the result, which we obtain by doing an
11017 : : * initial low-precision calculation of exp * ln(base).
11018 : : *
11019 : : * We want result = e ^ (exp * ln(base))
11020 : : * so result dweight = log10(result) = exp * ln(base) * log10(e)
11021 : : *
11022 : : * We also perform a crude overflow test here so that we can exit early if
11023 : : * the full-precision result is sure to overflow, and to guard against
11024 : : * integer overflow when determining the scale for the real calculation.
11025 : : * exp_var() supports inputs up to NUMERIC_MAX_RESULT_SCALE * 3, so the
11026 : : * result will overflow if exp * ln(base) >= NUMERIC_MAX_RESULT_SCALE * 3.
11027 : : * Since the values here are only approximations, we apply a small fuzz
11028 : : * factor to this overflow test and let exp_var() determine the exact
11029 : : * overflow threshold so that it is consistent for all inputs.
11030 : : *----------
11031 : : */
4032 tgl@sss.pgh.pa.us 11032 : 94 : ln_dweight = estimate_ln_dweight(base);
11033 : :
11034 : : /*
11035 : : * Set the scale for the low-precision calculation, computing ln(base) to
11036 : : * around 8 significant digits. Note that ln_dweight may be as small as
11037 : : * -NUMERIC_DSCALE_MAX, so the scale may exceed NUMERIC_MAX_DISPLAY_SCALE
11038 : : * here.
11039 : : */
11040 : 94 : local_rscale = 8 - ln_dweight;
11041 : 94 : local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11042 : :
8653 11043 : 94 : ln_var(base, &ln_base, local_rscale);
11044 : :
11045 : 94 : mul_var(&ln_base, exp, &ln_num, local_rscale);
11046 : :
8823 11047 : 94 : val = numericvar_to_double_no_overflow(&ln_num);
11048 : :
11049 : : /* initial overflow/underflow test with fuzz factor */
1513 peter@eisentraut.org 11050 [ + + ]: 94 : if (fabs(val) > NUMERIC_MAX_RESULT_SCALE * 3.01)
11051 : : {
1946 dean.a.rasheed@gmail 11052 [ - + ]: 5 : if (val > 0)
1946 dean.a.rasheed@gmail 11053 [ # # ]:UBC 0 : ereport(ERROR,
11054 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
11055 : : errmsg("value overflows numeric format")));
1946 dean.a.rasheed@gmail 11056 :CBC 5 : zero_var(result);
11057 : 5 : result->dscale = NUMERIC_MAX_DISPLAY_SCALE;
11058 : 5 : return;
11059 : : }
11060 : :
3859 11061 : 89 : val *= 0.434294481903252; /* approximate decimal result weight */
11062 : :
11063 : : /* choose the result scale */
8653 tgl@sss.pgh.pa.us 11064 : 89 : rscale = NUMERIC_MIN_SIG_DIGITS - (int) val;
11065 : 89 : rscale = Max(rscale, base->dscale);
11066 : 89 : rscale = Max(rscale, exp->dscale);
11067 : 89 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
11068 : 89 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
11069 : :
11070 : : /* significant digits required in the result */
1946 dean.a.rasheed@gmail 11071 : 89 : sig_digits = rscale + (int) val;
11072 : 89 : sig_digits = Max(sig_digits, 0);
11073 : :
11074 : : /* set the scale for the real exp * ln(base) calculation */
11075 : 89 : local_rscale = sig_digits - ln_dweight + 8;
4032 tgl@sss.pgh.pa.us 11076 : 89 : local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11077 : :
11078 : : /* and do the real calculation */
11079 : :
11080 : 89 : ln_var(base, &ln_base, local_rscale);
11081 : :
11082 : 89 : mul_var(&ln_base, exp, &ln_num, local_rscale);
11083 : :
8653 11084 : 89 : exp_var(&ln_num, result, rscale);
11085 : :
1946 dean.a.rasheed@gmail 11086 [ + + + - ]: 89 : if (res_sign == NUMERIC_NEG && result->ndigits > 0)
11087 : 5 : result->sign = NUMERIC_NEG;
11088 : :
8653 tgl@sss.pgh.pa.us 11089 : 89 : free_var(&ln_num);
11090 : 89 : free_var(&ln_base);
1946 dean.a.rasheed@gmail 11091 : 89 : free_var(&abs_base);
11092 : : }
11093 : :
11094 : : /*
11095 : : * power_var_int() -
11096 : : *
11097 : : * Raise base to the power of exp, where exp is an integer.
11098 : : *
11099 : : * Note: this routine chooses dscale of the result.
11100 : : */
11101 : : static void
1500 11102 : 848 : power_var_int(const NumericVar *base, int exp, int exp_dscale,
11103 : : NumericVar *result)
11104 : : {
11105 : : double f;
11106 : : int p;
11107 : : int i;
11108 : : int rscale;
11109 : : int sig_digits;
11110 : : unsigned int mask;
11111 : : bool neg;
11112 : : NumericVar base_prod;
11113 : : int local_rscale;
11114 : :
11115 : : /*
11116 : : * Choose the result scale. For this we need an estimate of the decimal
11117 : : * weight of the result, which we obtain by approximating using double
11118 : : * precision arithmetic.
11119 : : *
11120 : : * We also perform crude overflow/underflow tests here so that we can exit
11121 : : * early if the result is sure to overflow/underflow, and to guard against
11122 : : * integer overflow when choosing the result scale.
11123 : : */
11124 [ + + ]: 848 : if (base->ndigits != 0)
11125 : : {
11126 : : /*----------
11127 : : * Choose f (double) and p (int) such that base ~= f * 10^p.
11128 : : * Then log10(result) = log10(base^exp) ~= exp * (log10(f) + p).
11129 : : *----------
11130 : : */
11131 : 826 : f = base->digits[0];
11132 : 826 : p = base->weight * DEC_DIGITS;
11133 : :
11134 [ + + + - ]: 891 : for (i = 1; i < base->ndigits && i * DEC_DIGITS < 16; i++)
11135 : : {
11136 : 65 : f = f * NBASE + base->digits[i];
11137 : 65 : p -= DEC_DIGITS;
11138 : : }
11139 : :
11140 : 826 : f = exp * (log10(f) + p); /* approximate decimal result weight */
11141 : : }
11142 : : else
11143 : 22 : f = 0; /* result is 0 or 1 (weight 0), or error */
11144 : :
11145 : : /* overflow/underflow tests with fuzz factors */
873 11146 [ + + ]: 848 : if (f > (NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS)
1500 11147 [ + - ]: 8 : ereport(ERROR,
11148 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
11149 : : errmsg("value overflows numeric format")));
11150 [ + + ]: 840 : if (f + 1 < -NUMERIC_MAX_DISPLAY_SCALE)
11151 : : {
11152 : 10 : zero_var(result);
11153 : 10 : result->dscale = NUMERIC_MAX_DISPLAY_SCALE;
11154 : 151 : return;
11155 : : }
11156 : :
11157 : : /*
11158 : : * Choose the result scale in the same way as power_var(), so it has at
11159 : : * least NUMERIC_MIN_SIG_DIGITS significant digits and is not less than
11160 : : * either input's display scale.
11161 : : */
11162 : 830 : rscale = NUMERIC_MIN_SIG_DIGITS - (int) f;
11163 : 830 : rscale = Max(rscale, base->dscale);
11164 : 830 : rscale = Max(rscale, exp_dscale);
11165 : 830 : rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
11166 : 830 : rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
11167 : :
11168 : : /* Handle some common special cases, as well as corner cases */
8653 tgl@sss.pgh.pa.us 11169 [ + + + + : 830 : switch (exp)
+ ]
11170 : : {
11171 : 52 : case 0:
11172 : :
11173 : : /*
11174 : : * While 0 ^ 0 can be either 1 or indeterminate (error), we treat
11175 : : * it as 1 because most programming languages do this. SQL:2003
11176 : : * also requires a return value of 1.
11177 : : * https://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_zero_power
11178 : : */
11179 : 52 : set_var_from_var(&const_one, result);
8517 bruce@momjian.us 11180 : 52 : result->dscale = rscale; /* no need to round */
8653 tgl@sss.pgh.pa.us 11181 : 52 : return;
11182 : 32 : case 1:
11183 : 32 : set_var_from_var(base, result);
11184 : 32 : round_var(result, rscale);
11185 : 32 : return;
11186 : 21 : case -1:
785 dean.a.rasheed@gmail 11187 : 21 : div_var(&const_one, base, result, rscale, true, true);
8653 tgl@sss.pgh.pa.us 11188 : 21 : return;
11189 : 36 : case 2:
11190 : 36 : mul_var(base, base, result, rscale);
11191 : 36 : return;
11192 : 689 : default:
11193 : 689 : break;
11194 : : }
11195 : :
11196 : : /* Handle the special case where the base is zero */
4032 11197 [ - + ]: 689 : if (base->ndigits == 0)
11198 : : {
4032 tgl@sss.pgh.pa.us 11199 [ # # ]:UBC 0 : if (exp < 0)
11200 [ # # ]: 0 : ereport(ERROR,
11201 : : (errcode(ERRCODE_DIVISION_BY_ZERO),
11202 : : errmsg("division by zero")));
11203 : 0 : zero_var(result);
11204 : 0 : result->dscale = rscale;
11205 : 0 : return;
11206 : : }
11207 : :
11208 : : /*
11209 : : * The general case repeatedly multiplies base according to the bit
11210 : : * pattern of exp.
11211 : : *
11212 : : * The local rscale used for each multiplication is varied to keep a fixed
11213 : : * number of significant digits, sufficient to give the required result
11214 : : * scale.
11215 : : */
11216 : :
11217 : : /*
11218 : : * Approximate number of significant digits in the result. Note that the
11219 : : * underflow test above, together with the choice of rscale, ensures that
11220 : : * this approximation is necessarily > 0.
11221 : : */
4032 tgl@sss.pgh.pa.us 11222 :CBC 689 : sig_digits = 1 + rscale + (int) f;
11223 : :
11224 : : /*
11225 : : * The multiplications to produce the result may introduce an error of up
11226 : : * to around log10(abs(exp)) digits, so work with this many extra digits
11227 : : * of precision (plus a few more for good measure).
11228 : : */
2153 dean.a.rasheed@gmail 11229 : 689 : sig_digits += (int) log(fabs((double) exp)) + 8;
11230 : :
11231 : : /*
11232 : : * Now we can proceed with the multiplications.
11233 : : */
8653 tgl@sss.pgh.pa.us 11234 : 689 : neg = (exp < 0);
835 nathan@postgresql.or 11235 : 689 : mask = pg_abs_s32(exp);
11236 : :
8653 tgl@sss.pgh.pa.us 11237 : 689 : init_var(&base_prod);
11238 : 689 : set_var_from_var(base, &base_prod);
11239 : :
4461 11240 [ + + ]: 689 : if (mask & 1)
8653 11241 : 343 : set_var_from_var(base, result);
11242 : : else
11243 : 346 : set_var_from_var(&const_one, result);
11244 : :
4461 11245 [ + + ]: 3618 : while ((mask >>= 1) > 0)
11246 : : {
11247 : : /*
11248 : : * Do the multiplications using rscales large enough to hold the
11249 : : * results to the required number of significant digits, but don't
11250 : : * waste time by exceeding the scales of the numbers themselves.
11251 : : */
4032 11252 : 2929 : local_rscale = sig_digits - 2 * base_prod.weight * DEC_DIGITS;
11253 : 2929 : local_rscale = Min(local_rscale, 2 * base_prod.dscale);
11254 : 2929 : local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11255 : :
8653 11256 : 2929 : mul_var(&base_prod, &base_prod, &base_prod, local_rscale);
11257 : :
4461 11258 [ + + ]: 2929 : if (mask & 1)
11259 : : {
4032 11260 : 1932 : local_rscale = sig_digits -
11261 : 1932 : (base_prod.weight + result->weight) * DEC_DIGITS;
11262 : 1932 : local_rscale = Min(local_rscale,
11263 : : base_prod.dscale + result->dscale);
11264 : 1932 : local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
11265 : :
8653 11266 : 1932 : mul_var(&base_prod, result, result, local_rscale);
11267 : : }
11268 : :
11269 : : /*
11270 : : * When abs(base) > 1, the number of digits to the left of the decimal
11271 : : * point in base_prod doubles at each iteration, so if exp is large we
11272 : : * could easily spend large amounts of time and memory space doing the
11273 : : * multiplications. But once the weight exceeds what will fit in
11274 : : * int16, the final result is guaranteed to overflow (or underflow, if
11275 : : * exp < 0), so we can give up before wasting too many cycles.
11276 : : */
873 dean.a.rasheed@gmail 11277 [ + - ]: 2929 : if (base_prod.weight > NUMERIC_WEIGHT_MAX ||
11278 [ - + ]: 2929 : result->weight > NUMERIC_WEIGHT_MAX)
11279 : : {
11280 : : /* overflow, unless neg, in which case result should be 0 */
4461 tgl@sss.pgh.pa.us 11281 [ # # ]:UBC 0 : if (!neg)
11282 [ # # ]: 0 : ereport(ERROR,
11283 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
11284 : : errmsg("value overflows numeric format")));
11285 : 0 : zero_var(result);
11286 : 0 : neg = false;
11287 : 0 : break;
11288 : : }
11289 : : }
11290 : :
8653 tgl@sss.pgh.pa.us 11291 :CBC 689 : free_var(&base_prod);
11292 : :
11293 : : /* Compensate for input sign, and round to requested rscale */
11294 [ + + ]: 689 : if (neg)
785 dean.a.rasheed@gmail 11295 : 328 : div_var(&const_one, result, result, rscale, true, false);
11296 : : else
8653 tgl@sss.pgh.pa.us 11297 : 361 : round_var(result, rscale);
11298 : : }
11299 : :
11300 : : /*
11301 : : * power_ten_int() -
11302 : : *
11303 : : * Raise ten to the power of exp, where exp is an integer. Note that unlike
11304 : : * power_var_int(), this does no overflow/underflow checking or rounding.
11305 : : */
11306 : : static void
1941 dean.a.rasheed@gmail 11307 : 200 : power_ten_int(int exp, NumericVar *result)
11308 : : {
11309 : : /* Construct the result directly, starting from 10^0 = 1 */
11310 : 200 : set_var_from_var(&const_one, result);
11311 : :
11312 : : /* Scale needed to represent the result exactly */
11313 [ + + ]: 200 : result->dscale = exp < 0 ? -exp : 0;
11314 : :
11315 : : /* Base-NBASE weight of result and remaining exponent */
11316 [ + + ]: 200 : if (exp >= 0)
11317 : 156 : result->weight = exp / DEC_DIGITS;
11318 : : else
11319 : 44 : result->weight = (exp + 1) / DEC_DIGITS - 1;
11320 : :
11321 : 200 : exp -= result->weight * DEC_DIGITS;
11322 : :
11323 : : /* Final adjustment of the result's single NBASE digit */
11324 [ + + ]: 476 : while (exp-- > 0)
11325 : 276 : result->digits[0] *= 10;
11326 : 200 : }
11327 : :
11328 : : /*
11329 : : * random_var() - return a random value in the range [rmin, rmax].
11330 : : */
11331 : : static void
976 11332 : 22292 : random_var(pg_prng_state *state, const NumericVar *rmin,
11333 : : const NumericVar *rmax, NumericVar *result)
11334 : : {
11335 : : int rscale;
11336 : : NumericVar rlen;
11337 : : int res_ndigits;
11338 : : int n;
11339 : : int pow10;
11340 : : int i;
11341 : : uint64 rlen64;
11342 : : int rlen64_ndigits;
11343 : :
11344 : 22292 : rscale = Max(rmin->dscale, rmax->dscale);
11345 : :
11346 : : /* Compute rlen = rmax - rmin and check the range bounds */
11347 : 22292 : init_var(&rlen);
11348 : 22292 : sub_var(rmax, rmin, &rlen);
11349 : :
11350 [ + + ]: 22292 : if (rlen.sign == NUMERIC_NEG)
11351 [ + - ]: 4 : ereport(ERROR,
11352 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
11353 : : errmsg("lower bound must be less than or equal to upper bound"));
11354 : :
11355 : : /* Special case for an empty range */
11356 [ + + ]: 22288 : if (rlen.ndigits == 0)
11357 : : {
11358 : 8 : set_var_from_var(rmin, result);
11359 : 8 : result->dscale = rscale;
11360 : 8 : free_var(&rlen);
11361 : 8 : return;
11362 : : }
11363 : :
11364 : : /*
11365 : : * Otherwise, select a random value in the range [0, rlen = rmax - rmin],
11366 : : * and shift it to the required range by adding rmin.
11367 : : */
11368 : :
11369 : : /* Required result digits */
11370 : 22280 : res_ndigits = rlen.weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
11371 : :
11372 : : /*
11373 : : * To get the required rscale, the final result digit must be a multiple
11374 : : * of pow10 = 10^n, where n = (-rscale) mod DEC_DIGITS.
11375 : : */
11376 : 22280 : n = ((rscale + DEC_DIGITS - 1) / DEC_DIGITS) * DEC_DIGITS - rscale;
11377 : 22280 : pow10 = 1;
11378 [ + + ]: 58600 : for (i = 0; i < n; i++)
11379 : 36320 : pow10 *= 10;
11380 : :
11381 : : /*
11382 : : * To choose a random value uniformly from the range [0, rlen], we choose
11383 : : * from the slightly larger range [0, rlen2], where rlen2 is formed from
11384 : : * rlen by copying the first 4 NBASE digits, and setting all remaining
11385 : : * decimal digits to "9".
11386 : : *
11387 : : * Without loss of generality, we can ignore the weight of rlen2 and treat
11388 : : * it as a pure integer for the purposes of this discussion. The process
11389 : : * above gives rlen2 + 1 = rlen64 * 10^N, for some integer N, where rlen64
11390 : : * is a 64-bit integer formed from the first 4 NBASE digits copied from
11391 : : * rlen. Since this trivially factors into smaller pieces that fit in
11392 : : * 64-bit integers, the task of choosing a random value uniformly from the
11393 : : * rlen2 + 1 possible values in [0, rlen2] is much simpler.
11394 : : *
11395 : : * If the random value selected is too large, it is rejected, and we try
11396 : : * again until we get a result <= rlen, ensuring that the overall result
11397 : : * is uniform (no particular value is any more likely than any other).
11398 : : *
11399 : : * Since rlen64 holds 4 NBASE digits from rlen, it contains at least
11400 : : * DEC_DIGITS * 3 + 1 decimal digits (i.e., at least 13 decimal digits,
11401 : : * when DEC_DIGITS is 4). Therefore the probability of needing to reject
11402 : : * the value chosen and retry is less than 1e-13.
11403 : : */
11404 : 22280 : rlen64 = (uint64) rlen.digits[0];
11405 : 22280 : rlen64_ndigits = 1;
11406 [ + + + + ]: 50808 : while (rlen64_ndigits < res_ndigits && rlen64_ndigits < 4)
11407 : : {
11408 : 28528 : rlen64 *= NBASE;
11409 [ + + ]: 28528 : if (rlen64_ndigits < rlen.ndigits)
11410 : 4408 : rlen64 += rlen.digits[rlen64_ndigits];
11411 : 28528 : rlen64_ndigits++;
11412 : : }
11413 : :
11414 : : /* Loop until we get a result <= rlen */
11415 : : do
11416 : : {
11417 : : NumericDigit *res_digits;
11418 : : uint64 rand;
11419 : : int whole_ndigits;
11420 : :
11421 : 22280 : alloc_var(result, res_ndigits);
11422 : 22280 : result->sign = NUMERIC_POS;
11423 : 22280 : result->weight = rlen.weight;
11424 : 22280 : result->dscale = rscale;
11425 : 22280 : res_digits = result->digits;
11426 : :
11427 : : /*
11428 : : * Set the first rlen64_ndigits using a random value in [0, rlen64].
11429 : : *
11430 : : * If this is the whole result, and rscale is not a multiple of
11431 : : * DEC_DIGITS (pow10 from above is not 1), then we need this to be a
11432 : : * multiple of pow10.
11433 : : */
11434 [ + + + + ]: 22280 : if (rlen64_ndigits == res_ndigits && pow10 != 1)
11435 : 14088 : rand = pg_prng_uint64_range(state, 0, rlen64 / pow10) * pow10;
11436 : : else
11437 : 8192 : rand = pg_prng_uint64_range(state, 0, rlen64);
11438 : :
11439 [ + + ]: 73088 : for (i = rlen64_ndigits - 1; i >= 0; i--)
11440 : : {
11441 : 50808 : res_digits[i] = (NumericDigit) (rand % NBASE);
11442 : 50808 : rand = rand / NBASE;
11443 : : }
11444 : :
11445 : : /*
11446 : : * Set the remaining digits to random values in range [0, NBASE),
11447 : : * noting that the last digit needs to be a multiple of pow10.
11448 : : */
11449 : 22280 : whole_ndigits = res_ndigits;
11450 [ + + ]: 22280 : if (pow10 != 1)
11451 : 22140 : whole_ndigits--;
11452 : :
11453 : : /* Set whole digits in groups of 4 for best performance */
11454 : 22280 : i = rlen64_ndigits;
11455 [ + + ]: 22320 : while (i < whole_ndigits - 3)
11456 : : {
11457 : 40 : rand = pg_prng_uint64_range(state, 0,
11458 : : (uint64) NBASE * NBASE * NBASE * NBASE - 1);
11459 : 40 : res_digits[i++] = (NumericDigit) (rand % NBASE);
11460 : 40 : rand = rand / NBASE;
11461 : 40 : res_digits[i++] = (NumericDigit) (rand % NBASE);
11462 : 40 : rand = rand / NBASE;
11463 : 40 : res_digits[i++] = (NumericDigit) (rand % NBASE);
11464 : 40 : rand = rand / NBASE;
11465 : 40 : res_digits[i++] = (NumericDigit) rand;
11466 : : }
11467 : :
11468 : : /* Remaining whole digits */
11469 [ + + ]: 22420 : while (i < whole_ndigits)
11470 : : {
11471 : 140 : rand = pg_prng_uint64_range(state, 0, NBASE - 1);
11472 : 140 : res_digits[i++] = (NumericDigit) rand;
11473 : : }
11474 : :
11475 : : /* Final partial digit (multiple of pow10) */
11476 [ + + ]: 22280 : if (i < res_ndigits)
11477 : : {
11478 : 8052 : rand = pg_prng_uint64_range(state, 0, NBASE / pow10 - 1) * pow10;
11479 : 8052 : res_digits[i] = (NumericDigit) rand;
11480 : : }
11481 : :
11482 : : /* Remove leading/trailing zeroes */
11483 : 22280 : strip_var(result);
11484 : :
11485 : : /* If result > rlen, try again */
11486 : :
11487 [ - + ]: 22280 : } while (cmp_var(result, &rlen) > 0);
11488 : :
11489 : : /* Offset the result to the required range */
11490 : 22280 : add_var(result, rmin, result);
11491 : :
11492 : 22280 : free_var(&rlen);
11493 : : }
11494 : :
11495 : :
11496 : : /* ----------------------------------------------------------------------
11497 : : *
11498 : : * Following are the lowest level functions that operate unsigned
11499 : : * on the variable level
11500 : : *
11501 : : * ----------------------------------------------------------------------
11502 : : */
11503 : :
11504 : :
11505 : : /* ----------
11506 : : * cmp_abs() -
11507 : : *
11508 : : * Compare the absolute values of var1 and var2
11509 : : * Returns: -1 for ABS(var1) < ABS(var2)
11510 : : * 0 for ABS(var1) == ABS(var2)
11511 : : * 1 for ABS(var1) > ABS(var2)
11512 : : * ----------
11513 : : */
11514 : : static int
3366 andres@anarazel.de 11515 : 473747 : cmp_abs(const NumericVar *var1, const NumericVar *var2)
11516 : : {
7599 bruce@momjian.us 11517 : 947494 : return cmp_abs_common(var1->digits, var1->ndigits, var1->weight,
11518 : 473747 : var2->digits, var2->ndigits, var2->weight);
11519 : : }
11520 : :
11521 : : /* ----------
11522 : : * cmp_abs_common() -
11523 : : *
11524 : : * Main routine of cmp_abs(). This function can be used by both
11525 : : * NumericVar and Numeric.
11526 : : * ----------
11527 : : */
11528 : : static int
11529 : 18768069 : cmp_abs_common(const NumericDigit *var1digits, int var1ndigits, int var1weight,
11530 : : const NumericDigit *var2digits, int var2ndigits, int var2weight)
11531 : : {
10049 11532 : 18768069 : int i1 = 0;
11533 : 18768069 : int i2 = 0;
11534 : :
11535 : : /* Check any digits before the first common digit */
11536 : :
7599 11537 [ + + + + ]: 18768069 : while (var1weight > var2weight && i1 < var1ndigits)
11538 : : {
8653 tgl@sss.pgh.pa.us 11539 [ + - ]: 15136 : if (var1digits[i1++] != 0)
10049 bruce@momjian.us 11540 : 15136 : return 1;
7599 bruce@momjian.us 11541 :UBC 0 : var1weight--;
11542 : : }
7599 bruce@momjian.us 11543 [ + + + + ]:CBC 18752933 : while (var2weight > var1weight && i2 < var2ndigits)
11544 : : {
8653 tgl@sss.pgh.pa.us 11545 [ + - ]: 101115 : if (var2digits[i2++] != 0)
10049 bruce@momjian.us 11546 : 101115 : return -1;
7599 bruce@momjian.us 11547 :UBC 0 : var2weight--;
11548 : : }
11549 : :
11550 : : /* At this point, either w1 == w2 or we've run out of digits */
11551 : :
7599 bruce@momjian.us 11552 [ + + ]:CBC 18651818 : if (var1weight == var2weight)
11553 : : {
11554 [ + + + + ]: 29662161 : while (i1 < var1ndigits && i2 < var2ndigits)
11555 : : {
8653 tgl@sss.pgh.pa.us 11556 : 19973720 : int stat = var1digits[i1++] - var2digits[i2++];
11557 : :
10190 JanWieck@Yahoo.com 11558 [ + + ]: 19973720 : if (stat)
11559 : : {
11560 [ + + ]: 8959129 : if (stat > 0)
11561 : 5285438 : return 1;
11562 : 3673691 : return -1;
11563 : : }
11564 : : }
11565 : : }
11566 : :
11567 : : /*
11568 : : * At this point, we've run out of digits on one side or the other; so any
11569 : : * remaining nonzero digits imply that side is larger
11570 : : */
7599 bruce@momjian.us 11571 [ + + ]: 9692794 : while (i1 < var1ndigits)
11572 : : {
8653 tgl@sss.pgh.pa.us 11573 [ + + ]: 6271 : if (var1digits[i1++] != 0)
10195 JanWieck@Yahoo.com 11574 : 6166 : return 1;
11575 : : }
7599 bruce@momjian.us 11576 [ + + ]: 9686775 : while (i2 < var2ndigits)
11577 : : {
8653 tgl@sss.pgh.pa.us 11578 [ + + ]: 910 : if (var2digits[i2++] != 0)
10195 JanWieck@Yahoo.com 11579 : 658 : return -1;
11580 : : }
11581 : :
11582 : 9685865 : return 0;
11583 : : }
11584 : :
11585 : :
11586 : : /*
11587 : : * add_abs() -
11588 : : *
11589 : : * Add the absolute values of two variables into result.
11590 : : * result might point to one of the operands without danger.
11591 : : */
11592 : : static void
3366 andres@anarazel.de 11593 : 299588 : add_abs(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
11594 : : {
11595 : : NumericDigit *res_buf;
11596 : : NumericDigit *res_digits;
11597 : : int res_ndigits;
11598 : : int res_weight;
11599 : : int res_rscale,
11600 : : rscale1,
11601 : : rscale2;
11602 : : int res_dscale;
11603 : : int i,
11604 : : i1,
11605 : : i2;
10049 bruce@momjian.us 11606 : 299588 : int carry = 0;
11607 : :
11608 : : /* copy these values into local vars for speed in inner loop */
9630 tgl@sss.pgh.pa.us 11609 : 299588 : int var1ndigits = var1->ndigits;
11610 : 299588 : int var2ndigits = var2->ndigits;
11611 : 299588 : NumericDigit *var1digits = var1->digits;
11612 : 299588 : NumericDigit *var2digits = var2->digits;
11613 : :
9049 bruce@momjian.us 11614 : 299588 : res_weight = Max(var1->weight, var2->weight) + 1;
11615 : :
11616 : 299588 : res_dscale = Max(var1->dscale, var2->dscale);
11617 : :
11618 : : /* Note: here we are figuring rscale in base-NBASE digits */
8653 tgl@sss.pgh.pa.us 11619 : 299588 : rscale1 = var1->ndigits - var1->weight - 1;
11620 : 299588 : rscale2 = var2->ndigits - var2->weight - 1;
11621 : 299588 : res_rscale = Max(rscale1, rscale2);
11622 : :
10195 JanWieck@Yahoo.com 11623 : 299588 : res_ndigits = res_rscale + res_weight + 1;
9811 tgl@sss.pgh.pa.us 11624 [ - + ]: 299588 : if (res_ndigits <= 0)
9811 tgl@sss.pgh.pa.us 11625 :UBC 0 : res_ndigits = 1;
11626 : :
8653 tgl@sss.pgh.pa.us 11627 :CBC 299588 : res_buf = digitbuf_alloc(res_ndigits + 1);
11628 : 299588 : res_buf[0] = 0; /* spare digit for later rounding */
11629 : 299588 : res_digits = res_buf + 1;
11630 : :
10195 JanWieck@Yahoo.com 11631 : 299588 : i1 = res_rscale + var1->weight + 1;
11632 : 299588 : i2 = res_rscale + var2->weight + 1;
11633 [ + + ]: 2774267 : for (i = res_ndigits - 1; i >= 0; i--)
11634 : : {
11635 : 2474679 : i1--;
11636 : 2474679 : i2--;
9630 tgl@sss.pgh.pa.us 11637 [ + + + + ]: 2474679 : if (i1 >= 0 && i1 < var1ndigits)
11638 : 1151003 : carry += var1digits[i1];
11639 [ + + + + ]: 2474679 : if (i2 >= 0 && i2 < var2ndigits)
11640 : 1074535 : carry += var2digits[i2];
11641 : :
8653 11642 [ + + ]: 2474679 : if (carry >= NBASE)
11643 : : {
11644 : 454296 : res_digits[i] = carry - NBASE;
9630 11645 : 454296 : carry = 1;
11646 : : }
11647 : : else
11648 : : {
11649 : 2020383 : res_digits[i] = carry;
11650 : 2020383 : carry = 0;
11651 : : }
11652 : : }
11653 : :
11654 [ - + ]: 299588 : Assert(carry == 0); /* else we failed to allow for carry out */
11655 : :
10195 JanWieck@Yahoo.com 11656 [ + + ]: 299588 : digitbuf_free(result->buf);
11657 : 299588 : result->ndigits = res_ndigits;
10049 bruce@momjian.us 11658 : 299588 : result->buf = res_buf;
11659 : 299588 : result->digits = res_digits;
11660 : 299588 : result->weight = res_weight;
11661 : 299588 : result->dscale = res_dscale;
11662 : :
11663 : : /* Remove leading/trailing zeroes */
8653 tgl@sss.pgh.pa.us 11664 : 299588 : strip_var(result);
10195 JanWieck@Yahoo.com 11665 : 299588 : }
11666 : :
11667 : :
11668 : : /*
11669 : : * sub_abs()
11670 : : *
11671 : : * Subtract the absolute value of var2 from the absolute value of var1
11672 : : * and store in result. result might point to one of the operands
11673 : : * without danger.
11674 : : *
11675 : : * ABS(var1) MUST BE GREATER OR EQUAL ABS(var2) !!!
11676 : : */
11677 : : static void
3366 andres@anarazel.de 11678 : 440590 : sub_abs(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
11679 : : {
11680 : : NumericDigit *res_buf;
11681 : : NumericDigit *res_digits;
11682 : : int res_ndigits;
11683 : : int res_weight;
11684 : : int res_rscale,
11685 : : rscale1,
11686 : : rscale2;
11687 : : int res_dscale;
11688 : : int i,
11689 : : i1,
11690 : : i2;
10049 bruce@momjian.us 11691 : 440590 : int borrow = 0;
11692 : :
11693 : : /* copy these values into local vars for speed in inner loop */
9630 tgl@sss.pgh.pa.us 11694 : 440590 : int var1ndigits = var1->ndigits;
11695 : 440590 : int var2ndigits = var2->ndigits;
11696 : 440590 : NumericDigit *var1digits = var1->digits;
11697 : 440590 : NumericDigit *var2digits = var2->digits;
11698 : :
10195 JanWieck@Yahoo.com 11699 : 440590 : res_weight = var1->weight;
11700 : :
9049 bruce@momjian.us 11701 : 440590 : res_dscale = Max(var1->dscale, var2->dscale);
11702 : :
11703 : : /* Note: here we are figuring rscale in base-NBASE digits */
8653 tgl@sss.pgh.pa.us 11704 : 440590 : rscale1 = var1->ndigits - var1->weight - 1;
11705 : 440590 : rscale2 = var2->ndigits - var2->weight - 1;
11706 : 440590 : res_rscale = Max(rscale1, rscale2);
11707 : :
10195 JanWieck@Yahoo.com 11708 : 440590 : res_ndigits = res_rscale + res_weight + 1;
9811 tgl@sss.pgh.pa.us 11709 [ - + ]: 440590 : if (res_ndigits <= 0)
9811 tgl@sss.pgh.pa.us 11710 :UBC 0 : res_ndigits = 1;
11711 : :
8653 tgl@sss.pgh.pa.us 11712 :CBC 440590 : res_buf = digitbuf_alloc(res_ndigits + 1);
11713 : 440590 : res_buf[0] = 0; /* spare digit for later rounding */
11714 : 440590 : res_digits = res_buf + 1;
11715 : :
10195 JanWieck@Yahoo.com 11716 : 440590 : i1 = res_rscale + var1->weight + 1;
11717 : 440590 : i2 = res_rscale + var2->weight + 1;
11718 [ + + ]: 3831063 : for (i = res_ndigits - 1; i >= 0; i--)
11719 : : {
11720 : 3390473 : i1--;
11721 : 3390473 : i2--;
9630 tgl@sss.pgh.pa.us 11722 [ + - + + ]: 3390473 : if (i1 >= 0 && i1 < var1ndigits)
11723 : 3077227 : borrow += var1digits[i1];
11724 [ + + + + ]: 3390473 : if (i2 >= 0 && i2 < var2ndigits)
11725 : 2707078 : borrow -= var2digits[i2];
11726 : :
10195 JanWieck@Yahoo.com 11727 [ + + ]: 3390473 : if (borrow < 0)
11728 : : {
8653 tgl@sss.pgh.pa.us 11729 : 337228 : res_digits[i] = borrow + NBASE;
10195 JanWieck@Yahoo.com 11730 : 337228 : borrow = -1;
11731 : : }
11732 : : else
11733 : : {
11734 : 3053245 : res_digits[i] = borrow;
11735 : 3053245 : borrow = 0;
11736 : : }
11737 : : }
11738 : :
9630 tgl@sss.pgh.pa.us 11739 [ - + ]: 440590 : Assert(borrow == 0); /* else caller gave us var1 < var2 */
11740 : :
10195 JanWieck@Yahoo.com 11741 [ + + ]: 440590 : digitbuf_free(result->buf);
11742 : 440590 : result->ndigits = res_ndigits;
10049 bruce@momjian.us 11743 : 440590 : result->buf = res_buf;
11744 : 440590 : result->digits = res_digits;
11745 : 440590 : result->weight = res_weight;
11746 : 440590 : result->dscale = res_dscale;
11747 : :
11748 : : /* Remove leading/trailing zeroes */
8653 tgl@sss.pgh.pa.us 11749 : 440590 : strip_var(result);
11750 : 440590 : }
11751 : :
11752 : : /*
11753 : : * round_var
11754 : : *
11755 : : * Round the value of a variable to no more than rscale decimal digits
11756 : : * after the decimal point. NOTE: we allow rscale < 0 here, implying
11757 : : * rounding before the decimal point.
11758 : : */
11759 : : static void
11760 : 170297 : round_var(NumericVar *var, int rscale)
11761 : : {
8517 bruce@momjian.us 11762 : 170297 : NumericDigit *digits = var->digits;
11763 : : int di;
11764 : : int ndigits;
11765 : : int carry;
11766 : :
8653 tgl@sss.pgh.pa.us 11767 : 170297 : var->dscale = rscale;
11768 : :
11769 : : /* decimal digits wanted */
11770 : 170297 : di = (var->weight + 1) * DEC_DIGITS + rscale;
11771 : :
11772 : : /*
11773 : : * If di = 0, the value loses all digits, but could round up to 1 if its
11774 : : * first extra digit is >= 5. If di < 0 the result must be 0.
11775 : : */
11776 [ + + ]: 170297 : if (di < 0)
11777 : : {
11778 : 71 : var->ndigits = 0;
11779 : 71 : var->weight = 0;
11780 : 71 : var->sign = NUMERIC_POS;
11781 : : }
11782 : : else
11783 : : {
11784 : : /* NBASE digits wanted */
8517 bruce@momjian.us 11785 : 170226 : ndigits = (di + DEC_DIGITS - 1) / DEC_DIGITS;
11786 : :
11787 : : /* 0, or number of decimal digits to keep in last NBASE digit */
8653 tgl@sss.pgh.pa.us 11788 : 170226 : di %= DEC_DIGITS;
11789 : :
11790 [ + + ]: 170226 : if (ndigits < var->ndigits ||
11791 [ + + + + ]: 32760 : (ndigits == var->ndigits && di > 0))
11792 : : {
11793 : 139943 : var->ndigits = ndigits;
11794 : :
11795 : : #if DEC_DIGITS == 1
11796 : : /* di must be zero */
11797 : : carry = (digits[ndigits] >= HALF_NBASE) ? 1 : 0;
11798 : : #else
11799 [ + + ]: 139943 : if (di == 0)
11800 : 109932 : carry = (digits[ndigits] >= HALF_NBASE) ? 1 : 0;
11801 : : else
11802 : : {
11803 : : /* Must round within last NBASE digit */
11804 : : int extra,
11805 : : pow10;
11806 : :
11807 : : #if DEC_DIGITS == 4
11808 : 30011 : pow10 = round_powers[di];
11809 : : #elif DEC_DIGITS == 2
11810 : : pow10 = 10;
11811 : : #else
11812 : : #error unsupported NBASE
11813 : : #endif
11814 : 30011 : extra = digits[--ndigits] % pow10;
11815 : 30011 : digits[ndigits] -= extra;
11816 : 30011 : carry = 0;
8517 bruce@momjian.us 11817 [ + + ]: 30011 : if (extra >= pow10 / 2)
11818 : : {
8653 tgl@sss.pgh.pa.us 11819 : 13999 : pow10 += digits[ndigits];
11820 [ + + ]: 13999 : if (pow10 >= NBASE)
11821 : : {
11822 : 611 : pow10 -= NBASE;
11823 : 611 : carry = 1;
11824 : : }
11825 : 13999 : digits[ndigits] = pow10;
11826 : : }
11827 : : }
11828 : : #endif
11829 : :
11830 : : /* Propagate carry if needed */
11831 [ + + ]: 166877 : while (carry)
11832 : : {
11833 : 26934 : carry += digits[--ndigits];
11834 [ + + ]: 26934 : if (carry >= NBASE)
11835 : : {
11836 : 20548 : digits[ndigits] = carry - NBASE;
11837 : 20548 : carry = 1;
11838 : : }
11839 : : else
11840 : : {
11841 : 6386 : digits[ndigits] = carry;
11842 : 6386 : carry = 0;
11843 : : }
11844 : : }
11845 : :
11846 [ + + ]: 139943 : if (ndigits < 0)
11847 : : {
11848 [ - + ]: 65 : Assert(ndigits == -1); /* better not have added > 1 digit */
11849 [ - + ]: 65 : Assert(var->digits > var->buf);
11850 : 65 : var->digits--;
11851 : 65 : var->ndigits++;
11852 : 65 : var->weight++;
11853 : : }
11854 : : }
11855 : : }
11856 : 170297 : }
11857 : :
11858 : : /*
11859 : : * trunc_var
11860 : : *
11861 : : * Truncate (towards zero) the value of a variable at rscale decimal digits
11862 : : * after the decimal point. NOTE: we allow rscale < 0 here, implying
11863 : : * truncation before the decimal point.
11864 : : */
11865 : : static void
11866 : 282549 : trunc_var(NumericVar *var, int rscale)
11867 : : {
11868 : : int di;
11869 : : int ndigits;
11870 : :
11871 : 282549 : var->dscale = rscale;
11872 : :
11873 : : /* decimal digits wanted */
11874 : 282549 : di = (var->weight + 1) * DEC_DIGITS + rscale;
11875 : :
11876 : : /*
11877 : : * If di <= 0, the value loses all digits.
11878 : : */
11879 [ + + ]: 282549 : if (di <= 0)
11880 : : {
11881 : 66 : var->ndigits = 0;
11882 : 66 : var->weight = 0;
11883 : 66 : var->sign = NUMERIC_POS;
11884 : : }
11885 : : else
11886 : : {
11887 : : /* NBASE digits wanted */
8517 bruce@momjian.us 11888 : 282483 : ndigits = (di + DEC_DIGITS - 1) / DEC_DIGITS;
11889 : :
8653 tgl@sss.pgh.pa.us 11890 [ + + ]: 282483 : if (ndigits <= var->ndigits)
11891 : : {
11892 : 282295 : var->ndigits = ndigits;
11893 : :
11894 : : #if DEC_DIGITS == 1
11895 : : /* no within-digit stuff to worry about */
11896 : : #else
11897 : : /* 0, or number of decimal digits to keep in last NBASE digit */
11898 : 282295 : di %= DEC_DIGITS;
11899 : :
11900 [ + + ]: 282295 : if (di > 0)
11901 : : {
11902 : : /* Must truncate within last NBASE digit */
8517 bruce@momjian.us 11903 : 63 : NumericDigit *digits = var->digits;
11904 : : int extra,
11905 : : pow10;
11906 : :
11907 : : #if DEC_DIGITS == 4
8653 tgl@sss.pgh.pa.us 11908 : 63 : pow10 = round_powers[di];
11909 : : #elif DEC_DIGITS == 2
11910 : : pow10 = 10;
11911 : : #else
11912 : : #error unsupported NBASE
11913 : : #endif
11914 : 63 : extra = digits[--ndigits] % pow10;
11915 : 63 : digits[ndigits] -= extra;
11916 : : }
11917 : : #endif
11918 : : }
11919 : : }
11920 : 282549 : }
11921 : :
11922 : : /*
11923 : : * strip_var
11924 : : *
11925 : : * Strip any leading and trailing zeroes from a numeric variable
11926 : : */
11927 : : static void
11928 : 2241980 : strip_var(NumericVar *var)
11929 : : {
8517 bruce@momjian.us 11930 : 2241980 : NumericDigit *digits = var->digits;
8653 tgl@sss.pgh.pa.us 11931 : 2241980 : int ndigits = var->ndigits;
11932 : :
11933 : : /* Strip leading zeroes */
11934 [ + + + + ]: 3821424 : while (ndigits > 0 && *digits == 0)
11935 : : {
11936 : 1579444 : digits++;
11937 : 1579444 : var->weight--;
11938 : 1579444 : ndigits--;
11939 : : }
11940 : :
11941 : : /* Strip trailing zeroes */
11942 [ + + + + ]: 2694260 : while (ndigits > 0 && digits[ndigits - 1] == 0)
11943 : 452280 : ndigits--;
11944 : :
11945 : : /* If it's zero, normalize the sign and weight */
11946 [ + + ]: 2241980 : if (ndigits == 0)
11947 : : {
11948 : 35546 : var->sign = NUMERIC_POS;
11949 : 35546 : var->weight = 0;
11950 : : }
11951 : :
11952 : 2241980 : var->digits = digits;
11953 : 2241980 : var->ndigits = ndigits;
10195 JanWieck@Yahoo.com 11954 : 2241980 : }
11955 : :
11956 : :
11957 : : /* ----------------------------------------------------------------------
11958 : : *
11959 : : * Fast sum accumulator functions
11960 : : *
11961 : : * ----------------------------------------------------------------------
11962 : : */
11963 : :
11964 : : /*
11965 : : * Reset the accumulator's value to zero. The buffers to hold the digits
11966 : : * are not free'd.
11967 : : */
11968 : : static void
3739 heikki.linnakangas@i 11969 : 12 : accum_sum_reset(NumericSumAccum *accum)
11970 : : {
11971 : : int i;
11972 : :
11973 : 12 : accum->dscale = 0;
11974 [ + + ]: 44 : for (i = 0; i < accum->ndigits; i++)
11975 : : {
11976 : 32 : accum->pos_digits[i] = 0;
11977 : 32 : accum->neg_digits[i] = 0;
11978 : : }
11979 : 12 : }
11980 : :
11981 : : /*
11982 : : * Accumulate a new value.
11983 : : */
11984 : : static void
3366 andres@anarazel.de 11985 : 1570448 : accum_sum_add(NumericSumAccum *accum, const NumericVar *val)
11986 : : {
11987 : : int32 *accum_digits;
11988 : : int val_ndigits;
11989 : : NumericDigit *val_digits;
11990 : :
11991 : : /*
11992 : : * If we have accumulated too many values since the last carry
11993 : : * propagation, do it now, to avoid overflowing. (We could allow more
11994 : : * than NBASE - 1, if we reserved two extra digits, rather than one, for
11995 : : * carry propagation. But even with NBASE - 1, this needs to be done so
11996 : : * seldom, that the performance difference is negligible.)
11997 : : */
3739 heikki.linnakangas@i 11998 [ + + ]: 1570448 : if (accum->num_uncarried == NBASE - 1)
11999 : 101 : accum_sum_carry(accum);
12000 : :
12001 : : /*
12002 : : * Adjust the weight or scale of the old value, so that it can accommodate
12003 : : * the new value.
12004 : : */
12005 : 1570448 : accum_sum_rescale(accum, val);
12006 : :
12007 : : /* */
12008 [ + + ]: 1570448 : if (val->sign == NUMERIC_POS)
12009 : 1169996 : accum_digits = accum->pos_digits;
12010 : : else
12011 : 400452 : accum_digits = accum->neg_digits;
12012 : :
12013 : : /* copy these values into local vars for speed in loop */
12014 : 1570448 : val_ndigits = val->ndigits;
12015 : 1570448 : val_digits = val->digits;
12016 : :
46 heikki.linnakangas@i 12017 :GNC 1570448 : accum_digits += accum->weight - val->weight;
12018 [ + + ]: 7926592 : for (int i = 0; i < val_ndigits; i++)
12019 : 6356144 : accum_digits[i] += (int32) val_digits[i];
12020 : :
3739 heikki.linnakangas@i 12021 :CBC 1570448 : accum->num_uncarried++;
12022 : 1570448 : }
12023 : :
12024 : : /*
12025 : : * Propagate carries.
12026 : : */
12027 : : static void
12028 : 115159 : accum_sum_carry(NumericSumAccum *accum)
12029 : : {
12030 : : int i;
12031 : : int ndigits;
12032 : : int32 *dig;
12033 : : int32 carry;
12034 : 115159 : int32 newdig = 0;
12035 : :
12036 : : /*
12037 : : * If no new values have been added since last carry propagation, nothing
12038 : : * to do.
12039 : : */
12040 [ + + ]: 115159 : if (accum->num_uncarried == 0)
12041 : 48 : return;
12042 : :
12043 : : /*
12044 : : * We maintain that the weight of the accumulator is always one larger
12045 : : * than needed to hold the current value, before carrying, to make sure
12046 : : * there is enough space for the possible extra digit when carry is
12047 : : * propagated. We cannot expand the buffer here, unless we require
12048 : : * callers of accum_sum_final() to switch to the right memory context.
12049 : : */
12050 [ + - - + ]: 115111 : Assert(accum->pos_digits[0] == 0 && accum->neg_digits[0] == 0);
12051 : :
12052 : 115111 : ndigits = accum->ndigits;
12053 : :
12054 : : /* Propagate carry in the positive sum */
12055 : 115111 : dig = accum->pos_digits;
12056 : 115111 : carry = 0;
12057 [ + + ]: 1736981 : for (i = ndigits - 1; i >= 0; i--)
12058 : : {
12059 : 1621870 : newdig = dig[i] + carry;
12060 [ + + ]: 1621870 : if (newdig >= NBASE)
12061 : : {
12062 : 73872 : carry = newdig / NBASE;
12063 : 73872 : newdig -= carry * NBASE;
12064 : : }
12065 : : else
12066 : 1547998 : carry = 0;
12067 : 1621870 : dig[i] = newdig;
12068 : : }
12069 : : /* Did we use up the digit reserved for carry propagation? */
12070 [ + + ]: 115111 : if (newdig > 0)
12071 : 1760 : accum->have_carry_space = false;
12072 : :
12073 : : /* And the same for the negative sum */
12074 : 115111 : dig = accum->neg_digits;
12075 : 115111 : carry = 0;
12076 [ + + ]: 1736981 : for (i = ndigits - 1; i >= 0; i--)
12077 : : {
12078 : 1621870 : newdig = dig[i] + carry;
12079 [ + + ]: 1621870 : if (newdig >= NBASE)
12080 : : {
12081 : 132 : carry = newdig / NBASE;
12082 : 132 : newdig -= carry * NBASE;
12083 : : }
12084 : : else
12085 : 1621738 : carry = 0;
12086 : 1621870 : dig[i] = newdig;
12087 : : }
12088 [ + + ]: 115111 : if (newdig > 0)
12089 : 20 : accum->have_carry_space = false;
12090 : :
12091 : 115111 : accum->num_uncarried = 0;
12092 : : }
12093 : :
12094 : : /*
12095 : : * Re-scale accumulator to accommodate new value.
12096 : : *
12097 : : * If the new value has more digits than the current digit buffers in the
12098 : : * accumulator, enlarge the buffers.
12099 : : */
12100 : : static void
3366 andres@anarazel.de 12101 : 1570448 : accum_sum_rescale(NumericSumAccum *accum, const NumericVar *val)
12102 : : {
3739 heikki.linnakangas@i 12103 : 1570448 : int old_weight = accum->weight;
12104 : 1570448 : int old_ndigits = accum->ndigits;
12105 : : int accum_ndigits;
12106 : : int accum_weight;
12107 : : int accum_rscale;
12108 : : int val_rscale;
12109 : :
12110 : 1570448 : accum_weight = old_weight;
12111 : 1570448 : accum_ndigits = old_ndigits;
12112 : :
12113 : : /*
12114 : : * Does the new value have a larger weight? If so, enlarge the buffers,
12115 : : * and shift the existing value to the new weight, by adding leading
12116 : : * zeros.
12117 : : *
12118 : : * We enforce that the accumulator always has a weight one larger than
12119 : : * needed for the inputs, so that we have space for an extra digit at the
12120 : : * final carry-propagation phase, if necessary.
12121 : : */
12122 [ + + ]: 1570448 : if (val->weight >= accum_weight)
12123 : : {
12124 : 174806 : accum_weight = val->weight + 1;
12125 : 174806 : accum_ndigits = accum_ndigits + (accum_weight - old_weight);
12126 : : }
12127 : :
12128 : : /*
12129 : : * Even though the new value is small, we might've used up the space
12130 : : * reserved for the carry digit in the last call to accum_sum_carry(). If
12131 : : * so, enlarge to make room for another one.
12132 : : */
12133 [ + + ]: 1395642 : else if (!accum->have_carry_space)
12134 : : {
12135 : 53 : accum_weight++;
12136 : 53 : accum_ndigits++;
12137 : : }
12138 : :
12139 : : /* Is the new value wider on the right side? */
12140 : 1570448 : accum_rscale = accum_ndigits - accum_weight - 1;
12141 : 1570448 : val_rscale = val->ndigits - val->weight - 1;
12142 [ + + ]: 1570448 : if (val_rscale > accum_rscale)
12143 : 114822 : accum_ndigits = accum_ndigits + (val_rscale - accum_rscale);
12144 : :
12145 [ + + - + ]: 1570448 : if (accum_ndigits != old_ndigits ||
12146 : : accum_weight != old_weight)
12147 : : {
12148 : : int32 *new_pos_digits;
12149 : : int32 *new_neg_digits;
12150 : : int weightdiff;
12151 : :
12152 : 175059 : weightdiff = accum_weight - old_weight;
12153 : :
103 michael@paquier.xyz 12154 :GNC 175059 : new_pos_digits = palloc0_array(int32, accum_ndigits);
12155 : 175059 : new_neg_digits = palloc0_array(int32, accum_ndigits);
12156 : :
3739 heikki.linnakangas@i 12157 [ + + ]:CBC 175059 : if (accum->pos_digits)
12158 : : {
12159 : 60285 : memcpy(&new_pos_digits[weightdiff], accum->pos_digits,
12160 : : old_ndigits * sizeof(int32));
12161 : 60285 : pfree(accum->pos_digits);
12162 : :
12163 : 60285 : memcpy(&new_neg_digits[weightdiff], accum->neg_digits,
12164 : : old_ndigits * sizeof(int32));
12165 : 60285 : pfree(accum->neg_digits);
12166 : : }
12167 : :
12168 : 175059 : accum->pos_digits = new_pos_digits;
12169 : 175059 : accum->neg_digits = new_neg_digits;
12170 : :
12171 : 175059 : accum->weight = accum_weight;
12172 : 175059 : accum->ndigits = accum_ndigits;
12173 : :
12174 [ + - - + ]: 175059 : Assert(accum->pos_digits[0] == 0 && accum->neg_digits[0] == 0);
12175 : 175059 : accum->have_carry_space = true;
12176 : : }
12177 : :
12178 [ + + ]: 1570448 : if (val->dscale > accum->dscale)
12179 : 200 : accum->dscale = val->dscale;
12180 : 1570448 : }
12181 : :
12182 : : /*
12183 : : * Return the current value of the accumulator. This perform final carry
12184 : : * propagation, and adds together the positive and negative sums.
12185 : : *
12186 : : * Unlike all the other routines, the caller is not required to switch to
12187 : : * the memory context that holds the accumulator.
12188 : : */
12189 : : static void
12190 : 115058 : accum_sum_final(NumericSumAccum *accum, NumericVar *result)
12191 : : {
12192 : : int i;
12193 : : NumericVar pos_var;
12194 : : NumericVar neg_var;
12195 : :
12196 [ - + ]: 115058 : if (accum->ndigits == 0)
12197 : : {
3739 heikki.linnakangas@i 12198 :UBC 0 : set_var_from_var(&const_zero, result);
12199 : 0 : return;
12200 : : }
12201 : :
12202 : : /* Perform final carry */
3739 heikki.linnakangas@i 12203 :CBC 115058 : accum_sum_carry(accum);
12204 : :
12205 : : /* Create NumericVars representing the positive and negative sums */
12206 : 115058 : init_var(&pos_var);
12207 : 115058 : init_var(&neg_var);
12208 : :
12209 : 115058 : pos_var.ndigits = neg_var.ndigits = accum->ndigits;
12210 : 115058 : pos_var.weight = neg_var.weight = accum->weight;
12211 : 115058 : pos_var.dscale = neg_var.dscale = accum->dscale;
12212 : 115058 : pos_var.sign = NUMERIC_POS;
12213 : 115058 : neg_var.sign = NUMERIC_NEG;
12214 : :
12215 : 115058 : pos_var.buf = pos_var.digits = digitbuf_alloc(accum->ndigits);
12216 : 115058 : neg_var.buf = neg_var.digits = digitbuf_alloc(accum->ndigits);
12217 : :
12218 [ + + ]: 1736703 : for (i = 0; i < accum->ndigits; i++)
12219 : : {
12220 [ - + ]: 1621645 : Assert(accum->pos_digits[i] < NBASE);
12221 : 1621645 : pos_var.digits[i] = (int16) accum->pos_digits[i];
12222 : :
12223 [ - + ]: 1621645 : Assert(accum->neg_digits[i] < NBASE);
12224 : 1621645 : neg_var.digits[i] = (int16) accum->neg_digits[i];
12225 : : }
12226 : :
12227 : : /* And add them together */
12228 : 115058 : add_var(&pos_var, &neg_var, result);
12229 : :
12230 : : /* Remove leading/trailing zeroes */
12231 : 115058 : strip_var(result);
12232 : : }
12233 : :
12234 : : /*
12235 : : * Copy an accumulator's state.
12236 : : *
12237 : : * 'dst' is assumed to be uninitialized beforehand. No attempt is made at
12238 : : * freeing old values.
12239 : : */
12240 : : static void
12241 : 28 : accum_sum_copy(NumericSumAccum *dst, NumericSumAccum *src)
12242 : : {
103 michael@paquier.xyz 12243 :GNC 28 : dst->pos_digits = palloc_array(int32, src->ndigits);
12244 : 28 : dst->neg_digits = palloc_array(int32, src->ndigits);
12245 : :
3739 heikki.linnakangas@i 12246 :CBC 28 : memcpy(dst->pos_digits, src->pos_digits, src->ndigits * sizeof(int32));
12247 : 28 : memcpy(dst->neg_digits, src->neg_digits, src->ndigits * sizeof(int32));
12248 : 28 : dst->num_uncarried = src->num_uncarried;
12249 : 28 : dst->ndigits = src->ndigits;
12250 : 28 : dst->weight = src->weight;
12251 : 28 : dst->dscale = src->dscale;
12252 : 28 : }
12253 : :
12254 : : /*
12255 : : * Add the current value of 'accum2' into 'accum'.
12256 : : */
12257 : : static void
12258 : 36 : accum_sum_combine(NumericSumAccum *accum, NumericSumAccum *accum2)
12259 : : {
12260 : : NumericVar tmp_var;
12261 : :
12262 : 36 : init_var(&tmp_var);
12263 : :
12264 : 36 : accum_sum_final(accum2, &tmp_var);
12265 : 36 : accum_sum_add(accum, &tmp_var);
12266 : :
12267 : 36 : free_var(&tmp_var);
12268 : 36 : }
|