LCOV - code coverage report
Current view: top level - src/backend/utils/adt - numeric.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 94.6 % 3992 3777
Test Date: 2026-07-12 05:15:34 Functions: 99.1 % 212 210
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 79.0 % 2453 1938

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * numeric.c
       4                 :             :  *    An exact numeric data type for the Postgres database system
       5                 :             :  *
       6                 :             :  * Original coding 1998, Jan Wieck.  Heavily revised 2003, Tom Lane.
       7                 :             :  *
       8                 :             :  * Many of the algorithmic ideas are borrowed from David M. Smith's "FM"
       9                 :             :  * multiple-precision math library, most recently published as Algorithm
      10                 :             :  * 786: Multiple-Precision Complex Arithmetic and Functions, ACM
      11                 :             :  * Transactions on Mathematical Software, Vol. 24, No. 4, December 1998,
      12                 :             :  * pages 359-367.
      13                 :             :  *
      14                 :             :  * Copyright (c) 1998-2026, PostgreSQL Global Development Group
      15                 :             :  *
      16                 :             :  * IDENTIFICATION
      17                 :             :  *    src/backend/utils/adt/numeric.c
      18                 :             :  *
      19                 :             :  *-------------------------------------------------------------------------
      20                 :             :  */
      21                 :             : 
      22                 :             : #include "postgres.h"
      23                 :             : 
      24                 :             : #include <ctype.h>
      25                 :             : #include <float.h>
      26                 :             : #include <limits.h>
      27                 :             : #include <math.h>
      28                 :             : 
      29                 :             : #include "common/hashfn.h"
      30                 :             : #include "common/int.h"
      31                 :             : #include "common/int128.h"
      32                 :             : #include "funcapi.h"
      33                 :             : #include "lib/hyperloglog.h"
      34                 :             : #include "libpq/pqformat.h"
      35                 :             : #include "miscadmin.h"
      36                 :             : #include "nodes/nodeFuncs.h"
      37                 :             : #include "nodes/supportnodes.h"
      38                 :             : #include "optimizer/optimizer.h"
      39                 :             : #include "utils/array.h"
      40                 :             : #include "utils/builtins.h"
      41                 :             : #include "utils/float.h"
      42                 :             : #include "utils/guc.h"
      43                 :             : #include "utils/numeric.h"
      44                 :             : #include "utils/pg_lsn.h"
      45                 :             : #include "utils/sortsupport.h"
      46                 :             : 
      47                 :             : /* ----------
      48                 :             :  * Uncomment the following to enable compilation of dump_numeric()
      49                 :             :  * and dump_var() and to get a dump of any result produced by make_result().
      50                 :             :  * ----------
      51                 :             :  */
      52                 :             : /* #define NUMERIC_DEBUG */
      53                 :             : 
      54                 :             : 
      55                 :             : /* ----------
      56                 :             :  * Local data types
      57                 :             :  *
      58                 :             :  * Numeric values are represented in a base-NBASE floating point format.
      59                 :             :  * Each "digit" ranges from 0 to NBASE-1.  The type NumericDigit is signed
      60                 :             :  * and wide enough to store a digit.  We assume that NBASE*NBASE can fit in
      61                 :             :  * an int.  Although the purely calculational routines could handle any even
      62                 :             :  * NBASE that's less than sqrt(INT_MAX), in practice we are only interested
      63                 :             :  * in NBASE a power of ten, so that I/O conversions and decimal rounding
      64                 :             :  * are easy.  Also, it's actually more efficient if NBASE is rather less than
      65                 :             :  * sqrt(INT_MAX), so that there is "headroom" for mul_var and div_var to
      66                 :             :  * postpone processing carries.
      67                 :             :  *
      68                 :             :  * Values of NBASE other than 10000 are considered of historical interest only
      69                 :             :  * and are no longer supported in any sense; no mechanism exists for the client
      70                 :             :  * to discover the base, so every client supporting binary mode expects the
      71                 :             :  * base-10000 format.  If you plan to change this, also note the numeric
      72                 :             :  * abbreviation code, which assumes NBASE=10000.
      73                 :             :  * ----------
      74                 :             :  */
      75                 :             : 
      76                 :             : #if 0
      77                 :             : #define NBASE       10
      78                 :             : #define HALF_NBASE  5
      79                 :             : #define DEC_DIGITS  1           /* decimal digits per NBASE digit */
      80                 :             : #define MUL_GUARD_DIGITS    4   /* these are measured in NBASE digits */
      81                 :             : #define DIV_GUARD_DIGITS    8
      82                 :             : 
      83                 :             : typedef signed char NumericDigit;
      84                 :             : #endif
      85                 :             : 
      86                 :             : #if 0
      87                 :             : #define NBASE       100
      88                 :             : #define HALF_NBASE  50
      89                 :             : #define DEC_DIGITS  2           /* decimal digits per NBASE digit */
      90                 :             : #define MUL_GUARD_DIGITS    3   /* these are measured in NBASE digits */
      91                 :             : #define DIV_GUARD_DIGITS    6
      92                 :             : 
      93                 :             : typedef signed char NumericDigit;
      94                 :             : #endif
      95                 :             : 
      96                 :             : #if 1
      97                 :             : #define NBASE       10000
      98                 :             : #define HALF_NBASE  5000
      99                 :             : #define DEC_DIGITS  4           /* decimal digits per NBASE digit */
     100                 :             : #define MUL_GUARD_DIGITS    2   /* these are measured in NBASE digits */
     101                 :             : #define DIV_GUARD_DIGITS    4
     102                 :             : 
     103                 :             : typedef int16 NumericDigit;
     104                 :             : #endif
     105                 :             : 
     106                 :             : #define NBASE_SQR   (NBASE * NBASE)
     107                 :             : 
     108                 :             : /*
     109                 :             :  * The Numeric type as stored on disk.
     110                 :             :  *
     111                 :             :  * If the high bits of the first word of a NumericChoice (n_header, or
     112                 :             :  * n_short.n_header, or n_long.n_sign_dscale) are NUMERIC_SHORT, then the
     113                 :             :  * numeric follows the NumericShort format; if they are NUMERIC_POS or
     114                 :             :  * NUMERIC_NEG, it follows the NumericLong format. If they are NUMERIC_SPECIAL,
     115                 :             :  * the value is a NaN or Infinity.  We currently always store SPECIAL values
     116                 :             :  * using just two bytes (i.e. only n_header), but previous releases used only
     117                 :             :  * the NumericLong format, so we might find 4-byte NaNs (though not infinities)
     118                 :             :  * on disk if a database has been migrated using pg_upgrade.  In either case,
     119                 :             :  * the low-order bits of a special value's header are reserved and currently
     120                 :             :  * should always be set to zero.
     121                 :             :  *
     122                 :             :  * In the NumericShort format, the remaining 14 bits of the header word
     123                 :             :  * (n_short.n_header) are allocated as follows: 1 for sign (positive or
     124                 :             :  * negative), 6 for dynamic scale, and 7 for weight.  In practice, most
     125                 :             :  * commonly-encountered values can be represented this way.
     126                 :             :  *
     127                 :             :  * In the NumericLong format, the remaining 14 bits of the header word
     128                 :             :  * (n_long.n_sign_dscale) represent the display scale; and the weight is
     129                 :             :  * stored separately in n_weight.
     130                 :             :  *
     131                 :             :  * NOTE: by convention, values in the packed form have been stripped of
     132                 :             :  * all leading and trailing zero digits (where a "digit" is of base NBASE).
     133                 :             :  * In particular, if the value is zero, there will be no digits at all!
     134                 :             :  * The weight is arbitrary in that case, but we normally set it to zero.
     135                 :             :  */
     136                 :             : 
     137                 :             : struct NumericShort
     138                 :             : {
     139                 :             :     uint16      n_header;       /* Sign + display scale + weight */
     140                 :             :     NumericDigit n_data[FLEXIBLE_ARRAY_MEMBER]; /* Digits */
     141                 :             : };
     142                 :             : 
     143                 :             : struct NumericLong
     144                 :             : {
     145                 :             :     uint16      n_sign_dscale;  /* Sign + display scale */
     146                 :             :     int16       n_weight;       /* Weight of 1st digit  */
     147                 :             :     NumericDigit n_data[FLEXIBLE_ARRAY_MEMBER]; /* Digits */
     148                 :             : };
     149                 :             : 
     150                 :             : union NumericChoice
     151                 :             : {
     152                 :             :     uint16      n_header;       /* Header word */
     153                 :             :     struct NumericLong n_long;  /* Long form (4-byte header) */
     154                 :             :     struct NumericShort n_short;    /* Short form (2-byte header) */
     155                 :             : };
     156                 :             : 
     157                 :             : struct NumericData
     158                 :             : {
     159                 :             :     int32       vl_len_;        /* varlena header (do not touch directly!) */
     160                 :             :     union NumericChoice choice; /* choice of format */
     161                 :             : };
     162                 :             : 
     163                 :             : 
     164                 :             : /*
     165                 :             :  * Interpretation of high bits.
     166                 :             :  */
     167                 :             : 
     168                 :             : #define NUMERIC_SIGN_MASK   0xC000
     169                 :             : #define NUMERIC_POS         0x0000
     170                 :             : #define NUMERIC_NEG         0x4000
     171                 :             : #define NUMERIC_SHORT       0x8000
     172                 :             : #define NUMERIC_SPECIAL     0xC000
     173                 :             : 
     174                 :             : #define NUMERIC_FLAGBITS(n) ((n)->choice.n_header & NUMERIC_SIGN_MASK)
     175                 :             : #define NUMERIC_IS_SHORT(n)     (NUMERIC_FLAGBITS(n) == NUMERIC_SHORT)
     176                 :             : #define NUMERIC_IS_SPECIAL(n)   (NUMERIC_FLAGBITS(n) == NUMERIC_SPECIAL)
     177                 :             : 
     178                 :             : #define NUMERIC_HDRSZ   (VARHDRSZ + sizeof(uint16) + sizeof(int16))
     179                 :             : #define NUMERIC_HDRSZ_SHORT (VARHDRSZ + sizeof(uint16))
     180                 :             : 
     181                 :             : /*
     182                 :             :  * If the flag bits are NUMERIC_SHORT or NUMERIC_SPECIAL, we want the short
     183                 :             :  * header; otherwise, we want the long one.  Instead of testing against each
     184                 :             :  * value, we can just look at the high bit, for a slight efficiency gain.
     185                 :             :  */
     186                 :             : #define NUMERIC_HEADER_IS_SHORT(n)  (((n)->choice.n_header & 0x8000) != 0)
     187                 :             : #define NUMERIC_HEADER_SIZE(n) \
     188                 :             :     (VARHDRSZ + sizeof(uint16) + \
     189                 :             :      (NUMERIC_HEADER_IS_SHORT(n) ? 0 : sizeof(int16)))
     190                 :             : 
     191                 :             : /*
     192                 :             :  * Definitions for special values (NaN, positive infinity, negative infinity).
     193                 :             :  *
     194                 :             :  * The two bits after the NUMERIC_SPECIAL bits are 00 for NaN, 01 for positive
     195                 :             :  * infinity, 11 for negative infinity.  (This makes the sign bit match where
     196                 :             :  * it is in a short-format value, though we make no use of that at present.)
     197                 :             :  * We could mask off the remaining bits before testing the active bits, but
     198                 :             :  * currently those bits must be zeroes, so masking would just add cycles.
     199                 :             :  */
     200                 :             : #define NUMERIC_EXT_SIGN_MASK   0xF000  /* high bits plus NaN/Inf flag bits */
     201                 :             : #define NUMERIC_NAN             0xC000
     202                 :             : #define NUMERIC_PINF            0xD000
     203                 :             : #define NUMERIC_NINF            0xF000
     204                 :             : #define NUMERIC_INF_SIGN_MASK   0x2000
     205                 :             : 
     206                 :             : #define NUMERIC_EXT_FLAGBITS(n) ((n)->choice.n_header & NUMERIC_EXT_SIGN_MASK)
     207                 :             : #define NUMERIC_IS_NAN(n)       ((n)->choice.n_header == NUMERIC_NAN)
     208                 :             : #define NUMERIC_IS_PINF(n)      ((n)->choice.n_header == NUMERIC_PINF)
     209                 :             : #define NUMERIC_IS_NINF(n)      ((n)->choice.n_header == NUMERIC_NINF)
     210                 :             : #define NUMERIC_IS_INF(n) \
     211                 :             :     (((n)->choice.n_header & ~NUMERIC_INF_SIGN_MASK) == NUMERIC_PINF)
     212                 :             : 
     213                 :             : /*
     214                 :             :  * Short format definitions.
     215                 :             :  */
     216                 :             : 
     217                 :             : #define NUMERIC_SHORT_SIGN_MASK         0x2000
     218                 :             : #define NUMERIC_SHORT_DSCALE_MASK       0x1F80
     219                 :             : #define NUMERIC_SHORT_DSCALE_SHIFT      7
     220                 :             : #define NUMERIC_SHORT_DSCALE_MAX        \
     221                 :             :     (NUMERIC_SHORT_DSCALE_MASK >> NUMERIC_SHORT_DSCALE_SHIFT)
     222                 :             : #define NUMERIC_SHORT_WEIGHT_SIGN_MASK  0x0040
     223                 :             : #define NUMERIC_SHORT_WEIGHT_MASK       0x003F
     224                 :             : #define NUMERIC_SHORT_WEIGHT_MAX        NUMERIC_SHORT_WEIGHT_MASK
     225                 :             : #define NUMERIC_SHORT_WEIGHT_MIN        (-(NUMERIC_SHORT_WEIGHT_MASK+1))
     226                 :             : 
     227                 :             : /*
     228                 :             :  * Extract sign, display scale, weight.  These macros extract field values
     229                 :             :  * suitable for the NumericVar format from the Numeric (on-disk) format.
     230                 :             :  *
     231                 :             :  * Note that we don't trouble to ensure that dscale and weight read as zero
     232                 :             :  * for an infinity; however, that doesn't matter since we never convert
     233                 :             :  * "special" numerics to NumericVar form.  Only the constants defined below
     234                 :             :  * (const_nan, etc) ever represent a non-finite value as a NumericVar.
     235                 :             :  */
     236                 :             : 
     237                 :             : #define NUMERIC_DSCALE_MASK         0x3FFF
     238                 :             : #define NUMERIC_DSCALE_MAX          NUMERIC_DSCALE_MASK
     239                 :             : 
     240                 :             : #define NUMERIC_SIGN(n) \
     241                 :             :     (NUMERIC_IS_SHORT(n) ? \
     242                 :             :         (((n)->choice.n_short.n_header & NUMERIC_SHORT_SIGN_MASK) ? \
     243                 :             :          NUMERIC_NEG : NUMERIC_POS) : \
     244                 :             :         (NUMERIC_IS_SPECIAL(n) ? \
     245                 :             :          NUMERIC_EXT_FLAGBITS(n) : NUMERIC_FLAGBITS(n)))
     246                 :             : #define NUMERIC_DSCALE(n)   (NUMERIC_HEADER_IS_SHORT((n)) ? \
     247                 :             :     ((n)->choice.n_short.n_header & NUMERIC_SHORT_DSCALE_MASK) \
     248                 :             :         >> NUMERIC_SHORT_DSCALE_SHIFT \
     249                 :             :     : ((n)->choice.n_long.n_sign_dscale & NUMERIC_DSCALE_MASK))
     250                 :             : #define NUMERIC_WEIGHT(n)   (NUMERIC_HEADER_IS_SHORT((n)) ? \
     251                 :             :     (((n)->choice.n_short.n_header & NUMERIC_SHORT_WEIGHT_SIGN_MASK ? \
     252                 :             :         ~NUMERIC_SHORT_WEIGHT_MASK : 0) \
     253                 :             :      | ((n)->choice.n_short.n_header & NUMERIC_SHORT_WEIGHT_MASK)) \
     254                 :             :     : ((n)->choice.n_long.n_weight))
     255                 :             : 
     256                 :             : /*
     257                 :             :  * Maximum weight of a stored Numeric value (based on the use of int16 for the
     258                 :             :  * weight in NumericLong).  Note that intermediate values held in NumericVar
     259                 :             :  * and NumericSumAccum variables may have much larger weights.
     260                 :             :  */
     261                 :             : #define NUMERIC_WEIGHT_MAX          PG_INT16_MAX
     262                 :             : 
     263                 :             : /* ----------
     264                 :             :  * NumericVar is the format we use for arithmetic.  The digit-array part
     265                 :             :  * is the same as the NumericData storage format, but the header is more
     266                 :             :  * complex.
     267                 :             :  *
     268                 :             :  * The value represented by a NumericVar is determined by the sign, weight,
     269                 :             :  * ndigits, and digits[] array.  If it is a "special" value (NaN or Inf)
     270                 :             :  * then only the sign field matters; ndigits should be zero, and the weight
     271                 :             :  * and dscale fields are ignored.
     272                 :             :  *
     273                 :             :  * Note: the first digit of a NumericVar's value is assumed to be multiplied
     274                 :             :  * by NBASE ** weight.  Another way to say it is that there are weight+1
     275                 :             :  * digits before the decimal point.  It is possible to have weight < 0.
     276                 :             :  *
     277                 :             :  * buf points at the physical start of the palloc'd digit buffer for the
     278                 :             :  * NumericVar.  digits points at the first digit in actual use (the one
     279                 :             :  * with the specified weight).  We normally leave an unused digit or two
     280                 :             :  * (preset to zeroes) between buf and digits, so that there is room to store
     281                 :             :  * a carry out of the top digit without reallocating space.  We just need to
     282                 :             :  * decrement digits (and increment weight) to make room for the carry digit.
     283                 :             :  * (There is no such extra space in a numeric value stored in the database,
     284                 :             :  * only in a NumericVar in memory.)
     285                 :             :  *
     286                 :             :  * If buf is NULL then the digit buffer isn't actually palloc'd and should
     287                 :             :  * not be freed --- see the constants below for an example.
     288                 :             :  *
     289                 :             :  * dscale, or display scale, is the nominal precision expressed as number
     290                 :             :  * of digits after the decimal point (it must always be >= 0 at present).
     291                 :             :  * dscale may be more than the number of physically stored fractional digits,
     292                 :             :  * implying that we have suppressed storage of significant trailing zeroes.
     293                 :             :  * It should never be less than the number of stored digits, since that would
     294                 :             :  * imply hiding digits that are present.  NOTE that dscale is always expressed
     295                 :             :  * in *decimal* digits, and so it may correspond to a fractional number of
     296                 :             :  * base-NBASE digits --- divide by DEC_DIGITS to convert to NBASE digits.
     297                 :             :  *
     298                 :             :  * rscale, or result scale, is the target precision for a computation.
     299                 :             :  * Like dscale it is expressed as number of *decimal* digits after the decimal
     300                 :             :  * point, and is always >= 0 at present.
     301                 :             :  * Note that rscale is not stored in variables --- it's figured on-the-fly
     302                 :             :  * from the dscales of the inputs.
     303                 :             :  *
     304                 :             :  * While we consistently use "weight" to refer to the base-NBASE weight of
     305                 :             :  * a numeric value, it is convenient in some scale-related calculations to
     306                 :             :  * make use of the base-10 weight (ie, the approximate log10 of the value).
     307                 :             :  * To avoid confusion, such a decimal-units weight is called a "dweight".
     308                 :             :  *
     309                 :             :  * NB: All the variable-level functions are written in a style that makes it
     310                 :             :  * possible to give one and the same variable as argument and destination.
     311                 :             :  * This is feasible because the digit buffer is separate from the variable.
     312                 :             :  * ----------
     313                 :             :  */
     314                 :             : typedef struct NumericVar
     315                 :             : {
     316                 :             :     int         ndigits;        /* # of digits in digits[] - can be 0! */
     317                 :             :     int         weight;         /* weight of first digit */
     318                 :             :     int         sign;           /* NUMERIC_POS, _NEG, _NAN, _PINF, or _NINF */
     319                 :             :     int         dscale;         /* display scale */
     320                 :             :     NumericDigit *buf;          /* start of palloc'd space for digits[] */
     321                 :             :     NumericDigit *digits;       /* base-NBASE digits */
     322                 :             : } NumericVar;
     323                 :             : 
     324                 :             : 
     325                 :             : /* ----------
     326                 :             :  * Data for generate_series
     327                 :             :  * ----------
     328                 :             :  */
     329                 :             : typedef struct
     330                 :             : {
     331                 :             :     NumericVar  current;
     332                 :             :     NumericVar  stop;
     333                 :             :     NumericVar  step;
     334                 :             : } generate_series_numeric_fctx;
     335                 :             : 
     336                 :             : 
     337                 :             : /* ----------
     338                 :             :  * Sort support.
     339                 :             :  * ----------
     340                 :             :  */
     341                 :             : typedef struct
     342                 :             : {
     343                 :             :     void       *buf;            /* buffer for short varlenas */
     344                 :             :     int64       input_count;    /* number of non-null values seen */
     345                 :             :     bool        estimating;     /* true if estimating cardinality */
     346                 :             : 
     347                 :             :     hyperLogLogState abbr_card; /* cardinality estimator */
     348                 :             : } NumericSortSupport;
     349                 :             : 
     350                 :             : 
     351                 :             : /* ----------
     352                 :             :  * Fast sum accumulator.
     353                 :             :  *
     354                 :             :  * NumericSumAccum is used to implement SUM(), and other standard aggregates
     355                 :             :  * that track the sum of input values.  It uses 32-bit integers to store the
     356                 :             :  * digits, instead of the normal 16-bit integers (with NBASE=10000).  This
     357                 :             :  * way, we can safely accumulate up to NBASE - 1 values without propagating
     358                 :             :  * carry, before risking overflow of any of the digits.  'num_uncarried'
     359                 :             :  * tracks how many values have been accumulated without propagating carry.
     360                 :             :  *
     361                 :             :  * Positive and negative values are accumulated separately, in 'pos_digits'
     362                 :             :  * and 'neg_digits'.  This is simpler and faster than deciding whether to add
     363                 :             :  * or subtract from the current value, for each new value (see sub_var() for
     364                 :             :  * the logic we avoid by doing this).  Both buffers are of same size, and
     365                 :             :  * have the same weight and scale.  In accum_sum_final(), the positive and
     366                 :             :  * negative sums are added together to produce the final result.
     367                 :             :  *
     368                 :             :  * When a new value has a larger ndigits or weight than the accumulator
     369                 :             :  * currently does, the accumulator is enlarged to accommodate the new value.
     370                 :             :  * We normally have one zero digit reserved for carry propagation, and that
     371                 :             :  * is indicated by the 'have_carry_space' flag.  When accum_sum_carry() uses
     372                 :             :  * up the reserved digit, it clears the 'have_carry_space' flag.  The next
     373                 :             :  * call to accum_sum_add() will enlarge the buffer, to make room for the
     374                 :             :  * extra digit, and set the flag again.
     375                 :             :  *
     376                 :             :  * To initialize a new accumulator, simply reset all fields to zeros.
     377                 :             :  *
     378                 :             :  * The accumulator does not handle NaNs.
     379                 :             :  * ----------
     380                 :             :  */
     381                 :             : typedef struct NumericSumAccum
     382                 :             : {
     383                 :             :     int         ndigits;
     384                 :             :     int         weight;
     385                 :             :     int         dscale;
     386                 :             :     int         num_uncarried;
     387                 :             :     bool        have_carry_space;
     388                 :             :     int32      *pos_digits;
     389                 :             :     int32      *neg_digits;
     390                 :             : } NumericSumAccum;
     391                 :             : 
     392                 :             : 
     393                 :             : /*
     394                 :             :  * We define our own macros for packing and unpacking abbreviated-key
     395                 :             :  * representations, just to have a notational indication that that's
     396                 :             :  * what we're doing.  Now that sizeof(Datum) is always 8, we can rely
     397                 :             :  * on fitting an int64 into Datum.
     398                 :             :  *
     399                 :             :  * The range of abbreviations for finite values is from +PG_INT64_MAX
     400                 :             :  * to -PG_INT64_MAX.  NaN has the abbreviation PG_INT64_MIN, and we
     401                 :             :  * define the sort ordering to make that work out properly (see further
     402                 :             :  * comments below).  PINF and NINF share the abbreviations of the largest
     403                 :             :  * and smallest finite abbreviation classes.
     404                 :             :  */
     405                 :             : #define NumericAbbrevGetDatum(X) Int64GetDatum(X)
     406                 :             : #define DatumGetNumericAbbrev(X) DatumGetInt64(X)
     407                 :             : #define NUMERIC_ABBREV_NAN       NumericAbbrevGetDatum(PG_INT64_MIN)
     408                 :             : #define NUMERIC_ABBREV_PINF      NumericAbbrevGetDatum(-PG_INT64_MAX)
     409                 :             : #define NUMERIC_ABBREV_NINF      NumericAbbrevGetDatum(PG_INT64_MAX)
     410                 :             : 
     411                 :             : 
     412                 :             : /* ----------
     413                 :             :  * Some preinitialized constants
     414                 :             :  * ----------
     415                 :             :  */
     416                 :             : static const NumericDigit const_zero_data[1] = {0};
     417                 :             : static const NumericVar const_zero =
     418                 :             : {0, 0, NUMERIC_POS, 0, NULL, (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, (NumericDigit *) const_one_data};
     423                 :             : 
     424                 :             : static const NumericVar const_minus_one =
     425                 :             : {1, 0, NUMERIC_NEG, 0, NULL, (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, (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, (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, (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                 :             :     ((NumericDigit *) palloc((ndigits) * sizeof(NumericDigit)))
     480                 :             : #define digitbuf_free(buf)  \
     481                 :             :     do { \
     482                 :             :          if ((buf) != NULL) \
     483                 :             :              pfree(buf); \
     484                 :             :     } while (0)
     485                 :             : 
     486                 :             : #define init_var(v)     memset(v, 0, sizeof(NumericVar))
     487                 :             : 
     488                 :             : #define NUMERIC_DIGITS(num) (NUMERIC_HEADER_IS_SHORT(num) ? \
     489                 :             :     (num)->choice.n_short.n_data : (num)->choice.n_long.n_data)
     490                 :             : #define NUMERIC_NDIGITS(num) \
     491                 :             :     ((VARSIZE(num) - NUMERIC_HEADER_SIZE(num)) / sizeof(NumericDigit))
     492                 :             : #define NUMERIC_CAN_BE_SHORT(scale,weight) \
     493                 :             :     ((scale) <= NUMERIC_SHORT_DSCALE_MAX && \
     494                 :             :     (weight) <= NUMERIC_SHORT_WEIGHT_MAX && \
     495                 :             :     (weight) >= NUMERIC_SHORT_WEIGHT_MIN)
     496                 :             : 
     497                 :             : static void alloc_var(NumericVar *var, int ndigits);
     498                 :             : static void free_var(NumericVar *var);
     499                 :             : static void zero_var(NumericVar *var);
     500                 :             : 
     501                 :             : static bool set_var_from_str(const char *str, const char *cp,
     502                 :             :                              NumericVar *dest, const char **endptr,
     503                 :             :                              Node *escontext);
     504                 :             : static bool set_var_from_non_decimal_integer_str(const char *str,
     505                 :             :                                                  const char *cp, int sign,
     506                 :             :                                                  int base, NumericVar *dest,
     507                 :             :                                                  const char **endptr,
     508                 :             :                                                  Node *escontext);
     509                 :             : static void set_var_from_num(Numeric num, NumericVar *dest);
     510                 :             : static void init_var_from_num(Numeric num, NumericVar *dest);
     511                 :             : static void set_var_from_var(const NumericVar *value, NumericVar *dest);
     512                 :             : static char *get_str_from_var(const NumericVar *var);
     513                 :             : static char *get_str_from_var_sci(const NumericVar *var, int rscale);
     514                 :             : 
     515                 :             : static void numericvar_serialize(StringInfo buf, const NumericVar *var);
     516                 :             : static void numericvar_deserialize(StringInfo buf, NumericVar *var);
     517                 :             : 
     518                 :             : static Numeric duplicate_numeric(Numeric num);
     519                 :             : static Numeric make_result(const NumericVar *var);
     520                 :             : static Numeric make_result_safe(const NumericVar *var, Node *escontext);
     521                 :             : 
     522                 :             : static bool apply_typmod(NumericVar *var, int32 typmod, Node *escontext);
     523                 :             : static bool apply_typmod_special(Numeric num, int32 typmod, Node *escontext);
     524                 :             : 
     525                 :             : static bool numericvar_to_int32(const NumericVar *var, int32 *result);
     526                 :             : static bool numericvar_to_int64(const NumericVar *var, int64 *result);
     527                 :             : static void int64_to_numericvar(int64 val, NumericVar *var);
     528                 :             : static bool numericvar_to_uint64(const NumericVar *var, uint64 *result);
     529                 :             : static void int128_to_numericvar(INT128 val, NumericVar *var);
     530                 :             : static double numericvar_to_double_no_overflow(const NumericVar *var);
     531                 :             : 
     532                 :             : static Datum numeric_abbrev_convert(Datum original_datum, SortSupport ssup);
     533                 :             : static bool numeric_abbrev_abort(int memtupcount, SortSupport ssup);
     534                 :             : static int  numeric_fast_cmp(Datum x, Datum y, SortSupport ssup);
     535                 :             : static int  numeric_cmp_abbrev(Datum x, Datum y, SortSupport ssup);
     536                 :             : 
     537                 :             : static Datum numeric_abbrev_convert_var(const NumericVar *var,
     538                 :             :                                         NumericSortSupport *nss);
     539                 :             : 
     540                 :             : static int  cmp_numerics(Numeric num1, Numeric num2);
     541                 :             : static int  cmp_var(const NumericVar *var1, const NumericVar *var2);
     542                 :             : static int  cmp_var_common(const NumericDigit *var1digits, int var1ndigits,
     543                 :             :                            int var1weight, int var1sign,
     544                 :             :                            const NumericDigit *var2digits, int var2ndigits,
     545                 :             :                            int var2weight, int var2sign);
     546                 :             : static void add_var(const NumericVar *var1, const NumericVar *var2,
     547                 :             :                     NumericVar *result);
     548                 :             : static void sub_var(const NumericVar *var1, const NumericVar *var2,
     549                 :             :                     NumericVar *result);
     550                 :             : static void mul_var(const NumericVar *var1, const NumericVar *var2,
     551                 :             :                     NumericVar *result,
     552                 :             :                     int rscale);
     553                 :             : static void mul_var_short(const NumericVar *var1, const NumericVar *var2,
     554                 :             :                           NumericVar *result);
     555                 :             : static void div_var(const NumericVar *var1, const NumericVar *var2,
     556                 :             :                     NumericVar *result, int rscale, bool round, bool exact);
     557                 :             : static void div_var_int(const NumericVar *var, int ival, int ival_weight,
     558                 :             :                         NumericVar *result, int rscale, bool round);
     559                 :             : #ifdef HAVE_INT128
     560                 :             : static void div_var_int64(const NumericVar *var, int64 ival, int ival_weight,
     561                 :             :                           NumericVar *result, int rscale, bool round);
     562                 :             : #endif
     563                 :             : static int  select_div_scale(const NumericVar *var1, const NumericVar *var2);
     564                 :             : static void mod_var(const NumericVar *var1, const NumericVar *var2,
     565                 :             :                     NumericVar *result);
     566                 :             : static void div_mod_var(const NumericVar *var1, const NumericVar *var2,
     567                 :             :                         NumericVar *quot, NumericVar *rem);
     568                 :             : static void ceil_var(const NumericVar *var, NumericVar *result);
     569                 :             : static void floor_var(const NumericVar *var, NumericVar *result);
     570                 :             : 
     571                 :             : static void gcd_var(const NumericVar *var1, const NumericVar *var2,
     572                 :             :                     NumericVar *result);
     573                 :             : static void sqrt_var(const NumericVar *arg, NumericVar *result, int rscale);
     574                 :             : static void exp_var(const NumericVar *arg, NumericVar *result, int rscale);
     575                 :             : static int  estimate_ln_dweight(const NumericVar *var);
     576                 :             : static void ln_var(const NumericVar *arg, NumericVar *result, int rscale);
     577                 :             : static void log_var(const NumericVar *base, const NumericVar *num,
     578                 :             :                     NumericVar *result);
     579                 :             : static void power_var(const NumericVar *base, const NumericVar *exp,
     580                 :             :                       NumericVar *result);
     581                 :             : static void power_var_int(const NumericVar *base, int exp, int exp_dscale,
     582                 :             :                           NumericVar *result);
     583                 :             : static void power_ten_int(int exp, NumericVar *result);
     584                 :             : static void random_var(pg_prng_state *state, const NumericVar *rmin,
     585                 :             :                        const NumericVar *rmax, NumericVar *result);
     586                 :             : 
     587                 :             : static int  cmp_abs(const NumericVar *var1, const NumericVar *var2);
     588                 :             : static int  cmp_abs_common(const NumericDigit *var1digits, int var1ndigits,
     589                 :             :                            int var1weight,
     590                 :             :                            const NumericDigit *var2digits, int var2ndigits,
     591                 :             :                            int var2weight);
     592                 :             : static void add_abs(const NumericVar *var1, const NumericVar *var2,
     593                 :             :                     NumericVar *result);
     594                 :             : static void sub_abs(const NumericVar *var1, const NumericVar *var2,
     595                 :             :                     NumericVar *result);
     596                 :             : static void round_var(NumericVar *var, int rscale);
     597                 :             : static void trunc_var(NumericVar *var, int rscale);
     598                 :             : static void strip_var(NumericVar *var);
     599                 :             : static void compute_bucket(Numeric operand, Numeric bound1, Numeric bound2,
     600                 :             :                            const NumericVar *count_var,
     601                 :             :                            NumericVar *result_var);
     602                 :             : 
     603                 :             : static void accum_sum_add(NumericSumAccum *accum, const NumericVar *val);
     604                 :             : static void accum_sum_rescale(NumericSumAccum *accum, const NumericVar *val);
     605                 :             : static void accum_sum_carry(NumericSumAccum *accum);
     606                 :             : static void accum_sum_reset(NumericSumAccum *accum);
     607                 :             : static void accum_sum_final(NumericSumAccum *accum, NumericVar *result);
     608                 :             : static void accum_sum_copy(NumericSumAccum *dst, NumericSumAccum *src);
     609                 :             : static void accum_sum_combine(NumericSumAccum *accum, NumericSumAccum *accum2);
     610                 :             : 
     611                 :             : 
     612                 :             : /* ----------------------------------------------------------------------
     613                 :             :  *
     614                 :             :  * Input-, output- and rounding-functions
     615                 :             :  *
     616                 :             :  * ----------------------------------------------------------------------
     617                 :             :  */
     618                 :             : 
     619                 :             : 
     620                 :             : /*
     621                 :             :  * numeric_in() -
     622                 :             :  *
     623                 :             :  *  Input function for numeric data type
     624                 :             :  */
     625                 :             : Datum
     626                 :      105001 : numeric_in(PG_FUNCTION_ARGS)
     627                 :             : {
     628                 :      105001 :     char       *str = PG_GETARG_CSTRING(0);
     629                 :             : #ifdef NOT_USED
     630                 :             :     Oid         typelem = PG_GETARG_OID(1);
     631                 :             : #endif
     632                 :      105001 :     int32       typmod = PG_GETARG_INT32(2);
     633                 :      105001 :     Node       *escontext = fcinfo->context;
     634                 :             :     Numeric     res;
     635                 :             :     const char *cp;
     636                 :             :     const char *numstart;
     637                 :             :     int         sign;
     638                 :             : 
     639                 :             :     /* Skip leading spaces */
     640                 :      105001 :     cp = str;
     641         [ +  + ]:      121281 :     while (*cp)
     642                 :             :     {
     643         [ +  + ]:      121269 :         if (!isspace((unsigned char) *cp))
     644                 :      104989 :             break;
     645                 :       16280 :         cp++;
     646                 :             :     }
     647                 :             : 
     648                 :             :     /*
     649                 :             :      * Process the number's sign. This duplicates logic in set_var_from_str(),
     650                 :             :      * but it's worth doing here, since it simplifies the handling of
     651                 :             :      * infinities and non-decimal integers.
     652                 :             :      */
     653                 :      105001 :     numstart = cp;
     654                 :      105001 :     sign = NUMERIC_POS;
     655                 :             : 
     656         [ +  + ]:      105001 :     if (*cp == '+')
     657                 :          32 :         cp++;
     658         [ +  + ]:      104969 :     else if (*cp == '-')
     659                 :             :     {
     660                 :        2522 :         sign = NUMERIC_NEG;
     661                 :        2522 :         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   [ +  +  +  + ]:      105001 :     if (!isdigit((unsigned char) *cp) && *cp != '.')
     672                 :             :     {
     673                 :             :         /*
     674                 :             :          * The number must be NaN or infinity; anything else can only be a
     675                 :             :          * syntax error. Note that NaN mustn't have a sign.
     676                 :             :          */
     677         [ +  + ]:        1201 :         if (pg_strncasecmp(numstart, "NaN", 3) == 0)
     678                 :             :         {
     679                 :         397 :             res = make_result(&const_nan);
     680                 :         397 :             cp = numstart + 3;
     681                 :             :         }
     682         [ +  + ]:         804 :         else if (pg_strncasecmp(cp, "Infinity", 8) == 0)
     683                 :             :         {
     684         [ +  + ]:         339 :             res = make_result(sign == NUMERIC_POS ? &const_pinf : &const_ninf);
     685                 :         339 :             cp += 8;
     686                 :             :         }
     687         [ +  + ]:         465 :         else if (pg_strncasecmp(cp, "inf", 3) == 0)
     688                 :             :         {
     689         [ +  + ]:         392 :             res = make_result(sign == NUMERIC_POS ? &const_pinf : &const_ninf);
     690                 :         392 :             cp += 3;
     691                 :             :         }
     692                 :             :         else
     693                 :          73 :             goto invalid_syntax;
     694                 :             : 
     695                 :             :         /*
     696                 :             :          * Check for trailing junk; there should be nothing left but spaces.
     697                 :             :          *
     698                 :             :          * We intentionally do this check before applying the typmod because
     699                 :             :          * we would like to throw any trailing-junk syntax error before any
     700                 :             :          * semantic error resulting from apply_typmod_special().
     701                 :             :          */
     702         [ +  + ]:        1156 :         while (*cp)
     703                 :             :         {
     704         [ -  + ]:          28 :             if (!isspace((unsigned char) *cp))
     705                 :           0 :                 goto invalid_syntax;
     706                 :          28 :             cp++;
     707                 :             :         }
     708                 :             : 
     709         [ -  + ]:        1128 :         if (!apply_typmod_special(res, typmod, escontext))
     710                 :           0 :             PG_RETURN_NULL();
     711                 :             :     }
     712                 :             :     else
     713                 :             :     {
     714                 :             :         /*
     715                 :             :          * We have a normal numeric value, which may be a non-decimal integer
     716                 :             :          * or a regular decimal number.
     717                 :             :          */
     718                 :             :         NumericVar  value;
     719                 :             :         int         base;
     720                 :             : 
     721                 :      103800 :         init_var(&value);
     722                 :             : 
     723                 :             :         /*
     724                 :             :          * Determine the number's base by looking for a non-decimal prefix
     725                 :             :          * indicator ("0x", "0o", or "0b").
     726                 :             :          */
     727         [ +  + ]:      103800 :         if (cp[0] == '0')
     728                 :             :         {
     729   [ +  +  +  + ]:       33929 :             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                 :       33825 :                 default:
     744                 :       33825 :                     base = 10;
     745                 :             :             }
     746                 :             :         }
     747                 :             :         else
     748                 :       69871 :             base = 10;
     749                 :             : 
     750                 :             :         /* Parse the rest of the number and apply the sign */
     751         [ +  + ]:      103800 :         if (base == 10)
     752                 :             :         {
     753         [ -  + ]:      103696 :             if (!set_var_from_str(str, cp, &value, &cp, escontext))
     754                 :          16 :                 PG_RETURN_NULL();
     755                 :      103664 :             value.sign = sign;
     756                 :             :         }
     757                 :             :         else
     758                 :             :         {
     759         [ -  + ]:         104 :             if (!set_var_from_non_decimal_integer_str(str, cp + 2, sign, base,
     760                 :             :                                                       &value, &cp, escontext))
     761                 :           0 :                 PG_RETURN_NULL();
     762                 :             :         }
     763                 :             : 
     764                 :             :         /*
     765                 :             :          * Should be nothing left but spaces. As above, throw any typmod error
     766                 :             :          * after finishing syntax check.
     767                 :             :          */
     768         [ +  + ]:      103808 :         while (*cp)
     769                 :             :         {
     770         [ +  + ]:         100 :             if (!isspace((unsigned char) *cp))
     771                 :          48 :                 goto invalid_syntax;
     772                 :          52 :             cp++;
     773                 :             :         }
     774                 :             : 
     775         [ +  + ]:      103708 :         if (!apply_typmod(&value, typmod, escontext))
     776                 :          16 :             PG_RETURN_NULL();
     777                 :             : 
     778                 :      103692 :         res = make_result_safe(&value, escontext);
     779                 :             : 
     780                 :      103692 :         free_var(&value);
     781                 :             :     }
     782                 :             : 
     783                 :      104820 :     PG_RETURN_NUMERIC(res);
     784                 :             : 
     785                 :         121 : invalid_syntax:
     786         [ +  + ]:         121 :     ereturn(escontext, (Datum) 0,
     787                 :             :             (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     788                 :             :              errmsg("invalid input syntax for type %s: \"%s\"",
     789                 :             :                     "numeric", str)));
     790                 :             : }
     791                 :             : 
     792                 :             : 
     793                 :             : /*
     794                 :             :  * numeric_out() -
     795                 :             :  *
     796                 :             :  *  Output function for numeric data type
     797                 :             :  */
     798                 :             : Datum
     799                 :      536778 : numeric_out(PG_FUNCTION_ARGS)
     800                 :             : {
     801                 :      536778 :     Numeric     num = PG_GETARG_NUMERIC(0);
     802                 :             :     NumericVar  x;
     803                 :             :     char       *str;
     804                 :             : 
     805                 :             :     /*
     806                 :             :      * Handle NaN and infinities
     807                 :             :      */
     808         [ +  + ]:      536778 :     if (NUMERIC_IS_SPECIAL(num))
     809                 :             :     {
     810         [ +  + ]:        2344 :         if (NUMERIC_IS_PINF(num))
     811                 :         688 :             PG_RETURN_CSTRING(pstrdup("Infinity"));
     812         [ +  + ]:        1656 :         else if (NUMERIC_IS_NINF(num))
     813                 :         436 :             PG_RETURN_CSTRING(pstrdup("-Infinity"));
     814                 :             :         else
     815                 :        1220 :             PG_RETURN_CSTRING(pstrdup("NaN"));
     816                 :             :     }
     817                 :             : 
     818                 :             :     /*
     819                 :             :      * Get the number in the variable format.
     820                 :             :      */
     821                 :      534434 :     init_var_from_num(num, &x);
     822                 :             : 
     823                 :      534434 :     str = get_str_from_var(&x);
     824                 :             : 
     825                 :      534434 :     PG_RETURN_CSTRING(str);
     826                 :             : }
     827                 :             : 
     828                 :             : /*
     829                 :             :  * numeric_is_nan() -
     830                 :             :  *
     831                 :             :  *  Is Numeric value a NaN?
     832                 :             :  */
     833                 :             : bool
     834                 :        4540 : numeric_is_nan(Numeric num)
     835                 :             : {
     836                 :        4540 :     return NUMERIC_IS_NAN(num);
     837                 :             : }
     838                 :             : 
     839                 :             : /*
     840                 :             :  * numeric_is_inf() -
     841                 :             :  *
     842                 :             :  *  Is Numeric value an infinity?
     843                 :             :  */
     844                 :             : bool
     845                 :         894 : numeric_is_inf(Numeric num)
     846                 :             : {
     847                 :         894 :     return NUMERIC_IS_INF(num);
     848                 :             : }
     849                 :             : 
     850                 :             : /*
     851                 :             :  * numeric_is_integral() -
     852                 :             :  *
     853                 :             :  *  Is Numeric value integral?
     854                 :             :  */
     855                 :             : static bool
     856                 :          54 : numeric_is_integral(Numeric num)
     857                 :             : {
     858                 :             :     NumericVar  arg;
     859                 :             : 
     860                 :             :     /* Reject NaN, but infinities are considered integral */
     861         [ +  + ]:          54 :     if (NUMERIC_IS_SPECIAL(num))
     862                 :             :     {
     863         [ -  + ]:          25 :         if (NUMERIC_IS_NAN(num))
     864                 :           0 :             return false;
     865                 :          25 :         return true;
     866                 :             :     }
     867                 :             : 
     868                 :             :     /* Integral if there are no digits to the right of the decimal point */
     869                 :          29 :     init_var_from_num(num, &arg);
     870                 :             : 
     871   [ +  +  +  + ]:          29 :     return (arg.ndigits == 0 || arg.ndigits <= arg.weight + 1);
     872                 :             : }
     873                 :             : 
     874                 :             : /*
     875                 :             :  * make_numeric_typmod() -
     876                 :             :  *
     877                 :             :  *  Pack numeric precision and scale values into a typmod.  The upper 16 bits
     878                 :             :  *  are used for the precision (though actually not all these bits are needed,
     879                 :             :  *  since the maximum allowed precision is 1000).  The lower 16 bits are for
     880                 :             :  *  the scale, but since the scale is constrained to the range [-1000, 1000],
     881                 :             :  *  we use just the lower 11 of those 16 bits, and leave the remaining 5 bits
     882                 :             :  *  unset, for possible future use.
     883                 :             :  *
     884                 :             :  *  For purely historical reasons VARHDRSZ is then added to the result, thus
     885                 :             :  *  the unused space in the upper 16 bits is not all as freely available as it
     886                 :             :  *  might seem.  (We can't let the result overflow to a negative int32, as
     887                 :             :  *  other parts of the system would interpret that as not-a-valid-typmod.)
     888                 :             :  */
     889                 :             : static inline int32
     890                 :        1087 : make_numeric_typmod(int precision, int scale)
     891                 :             : {
     892                 :        1087 :     return ((precision << 16) | (scale & 0x7ff)) + VARHDRSZ;
     893                 :             : }
     894                 :             : 
     895                 :             : /*
     896                 :             :  * Because of the offset, valid numeric typmods are at least VARHDRSZ
     897                 :             :  */
     898                 :             : static inline bool
     899                 :      120999 : is_valid_numeric_typmod(int32 typmod)
     900                 :             : {
     901                 :      120999 :     return typmod >= (int32) VARHDRSZ;
     902                 :             : }
     903                 :             : 
     904                 :             : /*
     905                 :             :  * numeric_typmod_precision() -
     906                 :             :  *
     907                 :             :  *  Extract the precision from a numeric typmod --- see make_numeric_typmod().
     908                 :             :  */
     909                 :             : static inline int
     910                 :       32937 : numeric_typmod_precision(int32 typmod)
     911                 :             : {
     912                 :       32937 :     return ((typmod - VARHDRSZ) >> 16) & 0xffff;
     913                 :             : }
     914                 :             : 
     915                 :             : /*
     916                 :             :  * numeric_typmod_scale() -
     917                 :             :  *
     918                 :             :  *  Extract the scale from a numeric typmod --- see make_numeric_typmod().
     919                 :             :  *
     920                 :             :  *  Note that the scale may be negative, so we must do sign extension when
     921                 :             :  *  unpacking it.  We do this using the bit hack (x^1024)-1024, which sign
     922                 :             :  *  extends an 11-bit two's complement number x.
     923                 :             :  */
     924                 :             : static inline int
     925                 :       28022 : numeric_typmod_scale(int32 typmod)
     926                 :             : {
     927                 :       28022 :     return (((typmod - VARHDRSZ) & 0x7ff) ^ 1024) - 1024;
     928                 :             : }
     929                 :             : 
     930                 :             : /*
     931                 :             :  * numeric_maximum_size() -
     932                 :             :  *
     933                 :             :  *  Maximum size of a numeric with given typmod, or -1 if unlimited/unknown.
     934                 :             :  */
     935                 :             : int32
     936                 :        4915 : numeric_maximum_size(int32 typmod)
     937                 :             : {
     938                 :             :     int         precision;
     939                 :             :     int         numeric_digits;
     940                 :             : 
     941         [ -  + ]:        4915 :     if (!is_valid_numeric_typmod(typmod))
     942                 :           0 :         return -1;
     943                 :             : 
     944                 :             :     /* precision (ie, max # of digits) is in upper bits of typmod */
     945                 :        4915 :     precision = numeric_typmod_precision(typmod);
     946                 :             : 
     947                 :             :     /*
     948                 :             :      * This formula computes the maximum number of NumericDigits we could need
     949                 :             :      * in order to store the specified number of decimal digits. Because the
     950                 :             :      * weight is stored as a number of NumericDigits rather than a number of
     951                 :             :      * decimal digits, it's possible that the first NumericDigit will contain
     952                 :             :      * only a single decimal digit.  Thus, the first two decimal digits can
     953                 :             :      * require two NumericDigits to store, but it isn't until we reach
     954                 :             :      * DEC_DIGITS + 2 decimal digits that we potentially need a third
     955                 :             :      * NumericDigit.
     956                 :             :      */
     957                 :        4915 :     numeric_digits = (precision + 2 * (DEC_DIGITS - 1)) / DEC_DIGITS;
     958                 :             : 
     959                 :             :     /*
     960                 :             :      * In most cases, the size of a numeric will be smaller than the value
     961                 :             :      * computed below, because the varlena header will typically get toasted
     962                 :             :      * down to a single byte before being stored on disk, and it may also be
     963                 :             :      * possible to use a short numeric header.  But our job here is to compute
     964                 :             :      * the worst case.
     965                 :             :      */
     966                 :        4915 :     return NUMERIC_HDRSZ + (numeric_digits * sizeof(NumericDigit));
     967                 :             : }
     968                 :             : 
     969                 :             : /*
     970                 :             :  * numeric_out_sci() -
     971                 :             :  *
     972                 :             :  *  Output function for numeric data type in scientific notation.
     973                 :             :  */
     974                 :             : char *
     975                 :         164 : numeric_out_sci(Numeric num, int scale)
     976                 :             : {
     977                 :             :     NumericVar  x;
     978                 :             :     char       *str;
     979                 :             : 
     980                 :             :     /*
     981                 :             :      * Handle NaN and infinities
     982                 :             :      */
     983         [ +  + ]:         164 :     if (NUMERIC_IS_SPECIAL(num))
     984                 :             :     {
     985         [ +  + ]:          12 :         if (NUMERIC_IS_PINF(num))
     986                 :           4 :             return pstrdup("Infinity");
     987         [ +  + ]:           8 :         else if (NUMERIC_IS_NINF(num))
     988                 :           4 :             return pstrdup("-Infinity");
     989                 :             :         else
     990                 :           4 :             return pstrdup("NaN");
     991                 :             :     }
     992                 :             : 
     993                 :         152 :     init_var_from_num(num, &x);
     994                 :             : 
     995                 :         152 :     str = get_str_from_var_sci(&x, scale);
     996                 :             : 
     997                 :         152 :     return str;
     998                 :             : }
     999                 :             : 
    1000                 :             : /*
    1001                 :             :  * numeric_normalize() -
    1002                 :             :  *
    1003                 :             :  *  Output function for numeric data type, suppressing insignificant trailing
    1004                 :             :  *  zeroes and then any trailing decimal point.  The intent of this is to
    1005                 :             :  *  produce strings that are equal if and only if the input numeric values
    1006                 :             :  *  compare equal.
    1007                 :             :  */
    1008                 :             : char *
    1009                 :       46516 : numeric_normalize(Numeric num)
    1010                 :             : {
    1011                 :             :     NumericVar  x;
    1012                 :             :     char       *str;
    1013                 :             :     int         last;
    1014                 :             : 
    1015                 :             :     /*
    1016                 :             :      * Handle NaN and infinities
    1017                 :             :      */
    1018         [ -  + ]:       46516 :     if (NUMERIC_IS_SPECIAL(num))
    1019                 :             :     {
    1020         [ #  # ]:           0 :         if (NUMERIC_IS_PINF(num))
    1021                 :           0 :             return pstrdup("Infinity");
    1022         [ #  # ]:           0 :         else if (NUMERIC_IS_NINF(num))
    1023                 :           0 :             return pstrdup("-Infinity");
    1024                 :             :         else
    1025                 :           0 :             return pstrdup("NaN");
    1026                 :             :     }
    1027                 :             : 
    1028                 :       46516 :     init_var_from_num(num, &x);
    1029                 :             : 
    1030                 :       46516 :     str = get_str_from_var(&x);
    1031                 :             : 
    1032                 :             :     /* If there's no decimal point, there's certainly nothing to remove. */
    1033         [ +  + ]:       46516 :     if (strchr(str, '.') != NULL)
    1034                 :             :     {
    1035                 :             :         /*
    1036                 :             :          * Back up over trailing fractional zeroes.  Since there is a decimal
    1037                 :             :          * point, this loop will terminate safely.
    1038                 :             :          */
    1039                 :          31 :         last = strlen(str) - 1;
    1040         [ +  + ]:          62 :         while (str[last] == '0')
    1041                 :          31 :             last--;
    1042                 :             : 
    1043                 :             :         /* We want to get rid of the decimal point too, if it's now last. */
    1044         [ +  - ]:          31 :         if (str[last] == '.')
    1045                 :          31 :             last--;
    1046                 :             : 
    1047                 :             :         /* Delete whatever we backed up over. */
    1048                 :          31 :         str[last + 1] = '\0';
    1049                 :             :     }
    1050                 :             : 
    1051                 :       46516 :     return str;
    1052                 :             : }
    1053                 :             : 
    1054                 :             : /*
    1055                 :             :  *      numeric_recv            - converts external binary format to numeric
    1056                 :             :  *
    1057                 :             :  * External format is a sequence of int16's:
    1058                 :             :  * ndigits, weight, sign, dscale, NumericDigits.
    1059                 :             :  */
    1060                 :             : Datum
    1061                 :          51 : numeric_recv(PG_FUNCTION_ARGS)
    1062                 :             : {
    1063                 :          51 :     StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
    1064                 :             : 
    1065                 :             : #ifdef NOT_USED
    1066                 :             :     Oid         typelem = PG_GETARG_OID(1);
    1067                 :             : #endif
    1068                 :          51 :     int32       typmod = PG_GETARG_INT32(2);
    1069                 :             :     NumericVar  value;
    1070                 :             :     Numeric     res;
    1071                 :             :     int         len,
    1072                 :             :                 i;
    1073                 :             : 
    1074                 :          51 :     init_var(&value);
    1075                 :             : 
    1076                 :          51 :     len = (uint16) pq_getmsgint(buf, sizeof(uint16));
    1077                 :             : 
    1078                 :          51 :     alloc_var(&value, len);
    1079                 :             : 
    1080                 :          51 :     value.weight = (int16) pq_getmsgint(buf, sizeof(int16));
    1081                 :             :     /* we allow any int16 for weight --- OK? */
    1082                 :             : 
    1083                 :          51 :     value.sign = (uint16) pq_getmsgint(buf, sizeof(uint16));
    1084         [ -  + ]:          51 :     if (!(value.sign == NUMERIC_POS ||
    1085         [ #  # ]:           0 :           value.sign == NUMERIC_NEG ||
    1086         [ #  # ]:           0 :           value.sign == NUMERIC_NAN ||
    1087         [ #  # ]:           0 :           value.sign == NUMERIC_PINF ||
    1088         [ #  # ]:           0 :           value.sign == NUMERIC_NINF))
    1089         [ #  # ]:           0 :         ereport(ERROR,
    1090                 :             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
    1091                 :             :                  errmsg("invalid sign in external \"numeric\" value")));
    1092                 :             : 
    1093                 :          51 :     value.dscale = (uint16) pq_getmsgint(buf, sizeof(uint16));
    1094         [ -  + ]:          51 :     if ((value.dscale & NUMERIC_DSCALE_MASK) != value.dscale)
    1095         [ #  # ]:           0 :         ereport(ERROR,
    1096                 :             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
    1097                 :             :                  errmsg("invalid scale in external \"numeric\" value")));
    1098                 :             : 
    1099         [ +  + ]:         137 :     for (i = 0; i < len; i++)
    1100                 :             :     {
    1101                 :          86 :         NumericDigit d = pq_getmsgint(buf, sizeof(NumericDigit));
    1102                 :             : 
    1103   [ +  -  -  + ]:          86 :         if (d < 0 || d >= NBASE)
    1104         [ #  # ]:           0 :             ereport(ERROR,
    1105                 :             :                     (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
    1106                 :             :                      errmsg("invalid digit in external \"numeric\" value")));
    1107                 :          86 :         value.digits[i] = d;
    1108                 :             :     }
    1109                 :             : 
    1110                 :             :     /*
    1111                 :             :      * If the given dscale would hide any digits, truncate those digits away.
    1112                 :             :      * We could alternatively throw an error, but that would take a bunch of
    1113                 :             :      * extra code (about as much as trunc_var involves), and it might cause
    1114                 :             :      * client compatibility issues.  Be careful not to apply trunc_var to
    1115                 :             :      * special values, as it could do the wrong thing; we don't need it
    1116                 :             :      * anyway, since make_result will ignore all but the sign field.
    1117                 :             :      *
    1118                 :             :      * After doing that, be sure to check the typmod restriction.
    1119                 :             :      */
    1120         [ -  + ]:          51 :     if (value.sign == NUMERIC_POS ||
    1121         [ #  # ]:           0 :         value.sign == NUMERIC_NEG)
    1122                 :             :     {
    1123                 :          51 :         trunc_var(&value, value.dscale);
    1124                 :             : 
    1125                 :          51 :         (void) apply_typmod(&value, typmod, NULL);
    1126                 :             : 
    1127                 :          51 :         res = make_result(&value);
    1128                 :             :     }
    1129                 :             :     else
    1130                 :             :     {
    1131                 :             :         /* apply_typmod_special wants us to make the Numeric first */
    1132                 :           0 :         res = make_result(&value);
    1133                 :             : 
    1134                 :           0 :         (void) apply_typmod_special(res, typmod, NULL);
    1135                 :             :     }
    1136                 :             : 
    1137                 :          51 :     free_var(&value);
    1138                 :             : 
    1139                 :          51 :     PG_RETURN_NUMERIC(res);
    1140                 :             : }
    1141                 :             : 
    1142                 :             : /*
    1143                 :             :  *      numeric_send            - converts numeric to binary format
    1144                 :             :  */
    1145                 :             : Datum
    1146                 :          35 : numeric_send(PG_FUNCTION_ARGS)
    1147                 :             : {
    1148                 :          35 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1149                 :             :     NumericVar  x;
    1150                 :             :     StringInfoData buf;
    1151                 :             :     int         i;
    1152                 :             : 
    1153                 :          35 :     init_var_from_num(num, &x);
    1154                 :             : 
    1155                 :          35 :     pq_begintypsend(&buf);
    1156                 :             : 
    1157                 :          35 :     pq_sendint16(&buf, x.ndigits);
    1158                 :          35 :     pq_sendint16(&buf, x.weight);
    1159                 :          35 :     pq_sendint16(&buf, x.sign);
    1160                 :          35 :     pq_sendint16(&buf, x.dscale);
    1161         [ +  + ]:          97 :     for (i = 0; i < x.ndigits; i++)
    1162                 :          62 :         pq_sendint16(&buf, x.digits[i]);
    1163                 :             : 
    1164                 :          35 :     PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
    1165                 :             : }
    1166                 :             : 
    1167                 :             : 
    1168                 :             : /*
    1169                 :             :  * numeric_support()
    1170                 :             :  *
    1171                 :             :  * Planner support function for the numeric() length coercion function.
    1172                 :             :  *
    1173                 :             :  * Flatten calls that solely represent increases in allowable precision.
    1174                 :             :  * Scale changes mutate every datum, so they are unoptimizable.  Some values,
    1175                 :             :  * e.g. 1E-1001, can only fit into an unconstrained numeric, so a change from
    1176                 :             :  * an unconstrained numeric to any constrained numeric is also unoptimizable.
    1177                 :             :  */
    1178                 :             : Datum
    1179                 :         427 : numeric_support(PG_FUNCTION_ARGS)
    1180                 :             : {
    1181                 :         427 :     Node       *rawreq = (Node *) PG_GETARG_POINTER(0);
    1182                 :         427 :     Node       *ret = NULL;
    1183                 :             : 
    1184         [ +  + ]:         427 :     if (IsA(rawreq, SupportRequestSimplify))
    1185                 :             :     {
    1186                 :         187 :         SupportRequestSimplify *req = (SupportRequestSimplify *) rawreq;
    1187                 :         187 :         FuncExpr   *expr = req->fcall;
    1188                 :             :         Node       *typmod;
    1189                 :             : 
    1190                 :             :         Assert(list_length(expr->args) >= 2);
    1191                 :             : 
    1192                 :         187 :         typmod = (Node *) lsecond(expr->args);
    1193                 :             : 
    1194   [ +  -  +  - ]:         187 :         if (IsA(typmod, Const) && !((Const *) typmod)->constisnull)
    1195                 :             :         {
    1196                 :         187 :             Node       *source = (Node *) linitial(expr->args);
    1197                 :         187 :             int32       old_typmod = exprTypmod(source);
    1198                 :         187 :             int32       new_typmod = DatumGetInt32(((Const *) typmod)->constvalue);
    1199                 :         187 :             int32       old_scale = numeric_typmod_scale(old_typmod);
    1200                 :         187 :             int32       new_scale = numeric_typmod_scale(new_typmod);
    1201                 :         187 :             int32       old_precision = numeric_typmod_precision(old_typmod);
    1202                 :         187 :             int32       new_precision = numeric_typmod_precision(new_typmod);
    1203                 :             : 
    1204                 :             :             /*
    1205                 :             :              * If new_typmod is invalid, the destination is unconstrained;
    1206                 :             :              * that's always OK.  If old_typmod is valid, the source is
    1207                 :             :              * constrained, and we're OK if the scale is unchanged and the
    1208                 :             :              * precision is not decreasing.  See further notes in function
    1209                 :             :              * header comment.
    1210                 :             :              */
    1211   [ +  -  +  + ]:         374 :             if (!is_valid_numeric_typmod(new_typmod) ||
    1212         [ +  + ]:         196 :                 (is_valid_numeric_typmod(old_typmod) &&
    1213         [ +  - ]:           4 :                  new_scale == old_scale && new_precision >= old_precision))
    1214                 :           4 :                 ret = relabel_to_typmod(source, new_typmod);
    1215                 :             :         }
    1216                 :             :     }
    1217                 :             : 
    1218                 :         427 :     PG_RETURN_POINTER(ret);
    1219                 :             : }
    1220                 :             : 
    1221                 :             : /*
    1222                 :             :  * numeric() -
    1223                 :             :  *
    1224                 :             :  *  This is a special function called by the Postgres database system
    1225                 :             :  *  before a value is stored in a tuple's attribute. The precision and
    1226                 :             :  *  scale of the attribute have to be applied on the value.
    1227                 :             :  */
    1228                 :             : Datum
    1229                 :        8091 : numeric     (PG_FUNCTION_ARGS)
    1230                 :             : {
    1231                 :        8091 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1232                 :        8091 :     int32       typmod = PG_GETARG_INT32(1);
    1233                 :             :     Numeric     new;
    1234                 :             :     int         precision;
    1235                 :             :     int         scale;
    1236                 :             :     int         ddigits;
    1237                 :             :     int         maxdigits;
    1238                 :             :     int         dscale;
    1239                 :             :     NumericVar  var;
    1240                 :             : 
    1241                 :             :     /*
    1242                 :             :      * Handle NaN and infinities: if apply_typmod_special doesn't complain,
    1243                 :             :      * just return a copy of the input.
    1244                 :             :      */
    1245         [ +  + ]:        8091 :     if (NUMERIC_IS_SPECIAL(num))
    1246                 :             :     {
    1247         [ -  + ]:         172 :         if (!apply_typmod_special(num, typmod, fcinfo->context))
    1248                 :           0 :             PG_RETURN_NULL();
    1249                 :         160 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    1250                 :             :     }
    1251                 :             : 
    1252                 :             :     /*
    1253                 :             :      * If the value isn't a valid type modifier, simply return a copy of the
    1254                 :             :      * input value
    1255                 :             :      */
    1256         [ -  + ]:        7919 :     if (!is_valid_numeric_typmod(typmod))
    1257                 :           0 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    1258                 :             : 
    1259                 :             :     /*
    1260                 :             :      * Get the precision and scale out of the typmod value
    1261                 :             :      */
    1262                 :        7919 :     precision = numeric_typmod_precision(typmod);
    1263                 :        7919 :     scale = numeric_typmod_scale(typmod);
    1264                 :        7919 :     maxdigits = precision - scale;
    1265                 :             : 
    1266                 :             :     /* The target display scale is non-negative */
    1267                 :        7919 :     dscale = Max(scale, 0);
    1268                 :             : 
    1269                 :             :     /*
    1270                 :             :      * If the number is certainly in bounds and due to the target scale no
    1271                 :             :      * rounding could be necessary, just make a copy of the input and modify
    1272                 :             :      * its scale fields, unless the larger scale forces us to abandon the
    1273                 :             :      * short representation.  (Note we assume the existing dscale is
    1274                 :             :      * honest...)
    1275                 :             :      */
    1276   [ +  +  +  + ]:        7919 :     ddigits = (NUMERIC_WEIGHT(num) + 1) * DEC_DIGITS;
    1277   [ +  +  +  +  :        7919 :     if (ddigits <= maxdigits && scale >= NUMERIC_DSCALE(num)
                   +  + ]
    1278   [ +  -  +  -  :        4839 :         && (NUMERIC_CAN_BE_SHORT(dscale, NUMERIC_WEIGHT(num))
          +  +  +  -  -  
          -  +  -  +  +  
             -  +  -  - ]
    1279         [ #  # ]:           0 :             || !NUMERIC_IS_SHORT(num)))
    1280                 :             :     {
    1281                 :        4839 :         new = duplicate_numeric(num);
    1282         [ +  - ]:        4839 :         if (NUMERIC_IS_SHORT(num))
    1283                 :        4839 :             new->choice.n_short.n_header =
    1284                 :        4839 :                 (num->choice.n_short.n_header & ~NUMERIC_SHORT_DSCALE_MASK)
    1285                 :        4839 :                 | (dscale << NUMERIC_SHORT_DSCALE_SHIFT);
    1286                 :             :         else
    1287   [ #  #  #  # ]:           0 :             new->choice.n_long.n_sign_dscale = NUMERIC_SIGN(new) |
    1288                 :           0 :                 ((uint16) dscale & NUMERIC_DSCALE_MASK);
    1289                 :        4839 :         PG_RETURN_NUMERIC(new);
    1290                 :             :     }
    1291                 :             : 
    1292                 :             :     /*
    1293                 :             :      * We really need to fiddle with things - unpack the number into a
    1294                 :             :      * variable and let apply_typmod() do it.
    1295                 :             :      */
    1296                 :        3080 :     init_var(&var);
    1297                 :             : 
    1298                 :        3080 :     set_var_from_num(num, &var);
    1299         [ -  + ]:        3080 :     if (!apply_typmod(&var, typmod, fcinfo->context))
    1300                 :           0 :         PG_RETURN_NULL();
    1301                 :        3032 :     new = make_result_safe(&var, fcinfo->context);
    1302                 :             : 
    1303                 :        3032 :     free_var(&var);
    1304                 :             : 
    1305                 :        3032 :     PG_RETURN_NUMERIC(new);
    1306                 :             : }
    1307                 :             : 
    1308                 :             : /*
    1309                 :             :  * make_numeric_typmod_safe() -
    1310                 :             :  *
    1311                 :             :  *  Validate a numeric precision/scale and pack them into a typmod value,
    1312                 :             :  *  with soft error handling.
    1313                 :             :  */
    1314                 :             : int32
    1315                 :        1132 : make_numeric_typmod_safe(int32 precision, int32 scale, Node *escontext)
    1316                 :             : {
    1317   [ +  +  +  + ]:        1132 :     if (precision < 1 || precision > NUMERIC_MAX_PRECISION)
    1318         [ +  + ]:          29 :         ereturn(escontext, -1,
    1319                 :             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1320                 :             :                  errmsg("NUMERIC precision %d must be between 1 and %d",
    1321                 :             :                         precision, NUMERIC_MAX_PRECISION)));
    1322   [ +  +  +  + ]:        1103 :     if (scale < NUMERIC_MIN_SCALE || scale > NUMERIC_MAX_SCALE)
    1323         [ +  + ]:          16 :         ereturn(escontext, -1,
    1324                 :             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1325                 :             :                  errmsg("NUMERIC scale %d must be between %d and %d",
    1326                 :             :                         scale, NUMERIC_MIN_SCALE, NUMERIC_MAX_SCALE)));
    1327                 :             : 
    1328                 :        1087 :     return make_numeric_typmod(precision, scale);
    1329                 :             : }
    1330                 :             : 
    1331                 :             : Datum
    1332                 :        1055 : numerictypmodin(PG_FUNCTION_ARGS)
    1333                 :             : {
    1334                 :        1055 :     ArrayType  *ta = PG_GETARG_ARRAYTYPE_P(0);
    1335                 :             :     int32      *tl;
    1336                 :             :     int         n;
    1337                 :             :     int32       typmod;
    1338                 :             : 
    1339                 :        1055 :     tl = ArrayGetIntegerTypmods(ta, &n);
    1340                 :             : 
    1341         [ +  + ]:        1055 :     if (n == 2)
    1342                 :        1043 :         typmod = make_numeric_typmod_safe(tl[0], tl[1], NULL);
    1343         [ +  + ]:          12 :     else if (n == 1)
    1344                 :             :     {
    1345                 :             :         /* scale defaults to zero */
    1346                 :           4 :         typmod = make_numeric_typmod_safe(tl[0], 0, NULL);
    1347                 :             :     }
    1348                 :             :     else
    1349                 :             :     {
    1350         [ +  - ]:           8 :         ereport(ERROR,
    1351                 :             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1352                 :             :                  errmsg("invalid NUMERIC type modifier")));
    1353                 :             :         typmod = 0;             /* keep compiler quiet */
    1354                 :             :     }
    1355                 :             : 
    1356                 :        1047 :     PG_RETURN_INT32(typmod);
    1357                 :             : }
    1358                 :             : 
    1359                 :             : Datum
    1360                 :         209 : numerictypmodout(PG_FUNCTION_ARGS)
    1361                 :             : {
    1362                 :         209 :     int32       typmod = PG_GETARG_INT32(0);
    1363                 :         209 :     char       *res = (char *) palloc(64);
    1364                 :             : 
    1365         [ +  - ]:         209 :     if (is_valid_numeric_typmod(typmod))
    1366                 :         209 :         snprintf(res, 64, "(%d,%d)",
    1367                 :             :                  numeric_typmod_precision(typmod),
    1368                 :             :                  numeric_typmod_scale(typmod));
    1369                 :             :     else
    1370                 :           0 :         *res = '\0';
    1371                 :             : 
    1372                 :         209 :     PG_RETURN_CSTRING(res);
    1373                 :             : }
    1374                 :             : 
    1375                 :             : 
    1376                 :             : /* ----------------------------------------------------------------------
    1377                 :             :  *
    1378                 :             :  * Sign manipulation, rounding and the like
    1379                 :             :  *
    1380                 :             :  * ----------------------------------------------------------------------
    1381                 :             :  */
    1382                 :             : 
    1383                 :             : Datum
    1384                 :       13004 : numeric_abs(PG_FUNCTION_ARGS)
    1385                 :             : {
    1386                 :       13004 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1387                 :             :     Numeric     res;
    1388                 :             : 
    1389                 :             :     /*
    1390                 :             :      * Do it the easy way directly on the packed format
    1391                 :             :      */
    1392                 :       13004 :     res = duplicate_numeric(num);
    1393                 :             : 
    1394         [ +  + ]:       13004 :     if (NUMERIC_IS_SHORT(num))
    1395                 :       12960 :         res->choice.n_short.n_header =
    1396                 :       12960 :             num->choice.n_short.n_header & ~NUMERIC_SHORT_SIGN_MASK;
    1397         [ +  + ]:          44 :     else if (NUMERIC_IS_SPECIAL(num))
    1398                 :             :     {
    1399                 :             :         /* This changes -Inf to Inf, and doesn't affect NaN */
    1400                 :          12 :         res->choice.n_short.n_header =
    1401                 :          12 :             num->choice.n_short.n_header & ~NUMERIC_INF_SIGN_MASK;
    1402                 :             :     }
    1403                 :             :     else
    1404         [ -  + ]:          32 :         res->choice.n_long.n_sign_dscale = NUMERIC_POS | NUMERIC_DSCALE(num);
    1405                 :             : 
    1406                 :       13004 :     PG_RETURN_NUMERIC(res);
    1407                 :             : }
    1408                 :             : 
    1409                 :             : 
    1410                 :             : Datum
    1411                 :         631 : numeric_uminus(PG_FUNCTION_ARGS)
    1412                 :             : {
    1413                 :         631 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1414                 :             :     Numeric     res;
    1415                 :             : 
    1416                 :             :     /*
    1417                 :             :      * Do it the easy way directly on the packed format
    1418                 :             :      */
    1419                 :         631 :     res = duplicate_numeric(num);
    1420                 :             : 
    1421         [ +  + ]:         631 :     if (NUMERIC_IS_SPECIAL(num))
    1422                 :             :     {
    1423                 :             :         /* Flip the sign, if it's Inf or -Inf */
    1424         [ +  + ]:          84 :         if (!NUMERIC_IS_NAN(num))
    1425                 :          56 :             res->choice.n_short.n_header =
    1426                 :          56 :                 num->choice.n_short.n_header ^ NUMERIC_INF_SIGN_MASK;
    1427                 :             :     }
    1428                 :             : 
    1429                 :             :     /*
    1430                 :             :      * The packed format is known to be totally zero digit trimmed always. So
    1431                 :             :      * once we've eliminated specials, we can identify a zero by the fact that
    1432                 :             :      * there are no digits at all. Do nothing to a zero.
    1433                 :             :      */
    1434   [ +  -  +  + ]:         547 :     else if (NUMERIC_NDIGITS(num) != 0)
    1435                 :             :     {
    1436                 :             :         /* Else, flip the sign */
    1437         [ +  - ]:         471 :         if (NUMERIC_IS_SHORT(num))
    1438                 :         471 :             res->choice.n_short.n_header =
    1439                 :         471 :                 num->choice.n_short.n_header ^ NUMERIC_SHORT_SIGN_MASK;
    1440   [ #  #  #  #  :           0 :         else if (NUMERIC_SIGN(num) == NUMERIC_POS)
                   #  # ]
    1441                 :           0 :             res->choice.n_long.n_sign_dscale =
    1442         [ #  # ]:           0 :                 NUMERIC_NEG | NUMERIC_DSCALE(num);
    1443                 :             :         else
    1444                 :           0 :             res->choice.n_long.n_sign_dscale =
    1445         [ #  # ]:           0 :                 NUMERIC_POS | NUMERIC_DSCALE(num);
    1446                 :             :     }
    1447                 :             : 
    1448                 :         631 :     PG_RETURN_NUMERIC(res);
    1449                 :             : }
    1450                 :             : 
    1451                 :             : 
    1452                 :             : Datum
    1453                 :           0 : numeric_uplus(PG_FUNCTION_ARGS)
    1454                 :             : {
    1455                 :           0 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1456                 :             : 
    1457                 :           0 :     PG_RETURN_NUMERIC(duplicate_numeric(num));
    1458                 :             : }
    1459                 :             : 
    1460                 :             : 
    1461                 :             : /*
    1462                 :             :  * numeric_sign_internal() -
    1463                 :             :  *
    1464                 :             :  * Returns -1 if the argument is less than 0, 0 if the argument is equal
    1465                 :             :  * to 0, and 1 if the argument is greater than zero.  Caller must have
    1466                 :             :  * taken care of the NaN case, but we can handle infinities here.
    1467                 :             :  */
    1468                 :             : static int
    1469                 :        2476 : numeric_sign_internal(Numeric num)
    1470                 :             : {
    1471         [ +  + ]:        2476 :     if (NUMERIC_IS_SPECIAL(num))
    1472                 :             :     {
    1473                 :             :         Assert(!NUMERIC_IS_NAN(num));
    1474                 :             :         /* Must be Inf or -Inf */
    1475         [ +  + ]:         223 :         if (NUMERIC_IS_PINF(num))
    1476                 :         129 :             return 1;
    1477                 :             :         else
    1478                 :          94 :             return -1;
    1479                 :             :     }
    1480                 :             : 
    1481                 :             :     /*
    1482                 :             :      * The packed format is known to be totally zero digit trimmed always. So
    1483                 :             :      * once we've eliminated specials, we can identify a zero by the fact that
    1484                 :             :      * there are no digits at all.
    1485                 :             :      */
    1486   [ +  +  +  + ]:        2253 :     else if (NUMERIC_NDIGITS(num) == 0)
    1487                 :         161 :         return 0;
    1488   [ +  +  -  +  :        2092 :     else if (NUMERIC_SIGN(num) == NUMERIC_NEG)
                   +  + ]
    1489                 :         511 :         return -1;
    1490                 :             :     else
    1491                 :        1581 :         return 1;
    1492                 :             : }
    1493                 :             : 
    1494                 :             : /*
    1495                 :             :  * numeric_sign() -
    1496                 :             :  *
    1497                 :             :  * returns -1 if the argument is less than 0, 0 if the argument is equal
    1498                 :             :  * to 0, and 1 if the argument is greater than zero.
    1499                 :             :  */
    1500                 :             : Datum
    1501                 :          32 : numeric_sign(PG_FUNCTION_ARGS)
    1502                 :             : {
    1503                 :          32 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1504                 :             : 
    1505                 :             :     /*
    1506                 :             :      * Handle NaN (infinities can be handled normally)
    1507                 :             :      */
    1508         [ +  + ]:          32 :     if (NUMERIC_IS_NAN(num))
    1509                 :           4 :         PG_RETURN_NUMERIC(make_result(&const_nan));
    1510                 :             : 
    1511   [ +  +  +  - ]:          28 :     switch (numeric_sign_internal(num))
    1512                 :             :     {
    1513                 :           4 :         case 0:
    1514                 :           4 :             PG_RETURN_NUMERIC(make_result(&const_zero));
    1515                 :          12 :         case 1:
    1516                 :          12 :             PG_RETURN_NUMERIC(make_result(&const_one));
    1517                 :          12 :         case -1:
    1518                 :          12 :             PG_RETURN_NUMERIC(make_result(&const_minus_one));
    1519                 :             :     }
    1520                 :             : 
    1521                 :             :     Assert(false);
    1522                 :           0 :     return (Datum) 0;
    1523                 :             : }
    1524                 :             : 
    1525                 :             : 
    1526                 :             : /*
    1527                 :             :  * numeric_round() -
    1528                 :             :  *
    1529                 :             :  *  Round a value to have 'scale' digits after the decimal point.
    1530                 :             :  *  We allow negative 'scale', implying rounding before the decimal
    1531                 :             :  *  point --- Oracle interprets rounding that way.
    1532                 :             :  */
    1533                 :             : Datum
    1534                 :        5217 : numeric_round(PG_FUNCTION_ARGS)
    1535                 :             : {
    1536                 :        5217 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1537                 :        5217 :     int32       scale = PG_GETARG_INT32(1);
    1538                 :             :     Numeric     res;
    1539                 :             :     NumericVar  arg;
    1540                 :             : 
    1541                 :             :     /*
    1542                 :             :      * Handle NaN and infinities
    1543                 :             :      */
    1544         [ +  + ]:        5217 :     if (NUMERIC_IS_SPECIAL(num))
    1545                 :          64 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    1546                 :             : 
    1547                 :             :     /*
    1548                 :             :      * Limit the scale value to avoid possible overflow in calculations.
    1549                 :             :      *
    1550                 :             :      * These limits are based on the maximum number of digits a Numeric value
    1551                 :             :      * can have before and after the decimal point, but we must allow for one
    1552                 :             :      * extra digit before the decimal point, in case the most significant
    1553                 :             :      * digit rounds up; we must check if that causes Numeric overflow.
    1554                 :             :      */
    1555                 :        5153 :     scale = Max(scale, -(NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS - 1);
    1556                 :        5153 :     scale = Min(scale, NUMERIC_DSCALE_MAX);
    1557                 :             : 
    1558                 :             :     /*
    1559                 :             :      * Unpack the argument and round it at the proper digit position
    1560                 :             :      */
    1561                 :        5153 :     init_var(&arg);
    1562                 :        5153 :     set_var_from_num(num, &arg);
    1563                 :             : 
    1564                 :        5153 :     round_var(&arg, scale);
    1565                 :             : 
    1566                 :             :     /* We don't allow negative output dscale */
    1567         [ +  + ]:        5153 :     if (scale < 0)
    1568                 :         149 :         arg.dscale = 0;
    1569                 :             : 
    1570                 :             :     /*
    1571                 :             :      * Return the rounded result
    1572                 :             :      */
    1573                 :        5153 :     res = make_result(&arg);
    1574                 :             : 
    1575                 :        5149 :     free_var(&arg);
    1576                 :        5149 :     PG_RETURN_NUMERIC(res);
    1577                 :             : }
    1578                 :             : 
    1579                 :             : 
    1580                 :             : /*
    1581                 :             :  * numeric_trunc() -
    1582                 :             :  *
    1583                 :             :  *  Truncate a value to have 'scale' digits after the decimal point.
    1584                 :             :  *  We allow negative 'scale', implying a truncation before the decimal
    1585                 :             :  *  point --- Oracle interprets truncation that way.
    1586                 :             :  */
    1587                 :             : Datum
    1588                 :         714 : numeric_trunc(PG_FUNCTION_ARGS)
    1589                 :             : {
    1590                 :         714 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1591                 :         714 :     int32       scale = PG_GETARG_INT32(1);
    1592                 :             :     Numeric     res;
    1593                 :             :     NumericVar  arg;
    1594                 :             : 
    1595                 :             :     /*
    1596                 :             :      * Handle NaN and infinities
    1597                 :             :      */
    1598         [ +  + ]:         714 :     if (NUMERIC_IS_SPECIAL(num))
    1599                 :          24 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    1600                 :             : 
    1601                 :             :     /*
    1602                 :             :      * Limit the scale value to avoid possible overflow in calculations.
    1603                 :             :      *
    1604                 :             :      * These limits are based on the maximum number of digits a Numeric value
    1605                 :             :      * can have before and after the decimal point.
    1606                 :             :      */
    1607                 :         690 :     scale = Max(scale, -(NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS);
    1608                 :         690 :     scale = Min(scale, NUMERIC_DSCALE_MAX);
    1609                 :             : 
    1610                 :             :     /*
    1611                 :             :      * Unpack the argument and truncate it at the proper digit position
    1612                 :             :      */
    1613                 :         690 :     init_var(&arg);
    1614                 :         690 :     set_var_from_num(num, &arg);
    1615                 :             : 
    1616                 :         690 :     trunc_var(&arg, scale);
    1617                 :             : 
    1618                 :             :     /* We don't allow negative output dscale */
    1619         [ +  + ]:         690 :     if (scale < 0)
    1620                 :          20 :         arg.dscale = 0;
    1621                 :             : 
    1622                 :             :     /*
    1623                 :             :      * Return the truncated result
    1624                 :             :      */
    1625                 :         690 :     res = make_result(&arg);
    1626                 :             : 
    1627                 :         690 :     free_var(&arg);
    1628                 :         690 :     PG_RETURN_NUMERIC(res);
    1629                 :             : }
    1630                 :             : 
    1631                 :             : 
    1632                 :             : /*
    1633                 :             :  * numeric_ceil() -
    1634                 :             :  *
    1635                 :             :  *  Return the smallest integer greater than or equal to the argument
    1636                 :             :  */
    1637                 :             : Datum
    1638                 :         148 : numeric_ceil(PG_FUNCTION_ARGS)
    1639                 :             : {
    1640                 :         148 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1641                 :             :     Numeric     res;
    1642                 :             :     NumericVar  result;
    1643                 :             : 
    1644                 :             :     /*
    1645                 :             :      * Handle NaN and infinities
    1646                 :             :      */
    1647         [ +  + ]:         148 :     if (NUMERIC_IS_SPECIAL(num))
    1648                 :          12 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    1649                 :             : 
    1650                 :         136 :     init_var_from_num(num, &result);
    1651                 :         136 :     ceil_var(&result, &result);
    1652                 :             : 
    1653                 :         136 :     res = make_result(&result);
    1654                 :         136 :     free_var(&result);
    1655                 :             : 
    1656                 :         136 :     PG_RETURN_NUMERIC(res);
    1657                 :             : }
    1658                 :             : 
    1659                 :             : 
    1660                 :             : /*
    1661                 :             :  * numeric_floor() -
    1662                 :             :  *
    1663                 :             :  *  Return the largest integer equal to or less than the argument
    1664                 :             :  */
    1665                 :             : Datum
    1666                 :          84 : numeric_floor(PG_FUNCTION_ARGS)
    1667                 :             : {
    1668                 :          84 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1669                 :             :     Numeric     res;
    1670                 :             :     NumericVar  result;
    1671                 :             : 
    1672                 :             :     /*
    1673                 :             :      * Handle NaN and infinities
    1674                 :             :      */
    1675         [ +  + ]:          84 :     if (NUMERIC_IS_SPECIAL(num))
    1676                 :          12 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    1677                 :             : 
    1678                 :          72 :     init_var_from_num(num, &result);
    1679                 :          72 :     floor_var(&result, &result);
    1680                 :             : 
    1681                 :          72 :     res = make_result(&result);
    1682                 :          72 :     free_var(&result);
    1683                 :             : 
    1684                 :          72 :     PG_RETURN_NUMERIC(res);
    1685                 :             : }
    1686                 :             : 
    1687                 :             : 
    1688                 :             : /*
    1689                 :             :  * generate_series_numeric() -
    1690                 :             :  *
    1691                 :             :  *  Generate series of numeric.
    1692                 :             :  */
    1693                 :             : Datum
    1694                 :       80256 : generate_series_numeric(PG_FUNCTION_ARGS)
    1695                 :             : {
    1696                 :       80256 :     return generate_series_step_numeric(fcinfo);
    1697                 :             : }
    1698                 :             : 
    1699                 :             : Datum
    1700                 :       80556 : generate_series_step_numeric(PG_FUNCTION_ARGS)
    1701                 :             : {
    1702                 :             :     generate_series_numeric_fctx *fctx;
    1703                 :             :     FuncCallContext *funcctx;
    1704                 :             :     MemoryContext oldcontext;
    1705                 :             : 
    1706         [ +  + ]:       80556 :     if (SRF_IS_FIRSTCALL())
    1707                 :             :     {
    1708                 :         116 :         Numeric     start_num = PG_GETARG_NUMERIC(0);
    1709                 :         116 :         Numeric     stop_num = PG_GETARG_NUMERIC(1);
    1710                 :         116 :         NumericVar  steploc = const_one;
    1711                 :             : 
    1712                 :             :         /* Reject NaN and infinities in start and stop values */
    1713         [ +  + ]:         116 :         if (NUMERIC_IS_SPECIAL(start_num))
    1714                 :             :         {
    1715         [ +  + ]:           8 :             if (NUMERIC_IS_NAN(start_num))
    1716         [ +  - ]:           4 :                 ereport(ERROR,
    1717                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1718                 :             :                          errmsg("start value cannot be NaN")));
    1719                 :             :             else
    1720         [ +  - ]:           4 :                 ereport(ERROR,
    1721                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1722                 :             :                          errmsg("start value cannot be infinity")));
    1723                 :             :         }
    1724         [ +  + ]:         108 :         if (NUMERIC_IS_SPECIAL(stop_num))
    1725                 :             :         {
    1726         [ +  + ]:           8 :             if (NUMERIC_IS_NAN(stop_num))
    1727         [ +  - ]:           4 :                 ereport(ERROR,
    1728                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1729                 :             :                          errmsg("stop value cannot be NaN")));
    1730                 :             :             else
    1731         [ +  - ]:           4 :                 ereport(ERROR,
    1732                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1733                 :             :                          errmsg("stop value cannot be infinity")));
    1734                 :             :         }
    1735                 :             : 
    1736                 :             :         /* see if we were given an explicit step size */
    1737         [ +  + ]:         100 :         if (PG_NARGS() == 3)
    1738                 :             :         {
    1739                 :          48 :             Numeric     step_num = PG_GETARG_NUMERIC(2);
    1740                 :             : 
    1741         [ +  + ]:          48 :             if (NUMERIC_IS_SPECIAL(step_num))
    1742                 :             :             {
    1743         [ +  + ]:           8 :                 if (NUMERIC_IS_NAN(step_num))
    1744         [ +  - ]:           4 :                     ereport(ERROR,
    1745                 :             :                             (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1746                 :             :                              errmsg("step size cannot be NaN")));
    1747                 :             :                 else
    1748         [ +  - ]:           4 :                     ereport(ERROR,
    1749                 :             :                             (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1750                 :             :                              errmsg("step size cannot be infinity")));
    1751                 :             :             }
    1752                 :             : 
    1753                 :          40 :             init_var_from_num(step_num, &steploc);
    1754                 :             : 
    1755         [ +  + ]:          40 :             if (cmp_var(&steploc, &const_zero) == 0)
    1756         [ +  - ]:           4 :                 ereport(ERROR,
    1757                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1758                 :             :                          errmsg("step size cannot equal zero")));
    1759                 :             :         }
    1760                 :             : 
    1761                 :             :         /* create a function context for cross-call persistence */
    1762                 :          88 :         funcctx = SRF_FIRSTCALL_INIT();
    1763                 :             : 
    1764                 :             :         /*
    1765                 :             :          * Switch to memory context appropriate for multiple function calls.
    1766                 :             :          */
    1767                 :          88 :         oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
    1768                 :             : 
    1769                 :             :         /* allocate memory for user context */
    1770                 :          88 :         fctx = palloc_object(generate_series_numeric_fctx);
    1771                 :             : 
    1772                 :             :         /*
    1773                 :             :          * Use fctx to keep state from call to call. Seed current with the
    1774                 :             :          * original start value. We must copy the start_num and stop_num
    1775                 :             :          * values rather than pointing to them, since we may have detoasted
    1776                 :             :          * them in the per-call context.
    1777                 :             :          */
    1778                 :          88 :         init_var(&fctx->current);
    1779                 :          88 :         init_var(&fctx->stop);
    1780                 :          88 :         init_var(&fctx->step);
    1781                 :             : 
    1782                 :          88 :         set_var_from_num(start_num, &fctx->current);
    1783                 :          88 :         set_var_from_num(stop_num, &fctx->stop);
    1784                 :          88 :         set_var_from_var(&steploc, &fctx->step);
    1785                 :             : 
    1786                 :          88 :         funcctx->user_fctx = fctx;
    1787                 :          88 :         MemoryContextSwitchTo(oldcontext);
    1788                 :             :     }
    1789                 :             : 
    1790                 :             :     /* stuff done on every call of the function */
    1791                 :       80528 :     funcctx = SRF_PERCALL_SETUP();
    1792                 :             : 
    1793                 :             :     /*
    1794                 :             :      * Get the saved state and use current state as the result of this
    1795                 :             :      * iteration.
    1796                 :             :      */
    1797                 :       80528 :     fctx = funcctx->user_fctx;
    1798                 :             : 
    1799   [ +  +  +  + ]:      160936 :     if ((fctx->step.sign == NUMERIC_POS &&
    1800                 :       80408 :          cmp_var(&fctx->current, &fctx->stop) <= 0) ||
    1801   [ +  +  +  + ]:         320 :         (fctx->step.sign == NUMERIC_NEG &&
    1802                 :         120 :          cmp_var(&fctx->current, &fctx->stop) >= 0))
    1803                 :             :     {
    1804                 :       80440 :         Numeric     result = make_result(&fctx->current);
    1805                 :             : 
    1806                 :             :         /* switch to memory context appropriate for iteration calculation */
    1807                 :       80440 :         oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
    1808                 :             : 
    1809                 :             :         /* increment current in preparation for next iteration */
    1810                 :       80440 :         add_var(&fctx->current, &fctx->step, &fctx->current);
    1811                 :       80440 :         MemoryContextSwitchTo(oldcontext);
    1812                 :             : 
    1813                 :             :         /* do when there is more left to send */
    1814                 :       80440 :         SRF_RETURN_NEXT(funcctx, NumericGetDatum(result));
    1815                 :             :     }
    1816                 :             :     else
    1817                 :             :         /* do when there is no more left */
    1818                 :          88 :         SRF_RETURN_DONE(funcctx);
    1819                 :             : }
    1820                 :             : 
    1821                 :             : /*
    1822                 :             :  * Planner support function for generate_series(numeric, numeric [, numeric])
    1823                 :             :  */
    1824                 :             : Datum
    1825                 :         535 : generate_series_numeric_support(PG_FUNCTION_ARGS)
    1826                 :             : {
    1827                 :         535 :     Node       *rawreq = (Node *) PG_GETARG_POINTER(0);
    1828                 :         535 :     Node       *ret = NULL;
    1829                 :             : 
    1830         [ +  + ]:         535 :     if (IsA(rawreq, SupportRequestRows))
    1831                 :             :     {
    1832                 :             :         /* Try to estimate the number of rows returned */
    1833                 :         130 :         SupportRequestRows *req = (SupportRequestRows *) rawreq;
    1834                 :             : 
    1835         [ +  - ]:         130 :         if (is_funcclause(req->node))    /* be paranoid */
    1836                 :             :         {
    1837                 :         130 :             List       *args = ((FuncExpr *) req->node)->args;
    1838                 :             :             Node       *arg1,
    1839                 :             :                        *arg2,
    1840                 :             :                        *arg3;
    1841                 :             : 
    1842                 :             :             /* We can use estimated argument values here */
    1843                 :         130 :             arg1 = estimate_expression_value(req->root, linitial(args));
    1844                 :         130 :             arg2 = estimate_expression_value(req->root, lsecond(args));
    1845         [ +  + ]:         130 :             if (list_length(args) >= 3)
    1846                 :          85 :                 arg3 = estimate_expression_value(req->root, lthird(args));
    1847                 :             :             else
    1848                 :          45 :                 arg3 = NULL;
    1849                 :             : 
    1850                 :             :             /*
    1851                 :             :              * If any argument is constant NULL, we can safely assume that
    1852                 :             :              * zero rows are returned.  Otherwise, if they're all non-NULL
    1853                 :             :              * constants, we can calculate the number of rows that will be
    1854                 :             :              * returned.
    1855                 :             :              */
    1856         [ +  + ]:         130 :             if ((IsA(arg1, Const) &&
    1857         [ +  - ]:         125 :                  ((Const *) arg1)->constisnull) ||
    1858         [ +  + ]:         130 :                 (IsA(arg2, Const) &&
    1859   [ +  -  +  + ]:         130 :                  ((Const *) arg2)->constisnull) ||
    1860         [ +  + ]:          85 :                 (arg3 != NULL && IsA(arg3, Const) &&
    1861         [ -  + ]:          80 :                  ((Const *) arg3)->constisnull))
    1862                 :             :             {
    1863                 :           0 :                 req->rows = 0;
    1864                 :           0 :                 ret = (Node *) req;
    1865                 :             :             }
    1866         [ +  + ]:         130 :             else if (IsA(arg1, Const) &&
    1867   [ +  +  +  + ]:         125 :                      IsA(arg2, Const) &&
    1868         [ +  + ]:          85 :                      (arg3 == NULL || IsA(arg3, Const)))
    1869                 :             :             {
    1870                 :             :                 Numeric     start_num;
    1871                 :             :                 Numeric     stop_num;
    1872                 :         115 :                 NumericVar  step = const_one;
    1873                 :             : 
    1874                 :             :                 /*
    1875                 :             :                  * If any argument is NaN or infinity, generate_series() will
    1876                 :             :                  * error out, so we needn't produce an estimate.
    1877                 :             :                  */
    1878                 :         115 :                 start_num = DatumGetNumeric(((Const *) arg1)->constvalue);
    1879                 :         115 :                 stop_num = DatumGetNumeric(((Const *) arg2)->constvalue);
    1880                 :             : 
    1881         [ +  + ]:         115 :                 if (NUMERIC_IS_SPECIAL(start_num) ||
    1882         [ +  + ]:         100 :                     NUMERIC_IS_SPECIAL(stop_num))
    1883                 :          40 :                     PG_RETURN_POINTER(NULL);
    1884                 :             : 
    1885         [ +  + ]:          90 :                 if (arg3)
    1886                 :             :                 {
    1887                 :             :                     Numeric     step_num;
    1888                 :             : 
    1889                 :          55 :                     step_num = DatumGetNumeric(((Const *) arg3)->constvalue);
    1890                 :             : 
    1891         [ +  + ]:          55 :                     if (NUMERIC_IS_SPECIAL(step_num))
    1892                 :          15 :                         PG_RETURN_POINTER(NULL);
    1893                 :             : 
    1894                 :          40 :                     init_var_from_num(step_num, &step);
    1895                 :             :                 }
    1896                 :             : 
    1897                 :             :                 /*
    1898                 :             :                  * The number of rows that will be returned is given by
    1899                 :             :                  * floor((stop - start) / step) + 1, if the sign of step
    1900                 :             :                  * matches the sign of stop - start.  Otherwise, no rows will
    1901                 :             :                  * be returned.
    1902                 :             :                  */
    1903         [ +  + ]:          75 :                 if (cmp_var(&step, &const_zero) != 0)
    1904                 :             :                 {
    1905                 :             :                     NumericVar  start;
    1906                 :             :                     NumericVar  stop;
    1907                 :             :                     NumericVar  res;
    1908                 :             : 
    1909                 :          65 :                     init_var_from_num(start_num, &start);
    1910                 :          65 :                     init_var_from_num(stop_num, &stop);
    1911                 :             : 
    1912                 :          65 :                     init_var(&res);
    1913                 :          65 :                     sub_var(&stop, &start, &res);
    1914                 :             : 
    1915         [ +  + ]:          65 :                     if (step.sign != res.sign)
    1916                 :             :                     {
    1917                 :             :                         /* no rows will be returned */
    1918                 :           5 :                         req->rows = 0;
    1919                 :           5 :                         ret = (Node *) req;
    1920                 :             :                     }
    1921                 :             :                     else
    1922                 :             :                     {
    1923         [ +  + ]:          60 :                         if (arg3)
    1924                 :          25 :                             div_var(&res, &step, &res, 0, false, false);
    1925                 :             :                         else
    1926                 :          35 :                             trunc_var(&res, 0); /* step = 1 */
    1927                 :             : 
    1928                 :          60 :                         req->rows = numericvar_to_double_no_overflow(&res) + 1;
    1929                 :          60 :                         ret = (Node *) req;
    1930                 :             :                     }
    1931                 :             : 
    1932                 :          65 :                     free_var(&res);
    1933                 :             :                 }
    1934                 :             :             }
    1935                 :             :         }
    1936                 :             :     }
    1937                 :             : 
    1938                 :         495 :     PG_RETURN_POINTER(ret);
    1939                 :             : }
    1940                 :             : 
    1941                 :             : 
    1942                 :             : /*
    1943                 :             :  * Implements the numeric version of the width_bucket() function
    1944                 :             :  * defined by SQL2003. See also width_bucket_float8().
    1945                 :             :  *
    1946                 :             :  * 'bound1' and 'bound2' are the lower and upper bounds of the
    1947                 :             :  * histogram's range, respectively. 'count' is the number of buckets
    1948                 :             :  * in the histogram. width_bucket() returns an integer indicating the
    1949                 :             :  * bucket number that 'operand' belongs to in an equiwidth histogram
    1950                 :             :  * with the specified characteristics. An operand smaller than the
    1951                 :             :  * lower bound is assigned to bucket 0. An operand greater than or equal
    1952                 :             :  * to the upper bound is assigned to an additional bucket (with number
    1953                 :             :  * count+1). We don't allow the histogram bounds to be NaN or +/- infinity,
    1954                 :             :  * but we do allow those values for the operand (taking NaN to be larger
    1955                 :             :  * than any other value, as we do in comparisons).
    1956                 :             :  */
    1957                 :             : Datum
    1958                 :         529 : width_bucket_numeric(PG_FUNCTION_ARGS)
    1959                 :             : {
    1960                 :         529 :     Numeric     operand = PG_GETARG_NUMERIC(0);
    1961                 :         529 :     Numeric     bound1 = PG_GETARG_NUMERIC(1);
    1962                 :         529 :     Numeric     bound2 = PG_GETARG_NUMERIC(2);
    1963                 :         529 :     int32       count = PG_GETARG_INT32(3);
    1964                 :             :     NumericVar  count_var;
    1965                 :             :     NumericVar  result_var;
    1966                 :             :     int32       result;
    1967                 :             : 
    1968         [ +  + ]:         529 :     if (count <= 0)
    1969         [ +  - ]:           8 :         ereport(ERROR,
    1970                 :             :                 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
    1971                 :             :                  errmsg("count must be greater than zero")));
    1972                 :             : 
    1973   [ +  +  +  + ]:         521 :     if (NUMERIC_IS_SPECIAL(bound1) || NUMERIC_IS_SPECIAL(bound2))
    1974                 :             :     {
    1975   [ +  +  -  + ]:          16 :         if (NUMERIC_IS_NAN(bound1) || NUMERIC_IS_NAN(bound2))
    1976         [ +  - ]:           4 :             ereport(ERROR,
    1977                 :             :                     (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
    1978                 :             :                      errmsg("lower and upper bounds cannot be NaN")));
    1979                 :             : 
    1980   [ +  +  +  - ]:          12 :         if (NUMERIC_IS_INF(bound1) || NUMERIC_IS_INF(bound2))
    1981         [ +  - ]:          12 :             ereport(ERROR,
    1982                 :             :                     (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
    1983                 :             :                      errmsg("lower and upper bounds must be finite")));
    1984                 :             :     }
    1985                 :             : 
    1986                 :         505 :     init_var(&result_var);
    1987                 :         505 :     init_var(&count_var);
    1988                 :             : 
    1989                 :             :     /* Convert 'count' to a numeric, for ease of use later */
    1990                 :         505 :     int64_to_numericvar((int64) count, &count_var);
    1991                 :             : 
    1992   [ +  +  +  - ]:         505 :     switch (cmp_numerics(bound1, bound2))
    1993                 :             :     {
    1994                 :           4 :         case 0:
    1995         [ +  - ]:           4 :             ereport(ERROR,
    1996                 :             :                     (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
    1997                 :             :                      errmsg("lower bound cannot equal upper bound")));
    1998                 :             :             break;
    1999                 :             : 
    2000                 :             :             /* bound1 < bound2 */
    2001                 :         372 :         case -1:
    2002         [ +  + ]:         372 :             if (cmp_numerics(operand, bound1) < 0)
    2003                 :          77 :                 set_var_from_var(&const_zero, &result_var);
    2004         [ +  + ]:         295 :             else if (cmp_numerics(operand, bound2) >= 0)
    2005                 :          78 :                 add_var(&count_var, &const_one, &result_var);
    2006                 :             :             else
    2007                 :         217 :                 compute_bucket(operand, bound1, bound2, &count_var,
    2008                 :             :                                &result_var);
    2009                 :         372 :             break;
    2010                 :             : 
    2011                 :             :             /* bound1 > bound2 */
    2012                 :         129 :         case 1:
    2013         [ +  + ]:         129 :             if (cmp_numerics(operand, bound1) > 0)
    2014                 :           8 :                 set_var_from_var(&const_zero, &result_var);
    2015         [ +  + ]:         121 :             else if (cmp_numerics(operand, bound2) <= 0)
    2016                 :          16 :                 add_var(&count_var, &const_one, &result_var);
    2017                 :             :             else
    2018                 :         105 :                 compute_bucket(operand, bound1, bound2, &count_var,
    2019                 :             :                                &result_var);
    2020                 :         129 :             break;
    2021                 :             :     }
    2022                 :             : 
    2023                 :             :     /* if result exceeds the range of a legal int4, we ereport here */
    2024         [ -  + ]:         501 :     if (!numericvar_to_int32(&result_var, &result))
    2025         [ #  # ]:           0 :         ereport(ERROR,
    2026                 :             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    2027                 :             :                  errmsg("integer out of range")));
    2028                 :             : 
    2029                 :         501 :     free_var(&count_var);
    2030                 :         501 :     free_var(&result_var);
    2031                 :             : 
    2032                 :         501 :     PG_RETURN_INT32(result);
    2033                 :             : }
    2034                 :             : 
    2035                 :             : /*
    2036                 :             :  * 'operand' is inside the bucket range, so determine the correct
    2037                 :             :  * bucket for it to go in. The calculations performed by this function
    2038                 :             :  * are derived directly from the SQL2003 spec. Note however that we
    2039                 :             :  * multiply by count before dividing, to avoid unnecessary roundoff error.
    2040                 :             :  */
    2041                 :             : static void
    2042                 :         322 : compute_bucket(Numeric operand, Numeric bound1, Numeric bound2,
    2043                 :             :                const NumericVar *count_var, NumericVar *result_var)
    2044                 :             : {
    2045                 :             :     NumericVar  bound1_var;
    2046                 :             :     NumericVar  bound2_var;
    2047                 :             :     NumericVar  operand_var;
    2048                 :             : 
    2049                 :         322 :     init_var_from_num(bound1, &bound1_var);
    2050                 :         322 :     init_var_from_num(bound2, &bound2_var);
    2051                 :         322 :     init_var_from_num(operand, &operand_var);
    2052                 :             : 
    2053                 :             :     /*
    2054                 :             :      * Per spec, bound1 is inclusive and bound2 is exclusive, and so we have
    2055                 :             :      * bound1 <= operand < bound2 or bound1 >= operand > bound2.  Either way,
    2056                 :             :      * the result is ((operand - bound1) * count) / (bound2 - bound1) + 1,
    2057                 :             :      * where the quotient is computed using floor division (i.e., division to
    2058                 :             :      * zero decimal places with truncation), which guarantees that the result
    2059                 :             :      * is in the range [1, count].  Reversing the bounds doesn't affect the
    2060                 :             :      * computation, because the signs cancel out when dividing.
    2061                 :             :      */
    2062                 :         322 :     sub_var(&operand_var, &bound1_var, &operand_var);
    2063                 :         322 :     sub_var(&bound2_var, &bound1_var, &bound2_var);
    2064                 :             : 
    2065                 :         322 :     mul_var(&operand_var, count_var, &operand_var,
    2066                 :         322 :             operand_var.dscale + count_var->dscale);
    2067                 :         322 :     div_var(&operand_var, &bound2_var, result_var, 0, false, true);
    2068                 :         322 :     add_var(result_var, &const_one, result_var);
    2069                 :             : 
    2070                 :         322 :     free_var(&bound1_var);
    2071                 :         322 :     free_var(&bound2_var);
    2072                 :         322 :     free_var(&operand_var);
    2073                 :         322 : }
    2074                 :             : 
    2075                 :             : /* ----------------------------------------------------------------------
    2076                 :             :  *
    2077                 :             :  * Comparison functions
    2078                 :             :  *
    2079                 :             :  * Note: btree indexes need these routines not to leak memory; therefore,
    2080                 :             :  * be careful to free working copies of toasted datums.  Most places don't
    2081                 :             :  * need to be so careful.
    2082                 :             :  *
    2083                 :             :  * Sort support:
    2084                 :             :  *
    2085                 :             :  * We implement the sortsupport strategy routine in order to get the benefit of
    2086                 :             :  * abbreviation. The ordinary numeric comparison can be quite slow as a result
    2087                 :             :  * of palloc/pfree cycles (due to detoasting packed values for alignment);
    2088                 :             :  * while this could be worked on itself, the abbreviation strategy gives more
    2089                 :             :  * speedup in many common cases.
    2090                 :             :  *
    2091                 :             :  * The abbreviated format is an int64. The representation is negated relative
    2092                 :             :  * to the original value, because we use the largest negative value for NaN,
    2093                 :             :  * which sorts higher than other values. We convert the absolute value of the
    2094                 :             :  * numeric to a 63-bit positive value, and then negate it if the original
    2095                 :             :  * number was positive.
    2096                 :             :  *
    2097                 :             :  * We abort the abbreviation process if the abbreviation cardinality is below
    2098                 :             :  * 0.01% of the row count (1 per 10k non-null rows).  The actual break-even
    2099                 :             :  * point is somewhat below that, perhaps 1 per 30k (at 1 per 100k there's a
    2100                 :             :  * very small penalty), but we don't want to build up too many abbreviated
    2101                 :             :  * values before first testing for abort, so we take the slightly pessimistic
    2102                 :             :  * number.  We make no attempt to estimate the cardinality of the real values,
    2103                 :             :  * since it plays no part in the cost model here (if the abbreviation is equal,
    2104                 :             :  * the cost of comparing equal and unequal underlying values is comparable).
    2105                 :             :  * We discontinue even checking for abort (saving us the hashing overhead) if
    2106                 :             :  * the estimated cardinality gets to 100k; that would be enough to support many
    2107                 :             :  * billions of rows while doing no worse than breaking even.
    2108                 :             :  *
    2109                 :             :  * ----------------------------------------------------------------------
    2110                 :             :  */
    2111                 :             : 
    2112                 :             : /*
    2113                 :             :  * Sort support strategy routine.
    2114                 :             :  */
    2115                 :             : Datum
    2116                 :         791 : numeric_sortsupport(PG_FUNCTION_ARGS)
    2117                 :             : {
    2118                 :         791 :     SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
    2119                 :             : 
    2120                 :         791 :     ssup->comparator = numeric_fast_cmp;
    2121                 :             : 
    2122         [ +  + ]:         791 :     if (ssup->abbreviate)
    2123                 :             :     {
    2124                 :             :         NumericSortSupport *nss;
    2125                 :         171 :         MemoryContext oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
    2126                 :             : 
    2127                 :         171 :         nss = palloc_object(NumericSortSupport);
    2128                 :             : 
    2129                 :             :         /*
    2130                 :             :          * palloc a buffer for handling unaligned packed values in addition to
    2131                 :             :          * the support struct
    2132                 :             :          */
    2133                 :         171 :         nss->buf = palloc(VARATT_SHORT_MAX + VARHDRSZ + 1);
    2134                 :             : 
    2135                 :         171 :         nss->input_count = 0;
    2136                 :         171 :         nss->estimating = true;
    2137                 :         171 :         initHyperLogLog(&nss->abbr_card, 10);
    2138                 :             : 
    2139                 :         171 :         ssup->ssup_extra = nss;
    2140                 :             : 
    2141                 :         171 :         ssup->abbrev_full_comparator = ssup->comparator;
    2142                 :         171 :         ssup->comparator = numeric_cmp_abbrev;
    2143                 :         171 :         ssup->abbrev_converter = numeric_abbrev_convert;
    2144                 :         171 :         ssup->abbrev_abort = numeric_abbrev_abort;
    2145                 :             : 
    2146                 :         171 :         MemoryContextSwitchTo(oldcontext);
    2147                 :             :     }
    2148                 :             : 
    2149                 :         791 :     PG_RETURN_VOID();
    2150                 :             : }
    2151                 :             : 
    2152                 :             : /*
    2153                 :             :  * Abbreviate a numeric datum, handling NaNs and detoasting
    2154                 :             :  * (must not leak memory!)
    2155                 :             :  */
    2156                 :             : static Datum
    2157                 :       12779 : numeric_abbrev_convert(Datum original_datum, SortSupport ssup)
    2158                 :             : {
    2159                 :       12779 :     NumericSortSupport *nss = ssup->ssup_extra;
    2160                 :       12779 :     void       *original_varatt = PG_DETOAST_DATUM_PACKED(original_datum);
    2161                 :             :     Numeric     value;
    2162                 :             :     Datum       result;
    2163                 :             : 
    2164                 :       12779 :     nss->input_count += 1;
    2165                 :             : 
    2166                 :             :     /*
    2167                 :             :      * This is to handle packed datums without needing a palloc/pfree cycle;
    2168                 :             :      * we keep and reuse a buffer large enough to handle any short datum.
    2169                 :             :      */
    2170         [ +  + ]:       12779 :     if (VARATT_IS_SHORT(original_varatt))
    2171                 :             :     {
    2172                 :         679 :         void       *buf = nss->buf;
    2173                 :         679 :         Size        sz = VARSIZE_SHORT(original_varatt) - VARHDRSZ_SHORT;
    2174                 :             : 
    2175                 :             :         Assert(sz <= VARATT_SHORT_MAX - VARHDRSZ_SHORT);
    2176                 :             : 
    2177                 :         679 :         SET_VARSIZE(buf, VARHDRSZ + sz);
    2178                 :         679 :         memcpy(VARDATA(buf), VARDATA_SHORT(original_varatt), sz);
    2179                 :             : 
    2180                 :         679 :         value = (Numeric) buf;
    2181                 :             :     }
    2182                 :             :     else
    2183                 :       12100 :         value = (Numeric) original_varatt;
    2184                 :             : 
    2185         [ +  + ]:       12779 :     if (NUMERIC_IS_SPECIAL(value))
    2186                 :             :     {
    2187         [ +  + ]:         100 :         if (NUMERIC_IS_PINF(value))
    2188                 :          32 :             result = NUMERIC_ABBREV_PINF;
    2189         [ +  + ]:          68 :         else if (NUMERIC_IS_NINF(value))
    2190                 :          32 :             result = NUMERIC_ABBREV_NINF;
    2191                 :             :         else
    2192                 :          36 :             result = NUMERIC_ABBREV_NAN;
    2193                 :             :     }
    2194                 :             :     else
    2195                 :             :     {
    2196                 :             :         NumericVar  var;
    2197                 :             : 
    2198                 :       12679 :         init_var_from_num(value, &var);
    2199                 :             : 
    2200                 :       12679 :         result = numeric_abbrev_convert_var(&var, nss);
    2201                 :             :     }
    2202                 :             : 
    2203                 :             :     /* should happen only for external/compressed toasts */
    2204         [ -  + ]:       12779 :     if (original_varatt != DatumGetPointer(original_datum))
    2205                 :           0 :         pfree(original_varatt);
    2206                 :             : 
    2207                 :       12779 :     return result;
    2208                 :             : }
    2209                 :             : 
    2210                 :             : /*
    2211                 :             :  * Consider whether to abort abbreviation.
    2212                 :             :  *
    2213                 :             :  * We pay no attention to the cardinality of the non-abbreviated data. There is
    2214                 :             :  * no reason to do so: unlike text, we have no fast check for equal values, so
    2215                 :             :  * we pay the full overhead whenever the abbreviations are equal regardless of
    2216                 :             :  * whether the underlying values are also equal.
    2217                 :             :  */
    2218                 :             : static bool
    2219                 :          96 : numeric_abbrev_abort(int memtupcount, SortSupport ssup)
    2220                 :             : {
    2221                 :          96 :     NumericSortSupport *nss = ssup->ssup_extra;
    2222                 :             :     double      abbr_card;
    2223                 :             : 
    2224   [ -  +  -  -  :          96 :     if (memtupcount < 10000 || nss->input_count < 10000 || !nss->estimating)
                   -  - ]
    2225                 :          96 :         return false;
    2226                 :             : 
    2227                 :           0 :     abbr_card = estimateHyperLogLog(&nss->abbr_card);
    2228                 :             : 
    2229                 :             :     /*
    2230                 :             :      * If we have >100k distinct values, then even if we were sorting many
    2231                 :             :      * billion rows we'd likely still break even, and the penalty of undoing
    2232                 :             :      * that many rows of abbrevs would probably not be worth it. Stop even
    2233                 :             :      * counting at that point.
    2234                 :             :      */
    2235         [ #  # ]:           0 :     if (abbr_card > 100000.0)
    2236                 :             :     {
    2237         [ #  # ]:           0 :         if (trace_sort)
    2238         [ #  # ]:           0 :             elog(LOG,
    2239                 :             :                  "numeric_abbrev: estimation ends at cardinality %f"
    2240                 :             :                  " after " INT64_FORMAT " values (%d rows)",
    2241                 :             :                  abbr_card, nss->input_count, memtupcount);
    2242                 :           0 :         nss->estimating = false;
    2243                 :           0 :         return false;
    2244                 :             :     }
    2245                 :             : 
    2246                 :             :     /*
    2247                 :             :      * Target minimum cardinality is 1 per ~10k of non-null inputs.  (The
    2248                 :             :      * break even point is somewhere between one per 100k rows, where
    2249                 :             :      * abbreviation has a very slight penalty, and 1 per 10k where it wins by
    2250                 :             :      * a measurable percentage.)  We use the relatively pessimistic 10k
    2251                 :             :      * threshold, and add a 0.5 row fudge factor, because it allows us to
    2252                 :             :      * abort earlier on genuinely pathological data where we've had exactly
    2253                 :             :      * one abbreviated value in the first 10k (non-null) rows.
    2254                 :             :      */
    2255         [ #  # ]:           0 :     if (abbr_card < nss->input_count / 10000.0 + 0.5)
    2256                 :             :     {
    2257         [ #  # ]:           0 :         if (trace_sort)
    2258         [ #  # ]:           0 :             elog(LOG,
    2259                 :             :                  "numeric_abbrev: aborting abbreviation at cardinality %f"
    2260                 :             :                  " below threshold %f after " INT64_FORMAT " values (%d rows)",
    2261                 :             :                  abbr_card, nss->input_count / 10000.0 + 0.5,
    2262                 :             :                  nss->input_count, memtupcount);
    2263                 :           0 :         return true;
    2264                 :             :     }
    2265                 :             : 
    2266         [ #  # ]:           0 :     if (trace_sort)
    2267         [ #  # ]:           0 :         elog(LOG,
    2268                 :             :              "numeric_abbrev: cardinality %f"
    2269                 :             :              " after " INT64_FORMAT " values (%d rows)",
    2270                 :             :              abbr_card, nss->input_count, memtupcount);
    2271                 :             : 
    2272                 :           0 :     return false;
    2273                 :             : }
    2274                 :             : 
    2275                 :             : /*
    2276                 :             :  * Non-fmgr interface to the comparison routine to allow sortsupport to elide
    2277                 :             :  * the fmgr call.  The saving here is small given how slow numeric comparisons
    2278                 :             :  * are, but it is a required part of the sort support API when abbreviations
    2279                 :             :  * are performed.
    2280                 :             :  *
    2281                 :             :  * Two palloc/pfree cycles could be saved here by using persistent buffers for
    2282                 :             :  * aligning short-varlena inputs, but this has not so far been considered to
    2283                 :             :  * be worth the effort.
    2284                 :             :  */
    2285                 :             : static int
    2286                 :    17208105 : numeric_fast_cmp(Datum x, Datum y, SortSupport ssup)
    2287                 :             : {
    2288                 :    17208105 :     Numeric     nx = DatumGetNumeric(x);
    2289                 :    17208105 :     Numeric     ny = DatumGetNumeric(y);
    2290                 :             :     int         result;
    2291                 :             : 
    2292                 :    17208105 :     result = cmp_numerics(nx, ny);
    2293                 :             : 
    2294         [ +  + ]:    17208105 :     if (nx != DatumGetPointer(x))
    2295                 :     7409856 :         pfree(nx);
    2296         [ +  + ]:    17208105 :     if (ny != DatumGetPointer(y))
    2297                 :     7409852 :         pfree(ny);
    2298                 :             : 
    2299                 :    17208105 :     return result;
    2300                 :             : }
    2301                 :             : 
    2302                 :             : /*
    2303                 :             :  * Compare abbreviations of values. (Abbreviations may be equal where the true
    2304                 :             :  * values differ, but if the abbreviations differ, they must reflect the
    2305                 :             :  * ordering of the true values.)
    2306                 :             :  */
    2307                 :             : static int
    2308                 :      125715 : numeric_cmp_abbrev(Datum x, Datum y, SortSupport ssup)
    2309                 :             : {
    2310                 :             :     /*
    2311                 :             :      * NOTE WELL: this is intentionally backwards, because the abbreviation is
    2312                 :             :      * negated relative to the original value, to handle NaN/infinity cases.
    2313                 :             :      */
    2314         [ +  + ]:      125715 :     if (DatumGetNumericAbbrev(x) < DatumGetNumericAbbrev(y))
    2315                 :       64703 :         return 1;
    2316         [ +  + ]:       61012 :     if (DatumGetNumericAbbrev(x) > DatumGetNumericAbbrev(y))
    2317                 :       60866 :         return -1;
    2318                 :         146 :     return 0;
    2319                 :             : }
    2320                 :             : 
    2321                 :             : /*
    2322                 :             :  * Abbreviate a NumericVar into the 64-bit sortsupport size.
    2323                 :             :  *
    2324                 :             :  * The 31-bit value is constructed as:
    2325                 :             :  *
    2326                 :             :  *  0 + 7bits digit weight + 24 bits digit value
    2327                 :             :  *
    2328                 :             :  * where the digit weight is in single decimal digits, not digit words, and
    2329                 :             :  * stored in excess-44 representation[1]. The 24-bit digit value is the 7 most
    2330                 :             :  * significant decimal digits of the value converted to binary. Values whose
    2331                 :             :  * weights would fall outside the representable range are rounded off to zero
    2332                 :             :  * (which is also used to represent actual zeros) or to 0x7FFFFFFF (which
    2333                 :             :  * otherwise cannot occur). Abbreviation therefore fails to gain any advantage
    2334                 :             :  * where values are outside the range 10^-44 to 10^83, which is not considered
    2335                 :             :  * to be a serious limitation, or when values are of the same magnitude and
    2336                 :             :  * equal in the first 7 decimal digits, which is considered to be an
    2337                 :             :  * unavoidable limitation given the available bits. (Stealing three more bits
    2338                 :             :  * to compare another digit would narrow the range of representable weights by
    2339                 :             :  * a factor of 8, which starts to look like a real limiting factor.)
    2340                 :             :  *
    2341                 :             :  * (The value 44 for the excess is essentially arbitrary)
    2342                 :             :  *
    2343                 :             :  * The 63-bit value is constructed as:
    2344                 :             :  *
    2345                 :             :  *  0 + 7bits weight + 4 x 14-bit packed digit words
    2346                 :             :  *
    2347                 :             :  * The weight in this case is again stored in excess-44, but this time it is
    2348                 :             :  * the original weight in digit words (i.e. powers of 10000). The first four
    2349                 :             :  * digit words of the value (if present; trailing zeros are assumed as needed)
    2350                 :             :  * are packed into 14 bits each to form the rest of the value. Again,
    2351                 :             :  * out-of-range values are rounded off to 0 or 0x7FFFFFFFFFFFFFFF. The
    2352                 :             :  * representable range in this case is 10^-176 to 10^332, which is considered
    2353                 :             :  * to be good enough for all practical purposes, and comparison of 4 words
    2354                 :             :  * means that at least 13 decimal digits are compared, which is considered to
    2355                 :             :  * be a reasonable compromise between effectiveness and efficiency in computing
    2356                 :             :  * the abbreviation.
    2357                 :             :  *
    2358                 :             :  * (The value 44 for the excess is even more arbitrary here, it was chosen just
    2359                 :             :  * to match the value used in the 31-bit case)
    2360                 :             :  *
    2361                 :             :  * [1] - Excess-k representation means that the value is offset by adding 'k'
    2362                 :             :  * and then treated as unsigned, so the smallest representable value is stored
    2363                 :             :  * with all bits zero. This allows simple comparisons to work on the composite
    2364                 :             :  * value.
    2365                 :             :  */
    2366                 :             : static Datum
    2367                 :       12679 : numeric_abbrev_convert_var(const NumericVar *var, NumericSortSupport *nss)
    2368                 :             : {
    2369                 :       12679 :     int         ndigits = var->ndigits;
    2370                 :       12679 :     int         weight = var->weight;
    2371                 :             :     int64       result;
    2372                 :             : 
    2373   [ +  +  -  + ]:       12679 :     if (ndigits == 0 || weight < -44)
    2374                 :             :     {
    2375                 :          34 :         result = 0;
    2376                 :             :     }
    2377         [ +  + ]:       12645 :     else if (weight > 83)
    2378                 :             :     {
    2379                 :           8 :         result = PG_INT64_MAX;
    2380                 :             :     }
    2381                 :             :     else
    2382                 :             :     {
    2383                 :       12637 :         result = ((int64) (weight + 44) << 56);
    2384                 :             : 
    2385   [ -  +  +  + ]:       12637 :         switch (ndigits)
    2386                 :             :         {
    2387                 :           0 :             default:
    2388                 :           0 :                 result |= ((int64) var->digits[3]);
    2389                 :             :                 pg_fallthrough;
    2390                 :        4138 :             case 3:
    2391                 :        4138 :                 result |= ((int64) var->digits[2]) << 14;
    2392                 :             :                 pg_fallthrough;
    2393                 :       12220 :             case 2:
    2394                 :       12220 :                 result |= ((int64) var->digits[1]) << 28;
    2395                 :             :                 pg_fallthrough;
    2396                 :       12637 :             case 1:
    2397                 :       12637 :                 result |= ((int64) var->digits[0]) << 42;
    2398                 :       12637 :                 break;
    2399                 :             :         }
    2400                 :             :     }
    2401                 :             : 
    2402                 :             :     /* the abbrev is negated relative to the original */
    2403         [ +  + ]:       12679 :     if (var->sign == NUMERIC_POS)
    2404                 :       12615 :         result = -result;
    2405                 :             : 
    2406         [ +  - ]:       12679 :     if (nss->estimating)
    2407                 :             :     {
    2408                 :       12679 :         uint32      tmp = ((uint32) result
    2409                 :       12679 :                            ^ (uint32) ((uint64) result >> 32));
    2410                 :             : 
    2411                 :       12679 :         addHyperLogLog(&nss->abbr_card, DatumGetUInt32(hash_uint32(tmp)));
    2412                 :             :     }
    2413                 :             : 
    2414                 :       12679 :     return NumericAbbrevGetDatum(result);
    2415                 :             : }
    2416                 :             : 
    2417                 :             : 
    2418                 :             : /*
    2419                 :             :  * Ordinary (non-sortsupport) comparisons follow.
    2420                 :             :  */
    2421                 :             : 
    2422                 :             : Datum
    2423                 :      486958 : numeric_cmp(PG_FUNCTION_ARGS)
    2424                 :             : {
    2425                 :      486958 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    2426                 :      486958 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    2427                 :             :     int         result;
    2428                 :             : 
    2429                 :      486958 :     result = cmp_numerics(num1, num2);
    2430                 :             : 
    2431         [ +  + ]:      486958 :     PG_FREE_IF_COPY(num1, 0);
    2432         [ +  + ]:      486958 :     PG_FREE_IF_COPY(num2, 1);
    2433                 :             : 
    2434                 :      486958 :     PG_RETURN_INT32(result);
    2435                 :             : }
    2436                 :             : 
    2437                 :             : 
    2438                 :             : Datum
    2439                 :      428523 : numeric_eq(PG_FUNCTION_ARGS)
    2440                 :             : {
    2441                 :      428523 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    2442                 :      428523 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    2443                 :             :     bool        result;
    2444                 :             : 
    2445                 :      428523 :     result = cmp_numerics(num1, num2) == 0;
    2446                 :             : 
    2447         [ +  + ]:      428523 :     PG_FREE_IF_COPY(num1, 0);
    2448         [ +  + ]:      428523 :     PG_FREE_IF_COPY(num2, 1);
    2449                 :             : 
    2450                 :      428523 :     PG_RETURN_BOOL(result);
    2451                 :             : }
    2452                 :             : 
    2453                 :             : Datum
    2454                 :        3584 : numeric_ne(PG_FUNCTION_ARGS)
    2455                 :             : {
    2456                 :        3584 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    2457                 :        3584 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    2458                 :             :     bool        result;
    2459                 :             : 
    2460                 :        3584 :     result = cmp_numerics(num1, num2) != 0;
    2461                 :             : 
    2462         [ +  + ]:        3584 :     PG_FREE_IF_COPY(num1, 0);
    2463         [ +  + ]:        3584 :     PG_FREE_IF_COPY(num2, 1);
    2464                 :             : 
    2465                 :        3584 :     PG_RETURN_BOOL(result);
    2466                 :             : }
    2467                 :             : 
    2468                 :             : Datum
    2469                 :       33690 : numeric_gt(PG_FUNCTION_ARGS)
    2470                 :             : {
    2471                 :       33690 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    2472                 :       33690 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    2473                 :             :     bool        result;
    2474                 :             : 
    2475                 :       33690 :     result = cmp_numerics(num1, num2) > 0;
    2476                 :             : 
    2477         [ +  + ]:       33690 :     PG_FREE_IF_COPY(num1, 0);
    2478         [ +  + ]:       33690 :     PG_FREE_IF_COPY(num2, 1);
    2479                 :             : 
    2480                 :       33690 :     PG_RETURN_BOOL(result);
    2481                 :             : }
    2482                 :             : 
    2483                 :             : Datum
    2484                 :        7947 : numeric_ge(PG_FUNCTION_ARGS)
    2485                 :             : {
    2486                 :        7947 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    2487                 :        7947 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    2488                 :             :     bool        result;
    2489                 :             : 
    2490                 :        7947 :     result = cmp_numerics(num1, num2) >= 0;
    2491                 :             : 
    2492         [ +  + ]:        7947 :     PG_FREE_IF_COPY(num1, 0);
    2493         [ -  + ]:        7947 :     PG_FREE_IF_COPY(num2, 1);
    2494                 :             : 
    2495                 :        7947 :     PG_RETURN_BOOL(result);
    2496                 :             : }
    2497                 :             : 
    2498                 :             : Datum
    2499                 :      198895 : numeric_lt(PG_FUNCTION_ARGS)
    2500                 :             : {
    2501                 :      198895 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    2502                 :      198895 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    2503                 :             :     bool        result;
    2504                 :             : 
    2505                 :      198895 :     result = cmp_numerics(num1, num2) < 0;
    2506                 :             : 
    2507         [ +  + ]:      198895 :     PG_FREE_IF_COPY(num1, 0);
    2508         [ +  + ]:      198895 :     PG_FREE_IF_COPY(num2, 1);
    2509                 :             : 
    2510                 :      198895 :     PG_RETURN_BOOL(result);
    2511                 :             : }
    2512                 :             : 
    2513                 :             : Datum
    2514                 :        9938 : numeric_le(PG_FUNCTION_ARGS)
    2515                 :             : {
    2516                 :        9938 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    2517                 :        9938 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    2518                 :             :     bool        result;
    2519                 :             : 
    2520                 :        9938 :     result = cmp_numerics(num1, num2) <= 0;
    2521                 :             : 
    2522         [ +  + ]:        9938 :     PG_FREE_IF_COPY(num1, 0);
    2523         [ +  + ]:        9938 :     PG_FREE_IF_COPY(num2, 1);
    2524                 :             : 
    2525                 :        9938 :     PG_RETURN_BOOL(result);
    2526                 :             : }
    2527                 :             : 
    2528                 :             : static int
    2529                 :    18392025 : cmp_numerics(Numeric num1, Numeric num2)
    2530                 :             : {
    2531                 :             :     int         result;
    2532                 :             : 
    2533                 :             :     /*
    2534                 :             :      * We consider all NANs to be equal and larger than any non-NAN (including
    2535                 :             :      * Infinity).  This is somewhat arbitrary; the important thing is to have
    2536                 :             :      * a consistent sort order.
    2537                 :             :      */
    2538         [ +  + ]:    18392025 :     if (NUMERIC_IS_SPECIAL(num1))
    2539                 :             :     {
    2540         [ +  + ]:        2104 :         if (NUMERIC_IS_NAN(num1))
    2541                 :             :         {
    2542         [ +  + ]:        1015 :             if (NUMERIC_IS_NAN(num2))
    2543                 :         476 :                 result = 0;     /* NAN = NAN */
    2544                 :             :             else
    2545                 :         539 :                 result = 1;     /* NAN > non-NAN */
    2546                 :             :         }
    2547         [ +  + ]:        1089 :         else if (NUMERIC_IS_PINF(num1))
    2548                 :             :         {
    2549         [ +  + ]:          87 :             if (NUMERIC_IS_NAN(num2))
    2550                 :          14 :                 result = -1;    /* PINF < NAN */
    2551         [ +  + ]:          73 :             else if (NUMERIC_IS_PINF(num2))
    2552                 :           4 :                 result = 0;     /* PINF = PINF */
    2553                 :             :             else
    2554                 :          69 :                 result = 1;     /* PINF > anything else */
    2555                 :             :         }
    2556                 :             :         else                    /* num1 must be NINF */
    2557                 :             :         {
    2558         [ +  + ]:        1002 :             if (NUMERIC_IS_NINF(num2))
    2559                 :           4 :                 result = 0;     /* NINF = NINF */
    2560                 :             :             else
    2561                 :         998 :                 result = -1;    /* NINF < anything else */
    2562                 :             :         }
    2563                 :             :     }
    2564         [ +  + ]:    18389921 :     else if (NUMERIC_IS_SPECIAL(num2))
    2565                 :             :     {
    2566         [ +  + ]:        7920 :         if (NUMERIC_IS_NINF(num2))
    2567                 :          12 :             result = 1;         /* normal > NINF */
    2568                 :             :         else
    2569                 :        7908 :             result = -1;        /* normal < NAN or PINF */
    2570                 :             :     }
    2571                 :             :     else
    2572                 :             :     {
    2573   [ +  +  +  + ]:    36764626 :         result = cmp_var_common(NUMERIC_DIGITS(num1), NUMERIC_NDIGITS(num1),
    2574   [ +  +  -  +  :    18382199 :                                 NUMERIC_WEIGHT(num1), NUMERIC_SIGN(num1),
             +  +  +  + ]
    2575   [ +  +  +  + ]:    18382001 :                                 NUMERIC_DIGITS(num2), NUMERIC_NDIGITS(num2),
    2576   [ +  +  -  +  :    18382427 :                                 NUMERIC_WEIGHT(num2), NUMERIC_SIGN(num2));
             +  +  +  + ]
    2577                 :             :     }
    2578                 :             : 
    2579                 :    18392025 :     return result;
    2580                 :             : }
    2581                 :             : 
    2582                 :             : /*
    2583                 :             :  * in_range support function for numeric.
    2584                 :             :  */
    2585                 :             : Datum
    2586                 :         768 : in_range_numeric_numeric(PG_FUNCTION_ARGS)
    2587                 :             : {
    2588                 :         768 :     Numeric     val = PG_GETARG_NUMERIC(0);
    2589                 :         768 :     Numeric     base = PG_GETARG_NUMERIC(1);
    2590                 :         768 :     Numeric     offset = PG_GETARG_NUMERIC(2);
    2591                 :         768 :     bool        sub = PG_GETARG_BOOL(3);
    2592                 :         768 :     bool        less = PG_GETARG_BOOL(4);
    2593                 :             :     bool        result;
    2594                 :             : 
    2595                 :             :     /*
    2596                 :             :      * Reject negative (including -Inf) or NaN offset.  Negative is per spec,
    2597                 :             :      * and NaN is because appropriate semantics for that seem non-obvious.
    2598                 :             :      */
    2599         [ +  + ]:         768 :     if (NUMERIC_IS_NAN(offset) ||
    2600         [ +  - ]:         764 :         NUMERIC_IS_NINF(offset) ||
    2601   [ +  +  -  +  :         764 :         NUMERIC_SIGN(offset) == NUMERIC_NEG)
          +  -  -  +  -  
                      - ]
    2602         [ +  - ]:           4 :         ereport(ERROR,
    2603                 :             :                 (errcode(ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE),
    2604                 :             :                  errmsg("invalid preceding or following size in window function")));
    2605                 :             : 
    2606                 :             :     /*
    2607                 :             :      * Deal with cases where val and/or base is NaN, following the rule that
    2608                 :             :      * NaN sorts after non-NaN (cf cmp_numerics).  The offset cannot affect
    2609                 :             :      * the conclusion.
    2610                 :             :      */
    2611         [ +  + ]:         764 :     if (NUMERIC_IS_NAN(val))
    2612                 :             :     {
    2613         [ +  + ]:         124 :         if (NUMERIC_IS_NAN(base))
    2614                 :          40 :             result = true;      /* NAN = NAN */
    2615                 :             :         else
    2616                 :          84 :             result = !less;     /* NAN > non-NAN */
    2617                 :             :     }
    2618         [ +  + ]:         640 :     else if (NUMERIC_IS_NAN(base))
    2619                 :             :     {
    2620                 :          84 :         result = less;          /* non-NAN < NAN */
    2621                 :             :     }
    2622                 :             : 
    2623                 :             :     /*
    2624                 :             :      * Deal with infinite offset (necessarily +Inf, at this point).
    2625                 :             :      */
    2626         [ +  + ]:         556 :     else if (NUMERIC_IS_SPECIAL(offset))
    2627                 :             :     {
    2628                 :             :         Assert(NUMERIC_IS_PINF(offset));
    2629   [ +  +  +  + ]:         280 :         if (sub ? NUMERIC_IS_PINF(base) : NUMERIC_IS_NINF(base))
    2630                 :             :         {
    2631                 :             :             /*
    2632                 :             :              * base +/- offset would produce NaN, so return true for any val
    2633                 :             :              * (see in_range_float8_float8() for reasoning).
    2634                 :             :              */
    2635                 :         116 :             result = true;
    2636                 :             :         }
    2637         [ +  + ]:         164 :         else if (sub)
    2638                 :             :         {
    2639                 :             :             /* base - offset must be -inf */
    2640         [ +  + ]:         100 :             if (less)
    2641                 :          36 :                 result = NUMERIC_IS_NINF(val);  /* only -inf is <= sum */
    2642                 :             :             else
    2643                 :          64 :                 result = true;  /* any val is >= sum */
    2644                 :             :         }
    2645                 :             :         else
    2646                 :             :         {
    2647                 :             :             /* base + offset must be +inf */
    2648         [ -  + ]:          64 :             if (less)
    2649                 :           0 :                 result = true;  /* any val is <= sum */
    2650                 :             :             else
    2651                 :          64 :                 result = NUMERIC_IS_PINF(val);  /* only +inf is >= sum */
    2652                 :             :         }
    2653                 :             :     }
    2654                 :             : 
    2655                 :             :     /*
    2656                 :             :      * Deal with cases where val and/or base is infinite.  The offset, being
    2657                 :             :      * now known finite, cannot affect the conclusion.
    2658                 :             :      */
    2659         [ +  + ]:         276 :     else if (NUMERIC_IS_SPECIAL(val))
    2660                 :             :     {
    2661         [ +  + ]:          52 :         if (NUMERIC_IS_PINF(val))
    2662                 :             :         {
    2663         [ +  + ]:          24 :             if (NUMERIC_IS_PINF(base))
    2664                 :          16 :                 result = true;  /* PINF = PINF */
    2665                 :             :             else
    2666                 :           8 :                 result = !less; /* PINF > any other non-NAN */
    2667                 :             :         }
    2668                 :             :         else                    /* val must be NINF */
    2669                 :             :         {
    2670         [ +  + ]:          28 :             if (NUMERIC_IS_NINF(base))
    2671                 :          20 :                 result = true;  /* NINF = NINF */
    2672                 :             :             else
    2673                 :           8 :                 result = less;  /* NINF < anything else */
    2674                 :             :         }
    2675                 :             :     }
    2676         [ +  + ]:         224 :     else if (NUMERIC_IS_SPECIAL(base))
    2677                 :             :     {
    2678         [ +  + ]:          16 :         if (NUMERIC_IS_NINF(base))
    2679                 :           8 :             result = !less;     /* normal > NINF */
    2680                 :             :         else
    2681                 :           8 :             result = less;      /* normal < PINF */
    2682                 :             :     }
    2683                 :             :     else
    2684                 :             :     {
    2685                 :             :         /*
    2686                 :             :          * Otherwise go ahead and compute base +/- offset.  While it's
    2687                 :             :          * possible for this to overflow the numeric format, it's unlikely
    2688                 :             :          * enough that we don't take measures to prevent it.
    2689                 :             :          */
    2690                 :             :         NumericVar  valv;
    2691                 :             :         NumericVar  basev;
    2692                 :             :         NumericVar  offsetv;
    2693                 :             :         NumericVar  sum;
    2694                 :             : 
    2695                 :         208 :         init_var_from_num(val, &valv);
    2696                 :         208 :         init_var_from_num(base, &basev);
    2697                 :         208 :         init_var_from_num(offset, &offsetv);
    2698                 :         208 :         init_var(&sum);
    2699                 :             : 
    2700         [ +  + ]:         208 :         if (sub)
    2701                 :         104 :             sub_var(&basev, &offsetv, &sum);
    2702                 :             :         else
    2703                 :         104 :             add_var(&basev, &offsetv, &sum);
    2704                 :             : 
    2705         [ +  + ]:         208 :         if (less)
    2706                 :         104 :             result = (cmp_var(&valv, &sum) <= 0);
    2707                 :             :         else
    2708                 :         104 :             result = (cmp_var(&valv, &sum) >= 0);
    2709                 :             : 
    2710                 :         208 :         free_var(&sum);
    2711                 :             :     }
    2712                 :             : 
    2713         [ +  - ]:         764 :     PG_FREE_IF_COPY(val, 0);
    2714         [ +  - ]:         764 :     PG_FREE_IF_COPY(base, 1);
    2715         [ -  + ]:         764 :     PG_FREE_IF_COPY(offset, 2);
    2716                 :             : 
    2717                 :         764 :     PG_RETURN_BOOL(result);
    2718                 :             : }
    2719                 :             : 
    2720                 :             : Datum
    2721                 :      405116 : hash_numeric(PG_FUNCTION_ARGS)
    2722                 :             : {
    2723                 :      405116 :     Numeric     key = PG_GETARG_NUMERIC(0);
    2724                 :             :     Datum       digit_hash;
    2725                 :             :     Datum       result;
    2726                 :             :     int         weight;
    2727                 :             :     int         start_offset;
    2728                 :             :     int         end_offset;
    2729                 :             :     int         i;
    2730                 :             :     int         hash_len;
    2731                 :             :     NumericDigit *digits;
    2732                 :             : 
    2733                 :             :     /* If it's NaN or infinity, don't try to hash the rest of the fields */
    2734         [ -  + ]:      405116 :     if (NUMERIC_IS_SPECIAL(key))
    2735                 :           0 :         PG_RETURN_UINT32(0);
    2736                 :             : 
    2737   [ +  -  +  + ]:      405116 :     weight = NUMERIC_WEIGHT(key);
    2738                 :      405116 :     start_offset = 0;
    2739                 :      405116 :     end_offset = 0;
    2740                 :             : 
    2741                 :             :     /*
    2742                 :             :      * Omit any leading or trailing zeros from the input to the hash. The
    2743                 :             :      * numeric implementation *should* guarantee that leading and trailing
    2744                 :             :      * zeros are suppressed, but we're paranoid. Note that we measure the
    2745                 :             :      * starting and ending offsets in units of NumericDigits, not bytes.
    2746                 :             :      */
    2747         [ +  - ]:      405116 :     digits = NUMERIC_DIGITS(key);
    2748   [ +  -  +  + ]:      405116 :     for (i = 0; i < NUMERIC_NDIGITS(key); i++)
    2749                 :             :     {
    2750         [ +  - ]:      404018 :         if (digits[i] != (NumericDigit) 0)
    2751                 :      404018 :             break;
    2752                 :             : 
    2753                 :           0 :         start_offset++;
    2754                 :             : 
    2755                 :             :         /*
    2756                 :             :          * The weight is effectively the # of digits before the decimal point,
    2757                 :             :          * so decrement it for each leading zero we skip.
    2758                 :             :          */
    2759                 :           0 :         weight--;
    2760                 :             :     }
    2761                 :             : 
    2762                 :             :     /*
    2763                 :             :      * If there are no non-zero digits, then the value of the number is zero,
    2764                 :             :      * regardless of any other fields.
    2765                 :             :      */
    2766   [ +  -  +  + ]:      405116 :     if (NUMERIC_NDIGITS(key) == start_offset)
    2767                 :        1098 :         PG_RETURN_UINT32(-1);
    2768                 :             : 
    2769   [ +  -  +  - ]:      404018 :     for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--)
    2770                 :             :     {
    2771         [ +  - ]:      404018 :         if (digits[i] != (NumericDigit) 0)
    2772                 :      404018 :             break;
    2773                 :             : 
    2774                 :           0 :         end_offset++;
    2775                 :             :     }
    2776                 :             : 
    2777                 :             :     /* If we get here, there should be at least one non-zero digit */
    2778                 :             :     Assert(start_offset + end_offset < NUMERIC_NDIGITS(key));
    2779                 :             : 
    2780                 :             :     /*
    2781                 :             :      * Note that we don't hash on the Numeric's scale, since two numerics can
    2782                 :             :      * compare equal but have different scales. We also don't hash on the
    2783                 :             :      * sign, although we could: since a sign difference implies inequality,
    2784                 :             :      * this shouldn't affect correctness.
    2785                 :             :      */
    2786         [ +  - ]:      404018 :     hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset;
    2787         [ +  - ]:      404018 :     digit_hash = hash_any((unsigned char *) (NUMERIC_DIGITS(key) + start_offset),
    2788                 :             :                           hash_len * sizeof(NumericDigit));
    2789                 :             : 
    2790                 :             :     /* Mix in the weight, via XOR */
    2791                 :      404018 :     result = digit_hash ^ weight;
    2792                 :             : 
    2793                 :      404018 :     PG_RETURN_DATUM(result);
    2794                 :             : }
    2795                 :             : 
    2796                 :             : /*
    2797                 :             :  * Returns 64-bit value by hashing a value to a 64-bit value, with a seed.
    2798                 :             :  * Otherwise, similar to hash_numeric.
    2799                 :             :  */
    2800                 :             : Datum
    2801                 :          56 : hash_numeric_extended(PG_FUNCTION_ARGS)
    2802                 :             : {
    2803                 :          56 :     Numeric     key = PG_GETARG_NUMERIC(0);
    2804                 :          56 :     uint64      seed = PG_GETARG_INT64(1);
    2805                 :             :     Datum       digit_hash;
    2806                 :             :     Datum       result;
    2807                 :             :     int         weight;
    2808                 :             :     int         start_offset;
    2809                 :             :     int         end_offset;
    2810                 :             :     int         i;
    2811                 :             :     int         hash_len;
    2812                 :             :     NumericDigit *digits;
    2813                 :             : 
    2814                 :             :     /* If it's NaN or infinity, don't try to hash the rest of the fields */
    2815         [ -  + ]:          56 :     if (NUMERIC_IS_SPECIAL(key))
    2816                 :           0 :         PG_RETURN_UINT64(seed);
    2817                 :             : 
    2818   [ +  -  -  + ]:          56 :     weight = NUMERIC_WEIGHT(key);
    2819                 :          56 :     start_offset = 0;
    2820                 :          56 :     end_offset = 0;
    2821                 :             : 
    2822         [ +  - ]:          56 :     digits = NUMERIC_DIGITS(key);
    2823   [ +  -  +  + ]:          56 :     for (i = 0; i < NUMERIC_NDIGITS(key); i++)
    2824                 :             :     {
    2825         [ +  - ]:          48 :         if (digits[i] != (NumericDigit) 0)
    2826                 :          48 :             break;
    2827                 :             : 
    2828                 :           0 :         start_offset++;
    2829                 :             : 
    2830                 :           0 :         weight--;
    2831                 :             :     }
    2832                 :             : 
    2833   [ +  -  +  + ]:          56 :     if (NUMERIC_NDIGITS(key) == start_offset)
    2834                 :           8 :         PG_RETURN_UINT64(seed - 1);
    2835                 :             : 
    2836   [ +  -  +  - ]:          48 :     for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--)
    2837                 :             :     {
    2838         [ +  - ]:          48 :         if (digits[i] != (NumericDigit) 0)
    2839                 :          48 :             break;
    2840                 :             : 
    2841                 :           0 :         end_offset++;
    2842                 :             :     }
    2843                 :             : 
    2844                 :             :     Assert(start_offset + end_offset < NUMERIC_NDIGITS(key));
    2845                 :             : 
    2846         [ +  - ]:          48 :     hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset;
    2847         [ +  - ]:          48 :     digit_hash = hash_any_extended((unsigned char *) (NUMERIC_DIGITS(key)
    2848                 :          48 :                                                       + start_offset),
    2849                 :             :                                    hash_len * sizeof(NumericDigit),
    2850                 :             :                                    seed);
    2851                 :             : 
    2852                 :          48 :     result = UInt64GetDatum(DatumGetUInt64(digit_hash) ^ weight);
    2853                 :             : 
    2854                 :          48 :     PG_RETURN_DATUM(result);
    2855                 :             : }
    2856                 :             : 
    2857                 :             : 
    2858                 :             : /* ----------------------------------------------------------------------
    2859                 :             :  *
    2860                 :             :  * Basic arithmetic functions
    2861                 :             :  *
    2862                 :             :  * ----------------------------------------------------------------------
    2863                 :             :  */
    2864                 :             : 
    2865                 :             : 
    2866                 :             : /*
    2867                 :             :  * numeric_add() -
    2868                 :             :  *
    2869                 :             :  *  Add two numerics
    2870                 :             :  */
    2871                 :             : Datum
    2872                 :      168448 : numeric_add(PG_FUNCTION_ARGS)
    2873                 :             : {
    2874                 :      168448 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    2875                 :      168448 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    2876                 :             :     Numeric     res;
    2877                 :             : 
    2878                 :      168448 :     res = numeric_add_safe(num1, num2, NULL);
    2879                 :             : 
    2880                 :      168448 :     PG_RETURN_NUMERIC(res);
    2881                 :             : }
    2882                 :             : 
    2883                 :             : /*
    2884                 :             :  * numeric_add_safe() -
    2885                 :             :  *
    2886                 :             :  *  Internal version of numeric_add() with support for soft error reporting.
    2887                 :             :  */
    2888                 :             : Numeric
    2889                 :      169358 : numeric_add_safe(Numeric num1, Numeric num2, Node *escontext)
    2890                 :             : {
    2891                 :             :     NumericVar  arg1;
    2892                 :             :     NumericVar  arg2;
    2893                 :             :     NumericVar  result;
    2894                 :             :     Numeric     res;
    2895                 :             : 
    2896                 :             :     /*
    2897                 :             :      * Handle NaN and infinities
    2898                 :             :      */
    2899   [ +  +  +  + ]:      169358 :     if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
    2900                 :             :     {
    2901   [ +  +  +  + ]:         132 :         if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
    2902                 :          52 :             return make_result(&const_nan);
    2903         [ +  + ]:          80 :         if (NUMERIC_IS_PINF(num1))
    2904                 :             :         {
    2905         [ +  + ]:          24 :             if (NUMERIC_IS_NINF(num2))
    2906                 :           4 :                 return make_result(&const_nan); /* Inf + -Inf */
    2907                 :             :             else
    2908                 :          20 :                 return make_result(&const_pinf);
    2909                 :             :         }
    2910         [ +  + ]:          56 :         if (NUMERIC_IS_NINF(num1))
    2911                 :             :         {
    2912         [ +  + ]:          24 :             if (NUMERIC_IS_PINF(num2))
    2913                 :           4 :                 return make_result(&const_nan); /* -Inf + Inf */
    2914                 :             :             else
    2915                 :          20 :                 return make_result(&const_ninf);
    2916                 :             :         }
    2917                 :             :         /* by here, num1 must be finite, so num2 is not */
    2918         [ +  + ]:          32 :         if (NUMERIC_IS_PINF(num2))
    2919                 :          16 :             return make_result(&const_pinf);
    2920                 :             :         Assert(NUMERIC_IS_NINF(num2));
    2921                 :          16 :         return make_result(&const_ninf);
    2922                 :             :     }
    2923                 :             : 
    2924                 :             :     /*
    2925                 :             :      * Unpack the values, let add_var() compute the result and return it.
    2926                 :             :      */
    2927                 :      169226 :     init_var_from_num(num1, &arg1);
    2928                 :      169226 :     init_var_from_num(num2, &arg2);
    2929                 :             : 
    2930                 :      169226 :     init_var(&result);
    2931                 :      169226 :     add_var(&arg1, &arg2, &result);
    2932                 :             : 
    2933                 :      169226 :     res = make_result_safe(&result, escontext);
    2934                 :             : 
    2935                 :      169226 :     free_var(&result);
    2936                 :             : 
    2937                 :      169226 :     return res;
    2938                 :             : }
    2939                 :             : 
    2940                 :             : 
    2941                 :             : /*
    2942                 :             :  * numeric_sub() -
    2943                 :             :  *
    2944                 :             :  *  Subtract one numeric from another
    2945                 :             :  */
    2946                 :             : Datum
    2947                 :       46512 : numeric_sub(PG_FUNCTION_ARGS)
    2948                 :             : {
    2949                 :       46512 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    2950                 :       46512 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    2951                 :             :     Numeric     res;
    2952                 :             : 
    2953                 :       46512 :     res = numeric_sub_safe(num1, num2, NULL);
    2954                 :             : 
    2955                 :       46512 :     PG_RETURN_NUMERIC(res);
    2956                 :             : }
    2957                 :             : 
    2958                 :             : 
    2959                 :             : /*
    2960                 :             :  * numeric_sub_safe() -
    2961                 :             :  *
    2962                 :             :  *  Internal version of numeric_sub() with support for soft error reporting.
    2963                 :             :  */
    2964                 :             : Numeric
    2965                 :       46816 : numeric_sub_safe(Numeric num1, Numeric num2, Node *escontext)
    2966                 :             : {
    2967                 :             :     NumericVar  arg1;
    2968                 :             :     NumericVar  arg2;
    2969                 :             :     NumericVar  result;
    2970                 :             :     Numeric     res;
    2971                 :             : 
    2972                 :             :     /*
    2973                 :             :      * Handle NaN and infinities
    2974                 :             :      */
    2975   [ +  +  +  + ]:       46816 :     if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
    2976                 :             :     {
    2977   [ +  +  +  + ]:         132 :         if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
    2978                 :          52 :             return make_result(&const_nan);
    2979         [ +  + ]:          80 :         if (NUMERIC_IS_PINF(num1))
    2980                 :             :         {
    2981         [ +  + ]:          24 :             if (NUMERIC_IS_PINF(num2))
    2982                 :           4 :                 return make_result(&const_nan); /* Inf - Inf */
    2983                 :             :             else
    2984                 :          20 :                 return make_result(&const_pinf);
    2985                 :             :         }
    2986         [ +  + ]:          56 :         if (NUMERIC_IS_NINF(num1))
    2987                 :             :         {
    2988         [ +  + ]:          24 :             if (NUMERIC_IS_NINF(num2))
    2989                 :           4 :                 return make_result(&const_nan); /* -Inf - -Inf */
    2990                 :             :             else
    2991                 :          20 :                 return make_result(&const_ninf);
    2992                 :             :         }
    2993                 :             :         /* by here, num1 must be finite, so num2 is not */
    2994         [ +  + ]:          32 :         if (NUMERIC_IS_PINF(num2))
    2995                 :          16 :             return make_result(&const_ninf);
    2996                 :             :         Assert(NUMERIC_IS_NINF(num2));
    2997                 :          16 :         return make_result(&const_pinf);
    2998                 :             :     }
    2999                 :             : 
    3000                 :             :     /*
    3001                 :             :      * Unpack the values, let sub_var() compute the result and return it.
    3002                 :             :      */
    3003                 :       46684 :     init_var_from_num(num1, &arg1);
    3004                 :       46684 :     init_var_from_num(num2, &arg2);
    3005                 :             : 
    3006                 :       46684 :     init_var(&result);
    3007                 :       46684 :     sub_var(&arg1, &arg2, &result);
    3008                 :             : 
    3009                 :       46684 :     res = make_result_safe(&result, escontext);
    3010                 :             : 
    3011                 :       46684 :     free_var(&result);
    3012                 :             : 
    3013                 :       46684 :     return res;
    3014                 :             : }
    3015                 :             : 
    3016                 :             : 
    3017                 :             : /*
    3018                 :             :  * numeric_mul() -
    3019                 :             :  *
    3020                 :             :  *  Calculate the product of two numerics
    3021                 :             :  */
    3022                 :             : Datum
    3023                 :      326759 : numeric_mul(PG_FUNCTION_ARGS)
    3024                 :             : {
    3025                 :      326759 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    3026                 :      326759 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    3027                 :             :     Numeric     res;
    3028                 :             : 
    3029                 :      326759 :     res = numeric_mul_safe(num1, num2, fcinfo->context);
    3030                 :             : 
    3031   [ -  +  -  -  :      326759 :     if (unlikely(SOFT_ERROR_OCCURRED(fcinfo->context)))
          -  +  -  -  -  
                      + ]
    3032                 :           0 :         PG_RETURN_NULL();
    3033                 :             : 
    3034                 :      326759 :     PG_RETURN_NUMERIC(res);
    3035                 :             : }
    3036                 :             : 
    3037                 :             : 
    3038                 :             : /*
    3039                 :             :  * numeric_mul_safe() -
    3040                 :             :  *
    3041                 :             :  *  Internal version of numeric_mul() with support for soft error reporting.
    3042                 :             :  */
    3043                 :             : Numeric
    3044                 :      326791 : numeric_mul_safe(Numeric num1, Numeric num2, Node *escontext)
    3045                 :             : {
    3046                 :             :     NumericVar  arg1;
    3047                 :             :     NumericVar  arg2;
    3048                 :             :     NumericVar  result;
    3049                 :             :     Numeric     res;
    3050                 :             : 
    3051                 :             :     /*
    3052                 :             :      * Handle NaN and infinities
    3053                 :             :      */
    3054   [ +  +  +  + ]:      326791 :     if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
    3055                 :             :     {
    3056   [ +  +  +  + ]:         132 :         if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
    3057                 :          52 :             return make_result(&const_nan);
    3058         [ +  + ]:          80 :         if (NUMERIC_IS_PINF(num1))
    3059                 :             :         {
    3060   [ +  +  +  - ]:          24 :             switch (numeric_sign_internal(num2))
    3061                 :             :             {
    3062                 :           4 :                 case 0:
    3063                 :           4 :                     return make_result(&const_nan); /* Inf * 0 */
    3064                 :          12 :                 case 1:
    3065                 :          12 :                     return make_result(&const_pinf);
    3066                 :           8 :                 case -1:
    3067                 :           8 :                     return make_result(&const_ninf);
    3068                 :             :             }
    3069                 :             :             Assert(false);
    3070                 :             :         }
    3071         [ +  + ]:          56 :         if (NUMERIC_IS_NINF(num1))
    3072                 :             :         {
    3073   [ +  +  +  - ]:          24 :             switch (numeric_sign_internal(num2))
    3074                 :             :             {
    3075                 :           4 :                 case 0:
    3076                 :           4 :                     return make_result(&const_nan); /* -Inf * 0 */
    3077                 :          12 :                 case 1:
    3078                 :          12 :                     return make_result(&const_ninf);
    3079                 :           8 :                 case -1:
    3080                 :           8 :                     return make_result(&const_pinf);
    3081                 :             :             }
    3082                 :             :             Assert(false);
    3083                 :             :         }
    3084                 :             :         /* by here, num1 must be finite, so num2 is not */
    3085         [ +  + ]:          32 :         if (NUMERIC_IS_PINF(num2))
    3086                 :             :         {
    3087   [ +  +  +  - ]:          16 :             switch (numeric_sign_internal(num1))
    3088                 :             :             {
    3089                 :           4 :                 case 0:
    3090                 :           4 :                     return make_result(&const_nan); /* 0 * Inf */
    3091                 :           8 :                 case 1:
    3092                 :           8 :                     return make_result(&const_pinf);
    3093                 :           4 :                 case -1:
    3094                 :           4 :                     return make_result(&const_ninf);
    3095                 :             :             }
    3096                 :             :             Assert(false);
    3097                 :             :         }
    3098                 :             :         Assert(NUMERIC_IS_NINF(num2));
    3099   [ +  +  +  - ]:          16 :         switch (numeric_sign_internal(num1))
    3100                 :             :         {
    3101                 :           4 :             case 0:
    3102                 :           4 :                 return make_result(&const_nan); /* 0 * -Inf */
    3103                 :           8 :             case 1:
    3104                 :           8 :                 return make_result(&const_ninf);
    3105                 :           4 :             case -1:
    3106                 :           4 :                 return make_result(&const_pinf);
    3107                 :             :         }
    3108                 :             :         Assert(false);
    3109                 :             :     }
    3110                 :             : 
    3111                 :             :     /*
    3112                 :             :      * Unpack the values, let mul_var() compute the result and return it.
    3113                 :             :      * Unlike add_var() and sub_var(), mul_var() will round its result. In the
    3114                 :             :      * case of numeric_mul(), which is invoked for the * operator on numerics,
    3115                 :             :      * we request exact representation for the product (rscale = sum(dscale of
    3116                 :             :      * arg1, dscale of arg2)).  If the exact result has more digits after the
    3117                 :             :      * decimal point than can be stored in a numeric, we round it.  Rounding
    3118                 :             :      * after computing the exact result ensures that the final result is
    3119                 :             :      * correctly rounded (rounding in mul_var() using a truncated product
    3120                 :             :      * would not guarantee this).
    3121                 :             :      */
    3122                 :      326659 :     init_var_from_num(num1, &arg1);
    3123                 :      326659 :     init_var_from_num(num2, &arg2);
    3124                 :             : 
    3125                 :      326659 :     init_var(&result);
    3126                 :      326659 :     mul_var(&arg1, &arg2, &result, arg1.dscale + arg2.dscale);
    3127                 :             : 
    3128         [ +  + ]:      326659 :     if (result.dscale > NUMERIC_DSCALE_MAX)
    3129                 :           5 :         round_var(&result, NUMERIC_DSCALE_MAX);
    3130                 :             : 
    3131                 :      326659 :     res = make_result_safe(&result, escontext);
    3132                 :             : 
    3133                 :      326659 :     free_var(&result);
    3134                 :             : 
    3135                 :      326659 :     return res;
    3136                 :             : }
    3137                 :             : 
    3138                 :             : 
    3139                 :             : /*
    3140                 :             :  * numeric_div() -
    3141                 :             :  *
    3142                 :             :  *  Divide one numeric into another
    3143                 :             :  */
    3144                 :             : Datum
    3145                 :       98474 : numeric_div(PG_FUNCTION_ARGS)
    3146                 :             : {
    3147                 :       98474 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    3148                 :       98474 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    3149                 :             :     Numeric     res;
    3150                 :             : 
    3151                 :       98474 :     res = numeric_div_safe(num1, num2, NULL);
    3152                 :             : 
    3153                 :       98453 :     PG_RETURN_NUMERIC(res);
    3154                 :             : }
    3155                 :             : 
    3156                 :             : 
    3157                 :             : /*
    3158                 :             :  * numeric_div_safe() -
    3159                 :             :  *
    3160                 :             :  *  Internal version of numeric_div() with support for soft error reporting.
    3161                 :             :  */
    3162                 :             : Numeric
    3163                 :       99035 : numeric_div_safe(Numeric num1, Numeric num2, Node *escontext)
    3164                 :             : {
    3165                 :             :     NumericVar  arg1;
    3166                 :             :     NumericVar  arg2;
    3167                 :             :     NumericVar  result;
    3168                 :             :     Numeric     res;
    3169                 :             :     int         rscale;
    3170                 :             : 
    3171                 :             :     /*
    3172                 :             :      * Handle NaN and infinities
    3173                 :             :      */
    3174   [ +  +  +  + ]:       99035 :     if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
    3175                 :             :     {
    3176   [ +  +  +  + ]:         133 :         if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
    3177                 :          53 :             return make_result(&const_nan);
    3178         [ +  + ]:          80 :         if (NUMERIC_IS_PINF(num1))
    3179                 :             :         {
    3180         [ +  + ]:          24 :             if (NUMERIC_IS_SPECIAL(num2))
    3181                 :           8 :                 return make_result(&const_nan); /* Inf / [-]Inf */
    3182   [ +  +  +  - ]:          16 :             switch (numeric_sign_internal(num2))
    3183                 :             :             {
    3184                 :           4 :                 case 0:
    3185                 :           4 :                     goto division_by_zero;
    3186                 :           8 :                 case 1:
    3187                 :           8 :                     return make_result(&const_pinf);
    3188                 :           4 :                 case -1:
    3189                 :           4 :                     return make_result(&const_ninf);
    3190                 :             :             }
    3191                 :             :             Assert(false);
    3192                 :             :         }
    3193         [ +  + ]:          56 :         if (NUMERIC_IS_NINF(num1))
    3194                 :             :         {
    3195         [ +  + ]:          24 :             if (NUMERIC_IS_SPECIAL(num2))
    3196                 :           8 :                 return make_result(&const_nan); /* -Inf / [-]Inf */
    3197   [ +  +  +  - ]:          16 :             switch (numeric_sign_internal(num2))
    3198                 :             :             {
    3199                 :           4 :                 case 0:
    3200                 :           4 :                     goto division_by_zero;
    3201                 :           8 :                 case 1:
    3202                 :           8 :                     return make_result(&const_ninf);
    3203                 :           4 :                 case -1:
    3204                 :           4 :                     return make_result(&const_pinf);
    3205                 :             :             }
    3206                 :             :             Assert(false);
    3207                 :             :         }
    3208                 :             :         /* by here, num1 must be finite, so num2 is not */
    3209                 :             : 
    3210                 :             :         /*
    3211                 :             :          * POSIX would have us return zero or minus zero if num1 is zero, and
    3212                 :             :          * otherwise throw an underflow error.  But the numeric type doesn't
    3213                 :             :          * really do underflow, so let's just return zero.
    3214                 :             :          */
    3215                 :          32 :         return make_result(&const_zero);
    3216                 :             :     }
    3217                 :             : 
    3218                 :             :     /*
    3219                 :             :      * Unpack the arguments
    3220                 :             :      */
    3221                 :       98902 :     init_var_from_num(num1, &arg1);
    3222                 :       98902 :     init_var_from_num(num2, &arg2);
    3223                 :             : 
    3224                 :       98902 :     init_var(&result);
    3225                 :             : 
    3226                 :             :     /*
    3227                 :             :      * Select scale for division result
    3228                 :             :      */
    3229                 :       98902 :     rscale = select_div_scale(&arg1, &arg2);
    3230                 :             : 
    3231                 :             :     /* Check for division by zero */
    3232   [ +  +  -  + ]:       98902 :     if (arg2.ndigits == 0 || arg2.digits[0] == 0)
    3233                 :          33 :         goto division_by_zero;
    3234                 :             : 
    3235                 :             :     /*
    3236                 :             :      * Do the divide and return the result
    3237                 :             :      */
    3238                 :       98869 :     div_var(&arg1, &arg2, &result, rscale, true, true);
    3239                 :             : 
    3240                 :       98869 :     res = make_result_safe(&result, escontext);
    3241                 :             : 
    3242                 :       98869 :     free_var(&result);
    3243                 :             : 
    3244                 :       98869 :     return res;
    3245                 :             : 
    3246                 :          41 : division_by_zero:
    3247         [ +  + ]:          41 :     ereturn(escontext, NULL,
    3248                 :             :             errcode(ERRCODE_DIVISION_BY_ZERO),
    3249                 :             :             errmsg("division by zero"));
    3250                 :             : }
    3251                 :             : 
    3252                 :             : 
    3253                 :             : /*
    3254                 :             :  * numeric_div_trunc() -
    3255                 :             :  *
    3256                 :             :  *  Divide one numeric into another, truncating the result to an integer
    3257                 :             :  */
    3258                 :             : Datum
    3259                 :         822 : numeric_div_trunc(PG_FUNCTION_ARGS)
    3260                 :             : {
    3261                 :         822 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    3262                 :         822 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    3263                 :             :     NumericVar  arg1;
    3264                 :             :     NumericVar  arg2;
    3265                 :             :     NumericVar  result;
    3266                 :             :     Numeric     res;
    3267                 :             : 
    3268                 :             :     /*
    3269                 :             :      * Handle NaN and infinities
    3270                 :             :      */
    3271   [ +  +  +  + ]:         822 :     if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
    3272                 :             :     {
    3273   [ +  +  +  + ]:         133 :         if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
    3274                 :          53 :             PG_RETURN_NUMERIC(make_result(&const_nan));
    3275         [ +  + ]:          80 :         if (NUMERIC_IS_PINF(num1))
    3276                 :             :         {
    3277         [ +  + ]:          24 :             if (NUMERIC_IS_SPECIAL(num2))
    3278                 :           8 :                 PG_RETURN_NUMERIC(make_result(&const_nan)); /* Inf / [-]Inf */
    3279   [ +  +  +  - ]:          16 :             switch (numeric_sign_internal(num2))
    3280                 :             :             {
    3281                 :           4 :                 case 0:
    3282         [ +  - ]:           4 :                     ereport(ERROR,
    3283                 :             :                             (errcode(ERRCODE_DIVISION_BY_ZERO),
    3284                 :             :                              errmsg("division by zero")));
    3285                 :             :                     break;
    3286                 :           8 :                 case 1:
    3287                 :           8 :                     PG_RETURN_NUMERIC(make_result(&const_pinf));
    3288                 :           4 :                 case -1:
    3289                 :           4 :                     PG_RETURN_NUMERIC(make_result(&const_ninf));
    3290                 :             :             }
    3291                 :             :             Assert(false);
    3292                 :             :         }
    3293         [ +  + ]:          56 :         if (NUMERIC_IS_NINF(num1))
    3294                 :             :         {
    3295         [ +  + ]:          24 :             if (NUMERIC_IS_SPECIAL(num2))
    3296                 :           8 :                 PG_RETURN_NUMERIC(make_result(&const_nan)); /* -Inf / [-]Inf */
    3297   [ +  +  +  - ]:          16 :             switch (numeric_sign_internal(num2))
    3298                 :             :             {
    3299                 :           4 :                 case 0:
    3300         [ +  - ]:           4 :                     ereport(ERROR,
    3301                 :             :                             (errcode(ERRCODE_DIVISION_BY_ZERO),
    3302                 :             :                              errmsg("division by zero")));
    3303                 :             :                     break;
    3304                 :           8 :                 case 1:
    3305                 :           8 :                     PG_RETURN_NUMERIC(make_result(&const_ninf));
    3306                 :           4 :                 case -1:
    3307                 :           4 :                     PG_RETURN_NUMERIC(make_result(&const_pinf));
    3308                 :             :             }
    3309                 :             :             Assert(false);
    3310                 :             :         }
    3311                 :             :         /* by here, num1 must be finite, so num2 is not */
    3312                 :             : 
    3313                 :             :         /*
    3314                 :             :          * POSIX would have us return zero or minus zero if num1 is zero, and
    3315                 :             :          * otherwise throw an underflow error.  But the numeric type doesn't
    3316                 :             :          * really do underflow, so let's just return zero.
    3317                 :             :          */
    3318                 :          32 :         PG_RETURN_NUMERIC(make_result(&const_zero));
    3319                 :             :     }
    3320                 :             : 
    3321                 :             :     /*
    3322                 :             :      * Unpack the arguments
    3323                 :             :      */
    3324                 :         689 :     init_var_from_num(num1, &arg1);
    3325                 :         689 :     init_var_from_num(num2, &arg2);
    3326                 :             : 
    3327                 :         689 :     init_var(&result);
    3328                 :             : 
    3329                 :             :     /*
    3330                 :             :      * Do the divide and return the result
    3331                 :             :      */
    3332                 :         689 :     div_var(&arg1, &arg2, &result, 0, false, true);
    3333                 :             : 
    3334                 :         685 :     res = make_result(&result);
    3335                 :             : 
    3336                 :         685 :     free_var(&result);
    3337                 :             : 
    3338                 :         685 :     PG_RETURN_NUMERIC(res);
    3339                 :             : }
    3340                 :             : 
    3341                 :             : 
    3342                 :             : /*
    3343                 :             :  * numeric_mod() -
    3344                 :             :  *
    3345                 :             :  *  Calculate the modulo of two numerics
    3346                 :             :  */
    3347                 :             : Datum
    3348                 :      275190 : numeric_mod(PG_FUNCTION_ARGS)
    3349                 :             : {
    3350                 :      275190 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    3351                 :      275190 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    3352                 :             :     Numeric     res;
    3353                 :             : 
    3354                 :      275190 :     res = numeric_mod_safe(num1, num2, NULL);
    3355                 :             : 
    3356                 :      275178 :     PG_RETURN_NUMERIC(res);
    3357                 :             : }
    3358                 :             : 
    3359                 :             : 
    3360                 :             : /*
    3361                 :             :  * numeric_mod_safe() -
    3362                 :             :  *
    3363                 :             :  *  Internal version of numeric_mod() with support for soft error reporting.
    3364                 :             :  */
    3365                 :             : Numeric
    3366                 :      275198 : numeric_mod_safe(Numeric num1, Numeric num2, Node *escontext)
    3367                 :             : {
    3368                 :             :     Numeric     res;
    3369                 :             :     NumericVar  arg1;
    3370                 :             :     NumericVar  arg2;
    3371                 :             :     NumericVar  result;
    3372                 :             : 
    3373                 :             :     /*
    3374                 :             :      * Handle NaN and infinities.  We follow POSIX fmod() on this, except that
    3375                 :             :      * POSIX treats x-is-infinite and y-is-zero identically, raising EDOM and
    3376                 :             :      * returning NaN.  We choose to throw error only for y-is-zero.
    3377                 :             :      */
    3378   [ +  +  +  + ]:      275198 :     if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
    3379                 :             :     {
    3380   [ +  +  +  + ]:         133 :         if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
    3381                 :          53 :             return make_result(&const_nan);
    3382         [ +  + ]:          80 :         if (NUMERIC_IS_INF(num1))
    3383                 :             :         {
    3384         [ +  + ]:          48 :             if (numeric_sign_internal(num2) == 0)
    3385                 :           8 :                 goto division_by_zero;
    3386                 :             : 
    3387                 :             :             /* Inf % any nonzero = NaN */
    3388                 :          40 :             return make_result(&const_nan);
    3389                 :             :         }
    3390                 :             :         /* num2 must be [-]Inf; result is num1 regardless of sign of num2 */
    3391                 :          32 :         return duplicate_numeric(num1);
    3392                 :             :     }
    3393                 :             : 
    3394                 :      275065 :     init_var_from_num(num1, &arg1);
    3395                 :      275065 :     init_var_from_num(num2, &arg2);
    3396                 :             : 
    3397                 :      275065 :     init_var(&result);
    3398                 :             : 
    3399                 :             :     /* Check for division by zero */
    3400   [ +  +  -  + ]:      275065 :     if (arg2.ndigits == 0 || arg2.digits[0] == 0)
    3401                 :           8 :         goto division_by_zero;
    3402                 :             : 
    3403                 :      275057 :     mod_var(&arg1, &arg2, &result);
    3404                 :             : 
    3405                 :      275057 :     res = make_result_safe(&result, escontext);
    3406                 :             : 
    3407                 :      275057 :     free_var(&result);
    3408                 :             : 
    3409                 :      275057 :     return res;
    3410                 :             : 
    3411                 :          16 : division_by_zero:
    3412         [ +  - ]:          16 :     ereturn(escontext, NULL,
    3413                 :             :             errcode(ERRCODE_DIVISION_BY_ZERO),
    3414                 :             :             errmsg("division by zero"));
    3415                 :             : }
    3416                 :             : 
    3417                 :             : 
    3418                 :             : /*
    3419                 :             :  * numeric_inc() -
    3420                 :             :  *
    3421                 :             :  *  Increment a number by one
    3422                 :             :  */
    3423                 :             : Datum
    3424                 :          32 : numeric_inc(PG_FUNCTION_ARGS)
    3425                 :             : {
    3426                 :          32 :     Numeric     num = PG_GETARG_NUMERIC(0);
    3427                 :             :     NumericVar  arg;
    3428                 :             :     Numeric     res;
    3429                 :             : 
    3430                 :             :     /*
    3431                 :             :      * Handle NaN and infinities
    3432                 :             :      */
    3433         [ +  + ]:          32 :     if (NUMERIC_IS_SPECIAL(num))
    3434                 :          12 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    3435                 :             : 
    3436                 :             :     /*
    3437                 :             :      * Compute the result and return it
    3438                 :             :      */
    3439                 :          20 :     init_var_from_num(num, &arg);
    3440                 :             : 
    3441                 :          20 :     add_var(&arg, &const_one, &arg);
    3442                 :             : 
    3443                 :          20 :     res = make_result(&arg);
    3444                 :             : 
    3445                 :          20 :     free_var(&arg);
    3446                 :             : 
    3447                 :          20 :     PG_RETURN_NUMERIC(res);
    3448                 :             : }
    3449                 :             : 
    3450                 :             : 
    3451                 :             : /*
    3452                 :             :  * numeric_smaller() -
    3453                 :             :  *
    3454                 :             :  *  Return the smaller of two numbers
    3455                 :             :  */
    3456                 :             : Datum
    3457                 :         543 : numeric_smaller(PG_FUNCTION_ARGS)
    3458                 :             : {
    3459                 :         543 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    3460                 :         543 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    3461                 :             : 
    3462                 :             :     /*
    3463                 :             :      * Use cmp_numerics so that this will agree with the comparison operators,
    3464                 :             :      * particularly as regards comparisons involving NaN.
    3465                 :             :      */
    3466         [ +  + ]:         543 :     if (cmp_numerics(num1, num2) < 0)
    3467                 :         436 :         PG_RETURN_NUMERIC(num1);
    3468                 :             :     else
    3469                 :         107 :         PG_RETURN_NUMERIC(num2);
    3470                 :             : }
    3471                 :             : 
    3472                 :             : 
    3473                 :             : /*
    3474                 :             :  * numeric_larger() -
    3475                 :             :  *
    3476                 :             :  *  Return the larger of two numbers
    3477                 :             :  */
    3478                 :             : Datum
    3479                 :       12420 : numeric_larger(PG_FUNCTION_ARGS)
    3480                 :             : {
    3481                 :       12420 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    3482                 :       12420 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    3483                 :             : 
    3484                 :             :     /*
    3485                 :             :      * Use cmp_numerics so that this will agree with the comparison operators,
    3486                 :             :      * particularly as regards comparisons involving NaN.
    3487                 :             :      */
    3488         [ +  + ]:       12420 :     if (cmp_numerics(num1, num2) > 0)
    3489                 :       11942 :         PG_RETURN_NUMERIC(num1);
    3490                 :             :     else
    3491                 :         478 :         PG_RETURN_NUMERIC(num2);
    3492                 :             : }
    3493                 :             : 
    3494                 :             : 
    3495                 :             : /* ----------------------------------------------------------------------
    3496                 :             :  *
    3497                 :             :  * Advanced math functions
    3498                 :             :  *
    3499                 :             :  * ----------------------------------------------------------------------
    3500                 :             :  */
    3501                 :             : 
    3502                 :             : /*
    3503                 :             :  * numeric_gcd() -
    3504                 :             :  *
    3505                 :             :  *  Calculate the greatest common divisor of two numerics
    3506                 :             :  */
    3507                 :             : Datum
    3508                 :         144 : numeric_gcd(PG_FUNCTION_ARGS)
    3509                 :             : {
    3510                 :         144 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    3511                 :         144 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    3512                 :             :     NumericVar  arg1;
    3513                 :             :     NumericVar  arg2;
    3514                 :             :     NumericVar  result;
    3515                 :             :     Numeric     res;
    3516                 :             : 
    3517                 :             :     /*
    3518                 :             :      * Handle NaN and infinities: we consider the result to be NaN in all such
    3519                 :             :      * cases.
    3520                 :             :      */
    3521   [ +  +  +  + ]:         144 :     if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
    3522                 :          64 :         PG_RETURN_NUMERIC(make_result(&const_nan));
    3523                 :             : 
    3524                 :             :     /*
    3525                 :             :      * Unpack the arguments
    3526                 :             :      */
    3527                 :          80 :     init_var_from_num(num1, &arg1);
    3528                 :          80 :     init_var_from_num(num2, &arg2);
    3529                 :             : 
    3530                 :          80 :     init_var(&result);
    3531                 :             : 
    3532                 :             :     /*
    3533                 :             :      * Find the GCD and return the result
    3534                 :             :      */
    3535                 :          80 :     gcd_var(&arg1, &arg2, &result);
    3536                 :             : 
    3537                 :          80 :     res = make_result(&result);
    3538                 :             : 
    3539                 :          80 :     free_var(&result);
    3540                 :             : 
    3541                 :          80 :     PG_RETURN_NUMERIC(res);
    3542                 :             : }
    3543                 :             : 
    3544                 :             : 
    3545                 :             : /*
    3546                 :             :  * numeric_lcm() -
    3547                 :             :  *
    3548                 :             :  *  Calculate the least common multiple of two numerics
    3549                 :             :  */
    3550                 :             : Datum
    3551                 :         164 : numeric_lcm(PG_FUNCTION_ARGS)
    3552                 :             : {
    3553                 :         164 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    3554                 :         164 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    3555                 :             :     NumericVar  arg1;
    3556                 :             :     NumericVar  arg2;
    3557                 :             :     NumericVar  result;
    3558                 :             :     Numeric     res;
    3559                 :             : 
    3560                 :             :     /*
    3561                 :             :      * Handle NaN and infinities: we consider the result to be NaN in all such
    3562                 :             :      * cases.
    3563                 :             :      */
    3564   [ +  +  +  + ]:         164 :     if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
    3565                 :          64 :         PG_RETURN_NUMERIC(make_result(&const_nan));
    3566                 :             : 
    3567                 :             :     /*
    3568                 :             :      * Unpack the arguments
    3569                 :             :      */
    3570                 :         100 :     init_var_from_num(num1, &arg1);
    3571                 :         100 :     init_var_from_num(num2, &arg2);
    3572                 :             : 
    3573                 :         100 :     init_var(&result);
    3574                 :             : 
    3575                 :             :     /*
    3576                 :             :      * Compute the result using lcm(x, y) = abs(x / gcd(x, y) * y), returning
    3577                 :             :      * zero if either input is zero.
    3578                 :             :      *
    3579                 :             :      * Note that the division is guaranteed to be exact, returning an integer
    3580                 :             :      * result, so the LCM is an integral multiple of both x and y.  A display
    3581                 :             :      * scale of Min(x.dscale, y.dscale) would be sufficient to represent it,
    3582                 :             :      * but as with other numeric functions, we choose to return a result whose
    3583                 :             :      * display scale is no smaller than either input.
    3584                 :             :      */
    3585   [ +  +  +  + ]:         100 :     if (arg1.ndigits == 0 || arg2.ndigits == 0)
    3586                 :          32 :         set_var_from_var(&const_zero, &result);
    3587                 :             :     else
    3588                 :             :     {
    3589                 :          68 :         gcd_var(&arg1, &arg2, &result);
    3590                 :          68 :         div_var(&arg1, &result, &result, 0, false, true);
    3591                 :          68 :         mul_var(&arg2, &result, &result, arg2.dscale);
    3592                 :          68 :         result.sign = NUMERIC_POS;
    3593                 :             :     }
    3594                 :             : 
    3595                 :         100 :     result.dscale = Max(arg1.dscale, arg2.dscale);
    3596                 :             : 
    3597                 :         100 :     res = make_result(&result);
    3598                 :             : 
    3599                 :          96 :     free_var(&result);
    3600                 :             : 
    3601                 :          96 :     PG_RETURN_NUMERIC(res);
    3602                 :             : }
    3603                 :             : 
    3604                 :             : 
    3605                 :             : /*
    3606                 :             :  * numeric_fac()
    3607                 :             :  *
    3608                 :             :  * Compute factorial
    3609                 :             :  */
    3610                 :             : Datum
    3611                 :          33 : numeric_fac(PG_FUNCTION_ARGS)
    3612                 :             : {
    3613                 :          33 :     int64       num = PG_GETARG_INT64(0);
    3614                 :             :     Numeric     res;
    3615                 :             :     NumericVar  fact;
    3616                 :             :     NumericVar  result;
    3617                 :             : 
    3618         [ +  + ]:          33 :     if (num < 0)
    3619         [ +  - ]:           4 :         ereport(ERROR,
    3620                 :             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    3621                 :             :                  errmsg("factorial of a negative number is undefined")));
    3622         [ +  + ]:          29 :     if (num <= 1)
    3623                 :             :     {
    3624                 :           5 :         res = make_result(&const_one);
    3625                 :           5 :         PG_RETURN_NUMERIC(res);
    3626                 :             :     }
    3627                 :             :     /* Fail immediately if the result would overflow */
    3628         [ +  + ]:          24 :     if (num > 32177)
    3629         [ +  - ]:           4 :         ereport(ERROR,
    3630                 :             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    3631                 :             :                  errmsg("value overflows numeric format")));
    3632                 :             : 
    3633                 :          20 :     init_var(&fact);
    3634                 :          20 :     init_var(&result);
    3635                 :             : 
    3636                 :          20 :     int64_to_numericvar(num, &result);
    3637                 :             : 
    3638         [ +  + ]:         245 :     for (num = num - 1; num > 1; num--)
    3639                 :             :     {
    3640                 :             :         /* this loop can take awhile, so allow it to be interrupted */
    3641         [ -  + ]:         225 :         CHECK_FOR_INTERRUPTS();
    3642                 :             : 
    3643                 :         225 :         int64_to_numericvar(num, &fact);
    3644                 :             : 
    3645                 :         225 :         mul_var(&result, &fact, &result, 0);
    3646                 :             :     }
    3647                 :             : 
    3648                 :          20 :     res = make_result(&result);
    3649                 :             : 
    3650                 :          20 :     free_var(&fact);
    3651                 :          20 :     free_var(&result);
    3652                 :             : 
    3653                 :          20 :     PG_RETURN_NUMERIC(res);
    3654                 :             : }
    3655                 :             : 
    3656                 :             : 
    3657                 :             : /*
    3658                 :             :  * numeric_sqrt() -
    3659                 :             :  *
    3660                 :             :  *  Compute the square root of a numeric.
    3661                 :             :  */
    3662                 :             : Datum
    3663                 :         108 : numeric_sqrt(PG_FUNCTION_ARGS)
    3664                 :             : {
    3665                 :         108 :     Numeric     num = PG_GETARG_NUMERIC(0);
    3666                 :             :     Numeric     res;
    3667                 :             :     NumericVar  arg;
    3668                 :             :     NumericVar  result;
    3669                 :             :     int         sweight;
    3670                 :             :     int         rscale;
    3671                 :             : 
    3672                 :             :     /*
    3673                 :             :      * Handle NaN and infinities
    3674                 :             :      */
    3675         [ +  + ]:         108 :     if (NUMERIC_IS_SPECIAL(num))
    3676                 :             :     {
    3677                 :             :         /* error should match that in sqrt_var() */
    3678         [ +  + ]:          12 :         if (NUMERIC_IS_NINF(num))
    3679         [ +  - ]:           4 :             ereport(ERROR,
    3680                 :             :                     (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
    3681                 :             :                      errmsg("cannot take square root of a negative number")));
    3682                 :             :         /* For NAN or PINF, just duplicate the input */
    3683                 :           8 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    3684                 :             :     }
    3685                 :             : 
    3686                 :             :     /*
    3687                 :             :      * Unpack the argument and determine the result scale.  We choose a scale
    3688                 :             :      * to give at least NUMERIC_MIN_SIG_DIGITS significant digits; but in any
    3689                 :             :      * case not less than the input's dscale.
    3690                 :             :      */
    3691                 :          96 :     init_var_from_num(num, &arg);
    3692                 :             : 
    3693                 :          96 :     init_var(&result);
    3694                 :             : 
    3695                 :             :     /*
    3696                 :             :      * Assume the input was normalized, so arg.weight is accurate.  The result
    3697                 :             :      * then has at least sweight = floor(arg.weight * DEC_DIGITS / 2 + 1)
    3698                 :             :      * digits before the decimal point.  When DEC_DIGITS is even, we can save
    3699                 :             :      * a few cycles, since the division is exact and there is no need to round
    3700                 :             :      * towards negative infinity.
    3701                 :             :      */
    3702                 :             : #if DEC_DIGITS == ((DEC_DIGITS / 2) * 2)
    3703                 :          96 :     sweight = arg.weight * DEC_DIGITS / 2 + 1;
    3704                 :             : #else
    3705                 :             :     if (arg.weight >= 0)
    3706                 :             :         sweight = arg.weight * DEC_DIGITS / 2 + 1;
    3707                 :             :     else
    3708                 :             :         sweight = 1 - (1 - arg.weight * DEC_DIGITS) / 2;
    3709                 :             : #endif
    3710                 :             : 
    3711                 :          96 :     rscale = NUMERIC_MIN_SIG_DIGITS - sweight;
    3712                 :          96 :     rscale = Max(rscale, arg.dscale);
    3713                 :          96 :     rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
    3714                 :          96 :     rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
    3715                 :             : 
    3716                 :             :     /*
    3717                 :             :      * Let sqrt_var() do the calculation and return the result.
    3718                 :             :      */
    3719                 :          96 :     sqrt_var(&arg, &result, rscale);
    3720                 :             : 
    3721                 :          92 :     res = make_result(&result);
    3722                 :             : 
    3723                 :          92 :     free_var(&result);
    3724                 :             : 
    3725                 :          92 :     PG_RETURN_NUMERIC(res);
    3726                 :             : }
    3727                 :             : 
    3728                 :             : 
    3729                 :             : /*
    3730                 :             :  * numeric_exp() -
    3731                 :             :  *
    3732                 :             :  *  Raise e to the power of x
    3733                 :             :  */
    3734                 :             : Datum
    3735                 :          65 : numeric_exp(PG_FUNCTION_ARGS)
    3736                 :             : {
    3737                 :          65 :     Numeric     num = PG_GETARG_NUMERIC(0);
    3738                 :             :     Numeric     res;
    3739                 :             :     NumericVar  arg;
    3740                 :             :     NumericVar  result;
    3741                 :             :     int         rscale;
    3742                 :             :     double      val;
    3743                 :             : 
    3744                 :             :     /*
    3745                 :             :      * Handle NaN and infinities
    3746                 :             :      */
    3747         [ +  + ]:          65 :     if (NUMERIC_IS_SPECIAL(num))
    3748                 :             :     {
    3749                 :             :         /* Per POSIX, exp(-Inf) is zero */
    3750         [ +  + ]:          15 :         if (NUMERIC_IS_NINF(num))
    3751                 :           5 :             PG_RETURN_NUMERIC(make_result(&const_zero));
    3752                 :             :         /* For NAN or PINF, just duplicate the input */
    3753                 :          10 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    3754                 :             :     }
    3755                 :             : 
    3756                 :             :     /*
    3757                 :             :      * Unpack the argument and determine the result scale.  We choose a scale
    3758                 :             :      * to give at least NUMERIC_MIN_SIG_DIGITS significant digits; but in any
    3759                 :             :      * case not less than the input's dscale.
    3760                 :             :      */
    3761                 :          50 :     init_var_from_num(num, &arg);
    3762                 :             : 
    3763                 :          50 :     init_var(&result);
    3764                 :             : 
    3765                 :             :     /* convert input to float8, ignoring overflow */
    3766                 :          50 :     val = numericvar_to_double_no_overflow(&arg);
    3767                 :             : 
    3768                 :             :     /*
    3769                 :             :      * log10(result) = num * log10(e), so this is approximately the decimal
    3770                 :             :      * weight of the result:
    3771                 :             :      */
    3772                 :          50 :     val *= 0.434294481903252;
    3773                 :             : 
    3774                 :             :     /* limit to something that won't cause integer overflow */
    3775         [ +  + ]:          50 :     val = Max(val, -NUMERIC_MAX_RESULT_SCALE);
    3776         [ +  - ]:          50 :     val = Min(val, NUMERIC_MAX_RESULT_SCALE);
    3777                 :             : 
    3778                 :          50 :     rscale = NUMERIC_MIN_SIG_DIGITS - (int) val;
    3779                 :          50 :     rscale = Max(rscale, arg.dscale);
    3780                 :          50 :     rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
    3781                 :          50 :     rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
    3782                 :             : 
    3783                 :             :     /*
    3784                 :             :      * Let exp_var() do the calculation and return the result.
    3785                 :             :      */
    3786                 :          50 :     exp_var(&arg, &result, rscale);
    3787                 :             : 
    3788                 :          50 :     res = make_result(&result);
    3789                 :             : 
    3790                 :          50 :     free_var(&result);
    3791                 :             : 
    3792                 :          50 :     PG_RETURN_NUMERIC(res);
    3793                 :             : }
    3794                 :             : 
    3795                 :             : 
    3796                 :             : /*
    3797                 :             :  * numeric_ln() -
    3798                 :             :  *
    3799                 :             :  *  Compute the natural logarithm of x
    3800                 :             :  */
    3801                 :             : Datum
    3802                 :         140 : numeric_ln(PG_FUNCTION_ARGS)
    3803                 :             : {
    3804                 :         140 :     Numeric     num = PG_GETARG_NUMERIC(0);
    3805                 :             :     Numeric     res;
    3806                 :             :     NumericVar  arg;
    3807                 :             :     NumericVar  result;
    3808                 :             :     int         ln_dweight;
    3809                 :             :     int         rscale;
    3810                 :             : 
    3811                 :             :     /*
    3812                 :             :      * Handle NaN and infinities
    3813                 :             :      */
    3814         [ +  + ]:         140 :     if (NUMERIC_IS_SPECIAL(num))
    3815                 :             :     {
    3816         [ +  + ]:          12 :         if (NUMERIC_IS_NINF(num))
    3817         [ +  - ]:           4 :             ereport(ERROR,
    3818                 :             :                     (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
    3819                 :             :                      errmsg("cannot take logarithm of a negative number")));
    3820                 :             :         /* For NAN or PINF, just duplicate the input */
    3821                 :           8 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    3822                 :             :     }
    3823                 :             : 
    3824                 :         128 :     init_var_from_num(num, &arg);
    3825                 :         128 :     init_var(&result);
    3826                 :             : 
    3827                 :             :     /* Estimated dweight of logarithm */
    3828                 :         128 :     ln_dweight = estimate_ln_dweight(&arg);
    3829                 :             : 
    3830                 :         128 :     rscale = NUMERIC_MIN_SIG_DIGITS - ln_dweight;
    3831                 :         128 :     rscale = Max(rscale, arg.dscale);
    3832                 :         128 :     rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
    3833                 :         128 :     rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
    3834                 :             : 
    3835                 :         128 :     ln_var(&arg, &result, rscale);
    3836                 :             : 
    3837                 :         112 :     res = make_result(&result);
    3838                 :             : 
    3839                 :         112 :     free_var(&result);
    3840                 :             : 
    3841                 :         112 :     PG_RETURN_NUMERIC(res);
    3842                 :             : }
    3843                 :             : 
    3844                 :             : 
    3845                 :             : /*
    3846                 :             :  * numeric_log() -
    3847                 :             :  *
    3848                 :             :  *  Compute the logarithm of x in a given base
    3849                 :             :  */
    3850                 :             : Datum
    3851                 :         240 : numeric_log(PG_FUNCTION_ARGS)
    3852                 :             : {
    3853                 :         240 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    3854                 :         240 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    3855                 :             :     Numeric     res;
    3856                 :             :     NumericVar  arg1;
    3857                 :             :     NumericVar  arg2;
    3858                 :             :     NumericVar  result;
    3859                 :             : 
    3860                 :             :     /*
    3861                 :             :      * Handle NaN and infinities
    3862                 :             :      */
    3863   [ +  +  +  + ]:         240 :     if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
    3864                 :             :     {
    3865                 :             :         int         sign1,
    3866                 :             :                     sign2;
    3867                 :             : 
    3868   [ +  +  +  + ]:          84 :         if (NUMERIC_IS_NAN(num1) || NUMERIC_IS_NAN(num2))
    3869                 :          36 :             PG_RETURN_NUMERIC(make_result(&const_nan));
    3870                 :             :         /* fail on negative inputs including -Inf, as log_var would */
    3871                 :          48 :         sign1 = numeric_sign_internal(num1);
    3872                 :          48 :         sign2 = numeric_sign_internal(num2);
    3873   [ +  +  +  + ]:          48 :         if (sign1 < 0 || sign2 < 0)
    3874         [ +  - ]:          16 :             ereport(ERROR,
    3875                 :             :                     (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
    3876                 :             :                      errmsg("cannot take logarithm of a negative number")));
    3877                 :             :         /* fail on zero inputs, as log_var would */
    3878   [ +  -  +  + ]:          32 :         if (sign1 == 0 || sign2 == 0)
    3879         [ +  - ]:           4 :             ereport(ERROR,
    3880                 :             :                     (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
    3881                 :             :                      errmsg("cannot take logarithm of zero")));
    3882         [ +  + ]:          28 :         if (NUMERIC_IS_PINF(num1))
    3883                 :             :         {
    3884                 :             :             /* log(Inf, Inf) reduces to Inf/Inf, so it's NaN */
    3885         [ +  + ]:          12 :             if (NUMERIC_IS_PINF(num2))
    3886                 :           4 :                 PG_RETURN_NUMERIC(make_result(&const_nan));
    3887                 :             :             /* log(Inf, finite-positive) is zero (we don't throw underflow) */
    3888                 :           8 :             PG_RETURN_NUMERIC(make_result(&const_zero));
    3889                 :             :         }
    3890                 :             :         Assert(NUMERIC_IS_PINF(num2));
    3891                 :             :         /* log(finite-positive, Inf) is Inf */
    3892                 :          16 :         PG_RETURN_NUMERIC(make_result(&const_pinf));
    3893                 :             :     }
    3894                 :             : 
    3895                 :             :     /*
    3896                 :             :      * Initialize things
    3897                 :             :      */
    3898                 :         156 :     init_var_from_num(num1, &arg1);
    3899                 :         156 :     init_var_from_num(num2, &arg2);
    3900                 :         156 :     init_var(&result);
    3901                 :             : 
    3902                 :             :     /*
    3903                 :             :      * Call log_var() to compute and return the result; note it handles scale
    3904                 :             :      * selection itself.
    3905                 :             :      */
    3906                 :         156 :     log_var(&arg1, &arg2, &result);
    3907                 :             : 
    3908                 :         116 :     res = make_result(&result);
    3909                 :             : 
    3910                 :         116 :     free_var(&result);
    3911                 :             : 
    3912                 :         116 :     PG_RETURN_NUMERIC(res);
    3913                 :             : }
    3914                 :             : 
    3915                 :             : 
    3916                 :             : /*
    3917                 :             :  * numeric_power() -
    3918                 :             :  *
    3919                 :             :  *  Raise x to the power of y
    3920                 :             :  */
    3921                 :             : Datum
    3922                 :        1149 : numeric_power(PG_FUNCTION_ARGS)
    3923                 :             : {
    3924                 :        1149 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    3925                 :        1149 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    3926                 :             :     Numeric     res;
    3927                 :             :     NumericVar  arg1;
    3928                 :             :     NumericVar  arg2;
    3929                 :             :     NumericVar  result;
    3930                 :             :     int         sign1,
    3931                 :             :                 sign2;
    3932                 :             : 
    3933                 :             :     /*
    3934                 :             :      * Handle NaN and infinities
    3935                 :             :      */
    3936   [ +  +  +  + ]:        1149 :     if (NUMERIC_IS_SPECIAL(num1) || NUMERIC_IS_SPECIAL(num2))
    3937                 :             :     {
    3938                 :             :         /*
    3939                 :             :          * We follow the POSIX spec for pow(3), which says that NaN ^ 0 = 1,
    3940                 :             :          * and 1 ^ NaN = 1, while all other cases with NaN inputs yield NaN
    3941                 :             :          * (with no error).
    3942                 :             :          */
    3943         [ +  + ]:         173 :         if (NUMERIC_IS_NAN(num1))
    3944                 :             :         {
    3945         [ +  + ]:          39 :             if (!NUMERIC_IS_SPECIAL(num2))
    3946                 :             :             {
    3947                 :          26 :                 init_var_from_num(num2, &arg2);
    3948         [ +  + ]:          26 :                 if (cmp_var(&arg2, &const_zero) == 0)
    3949                 :           9 :                     PG_RETURN_NUMERIC(make_result(&const_one));
    3950                 :             :             }
    3951                 :          30 :             PG_RETURN_NUMERIC(make_result(&const_nan));
    3952                 :             :         }
    3953         [ +  + ]:         134 :         if (NUMERIC_IS_NAN(num2))
    3954                 :             :         {
    3955         [ +  + ]:          30 :             if (!NUMERIC_IS_SPECIAL(num1))
    3956                 :             :             {
    3957                 :          26 :                 init_var_from_num(num1, &arg1);
    3958         [ +  + ]:          26 :                 if (cmp_var(&arg1, &const_one) == 0)
    3959                 :           9 :                     PG_RETURN_NUMERIC(make_result(&const_one));
    3960                 :             :             }
    3961                 :          21 :             PG_RETURN_NUMERIC(make_result(&const_nan));
    3962                 :             :         }
    3963                 :             :         /* At least one input is infinite, but error rules still apply */
    3964                 :         104 :         sign1 = numeric_sign_internal(num1);
    3965                 :         104 :         sign2 = numeric_sign_internal(num2);
    3966   [ +  +  +  + ]:         104 :         if (sign1 == 0 && sign2 < 0)
    3967         [ +  - ]:           4 :             ereport(ERROR,
    3968                 :             :                     (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
    3969                 :             :                      errmsg("zero raised to a negative power is undefined")));
    3970   [ +  +  +  + ]:         100 :         if (sign1 < 0 && !numeric_is_integral(num2))
    3971         [ +  - ]:           4 :             ereport(ERROR,
    3972                 :             :                     (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
    3973                 :             :                      errmsg("a negative number raised to a non-integer power yields a complex result")));
    3974                 :             : 
    3975                 :             :         /*
    3976                 :             :          * POSIX gives this series of rules for pow(3) with infinite inputs:
    3977                 :             :          *
    3978                 :             :          * For any value of y, if x is +1, 1.0 shall be returned.
    3979                 :             :          */
    3980         [ +  + ]:          96 :         if (!NUMERIC_IS_SPECIAL(num1))
    3981                 :             :         {
    3982                 :          31 :             init_var_from_num(num1, &arg1);
    3983         [ +  + ]:          31 :             if (cmp_var(&arg1, &const_one) == 0)
    3984                 :           4 :                 PG_RETURN_NUMERIC(make_result(&const_one));
    3985                 :             :         }
    3986                 :             : 
    3987                 :             :         /*
    3988                 :             :          * For any value of x, if y is [-]0, 1.0 shall be returned.
    3989                 :             :          */
    3990         [ +  + ]:          92 :         if (sign2 == 0)
    3991                 :           9 :             PG_RETURN_NUMERIC(make_result(&const_one));
    3992                 :             : 
    3993                 :             :         /*
    3994                 :             :          * For any odd integer value of y > 0, if x is [-]0, [-]0 shall be
    3995                 :             :          * returned.  For y > 0 and not an odd integer, if x is [-]0, +0 shall
    3996                 :             :          * be returned.  (Since we don't deal in minus zero, we need not
    3997                 :             :          * distinguish these two cases.)
    3998                 :             :          */
    3999   [ +  +  +  - ]:          83 :         if (sign1 == 0 && sign2 > 0)
    4000                 :           4 :             PG_RETURN_NUMERIC(make_result(&const_zero));
    4001                 :             : 
    4002                 :             :         /*
    4003                 :             :          * If x is -1, and y is [-]Inf, 1.0 shall be returned.
    4004                 :             :          *
    4005                 :             :          * For |x| < 1, if y is -Inf, +Inf shall be returned.
    4006                 :             :          *
    4007                 :             :          * For |x| > 1, if y is -Inf, +0 shall be returned.
    4008                 :             :          *
    4009                 :             :          * For |x| < 1, if y is +Inf, +0 shall be returned.
    4010                 :             :          *
    4011                 :             :          * For |x| > 1, if y is +Inf, +Inf shall be returned.
    4012                 :             :          */
    4013         [ +  + ]:          79 :         if (NUMERIC_IS_INF(num2))
    4014                 :             :         {
    4015                 :             :             bool        abs_x_gt_one;
    4016                 :             : 
    4017         [ +  + ]:          42 :             if (NUMERIC_IS_SPECIAL(num1))
    4018                 :          19 :                 abs_x_gt_one = true;    /* x is either Inf or -Inf */
    4019                 :             :             else
    4020                 :             :             {
    4021                 :          23 :                 init_var_from_num(num1, &arg1);
    4022         [ +  + ]:          23 :                 if (cmp_var(&arg1, &const_minus_one) == 0)
    4023                 :           5 :                     PG_RETURN_NUMERIC(make_result(&const_one));
    4024                 :          18 :                 arg1.sign = NUMERIC_POS;    /* now arg1 = abs(x) */
    4025                 :          18 :                 abs_x_gt_one = (cmp_var(&arg1, &const_one) > 0);
    4026                 :             :             }
    4027         [ +  + ]:          37 :             if (abs_x_gt_one == (sign2 > 0))
    4028                 :          22 :                 PG_RETURN_NUMERIC(make_result(&const_pinf));
    4029                 :             :             else
    4030                 :          15 :                 PG_RETURN_NUMERIC(make_result(&const_zero));
    4031                 :             :         }
    4032                 :             : 
    4033                 :             :         /*
    4034                 :             :          * For y < 0, if x is +Inf, +0 shall be returned.
    4035                 :             :          *
    4036                 :             :          * For y > 0, if x is +Inf, +Inf shall be returned.
    4037                 :             :          */
    4038         [ +  + ]:          37 :         if (NUMERIC_IS_PINF(num1))
    4039                 :             :         {
    4040         [ +  + ]:          17 :             if (sign2 > 0)
    4041                 :          12 :                 PG_RETURN_NUMERIC(make_result(&const_pinf));
    4042                 :             :             else
    4043                 :           5 :                 PG_RETURN_NUMERIC(make_result(&const_zero));
    4044                 :             :         }
    4045                 :             : 
    4046                 :             :         Assert(NUMERIC_IS_NINF(num1));
    4047                 :             : 
    4048                 :             :         /*
    4049                 :             :          * For y an odd integer < 0, if x is -Inf, -0 shall be returned.  For
    4050                 :             :          * y < 0 and not an odd integer, if x is -Inf, +0 shall be returned.
    4051                 :             :          * (Again, we need not distinguish these two cases.)
    4052                 :             :          */
    4053         [ +  + ]:          20 :         if (sign2 < 0)
    4054                 :          10 :             PG_RETURN_NUMERIC(make_result(&const_zero));
    4055                 :             : 
    4056                 :             :         /*
    4057                 :             :          * For y an odd integer > 0, if x is -Inf, -Inf shall be returned. For
    4058                 :             :          * y > 0 and not an odd integer, if x is -Inf, +Inf shall be returned.
    4059                 :             :          */
    4060                 :          10 :         init_var_from_num(num2, &arg2);
    4061   [ +  -  +  - ]:          10 :         if (arg2.ndigits > 0 && arg2.ndigits == arg2.weight + 1 &&
    4062         [ +  + ]:          10 :             (arg2.digits[arg2.ndigits - 1] & 1))
    4063                 :           5 :             PG_RETURN_NUMERIC(make_result(&const_ninf));
    4064                 :             :         else
    4065                 :           5 :             PG_RETURN_NUMERIC(make_result(&const_pinf));
    4066                 :             :     }
    4067                 :             : 
    4068                 :             :     /*
    4069                 :             :      * The SQL spec requires that we emit a particular SQLSTATE error code for
    4070                 :             :      * certain error conditions.  Specifically, we don't return a
    4071                 :             :      * divide-by-zero error code for 0 ^ -1.  Raising a negative number to a
    4072                 :             :      * non-integer power must produce the same error code, but that case is
    4073                 :             :      * handled in power_var().
    4074                 :             :      */
    4075                 :         976 :     sign1 = numeric_sign_internal(num1);
    4076                 :         976 :     sign2 = numeric_sign_internal(num2);
    4077                 :             : 
    4078   [ +  +  +  + ]:         976 :     if (sign1 == 0 && sign2 < 0)
    4079         [ +  - ]:           8 :         ereport(ERROR,
    4080                 :             :                 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
    4081                 :             :                  errmsg("zero raised to a negative power is undefined")));
    4082                 :             : 
    4083                 :             :     /*
    4084                 :             :      * Initialize things
    4085                 :             :      */
    4086                 :         968 :     init_var(&result);
    4087                 :         968 :     init_var_from_num(num1, &arg1);
    4088                 :         968 :     init_var_from_num(num2, &arg2);
    4089                 :             : 
    4090                 :             :     /*
    4091                 :             :      * Call power_var() to compute and return the result; note it handles
    4092                 :             :      * scale selection itself.
    4093                 :             :      */
    4094                 :         968 :     power_var(&arg1, &arg2, &result);
    4095                 :             : 
    4096                 :         948 :     res = make_result(&result);
    4097                 :             : 
    4098                 :         948 :     free_var(&result);
    4099                 :             : 
    4100                 :         948 :     PG_RETURN_NUMERIC(res);
    4101                 :             : }
    4102                 :             : 
    4103                 :             : /*
    4104                 :             :  * numeric_scale() -
    4105                 :             :  *
    4106                 :             :  *  Returns the scale, i.e. the count of decimal digits in the fractional part
    4107                 :             :  */
    4108                 :             : Datum
    4109                 :          81 : numeric_scale(PG_FUNCTION_ARGS)
    4110                 :             : {
    4111                 :          81 :     Numeric     num = PG_GETARG_NUMERIC(0);
    4112                 :             : 
    4113         [ +  + ]:          81 :     if (NUMERIC_IS_SPECIAL(num))
    4114                 :          14 :         PG_RETURN_NULL();
    4115                 :             : 
    4116         [ +  - ]:          67 :     PG_RETURN_INT32(NUMERIC_DSCALE(num));
    4117                 :             : }
    4118                 :             : 
    4119                 :             : /*
    4120                 :             :  * Calculate minimum scale for value.
    4121                 :             :  */
    4122                 :             : static int
    4123                 :         267 : get_min_scale(NumericVar *var)
    4124                 :             : {
    4125                 :             :     int         min_scale;
    4126                 :             :     int         last_digit_pos;
    4127                 :             : 
    4128                 :             :     /*
    4129                 :             :      * Ordinarily, the input value will be "stripped" so that the last
    4130                 :             :      * NumericDigit is nonzero.  But we don't want to get into an infinite
    4131                 :             :      * loop if it isn't, so explicitly find the last nonzero digit.
    4132                 :             :      */
    4133                 :         267 :     last_digit_pos = var->ndigits - 1;
    4134         [ +  + ]:         267 :     while (last_digit_pos >= 0 &&
    4135         [ -  + ]:         243 :            var->digits[last_digit_pos] == 0)
    4136                 :           0 :         last_digit_pos--;
    4137                 :             : 
    4138         [ +  + ]:         267 :     if (last_digit_pos >= 0)
    4139                 :             :     {
    4140                 :             :         /* compute min_scale assuming that last ndigit has no zeroes */
    4141                 :         243 :         min_scale = (last_digit_pos - var->weight) * DEC_DIGITS;
    4142                 :             : 
    4143                 :             :         /*
    4144                 :             :          * We could get a negative result if there are no digits after the
    4145                 :             :          * decimal point.  In this case the min_scale must be zero.
    4146                 :             :          */
    4147         [ +  + ]:         243 :         if (min_scale > 0)
    4148                 :             :         {
    4149                 :             :             /*
    4150                 :             :              * Reduce min_scale if trailing digit(s) in last NumericDigit are
    4151                 :             :              * zero.
    4152                 :             :              */
    4153                 :         135 :             NumericDigit last_digit = var->digits[last_digit_pos];
    4154                 :             : 
    4155         [ +  + ]:         365 :             while (last_digit % 10 == 0)
    4156                 :             :             {
    4157                 :         230 :                 min_scale--;
    4158                 :         230 :                 last_digit /= 10;
    4159                 :             :             }
    4160                 :             :         }
    4161                 :             :         else
    4162                 :         108 :             min_scale = 0;
    4163                 :             :     }
    4164                 :             :     else
    4165                 :          24 :         min_scale = 0;          /* result if input is zero */
    4166                 :             : 
    4167                 :         267 :     return min_scale;
    4168                 :             : }
    4169                 :             : 
    4170                 :             : /*
    4171                 :             :  * Returns minimum scale required to represent supplied value without loss.
    4172                 :             :  */
    4173                 :             : Datum
    4174                 :          60 : numeric_min_scale(PG_FUNCTION_ARGS)
    4175                 :             : {
    4176                 :          60 :     Numeric     num = PG_GETARG_NUMERIC(0);
    4177                 :             :     NumericVar  arg;
    4178                 :             :     int         min_scale;
    4179                 :             : 
    4180         [ +  + ]:          60 :     if (NUMERIC_IS_SPECIAL(num))
    4181                 :          10 :         PG_RETURN_NULL();
    4182                 :             : 
    4183                 :          50 :     init_var_from_num(num, &arg);
    4184                 :          50 :     min_scale = get_min_scale(&arg);
    4185                 :          50 :     free_var(&arg);
    4186                 :             : 
    4187                 :          50 :     PG_RETURN_INT32(min_scale);
    4188                 :             : }
    4189                 :             : 
    4190                 :             : /*
    4191                 :             :  * Reduce scale of numeric value to represent supplied value without loss.
    4192                 :             :  */
    4193                 :             : Datum
    4194                 :         227 : numeric_trim_scale(PG_FUNCTION_ARGS)
    4195                 :             : {
    4196                 :         227 :     Numeric     num = PG_GETARG_NUMERIC(0);
    4197                 :             :     Numeric     res;
    4198                 :             :     NumericVar  result;
    4199                 :             : 
    4200         [ +  + ]:         227 :     if (NUMERIC_IS_SPECIAL(num))
    4201                 :          10 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    4202                 :             : 
    4203                 :         217 :     init_var_from_num(num, &result);
    4204                 :         217 :     result.dscale = get_min_scale(&result);
    4205                 :         217 :     res = make_result(&result);
    4206                 :         217 :     free_var(&result);
    4207                 :             : 
    4208                 :         217 :     PG_RETURN_NUMERIC(res);
    4209                 :             : }
    4210                 :             : 
    4211                 :             : /*
    4212                 :             :  * Return a random numeric value in the range [rmin, rmax].
    4213                 :             :  */
    4214                 :             : Numeric
    4215                 :       22308 : random_numeric(pg_prng_state *state, Numeric rmin, Numeric rmax)
    4216                 :             : {
    4217                 :             :     NumericVar  rmin_var;
    4218                 :             :     NumericVar  rmax_var;
    4219                 :             :     NumericVar  result;
    4220                 :             :     Numeric     res;
    4221                 :             : 
    4222                 :             :     /* Range bounds must not be NaN/infinity */
    4223         [ +  + ]:       22308 :     if (NUMERIC_IS_SPECIAL(rmin))
    4224                 :             :     {
    4225         [ +  + ]:           8 :         if (NUMERIC_IS_NAN(rmin))
    4226         [ +  - ]:           4 :             ereport(ERROR,
    4227                 :             :                     errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    4228                 :             :                     errmsg("lower bound cannot be NaN"));
    4229                 :             :         else
    4230         [ +  - ]:           4 :             ereport(ERROR,
    4231                 :             :                     errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    4232                 :             :                     errmsg("lower bound cannot be infinity"));
    4233                 :             :     }
    4234         [ +  + ]:       22300 :     if (NUMERIC_IS_SPECIAL(rmax))
    4235                 :             :     {
    4236         [ +  + ]:           8 :         if (NUMERIC_IS_NAN(rmax))
    4237         [ +  - ]:           4 :             ereport(ERROR,
    4238                 :             :                     errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    4239                 :             :                     errmsg("upper bound cannot be NaN"));
    4240                 :             :         else
    4241         [ +  - ]:           4 :             ereport(ERROR,
    4242                 :             :                     errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    4243                 :             :                     errmsg("upper bound cannot be infinity"));
    4244                 :             :     }
    4245                 :             : 
    4246                 :             :     /* Return a random value in the range [rmin, rmax] */
    4247                 :       22292 :     init_var_from_num(rmin, &rmin_var);
    4248                 :       22292 :     init_var_from_num(rmax, &rmax_var);
    4249                 :             : 
    4250                 :       22292 :     init_var(&result);
    4251                 :             : 
    4252                 :       22292 :     random_var(state, &rmin_var, &rmax_var, &result);
    4253                 :             : 
    4254                 :       22288 :     res = make_result(&result);
    4255                 :             : 
    4256                 :       22288 :     free_var(&result);
    4257                 :             : 
    4258                 :       22288 :     return res;
    4259                 :             : }
    4260                 :             : 
    4261                 :             : 
    4262                 :             : /* ----------------------------------------------------------------------
    4263                 :             :  *
    4264                 :             :  * Type conversion functions
    4265                 :             :  *
    4266                 :             :  * ----------------------------------------------------------------------
    4267                 :             :  */
    4268                 :             : 
    4269                 :             : Numeric
    4270                 :     1246905 : int64_to_numeric(int64 val)
    4271                 :             : {
    4272                 :             :     Numeric     res;
    4273                 :             :     NumericVar  result;
    4274                 :             : 
    4275                 :     1246905 :     init_var(&result);
    4276                 :             : 
    4277                 :     1246905 :     int64_to_numericvar(val, &result);
    4278                 :             : 
    4279                 :     1246905 :     res = make_result(&result);
    4280                 :             : 
    4281                 :     1246905 :     free_var(&result);
    4282                 :             : 
    4283                 :     1246905 :     return res;
    4284                 :             : }
    4285                 :             : 
    4286                 :             : /*
    4287                 :             :  * Convert val1/(10**log10val2) to numeric.  This is much faster than normal
    4288                 :             :  * numeric division.
    4289                 :             :  */
    4290                 :             : Numeric
    4291                 :       15151 : int64_div_fast_to_numeric(int64 val1, int log10val2)
    4292                 :             : {
    4293                 :             :     Numeric     res;
    4294                 :             :     NumericVar  result;
    4295                 :             :     int         rscale;
    4296                 :             :     int         w;
    4297                 :             :     int         m;
    4298                 :             : 
    4299                 :       15151 :     init_var(&result);
    4300                 :             : 
    4301                 :             :     /* result scale */
    4302                 :       15151 :     rscale = log10val2 < 0 ? 0 : log10val2;
    4303                 :             : 
    4304                 :             :     /* how much to decrease the weight by */
    4305                 :       15151 :     w = log10val2 / DEC_DIGITS;
    4306                 :             :     /* how much is left to divide by */
    4307                 :       15151 :     m = log10val2 % DEC_DIGITS;
    4308         [ -  + ]:       15151 :     if (m < 0)
    4309                 :             :     {
    4310                 :           0 :         m += DEC_DIGITS;
    4311                 :           0 :         w--;
    4312                 :             :     }
    4313                 :             : 
    4314                 :             :     /*
    4315                 :             :      * If there is anything left to divide by (10^m with 0 < m < DEC_DIGITS),
    4316                 :             :      * multiply the dividend by 10^(DEC_DIGITS - m), and shift the weight by
    4317                 :             :      * one more.
    4318                 :             :      */
    4319         [ +  - ]:       15151 :     if (m > 0)
    4320                 :             :     {
    4321                 :             : #if DEC_DIGITS == 4
    4322                 :             :         static const int pow10[] = {1, 10, 100, 1000};
    4323                 :             : #elif DEC_DIGITS == 2
    4324                 :             :         static const int pow10[] = {1, 10};
    4325                 :             : #elif DEC_DIGITS == 1
    4326                 :             :         static const int pow10[] = {1};
    4327                 :             : #else
    4328                 :             : #error unsupported NBASE
    4329                 :             : #endif
    4330                 :       15151 :         int64       factor = pow10[DEC_DIGITS - m];
    4331                 :             :         int64       new_val1;
    4332                 :             : 
    4333                 :             :         StaticAssertDecl(lengthof(pow10) == DEC_DIGITS, "mismatch with DEC_DIGITS");
    4334                 :             : 
    4335         [ +  + ]:       15151 :         if (unlikely(pg_mul_s64_overflow(val1, factor, &new_val1)))
    4336                 :             :         {
    4337                 :             :             /* do the multiplication using 128-bit integers */
    4338                 :             :             INT128      tmp;
    4339                 :             : 
    4340                 :           9 :             tmp = int64_to_int128(0);
    4341                 :           9 :             int128_add_int64_mul_int64(&tmp, val1, factor);
    4342                 :             : 
    4343                 :           9 :             int128_to_numericvar(tmp, &result);
    4344                 :             :         }
    4345                 :             :         else
    4346                 :       15142 :             int64_to_numericvar(new_val1, &result);
    4347                 :             : 
    4348                 :       15151 :         w++;
    4349                 :             :     }
    4350                 :             :     else
    4351                 :           0 :         int64_to_numericvar(val1, &result);
    4352                 :             : 
    4353                 :       15151 :     result.weight -= w;
    4354                 :       15151 :     result.dscale = rscale;
    4355                 :             : 
    4356                 :       15151 :     res = make_result(&result);
    4357                 :             : 
    4358                 :       15151 :     free_var(&result);
    4359                 :             : 
    4360                 :       15151 :     return res;
    4361                 :             : }
    4362                 :             : 
    4363                 :             : Datum
    4364                 :     1039071 : int4_numeric(PG_FUNCTION_ARGS)
    4365                 :             : {
    4366                 :     1039071 :     int32       val = PG_GETARG_INT32(0);
    4367                 :             : 
    4368                 :     1039071 :     PG_RETURN_NUMERIC(int64_to_numeric(val));
    4369                 :             : }
    4370                 :             : 
    4371                 :             : /*
    4372                 :             :  * Internal version of numeric_int4() with support for soft error reporting.
    4373                 :             :  */
    4374                 :             : int32
    4375                 :        5142 : numeric_int4_safe(Numeric num, Node *escontext)
    4376                 :             : {
    4377                 :             :     NumericVar  x;
    4378                 :             :     int32       result;
    4379                 :             : 
    4380         [ +  + ]:        5142 :     if (NUMERIC_IS_SPECIAL(num))
    4381                 :             :     {
    4382         [ +  + ]:          12 :         if (NUMERIC_IS_NAN(num))
    4383         [ +  - ]:           4 :             ereturn(escontext, 0,
    4384                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4385                 :             :                      errmsg("cannot convert NaN to %s", "integer")));
    4386                 :             :         else
    4387         [ +  - ]:           8 :             ereturn(escontext, 0,
    4388                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4389                 :             :                      errmsg("cannot convert infinity to %s", "integer")));
    4390                 :             :     }
    4391                 :             : 
    4392                 :             :     /* Convert to variable format, then convert to int4 */
    4393                 :        5130 :     init_var_from_num(num, &x);
    4394                 :             : 
    4395         [ +  + ]:        5130 :     if (!numericvar_to_int32(&x, &result))
    4396         [ +  + ]:          70 :         ereturn(escontext, 0,
    4397                 :             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    4398                 :             :                  errmsg("integer out of range")));
    4399                 :             : 
    4400                 :        5060 :     return result;
    4401                 :             : }
    4402                 :             : 
    4403                 :             : Datum
    4404                 :        3727 : numeric_int4(PG_FUNCTION_ARGS)
    4405                 :             : {
    4406                 :        3727 :     Numeric     num = PG_GETARG_NUMERIC(0);
    4407                 :             :     int32       result;
    4408                 :             : 
    4409                 :        3727 :     result = numeric_int4_safe(num, fcinfo->context);
    4410                 :             : 
    4411   [ -  +  -  -  :        3707 :     if (unlikely(SOFT_ERROR_OCCURRED(fcinfo->context)))
          -  +  -  -  -  
                      + ]
    4412                 :           0 :         PG_RETURN_NULL();
    4413                 :             : 
    4414                 :        3707 :     PG_RETURN_INT32(result);
    4415                 :             : }
    4416                 :             : 
    4417                 :             : /*
    4418                 :             :  * Given a NumericVar, convert it to an int32. If the NumericVar
    4419                 :             :  * exceeds the range of an int32, false is returned, otherwise true is returned.
    4420                 :             :  * The input NumericVar is *not* free'd.
    4421                 :             :  */
    4422                 :             : static bool
    4423                 :        5631 : numericvar_to_int32(const NumericVar *var, int32 *result)
    4424                 :             : {
    4425                 :             :     int64       val;
    4426                 :             : 
    4427         [ +  + ]:        5631 :     if (!numericvar_to_int64(var, &val))
    4428                 :           4 :         return false;
    4429                 :             : 
    4430   [ +  +  +  + ]:        5627 :     if (unlikely(val < PG_INT32_MIN) || unlikely(val > PG_INT32_MAX))
    4431                 :          66 :         return false;
    4432                 :             : 
    4433                 :             :     /* Down-convert to int4 */
    4434                 :        5561 :     *result = (int32) val;
    4435                 :             : 
    4436                 :        5561 :     return true;
    4437                 :             : }
    4438                 :             : 
    4439                 :             : Datum
    4440                 :       24588 : int8_numeric(PG_FUNCTION_ARGS)
    4441                 :             : {
    4442                 :       24588 :     int64       val = PG_GETARG_INT64(0);
    4443                 :             : 
    4444                 :       24588 :     PG_RETURN_NUMERIC(int64_to_numeric(val));
    4445                 :             : }
    4446                 :             : 
    4447                 :             : /*
    4448                 :             :  * Internal version of numeric_int8() with support for soft error reporting.
    4449                 :             :  */
    4450                 :             : int64
    4451                 :         387 : numeric_int8_safe(Numeric num, Node *escontext)
    4452                 :             : {
    4453                 :             :     NumericVar  x;
    4454                 :             :     int64       result;
    4455                 :             : 
    4456         [ +  + ]:         387 :     if (NUMERIC_IS_SPECIAL(num))
    4457                 :             :     {
    4458         [ +  + ]:          12 :         if (NUMERIC_IS_NAN(num))
    4459         [ +  - ]:           4 :             ereturn(escontext, 0,
    4460                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4461                 :             :                      errmsg("cannot convert NaN to %s", "bigint")));
    4462                 :             :         else
    4463         [ +  - ]:           8 :             ereturn(escontext, 0,
    4464                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4465                 :             :                      errmsg("cannot convert infinity to %s", "bigint")));
    4466                 :             :     }
    4467                 :             : 
    4468                 :             :     /* Convert to variable format, then convert to int8 */
    4469                 :         375 :     init_var_from_num(num, &x);
    4470                 :             : 
    4471         [ +  + ]:         375 :     if (!numericvar_to_int64(&x, &result))
    4472         [ +  + ]:          40 :         ereturn(escontext, 0,
    4473                 :             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    4474                 :             :                  errmsg("bigint out of range")));
    4475                 :             : 
    4476                 :         335 :     return result;
    4477                 :             : }
    4478                 :             : 
    4479                 :             : Datum
    4480                 :         347 : numeric_int8(PG_FUNCTION_ARGS)
    4481                 :             : {
    4482                 :         347 :     Numeric     num = PG_GETARG_NUMERIC(0);
    4483                 :             :     int64       result;
    4484                 :             : 
    4485                 :         347 :     result = numeric_int8_safe(num, fcinfo->context);
    4486                 :             : 
    4487   [ -  +  -  -  :         303 :     if (unlikely(SOFT_ERROR_OCCURRED(fcinfo->context)))
          -  +  -  -  -  
                      + ]
    4488                 :           0 :         PG_RETURN_NULL();
    4489                 :             : 
    4490                 :         303 :     PG_RETURN_INT64(result);
    4491                 :             : }
    4492                 :             : 
    4493                 :             : 
    4494                 :             : Datum
    4495                 :           5 : int2_numeric(PG_FUNCTION_ARGS)
    4496                 :             : {
    4497                 :           5 :     int16       val = PG_GETARG_INT16(0);
    4498                 :             : 
    4499                 :           5 :     PG_RETURN_NUMERIC(int64_to_numeric(val));
    4500                 :             : }
    4501                 :             : 
    4502                 :             : 
    4503                 :             : Datum
    4504                 :          73 : numeric_int2(PG_FUNCTION_ARGS)
    4505                 :             : {
    4506                 :          73 :     Numeric     num = PG_GETARG_NUMERIC(0);
    4507                 :             :     NumericVar  x;
    4508                 :             :     int64       val;
    4509                 :             :     int16       result;
    4510                 :             : 
    4511         [ +  + ]:          73 :     if (NUMERIC_IS_SPECIAL(num))
    4512                 :             :     {
    4513         [ +  + ]:          12 :         if (NUMERIC_IS_NAN(num))
    4514         [ +  - ]:           4 :             ereturn(fcinfo->context, (Datum) 0,
    4515                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4516                 :             :                      errmsg("cannot convert NaN to %s", "smallint")));
    4517                 :             :         else
    4518         [ +  - ]:           8 :             ereturn(fcinfo->context, (Datum) 0,
    4519                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4520                 :             :                      errmsg("cannot convert infinity to %s", "smallint")));
    4521                 :             :     }
    4522                 :             : 
    4523                 :             :     /* Convert to variable format and thence to int8 */
    4524                 :          61 :     init_var_from_num(num, &x);
    4525                 :             : 
    4526         [ -  + ]:          61 :     if (!numericvar_to_int64(&x, &val))
    4527         [ #  # ]:           0 :         ereturn(fcinfo->context, (Datum) 0,
    4528                 :             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    4529                 :             :                  errmsg("smallint out of range")));
    4530                 :             : 
    4531   [ +  +  +  + ]:          61 :     if (unlikely(val < PG_INT16_MIN) || unlikely(val > PG_INT16_MAX))
    4532         [ +  - ]:           8 :         ereturn(fcinfo->context, (Datum) 0,
    4533                 :             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    4534                 :             :                  errmsg("smallint out of range")));
    4535                 :             : 
    4536                 :             :     /* Down-convert to int2 */
    4537                 :          53 :     result = (int16) val;
    4538                 :             : 
    4539                 :          53 :     PG_RETURN_INT16(result);
    4540                 :             : }
    4541                 :             : 
    4542                 :             : 
    4543                 :             : Datum
    4544                 :         654 : float8_numeric(PG_FUNCTION_ARGS)
    4545                 :             : {
    4546                 :         654 :     float8      val = PG_GETARG_FLOAT8(0);
    4547                 :             :     Numeric     res;
    4548                 :             :     NumericVar  result;
    4549                 :             :     char        buf[DBL_DIG + 100];
    4550                 :             :     const char *endptr;
    4551                 :             : 
    4552         [ +  + ]:         654 :     if (isnan(val))
    4553                 :           5 :         PG_RETURN_NUMERIC(make_result(&const_nan));
    4554                 :             : 
    4555         [ +  + ]:         649 :     if (isinf(val))
    4556                 :             :     {
    4557         [ +  + ]:          10 :         if (val < 0)
    4558                 :           5 :             PG_RETURN_NUMERIC(make_result(&const_ninf));
    4559                 :             :         else
    4560                 :           5 :             PG_RETURN_NUMERIC(make_result(&const_pinf));
    4561                 :             :     }
    4562                 :             : 
    4563                 :         639 :     snprintf(buf, sizeof(buf), "%.*g", DBL_DIG, val);
    4564                 :             : 
    4565                 :         639 :     init_var(&result);
    4566                 :             : 
    4567                 :             :     /* Assume we need not worry about leading/trailing spaces */
    4568         [ -  + ]:         639 :     if (!set_var_from_str(buf, buf, &result, &endptr, fcinfo->context))
    4569                 :           0 :         PG_RETURN_NULL();
    4570                 :             : 
    4571                 :         639 :     res = make_result(&result);
    4572                 :             : 
    4573                 :         639 :     free_var(&result);
    4574                 :             : 
    4575                 :         639 :     PG_RETURN_NUMERIC(res);
    4576                 :             : }
    4577                 :             : 
    4578                 :             : 
    4579                 :             : Datum
    4580                 :      347601 : numeric_float8(PG_FUNCTION_ARGS)
    4581                 :             : {
    4582                 :      347601 :     Numeric     num = PG_GETARG_NUMERIC(0);
    4583                 :             :     char       *tmp;
    4584                 :             :     Datum       result;
    4585                 :             : 
    4586         [ +  + ]:      347601 :     if (NUMERIC_IS_SPECIAL(num))
    4587                 :             :     {
    4588         [ +  + ]:          56 :         if (NUMERIC_IS_PINF(num))
    4589                 :          17 :             PG_RETURN_FLOAT8(get_float8_infinity());
    4590         [ +  + ]:          39 :         else if (NUMERIC_IS_NINF(num))
    4591                 :          17 :             PG_RETURN_FLOAT8(-get_float8_infinity());
    4592                 :             :         else
    4593                 :          22 :             PG_RETURN_FLOAT8(get_float8_nan());
    4594                 :             :     }
    4595                 :             : 
    4596                 :      347545 :     tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
    4597                 :             :                                               NumericGetDatum(num)));
    4598         [ -  + ]:      347545 :     if (!DirectInputFunctionCallSafe(float8in, tmp,
    4599                 :             :                                      InvalidOid, -1,
    4600                 :             :                                      (Node *) fcinfo->context,
    4601                 :             :                                      &result))
    4602                 :             :     {
    4603                 :           0 :         pfree(tmp);
    4604                 :           0 :         PG_RETURN_NULL();
    4605                 :             :     }
    4606                 :             : 
    4607                 :      347545 :     PG_RETURN_DATUM(result);
    4608                 :             : }
    4609                 :             : 
    4610                 :             : 
    4611                 :             : /*
    4612                 :             :  * Convert numeric to float8; if out of range, return +/- HUGE_VAL
    4613                 :             :  *
    4614                 :             :  * (internal helper function, not directly callable from SQL)
    4615                 :             :  */
    4616                 :             : Datum
    4617                 :          16 : numeric_float8_no_overflow(PG_FUNCTION_ARGS)
    4618                 :             : {
    4619                 :          16 :     Numeric     num = PG_GETARG_NUMERIC(0);
    4620                 :             :     double      val;
    4621                 :             : 
    4622         [ -  + ]:          16 :     if (NUMERIC_IS_SPECIAL(num))
    4623                 :             :     {
    4624         [ #  # ]:           0 :         if (NUMERIC_IS_PINF(num))
    4625                 :           0 :             val = HUGE_VAL;
    4626         [ #  # ]:           0 :         else if (NUMERIC_IS_NINF(num))
    4627                 :           0 :             val = -HUGE_VAL;
    4628                 :             :         else
    4629                 :           0 :             val = get_float8_nan();
    4630                 :             :     }
    4631                 :             :     else
    4632                 :             :     {
    4633                 :             :         NumericVar  x;
    4634                 :             : 
    4635                 :          16 :         init_var_from_num(num, &x);
    4636                 :          16 :         val = numericvar_to_double_no_overflow(&x);
    4637                 :             :     }
    4638                 :             : 
    4639                 :          16 :     PG_RETURN_FLOAT8(val);
    4640                 :             : }
    4641                 :             : 
    4642                 :             : Datum
    4643                 :       15083 : float4_numeric(PG_FUNCTION_ARGS)
    4644                 :             : {
    4645                 :       15083 :     float4      val = PG_GETARG_FLOAT4(0);
    4646                 :             :     Numeric     res;
    4647                 :             :     NumericVar  result;
    4648                 :             :     char        buf[FLT_DIG + 100];
    4649                 :             :     const char *endptr;
    4650                 :             : 
    4651         [ +  + ]:       15083 :     if (isnan(val))
    4652                 :           5 :         PG_RETURN_NUMERIC(make_result(&const_nan));
    4653                 :             : 
    4654         [ +  + ]:       15078 :     if (isinf(val))
    4655                 :             :     {
    4656         [ +  + ]:          10 :         if (val < 0)
    4657                 :           5 :             PG_RETURN_NUMERIC(make_result(&const_ninf));
    4658                 :             :         else
    4659                 :           5 :             PG_RETURN_NUMERIC(make_result(&const_pinf));
    4660                 :             :     }
    4661                 :             : 
    4662                 :       15068 :     snprintf(buf, sizeof(buf), "%.*g", FLT_DIG, val);
    4663                 :             : 
    4664                 :       15068 :     init_var(&result);
    4665                 :             : 
    4666                 :             :     /* Assume we need not worry about leading/trailing spaces */
    4667         [ -  + ]:       15068 :     if (!set_var_from_str(buf, buf, &result, &endptr, fcinfo->context))
    4668                 :           0 :         PG_RETURN_NULL();
    4669                 :             : 
    4670                 :       15068 :     res = make_result(&result);
    4671                 :             : 
    4672                 :       15068 :     free_var(&result);
    4673                 :             : 
    4674                 :       15068 :     PG_RETURN_NUMERIC(res);
    4675                 :             : }
    4676                 :             : 
    4677                 :             : 
    4678                 :             : Datum
    4679                 :        1718 : numeric_float4(PG_FUNCTION_ARGS)
    4680                 :             : {
    4681                 :        1718 :     Numeric     num = PG_GETARG_NUMERIC(0);
    4682                 :             :     char       *tmp;
    4683                 :             :     Datum       result;
    4684                 :             : 
    4685         [ +  + ]:        1718 :     if (NUMERIC_IS_SPECIAL(num))
    4686                 :             :     {
    4687         [ +  + ]:          56 :         if (NUMERIC_IS_PINF(num))
    4688                 :          17 :             PG_RETURN_FLOAT4(get_float4_infinity());
    4689         [ +  + ]:          39 :         else if (NUMERIC_IS_NINF(num))
    4690                 :          17 :             PG_RETURN_FLOAT4(-get_float4_infinity());
    4691                 :             :         else
    4692                 :          22 :             PG_RETURN_FLOAT4(get_float4_nan());
    4693                 :             :     }
    4694                 :             : 
    4695                 :        1662 :     tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
    4696                 :             :                                               NumericGetDatum(num)));
    4697                 :             : 
    4698         [ -  + ]:        1662 :     if (!DirectInputFunctionCallSafe(float4in, tmp,
    4699                 :             :                                      InvalidOid, -1,
    4700                 :             :                                      (Node *) fcinfo->context,
    4701                 :             :                                      &result))
    4702                 :             :     {
    4703                 :           0 :         pfree(tmp);
    4704                 :           0 :         PG_RETURN_NULL();
    4705                 :             :     }
    4706                 :             : 
    4707                 :        1662 :     pfree(tmp);
    4708                 :             : 
    4709                 :        1662 :     PG_RETURN_DATUM(result);
    4710                 :             : }
    4711                 :             : 
    4712                 :             : 
    4713                 :             : Datum
    4714                 :         104 : numeric_pg_lsn(PG_FUNCTION_ARGS)
    4715                 :             : {
    4716                 :         104 :     Numeric     num = PG_GETARG_NUMERIC(0);
    4717                 :             :     NumericVar  x;
    4718                 :             :     XLogRecPtr  result;
    4719                 :             : 
    4720         [ +  + ]:         104 :     if (NUMERIC_IS_SPECIAL(num))
    4721                 :             :     {
    4722         [ +  - ]:           4 :         if (NUMERIC_IS_NAN(num))
    4723         [ +  - ]:           4 :             ereport(ERROR,
    4724                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4725                 :             :                      errmsg("cannot convert NaN to %s", "pg_lsn")));
    4726                 :             :         else
    4727         [ #  # ]:           0 :             ereport(ERROR,
    4728                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4729                 :             :                      errmsg("cannot convert infinity to %s", "pg_lsn")));
    4730                 :             :     }
    4731                 :             : 
    4732                 :             :     /* Convert to variable format and thence to pg_lsn */
    4733                 :         100 :     init_var_from_num(num, &x);
    4734                 :             : 
    4735         [ +  + ]:         100 :     if (!numericvar_to_uint64(&x, (uint64 *) &result))
    4736         [ +  - ]:          16 :         ereport(ERROR,
    4737                 :             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    4738                 :             :                  errmsg("pg_lsn out of range")));
    4739                 :             : 
    4740                 :          84 :     PG_RETURN_LSN(result);
    4741                 :             : }
    4742                 :             : 
    4743                 :             : 
    4744                 :             : /* ----------------------------------------------------------------------
    4745                 :             :  *
    4746                 :             :  * Aggregate functions
    4747                 :             :  *
    4748                 :             :  * The transition datatype for all these aggregates is declared as INTERNAL.
    4749                 :             :  * Actually, it's a pointer to a NumericAggState allocated in the aggregate
    4750                 :             :  * context.  The digit buffers for the NumericVars will be there too.
    4751                 :             :  *
    4752                 :             :  * For integer inputs, some aggregates use special-purpose 64-bit or 128-bit
    4753                 :             :  * integer based transition datatypes to speed up calculations.
    4754                 :             :  *
    4755                 :             :  * ----------------------------------------------------------------------
    4756                 :             :  */
    4757                 :             : 
    4758                 :             : typedef struct NumericAggState
    4759                 :             : {
    4760                 :             :     bool        calcSumX2;      /* if true, calculate sumX2 */
    4761                 :             :     MemoryContext agg_context;  /* context we're calculating in */
    4762                 :             :     int64       N;              /* count of processed numbers */
    4763                 :             :     NumericSumAccum sumX;       /* sum of processed numbers */
    4764                 :             :     NumericSumAccum sumX2;      /* sum of squares of processed numbers */
    4765                 :             :     int         maxScale;       /* maximum scale seen so far */
    4766                 :             :     int64       maxScaleCount;  /* number of values seen with maximum scale */
    4767                 :             :     /* These counts are *not* included in N!  Use NA_TOTAL_COUNT() as needed */
    4768                 :             :     int64       NaNcount;       /* count of NaN values */
    4769                 :             :     int64       pInfcount;      /* count of +Inf values */
    4770                 :             :     int64       nInfcount;      /* count of -Inf values */
    4771                 :             : } NumericAggState;
    4772                 :             : 
    4773                 :             : #define NA_TOTAL_COUNT(na) \
    4774                 :             :     ((na)->N + (na)->NaNcount + (na)->pInfcount + (na)->nInfcount)
    4775                 :             : 
    4776                 :             : /*
    4777                 :             :  * Prepare state data for a numeric aggregate function that needs to compute
    4778                 :             :  * sum, count and optionally sum of squares of the input.
    4779                 :             :  */
    4780                 :             : static NumericAggState *
    4781                 :      114082 : makeNumericAggState(FunctionCallInfo fcinfo, bool calcSumX2)
    4782                 :             : {
    4783                 :             :     NumericAggState *state;
    4784                 :             :     MemoryContext agg_context;
    4785                 :             :     MemoryContext old_context;
    4786                 :             : 
    4787         [ -  + ]:      114082 :     if (!AggCheckCallContext(fcinfo, &agg_context))
    4788         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    4789                 :             : 
    4790                 :      114082 :     old_context = MemoryContextSwitchTo(agg_context);
    4791                 :             : 
    4792                 :      114082 :     state = palloc0_object(NumericAggState);
    4793                 :      114082 :     state->calcSumX2 = calcSumX2;
    4794                 :      114082 :     state->agg_context = agg_context;
    4795                 :             : 
    4796                 :      114082 :     MemoryContextSwitchTo(old_context);
    4797                 :             : 
    4798                 :      114082 :     return state;
    4799                 :             : }
    4800                 :             : 
    4801                 :             : /*
    4802                 :             :  * Like makeNumericAggState(), but allocate the state in the current memory
    4803                 :             :  * context.
    4804                 :             :  */
    4805                 :             : static NumericAggState *
    4806                 :          56 : makeNumericAggStateCurrentContext(bool calcSumX2)
    4807                 :             : {
    4808                 :             :     NumericAggState *state;
    4809                 :             : 
    4810                 :          56 :     state = palloc0_object(NumericAggState);
    4811                 :          56 :     state->calcSumX2 = calcSumX2;
    4812                 :          56 :     state->agg_context = CurrentMemoryContext;
    4813                 :             : 
    4814                 :          56 :     return state;
    4815                 :             : }
    4816                 :             : 
    4817                 :             : /*
    4818                 :             :  * Accumulate a new input value for numeric aggregate functions.
    4819                 :             :  */
    4820                 :             : static void
    4821                 :     1409012 : do_numeric_accum(NumericAggState *state, Numeric newval)
    4822                 :             : {
    4823                 :             :     NumericVar  X;
    4824                 :             :     NumericVar  X2;
    4825                 :             :     MemoryContext old_context;
    4826                 :             : 
    4827                 :             :     /* Count NaN/infinity inputs separately from all else */
    4828         [ +  + ]:     1409012 :     if (NUMERIC_IS_SPECIAL(newval))
    4829                 :             :     {
    4830         [ +  + ]:         108 :         if (NUMERIC_IS_PINF(newval))
    4831                 :          48 :             state->pInfcount++;
    4832         [ +  + ]:          60 :         else if (NUMERIC_IS_NINF(newval))
    4833                 :          24 :             state->nInfcount++;
    4834                 :             :         else
    4835                 :          36 :             state->NaNcount++;
    4836                 :         108 :         return;
    4837                 :             :     }
    4838                 :             : 
    4839                 :             :     /* load processed number in short-lived context */
    4840                 :     1408904 :     init_var_from_num(newval, &X);
    4841                 :             : 
    4842                 :             :     /*
    4843                 :             :      * Track the highest input dscale that we've seen, to support inverse
    4844                 :             :      * transitions (see do_numeric_discard).
    4845                 :             :      */
    4846         [ +  + ]:     1408904 :     if (X.dscale > state->maxScale)
    4847                 :             :     {
    4848                 :         104 :         state->maxScale = X.dscale;
    4849                 :         104 :         state->maxScaleCount = 1;
    4850                 :             :     }
    4851         [ +  + ]:     1408800 :     else if (X.dscale == state->maxScale)
    4852                 :     1408776 :         state->maxScaleCount++;
    4853                 :             : 
    4854                 :             :     /* if we need X^2, calculate that in short-lived context */
    4855         [ +  + ]:     1408904 :     if (state->calcSumX2)
    4856                 :             :     {
    4857                 :      160488 :         init_var(&X2);
    4858                 :      160488 :         mul_var(&X, &X, &X2, X.dscale * 2);
    4859                 :             :     }
    4860                 :             : 
    4861                 :             :     /* The rest of this needs to work in the aggregate context */
    4862                 :     1408904 :     old_context = MemoryContextSwitchTo(state->agg_context);
    4863                 :             : 
    4864                 :     1408904 :     state->N++;
    4865                 :             : 
    4866                 :             :     /* Accumulate sums */
    4867                 :     1408904 :     accum_sum_add(&(state->sumX), &X);
    4868                 :             : 
    4869         [ +  + ]:     1408904 :     if (state->calcSumX2)
    4870                 :      160488 :         accum_sum_add(&(state->sumX2), &X2);
    4871                 :             : 
    4872                 :     1408904 :     MemoryContextSwitchTo(old_context);
    4873                 :             : }
    4874                 :             : 
    4875                 :             : /*
    4876                 :             :  * Attempt to remove an input value from the aggregated state.
    4877                 :             :  *
    4878                 :             :  * If the value cannot be removed then the function will return false; the
    4879                 :             :  * possible reasons for failing are described below.
    4880                 :             :  *
    4881                 :             :  * If we aggregate the values 1.01 and 2 then the result will be 3.01.
    4882                 :             :  * If we are then asked to un-aggregate the 1.01 then we must fail as we
    4883                 :             :  * won't be able to tell what the new aggregated value's dscale should be.
    4884                 :             :  * We don't want to return 2.00 (dscale = 2), since the sum's dscale would
    4885                 :             :  * have been zero if we'd really aggregated only 2.
    4886                 :             :  *
    4887                 :             :  * Note: alternatively, we could count the number of inputs with each possible
    4888                 :             :  * dscale (up to some sane limit).  Not yet clear if it's worth the trouble.
    4889                 :             :  */
    4890                 :             : static bool
    4891                 :         228 : do_numeric_discard(NumericAggState *state, Numeric newval)
    4892                 :             : {
    4893                 :             :     NumericVar  X;
    4894                 :             :     NumericVar  X2;
    4895                 :             :     MemoryContext old_context;
    4896                 :             : 
    4897                 :             :     /* Count NaN/infinity inputs separately from all else */
    4898         [ +  + ]:         228 :     if (NUMERIC_IS_SPECIAL(newval))
    4899                 :             :     {
    4900         [ -  + ]:           4 :         if (NUMERIC_IS_PINF(newval))
    4901                 :           0 :             state->pInfcount--;
    4902         [ -  + ]:           4 :         else if (NUMERIC_IS_NINF(newval))
    4903                 :           0 :             state->nInfcount--;
    4904                 :             :         else
    4905                 :           4 :             state->NaNcount--;
    4906                 :           4 :         return true;
    4907                 :             :     }
    4908                 :             : 
    4909                 :             :     /* load processed number in short-lived context */
    4910                 :         224 :     init_var_from_num(newval, &X);
    4911                 :             : 
    4912                 :             :     /*
    4913                 :             :      * state->sumX's dscale is the maximum dscale of any of the inputs.
    4914                 :             :      * Removing the last input with that dscale would require us to recompute
    4915                 :             :      * the maximum dscale of the *remaining* inputs, which we cannot do unless
    4916                 :             :      * no more non-NaN inputs remain at all.  So we report a failure instead,
    4917                 :             :      * and force the aggregation to be redone from scratch.
    4918                 :             :      */
    4919         [ +  - ]:         224 :     if (X.dscale == state->maxScale)
    4920                 :             :     {
    4921   [ +  +  +  + ]:         224 :         if (state->maxScaleCount > 1 || state->maxScale == 0)
    4922                 :             :         {
    4923                 :             :             /*
    4924                 :             :              * Some remaining inputs have same dscale, or dscale hasn't gotten
    4925                 :             :              * above zero anyway
    4926                 :             :              */
    4927                 :         212 :             state->maxScaleCount--;
    4928                 :             :         }
    4929         [ +  + ]:          12 :         else if (state->N == 1)
    4930                 :             :         {
    4931                 :             :             /* No remaining non-NaN inputs at all, so reset maxScale */
    4932                 :           8 :             state->maxScale = 0;
    4933                 :           8 :             state->maxScaleCount = 0;
    4934                 :             :         }
    4935                 :             :         else
    4936                 :             :         {
    4937                 :             :             /* Correct new maxScale is uncertain, must fail */
    4938                 :           4 :             return false;
    4939                 :             :         }
    4940                 :             :     }
    4941                 :             : 
    4942                 :             :     /* if we need X^2, calculate that in short-lived context */
    4943         [ +  + ]:         220 :     if (state->calcSumX2)
    4944                 :             :     {
    4945                 :         192 :         init_var(&X2);
    4946                 :         192 :         mul_var(&X, &X, &X2, X.dscale * 2);
    4947                 :             :     }
    4948                 :             : 
    4949                 :             :     /* The rest of this needs to work in the aggregate context */
    4950                 :         220 :     old_context = MemoryContextSwitchTo(state->agg_context);
    4951                 :             : 
    4952         [ +  + ]:         220 :     if (state->N-- > 1)
    4953                 :             :     {
    4954                 :             :         /* Negate X, to subtract it from the sum */
    4955         [ +  - ]:         208 :         X.sign = (X.sign == NUMERIC_POS ? NUMERIC_NEG : NUMERIC_POS);
    4956                 :         208 :         accum_sum_add(&(state->sumX), &X);
    4957                 :             : 
    4958         [ +  + ]:         208 :         if (state->calcSumX2)
    4959                 :             :         {
    4960                 :             :             /* Negate X^2. X^2 is always positive */
    4961                 :         192 :             X2.sign = NUMERIC_NEG;
    4962                 :         192 :             accum_sum_add(&(state->sumX2), &X2);
    4963                 :             :         }
    4964                 :             :     }
    4965                 :             :     else
    4966                 :             :     {
    4967                 :             :         /* Zero the sums */
    4968                 :             :         Assert(state->N == 0);
    4969                 :             : 
    4970                 :          12 :         accum_sum_reset(&state->sumX);
    4971         [ -  + ]:          12 :         if (state->calcSumX2)
    4972                 :           0 :             accum_sum_reset(&state->sumX2);
    4973                 :             :     }
    4974                 :             : 
    4975                 :         220 :     MemoryContextSwitchTo(old_context);
    4976                 :             : 
    4977                 :         220 :     return true;
    4978                 :             : }
    4979                 :             : 
    4980                 :             : /*
    4981                 :             :  * Generic transition function for numeric aggregates that require sumX2.
    4982                 :             :  */
    4983                 :             : Datum
    4984                 :         428 : numeric_accum(PG_FUNCTION_ARGS)
    4985                 :             : {
    4986                 :             :     NumericAggState *state;
    4987                 :             : 
    4988         [ +  + ]:         428 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    4989                 :             : 
    4990                 :             :     /* Create the state data on the first call */
    4991         [ +  + ]:         428 :     if (state == NULL)
    4992                 :         116 :         state = makeNumericAggState(fcinfo, true);
    4993                 :             : 
    4994         [ +  + ]:         428 :     if (!PG_ARGISNULL(1))
    4995                 :         416 :         do_numeric_accum(state, PG_GETARG_NUMERIC(1));
    4996                 :             : 
    4997                 :         428 :     PG_RETURN_POINTER(state);
    4998                 :             : }
    4999                 :             : 
    5000                 :             : /*
    5001                 :             :  * Generic combine function for numeric aggregates which require sumX2
    5002                 :             :  */
    5003                 :             : Datum
    5004                 :          24 : numeric_combine(PG_FUNCTION_ARGS)
    5005                 :             : {
    5006                 :             :     NumericAggState *state1;
    5007                 :             :     NumericAggState *state2;
    5008                 :             :     MemoryContext agg_context;
    5009                 :             :     MemoryContext old_context;
    5010                 :             : 
    5011         [ -  + ]:          24 :     if (!AggCheckCallContext(fcinfo, &agg_context))
    5012         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5013                 :             : 
    5014         [ +  + ]:          24 :     state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    5015         [ +  - ]:          24 :     state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
    5016                 :             : 
    5017         [ -  + ]:          24 :     if (state2 == NULL)
    5018                 :           0 :         PG_RETURN_POINTER(state1);
    5019                 :             : 
    5020                 :             :     /* manually copy all fields from state2 to state1 */
    5021         [ +  + ]:          24 :     if (state1 == NULL)
    5022                 :             :     {
    5023                 :          12 :         old_context = MemoryContextSwitchTo(agg_context);
    5024                 :             : 
    5025                 :          12 :         state1 = makeNumericAggStateCurrentContext(true);
    5026                 :          12 :         state1->N = state2->N;
    5027                 :          12 :         state1->NaNcount = state2->NaNcount;
    5028                 :          12 :         state1->pInfcount = state2->pInfcount;
    5029                 :          12 :         state1->nInfcount = state2->nInfcount;
    5030                 :          12 :         state1->maxScale = state2->maxScale;
    5031                 :          12 :         state1->maxScaleCount = state2->maxScaleCount;
    5032                 :             : 
    5033                 :          12 :         accum_sum_copy(&state1->sumX, &state2->sumX);
    5034                 :          12 :         accum_sum_copy(&state1->sumX2, &state2->sumX2);
    5035                 :             : 
    5036                 :          12 :         MemoryContextSwitchTo(old_context);
    5037                 :             : 
    5038                 :          12 :         PG_RETURN_POINTER(state1);
    5039                 :             :     }
    5040                 :             : 
    5041                 :          12 :     state1->N += state2->N;
    5042                 :          12 :     state1->NaNcount += state2->NaNcount;
    5043                 :          12 :     state1->pInfcount += state2->pInfcount;
    5044                 :          12 :     state1->nInfcount += state2->nInfcount;
    5045                 :             : 
    5046         [ +  - ]:          12 :     if (state2->N > 0)
    5047                 :             :     {
    5048                 :             :         /*
    5049                 :             :          * These are currently only needed for moving aggregates, but let's do
    5050                 :             :          * the right thing anyway...
    5051                 :             :          */
    5052         [ -  + ]:          12 :         if (state2->maxScale > state1->maxScale)
    5053                 :             :         {
    5054                 :           0 :             state1->maxScale = state2->maxScale;
    5055                 :           0 :             state1->maxScaleCount = state2->maxScaleCount;
    5056                 :             :         }
    5057         [ +  - ]:          12 :         else if (state2->maxScale == state1->maxScale)
    5058                 :          12 :             state1->maxScaleCount += state2->maxScaleCount;
    5059                 :             : 
    5060                 :             :         /* The rest of this needs to work in the aggregate context */
    5061                 :          12 :         old_context = MemoryContextSwitchTo(agg_context);
    5062                 :             : 
    5063                 :             :         /* Accumulate sums */
    5064                 :          12 :         accum_sum_combine(&state1->sumX, &state2->sumX);
    5065                 :          12 :         accum_sum_combine(&state1->sumX2, &state2->sumX2);
    5066                 :             : 
    5067                 :          12 :         MemoryContextSwitchTo(old_context);
    5068                 :             :     }
    5069                 :          12 :     PG_RETURN_POINTER(state1);
    5070                 :             : }
    5071                 :             : 
    5072                 :             : /*
    5073                 :             :  * Generic transition function for numeric aggregates that don't require sumX2.
    5074                 :             :  */
    5075                 :             : Datum
    5076                 :     1248516 : numeric_avg_accum(PG_FUNCTION_ARGS)
    5077                 :             : {
    5078                 :             :     NumericAggState *state;
    5079                 :             : 
    5080         [ +  + ]:     1248516 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    5081                 :             : 
    5082                 :             :     /* Create the state data on the first call */
    5083         [ +  + ]:     1248516 :     if (state == NULL)
    5084                 :      113926 :         state = makeNumericAggState(fcinfo, false);
    5085                 :             : 
    5086         [ +  + ]:     1248516 :     if (!PG_ARGISNULL(1))
    5087                 :     1248476 :         do_numeric_accum(state, PG_GETARG_NUMERIC(1));
    5088                 :             : 
    5089                 :     1248516 :     PG_RETURN_POINTER(state);
    5090                 :             : }
    5091                 :             : 
    5092                 :             : /*
    5093                 :             :  * Combine function for numeric aggregates which don't require sumX2
    5094                 :             :  */
    5095                 :             : Datum
    5096                 :          16 : numeric_avg_combine(PG_FUNCTION_ARGS)
    5097                 :             : {
    5098                 :             :     NumericAggState *state1;
    5099                 :             :     NumericAggState *state2;
    5100                 :             :     MemoryContext agg_context;
    5101                 :             :     MemoryContext old_context;
    5102                 :             : 
    5103         [ -  + ]:          16 :     if (!AggCheckCallContext(fcinfo, &agg_context))
    5104         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5105                 :             : 
    5106         [ +  + ]:          16 :     state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    5107         [ +  - ]:          16 :     state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
    5108                 :             : 
    5109         [ -  + ]:          16 :     if (state2 == NULL)
    5110                 :           0 :         PG_RETURN_POINTER(state1);
    5111                 :             : 
    5112                 :             :     /* manually copy all fields from state2 to state1 */
    5113         [ +  + ]:          16 :     if (state1 == NULL)
    5114                 :             :     {
    5115                 :           4 :         old_context = MemoryContextSwitchTo(agg_context);
    5116                 :             : 
    5117                 :           4 :         state1 = makeNumericAggStateCurrentContext(false);
    5118                 :           4 :         state1->N = state2->N;
    5119                 :           4 :         state1->NaNcount = state2->NaNcount;
    5120                 :           4 :         state1->pInfcount = state2->pInfcount;
    5121                 :           4 :         state1->nInfcount = state2->nInfcount;
    5122                 :           4 :         state1->maxScale = state2->maxScale;
    5123                 :           4 :         state1->maxScaleCount = state2->maxScaleCount;
    5124                 :             : 
    5125                 :           4 :         accum_sum_copy(&state1->sumX, &state2->sumX);
    5126                 :             : 
    5127                 :           4 :         MemoryContextSwitchTo(old_context);
    5128                 :             : 
    5129                 :           4 :         PG_RETURN_POINTER(state1);
    5130                 :             :     }
    5131                 :             : 
    5132                 :          12 :     state1->N += state2->N;
    5133                 :          12 :     state1->NaNcount += state2->NaNcount;
    5134                 :          12 :     state1->pInfcount += state2->pInfcount;
    5135                 :          12 :     state1->nInfcount += state2->nInfcount;
    5136                 :             : 
    5137         [ +  - ]:          12 :     if (state2->N > 0)
    5138                 :             :     {
    5139                 :             :         /*
    5140                 :             :          * These are currently only needed for moving aggregates, but let's do
    5141                 :             :          * the right thing anyway...
    5142                 :             :          */
    5143         [ -  + ]:          12 :         if (state2->maxScale > state1->maxScale)
    5144                 :             :         {
    5145                 :           0 :             state1->maxScale = state2->maxScale;
    5146                 :           0 :             state1->maxScaleCount = state2->maxScaleCount;
    5147                 :             :         }
    5148         [ +  - ]:          12 :         else if (state2->maxScale == state1->maxScale)
    5149                 :          12 :             state1->maxScaleCount += state2->maxScaleCount;
    5150                 :             : 
    5151                 :             :         /* The rest of this needs to work in the aggregate context */
    5152                 :          12 :         old_context = MemoryContextSwitchTo(agg_context);
    5153                 :             : 
    5154                 :             :         /* Accumulate sums */
    5155                 :          12 :         accum_sum_combine(&state1->sumX, &state2->sumX);
    5156                 :             : 
    5157                 :          12 :         MemoryContextSwitchTo(old_context);
    5158                 :             :     }
    5159                 :          12 :     PG_RETURN_POINTER(state1);
    5160                 :             : }
    5161                 :             : 
    5162                 :             : /*
    5163                 :             :  * numeric_avg_serialize
    5164                 :             :  *      Serialize NumericAggState for numeric aggregates that don't require
    5165                 :             :  *      sumX2.
    5166                 :             :  */
    5167                 :             : Datum
    5168                 :          16 : numeric_avg_serialize(PG_FUNCTION_ARGS)
    5169                 :             : {
    5170                 :             :     NumericAggState *state;
    5171                 :             :     StringInfoData buf;
    5172                 :             :     bytea      *result;
    5173                 :             :     NumericVar  tmp_var;
    5174                 :             : 
    5175                 :             :     /* Ensure we disallow calling when not in aggregate context */
    5176         [ -  + ]:          16 :     if (!AggCheckCallContext(fcinfo, NULL))
    5177         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5178                 :             : 
    5179                 :          16 :     state = (NumericAggState *) PG_GETARG_POINTER(0);
    5180                 :             : 
    5181                 :          16 :     init_var(&tmp_var);
    5182                 :             : 
    5183                 :          16 :     pq_begintypsend(&buf);
    5184                 :             : 
    5185                 :             :     /* N */
    5186                 :          16 :     pq_sendint64(&buf, state->N);
    5187                 :             : 
    5188                 :             :     /* sumX */
    5189                 :          16 :     accum_sum_final(&state->sumX, &tmp_var);
    5190                 :          16 :     numericvar_serialize(&buf, &tmp_var);
    5191                 :             : 
    5192                 :             :     /* maxScale */
    5193                 :          16 :     pq_sendint32(&buf, state->maxScale);
    5194                 :             : 
    5195                 :             :     /* maxScaleCount */
    5196                 :          16 :     pq_sendint64(&buf, state->maxScaleCount);
    5197                 :             : 
    5198                 :             :     /* NaNcount */
    5199                 :          16 :     pq_sendint64(&buf, state->NaNcount);
    5200                 :             : 
    5201                 :             :     /* pInfcount */
    5202                 :          16 :     pq_sendint64(&buf, state->pInfcount);
    5203                 :             : 
    5204                 :             :     /* nInfcount */
    5205                 :          16 :     pq_sendint64(&buf, state->nInfcount);
    5206                 :             : 
    5207                 :          16 :     result = pq_endtypsend(&buf);
    5208                 :             : 
    5209                 :          16 :     free_var(&tmp_var);
    5210                 :             : 
    5211                 :          16 :     PG_RETURN_BYTEA_P(result);
    5212                 :             : }
    5213                 :             : 
    5214                 :             : /*
    5215                 :             :  * numeric_avg_deserialize
    5216                 :             :  *      Deserialize bytea into NumericAggState for numeric aggregates that
    5217                 :             :  *      don't require sumX2.
    5218                 :             :  */
    5219                 :             : Datum
    5220                 :          16 : numeric_avg_deserialize(PG_FUNCTION_ARGS)
    5221                 :             : {
    5222                 :             :     bytea      *sstate;
    5223                 :             :     NumericAggState *result;
    5224                 :             :     StringInfoData buf;
    5225                 :             :     NumericVar  tmp_var;
    5226                 :             : 
    5227         [ -  + ]:          16 :     if (!AggCheckCallContext(fcinfo, NULL))
    5228         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5229                 :             : 
    5230                 :          16 :     sstate = PG_GETARG_BYTEA_PP(0);
    5231                 :             : 
    5232                 :          16 :     init_var(&tmp_var);
    5233                 :             : 
    5234                 :             :     /*
    5235                 :             :      * Initialize a StringInfo so that we can "receive" it using the standard
    5236                 :             :      * recv-function infrastructure.
    5237                 :             :      */
    5238                 :          16 :     initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
    5239                 :          16 :                            VARSIZE_ANY_EXHDR(sstate));
    5240                 :             : 
    5241                 :          16 :     result = makeNumericAggStateCurrentContext(false);
    5242                 :             : 
    5243                 :             :     /* N */
    5244                 :          16 :     result->N = pq_getmsgint64(&buf);
    5245                 :             : 
    5246                 :             :     /* sumX */
    5247                 :          16 :     numericvar_deserialize(&buf, &tmp_var);
    5248                 :          16 :     accum_sum_add(&(result->sumX), &tmp_var);
    5249                 :             : 
    5250                 :             :     /* maxScale */
    5251                 :          16 :     result->maxScale = pq_getmsgint(&buf, 4);
    5252                 :             : 
    5253                 :             :     /* maxScaleCount */
    5254                 :          16 :     result->maxScaleCount = pq_getmsgint64(&buf);
    5255                 :             : 
    5256                 :             :     /* NaNcount */
    5257                 :          16 :     result->NaNcount = pq_getmsgint64(&buf);
    5258                 :             : 
    5259                 :             :     /* pInfcount */
    5260                 :          16 :     result->pInfcount = pq_getmsgint64(&buf);
    5261                 :             : 
    5262                 :             :     /* nInfcount */
    5263                 :          16 :     result->nInfcount = pq_getmsgint64(&buf);
    5264                 :             : 
    5265                 :          16 :     pq_getmsgend(&buf);
    5266                 :             : 
    5267                 :          16 :     free_var(&tmp_var);
    5268                 :             : 
    5269                 :          16 :     PG_RETURN_POINTER(result);
    5270                 :             : }
    5271                 :             : 
    5272                 :             : /*
    5273                 :             :  * numeric_serialize
    5274                 :             :  *      Serialization function for NumericAggState for numeric aggregates that
    5275                 :             :  *      require sumX2.
    5276                 :             :  */
    5277                 :             : Datum
    5278                 :          24 : numeric_serialize(PG_FUNCTION_ARGS)
    5279                 :             : {
    5280                 :             :     NumericAggState *state;
    5281                 :             :     StringInfoData buf;
    5282                 :             :     bytea      *result;
    5283                 :             :     NumericVar  tmp_var;
    5284                 :             : 
    5285                 :             :     /* Ensure we disallow calling when not in aggregate context */
    5286         [ -  + ]:          24 :     if (!AggCheckCallContext(fcinfo, NULL))
    5287         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5288                 :             : 
    5289                 :          24 :     state = (NumericAggState *) PG_GETARG_POINTER(0);
    5290                 :             : 
    5291                 :          24 :     init_var(&tmp_var);
    5292                 :             : 
    5293                 :          24 :     pq_begintypsend(&buf);
    5294                 :             : 
    5295                 :             :     /* N */
    5296                 :          24 :     pq_sendint64(&buf, state->N);
    5297                 :             : 
    5298                 :             :     /* sumX */
    5299                 :          24 :     accum_sum_final(&state->sumX, &tmp_var);
    5300                 :          24 :     numericvar_serialize(&buf, &tmp_var);
    5301                 :             : 
    5302                 :             :     /* sumX2 */
    5303                 :          24 :     accum_sum_final(&state->sumX2, &tmp_var);
    5304                 :          24 :     numericvar_serialize(&buf, &tmp_var);
    5305                 :             : 
    5306                 :             :     /* maxScale */
    5307                 :          24 :     pq_sendint32(&buf, state->maxScale);
    5308                 :             : 
    5309                 :             :     /* maxScaleCount */
    5310                 :          24 :     pq_sendint64(&buf, state->maxScaleCount);
    5311                 :             : 
    5312                 :             :     /* NaNcount */
    5313                 :          24 :     pq_sendint64(&buf, state->NaNcount);
    5314                 :             : 
    5315                 :             :     /* pInfcount */
    5316                 :          24 :     pq_sendint64(&buf, state->pInfcount);
    5317                 :             : 
    5318                 :             :     /* nInfcount */
    5319                 :          24 :     pq_sendint64(&buf, state->nInfcount);
    5320                 :             : 
    5321                 :          24 :     result = pq_endtypsend(&buf);
    5322                 :             : 
    5323                 :          24 :     free_var(&tmp_var);
    5324                 :             : 
    5325                 :          24 :     PG_RETURN_BYTEA_P(result);
    5326                 :             : }
    5327                 :             : 
    5328                 :             : /*
    5329                 :             :  * numeric_deserialize
    5330                 :             :  *      Deserialization function for NumericAggState for numeric aggregates that
    5331                 :             :  *      require sumX2.
    5332                 :             :  */
    5333                 :             : Datum
    5334                 :          24 : numeric_deserialize(PG_FUNCTION_ARGS)
    5335                 :             : {
    5336                 :             :     bytea      *sstate;
    5337                 :             :     NumericAggState *result;
    5338                 :             :     StringInfoData buf;
    5339                 :             :     NumericVar  tmp_var;
    5340                 :             : 
    5341         [ -  + ]:          24 :     if (!AggCheckCallContext(fcinfo, NULL))
    5342         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5343                 :             : 
    5344                 :          24 :     sstate = PG_GETARG_BYTEA_PP(0);
    5345                 :             : 
    5346                 :          24 :     init_var(&tmp_var);
    5347                 :             : 
    5348                 :             :     /*
    5349                 :             :      * Initialize a StringInfo so that we can "receive" it using the standard
    5350                 :             :      * recv-function infrastructure.
    5351                 :             :      */
    5352                 :          24 :     initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
    5353                 :          24 :                            VARSIZE_ANY_EXHDR(sstate));
    5354                 :             : 
    5355                 :          24 :     result = makeNumericAggStateCurrentContext(false);
    5356                 :             : 
    5357                 :             :     /* N */
    5358                 :          24 :     result->N = pq_getmsgint64(&buf);
    5359                 :             : 
    5360                 :             :     /* sumX */
    5361                 :          24 :     numericvar_deserialize(&buf, &tmp_var);
    5362                 :          24 :     accum_sum_add(&(result->sumX), &tmp_var);
    5363                 :             : 
    5364                 :             :     /* sumX2 */
    5365                 :          24 :     numericvar_deserialize(&buf, &tmp_var);
    5366                 :          24 :     accum_sum_add(&(result->sumX2), &tmp_var);
    5367                 :             : 
    5368                 :             :     /* maxScale */
    5369                 :          24 :     result->maxScale = pq_getmsgint(&buf, 4);
    5370                 :             : 
    5371                 :             :     /* maxScaleCount */
    5372                 :          24 :     result->maxScaleCount = pq_getmsgint64(&buf);
    5373                 :             : 
    5374                 :             :     /* NaNcount */
    5375                 :          24 :     result->NaNcount = pq_getmsgint64(&buf);
    5376                 :             : 
    5377                 :             :     /* pInfcount */
    5378                 :          24 :     result->pInfcount = pq_getmsgint64(&buf);
    5379                 :             : 
    5380                 :             :     /* nInfcount */
    5381                 :          24 :     result->nInfcount = pq_getmsgint64(&buf);
    5382                 :             : 
    5383                 :          24 :     pq_getmsgend(&buf);
    5384                 :             : 
    5385                 :          24 :     free_var(&tmp_var);
    5386                 :             : 
    5387                 :          24 :     PG_RETURN_POINTER(result);
    5388                 :             : }
    5389                 :             : 
    5390                 :             : /*
    5391                 :             :  * Generic inverse transition function for numeric aggregates
    5392                 :             :  * (with or without requirement for X^2).
    5393                 :             :  */
    5394                 :             : Datum
    5395                 :         152 : numeric_accum_inv(PG_FUNCTION_ARGS)
    5396                 :             : {
    5397                 :             :     NumericAggState *state;
    5398                 :             : 
    5399         [ +  - ]:         152 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    5400                 :             : 
    5401                 :             :     /* Should not get here with no state */
    5402         [ -  + ]:         152 :     if (state == NULL)
    5403         [ #  # ]:           0 :         elog(ERROR, "numeric_accum_inv called with NULL state");
    5404                 :             : 
    5405         [ +  + ]:         152 :     if (!PG_ARGISNULL(1))
    5406                 :             :     {
    5407                 :             :         /* If we fail to perform the inverse transition, return NULL */
    5408         [ +  + ]:         132 :         if (!do_numeric_discard(state, PG_GETARG_NUMERIC(1)))
    5409                 :           4 :             PG_RETURN_NULL();
    5410                 :             :     }
    5411                 :             : 
    5412                 :         148 :     PG_RETURN_POINTER(state);
    5413                 :             : }
    5414                 :             : 
    5415                 :             : 
    5416                 :             : /*
    5417                 :             :  * Integer data types in general use Numeric accumulators to share code and
    5418                 :             :  * avoid risk of overflow.  However for performance reasons optimized
    5419                 :             :  * special-purpose accumulator routines are used when possible:
    5420                 :             :  *
    5421                 :             :  * For 16-bit and 32-bit inputs, N and sum(X) fit into 64-bit, so 64-bit
    5422                 :             :  * accumulators are used for SUM and AVG of these data types.
    5423                 :             :  *
    5424                 :             :  * For 16-bit and 32-bit inputs, sum(X^2) fits into 128-bit, so 128-bit
    5425                 :             :  * accumulators are used for STDDEV_POP, STDDEV_SAMP, VAR_POP, and VAR_SAMP of
    5426                 :             :  * these data types.
    5427                 :             :  *
    5428                 :             :  * For 64-bit inputs, sum(X) fits into 128-bit, so a 128-bit accumulator is
    5429                 :             :  * used for SUM(int8) and AVG(int8).
    5430                 :             :  */
    5431                 :             : 
    5432                 :             : typedef struct Int128AggState
    5433                 :             : {
    5434                 :             :     bool        calcSumX2;      /* if true, calculate sumX2 */
    5435                 :             :     int64       N;              /* count of processed numbers */
    5436                 :             :     INT128      sumX;           /* sum of processed numbers */
    5437                 :             :     INT128      sumX2;          /* sum of squares of processed numbers */
    5438                 :             : } Int128AggState;
    5439                 :             : 
    5440                 :             : /*
    5441                 :             :  * Prepare state data for a 128-bit aggregate function that needs to compute
    5442                 :             :  * sum, count and optionally sum of squares of the input.
    5443                 :             :  */
    5444                 :             : static Int128AggState *
    5445                 :         622 : makeInt128AggState(FunctionCallInfo fcinfo, bool calcSumX2)
    5446                 :             : {
    5447                 :             :     Int128AggState *state;
    5448                 :             :     MemoryContext agg_context;
    5449                 :             :     MemoryContext old_context;
    5450                 :             : 
    5451         [ -  + ]:         622 :     if (!AggCheckCallContext(fcinfo, &agg_context))
    5452         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5453                 :             : 
    5454                 :         622 :     old_context = MemoryContextSwitchTo(agg_context);
    5455                 :             : 
    5456                 :         622 :     state = palloc0_object(Int128AggState);
    5457                 :         622 :     state->calcSumX2 = calcSumX2;
    5458                 :             : 
    5459                 :         622 :     MemoryContextSwitchTo(old_context);
    5460                 :             : 
    5461                 :         622 :     return state;
    5462                 :             : }
    5463                 :             : 
    5464                 :             : /*
    5465                 :             :  * Like makeInt128AggState(), but allocate the state in the current memory
    5466                 :             :  * context.
    5467                 :             :  */
    5468                 :             : static Int128AggState *
    5469                 :          36 : makeInt128AggStateCurrentContext(bool calcSumX2)
    5470                 :             : {
    5471                 :             :     Int128AggState *state;
    5472                 :             : 
    5473                 :          36 :     state = palloc0_object(Int128AggState);
    5474                 :          36 :     state->calcSumX2 = calcSumX2;
    5475                 :             : 
    5476                 :          36 :     return state;
    5477                 :             : }
    5478                 :             : 
    5479                 :             : /*
    5480                 :             :  * Accumulate a new input value for 128-bit aggregate functions.
    5481                 :             :  */
    5482                 :             : static void
    5483                 :      371610 : do_int128_accum(Int128AggState *state, int64 newval)
    5484                 :             : {
    5485         [ +  + ]:      371610 :     if (state->calcSumX2)
    5486                 :      161240 :         int128_add_int64_mul_int64(&state->sumX2, newval, newval);
    5487                 :             : 
    5488                 :      371610 :     int128_add_int64(&state->sumX, newval);
    5489                 :      371610 :     state->N++;
    5490                 :      371610 : }
    5491                 :             : 
    5492                 :             : /*
    5493                 :             :  * Remove an input value from the aggregated state.
    5494                 :             :  */
    5495                 :             : static void
    5496                 :         208 : do_int128_discard(Int128AggState *state, int64 newval)
    5497                 :             : {
    5498         [ +  + ]:         208 :     if (state->calcSumX2)
    5499                 :         192 :         int128_sub_int64_mul_int64(&state->sumX2, newval, newval);
    5500                 :             : 
    5501                 :         208 :     int128_sub_int64(&state->sumX, newval);
    5502                 :         208 :     state->N--;
    5503                 :         208 : }
    5504                 :             : 
    5505                 :             : Datum
    5506                 :         132 : int2_accum(PG_FUNCTION_ARGS)
    5507                 :             : {
    5508                 :             :     Int128AggState *state;
    5509                 :             : 
    5510         [ +  + ]:         132 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5511                 :             : 
    5512                 :             :     /* Create the state data on the first call */
    5513         [ +  + ]:         132 :     if (state == NULL)
    5514                 :          24 :         state = makeInt128AggState(fcinfo, true);
    5515                 :             : 
    5516         [ +  + ]:         132 :     if (!PG_ARGISNULL(1))
    5517                 :         120 :         do_int128_accum(state, PG_GETARG_INT16(1));
    5518                 :             : 
    5519                 :         132 :     PG_RETURN_POINTER(state);
    5520                 :             : }
    5521                 :             : 
    5522                 :             : Datum
    5523                 :      161132 : int4_accum(PG_FUNCTION_ARGS)
    5524                 :             : {
    5525                 :             :     Int128AggState *state;
    5526                 :             : 
    5527         [ +  + ]:      161132 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5528                 :             : 
    5529                 :             :     /* Create the state data on the first call */
    5530         [ +  + ]:      161132 :     if (state == NULL)
    5531                 :          50 :         state = makeInt128AggState(fcinfo, true);
    5532                 :             : 
    5533         [ +  + ]:      161132 :     if (!PG_ARGISNULL(1))
    5534                 :      161120 :         do_int128_accum(state, PG_GETARG_INT32(1));
    5535                 :             : 
    5536                 :      161132 :     PG_RETURN_POINTER(state);
    5537                 :             : }
    5538                 :             : 
    5539                 :             : Datum
    5540                 :      160132 : int8_accum(PG_FUNCTION_ARGS)
    5541                 :             : {
    5542                 :             :     NumericAggState *state;
    5543                 :             : 
    5544         [ +  + ]:      160132 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    5545                 :             : 
    5546                 :             :     /* Create the state data on the first call */
    5547         [ +  + ]:      160132 :     if (state == NULL)
    5548                 :          40 :         state = makeNumericAggState(fcinfo, true);
    5549                 :             : 
    5550         [ +  + ]:      160132 :     if (!PG_ARGISNULL(1))
    5551                 :      160120 :         do_numeric_accum(state, int64_to_numeric(PG_GETARG_INT64(1)));
    5552                 :             : 
    5553                 :      160132 :     PG_RETURN_POINTER(state);
    5554                 :             : }
    5555                 :             : 
    5556                 :             : /*
    5557                 :             :  * Combine function for Int128AggState for aggregates which require sumX2
    5558                 :             :  */
    5559                 :             : Datum
    5560                 :          16 : numeric_poly_combine(PG_FUNCTION_ARGS)
    5561                 :             : {
    5562                 :             :     Int128AggState *state1;
    5563                 :             :     Int128AggState *state2;
    5564                 :             :     MemoryContext agg_context;
    5565                 :             :     MemoryContext old_context;
    5566                 :             : 
    5567         [ -  + ]:          16 :     if (!AggCheckCallContext(fcinfo, &agg_context))
    5568         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5569                 :             : 
    5570         [ +  + ]:          16 :     state1 = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5571         [ +  - ]:          16 :     state2 = PG_ARGISNULL(1) ? NULL : (Int128AggState *) PG_GETARG_POINTER(1);
    5572                 :             : 
    5573         [ -  + ]:          16 :     if (state2 == NULL)
    5574                 :           0 :         PG_RETURN_POINTER(state1);
    5575                 :             : 
    5576                 :             :     /* manually copy all fields from state2 to state1 */
    5577         [ +  + ]:          16 :     if (state1 == NULL)
    5578                 :             :     {
    5579                 :           4 :         old_context = MemoryContextSwitchTo(agg_context);
    5580                 :             : 
    5581                 :           4 :         state1 = makeInt128AggState(fcinfo, true);
    5582                 :           4 :         state1->N = state2->N;
    5583                 :           4 :         state1->sumX = state2->sumX;
    5584                 :           4 :         state1->sumX2 = state2->sumX2;
    5585                 :             : 
    5586                 :           4 :         MemoryContextSwitchTo(old_context);
    5587                 :             : 
    5588                 :           4 :         PG_RETURN_POINTER(state1);
    5589                 :             :     }
    5590                 :             : 
    5591         [ +  - ]:          12 :     if (state2->N > 0)
    5592                 :             :     {
    5593                 :          12 :         state1->N += state2->N;
    5594                 :          12 :         int128_add_int128(&state1->sumX, state2->sumX);
    5595                 :          12 :         int128_add_int128(&state1->sumX2, state2->sumX2);
    5596                 :             :     }
    5597                 :          12 :     PG_RETURN_POINTER(state1);
    5598                 :             : }
    5599                 :             : 
    5600                 :             : /*
    5601                 :             :  * int128_serialize - serialize a 128-bit integer to binary format
    5602                 :             :  */
    5603                 :             : static inline void
    5604                 :          52 : int128_serialize(StringInfo buf, INT128 val)
    5605                 :             : {
    5606                 :          52 :     pq_sendint64(buf, PG_INT128_HI_INT64(val));
    5607                 :          52 :     pq_sendint64(buf, PG_INT128_LO_UINT64(val));
    5608                 :          52 : }
    5609                 :             : 
    5610                 :             : /*
    5611                 :             :  * int128_deserialize - deserialize binary format to a 128-bit integer.
    5612                 :             :  */
    5613                 :             : static inline INT128
    5614                 :          52 : int128_deserialize(StringInfo buf)
    5615                 :             : {
    5616                 :          52 :     int64       hi = pq_getmsgint64(buf);
    5617                 :          52 :     uint64      lo = pq_getmsgint64(buf);
    5618                 :             : 
    5619                 :          52 :     return make_int128(hi, lo);
    5620                 :             : }
    5621                 :             : 
    5622                 :             : /*
    5623                 :             :  * numeric_poly_serialize
    5624                 :             :  *      Serialize Int128AggState into bytea for aggregate functions which
    5625                 :             :  *      require sumX2.
    5626                 :             :  */
    5627                 :             : Datum
    5628                 :          16 : numeric_poly_serialize(PG_FUNCTION_ARGS)
    5629                 :             : {
    5630                 :             :     Int128AggState *state;
    5631                 :             :     StringInfoData buf;
    5632                 :             :     bytea      *result;
    5633                 :             : 
    5634                 :             :     /* Ensure we disallow calling when not in aggregate context */
    5635         [ -  + ]:          16 :     if (!AggCheckCallContext(fcinfo, NULL))
    5636         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5637                 :             : 
    5638                 :          16 :     state = (Int128AggState *) PG_GETARG_POINTER(0);
    5639                 :             : 
    5640                 :          16 :     pq_begintypsend(&buf);
    5641                 :             : 
    5642                 :             :     /* N */
    5643                 :          16 :     pq_sendint64(&buf, state->N);
    5644                 :             : 
    5645                 :             :     /* sumX */
    5646                 :          16 :     int128_serialize(&buf, state->sumX);
    5647                 :             : 
    5648                 :             :     /* sumX2 */
    5649                 :          16 :     int128_serialize(&buf, state->sumX2);
    5650                 :             : 
    5651                 :          16 :     result = pq_endtypsend(&buf);
    5652                 :             : 
    5653                 :          16 :     PG_RETURN_BYTEA_P(result);
    5654                 :             : }
    5655                 :             : 
    5656                 :             : /*
    5657                 :             :  * numeric_poly_deserialize
    5658                 :             :  *      Deserialize Int128AggState from bytea for aggregate functions which
    5659                 :             :  *      require sumX2.
    5660                 :             :  */
    5661                 :             : Datum
    5662                 :          16 : numeric_poly_deserialize(PG_FUNCTION_ARGS)
    5663                 :             : {
    5664                 :             :     bytea      *sstate;
    5665                 :             :     Int128AggState *result;
    5666                 :             :     StringInfoData buf;
    5667                 :             : 
    5668         [ -  + ]:          16 :     if (!AggCheckCallContext(fcinfo, NULL))
    5669         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5670                 :             : 
    5671                 :          16 :     sstate = PG_GETARG_BYTEA_PP(0);
    5672                 :             : 
    5673                 :             :     /*
    5674                 :             :      * Initialize a StringInfo so that we can "receive" it using the standard
    5675                 :             :      * recv-function infrastructure.
    5676                 :             :      */
    5677                 :          16 :     initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
    5678                 :          16 :                            VARSIZE_ANY_EXHDR(sstate));
    5679                 :             : 
    5680                 :          16 :     result = makeInt128AggStateCurrentContext(false);
    5681                 :             : 
    5682                 :             :     /* N */
    5683                 :          16 :     result->N = pq_getmsgint64(&buf);
    5684                 :             : 
    5685                 :             :     /* sumX */
    5686                 :          16 :     result->sumX = int128_deserialize(&buf);
    5687                 :             : 
    5688                 :             :     /* sumX2 */
    5689                 :          16 :     result->sumX2 = int128_deserialize(&buf);
    5690                 :             : 
    5691                 :          16 :     pq_getmsgend(&buf);
    5692                 :             : 
    5693                 :          16 :     PG_RETURN_POINTER(result);
    5694                 :             : }
    5695                 :             : 
    5696                 :             : /*
    5697                 :             :  * Transition function for int8 input when we don't need sumX2.
    5698                 :             :  */
    5699                 :             : Datum
    5700                 :      213245 : int8_avg_accum(PG_FUNCTION_ARGS)
    5701                 :             : {
    5702                 :             :     Int128AggState *state;
    5703                 :             : 
    5704         [ +  + ]:      213245 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5705                 :             : 
    5706                 :             :     /* Create the state data on the first call */
    5707         [ +  + ]:      213245 :     if (state == NULL)
    5708                 :         536 :         state = makeInt128AggState(fcinfo, false);
    5709                 :             : 
    5710         [ +  + ]:      213245 :     if (!PG_ARGISNULL(1))
    5711                 :      210370 :         do_int128_accum(state, PG_GETARG_INT64(1));
    5712                 :             : 
    5713                 :      213245 :     PG_RETURN_POINTER(state);
    5714                 :             : }
    5715                 :             : 
    5716                 :             : /*
    5717                 :             :  * Combine function for Int128AggState for aggregates which don't require
    5718                 :             :  * sumX2
    5719                 :             :  */
    5720                 :             : Datum
    5721                 :          20 : int8_avg_combine(PG_FUNCTION_ARGS)
    5722                 :             : {
    5723                 :             :     Int128AggState *state1;
    5724                 :             :     Int128AggState *state2;
    5725                 :             :     MemoryContext agg_context;
    5726                 :             :     MemoryContext old_context;
    5727                 :             : 
    5728         [ -  + ]:          20 :     if (!AggCheckCallContext(fcinfo, &agg_context))
    5729         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5730                 :             : 
    5731         [ +  + ]:          20 :     state1 = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5732         [ +  - ]:          20 :     state2 = PG_ARGISNULL(1) ? NULL : (Int128AggState *) PG_GETARG_POINTER(1);
    5733                 :             : 
    5734         [ -  + ]:          20 :     if (state2 == NULL)
    5735                 :           0 :         PG_RETURN_POINTER(state1);
    5736                 :             : 
    5737                 :             :     /* manually copy all fields from state2 to state1 */
    5738         [ +  + ]:          20 :     if (state1 == NULL)
    5739                 :             :     {
    5740                 :           8 :         old_context = MemoryContextSwitchTo(agg_context);
    5741                 :             : 
    5742                 :           8 :         state1 = makeInt128AggState(fcinfo, false);
    5743                 :           8 :         state1->N = state2->N;
    5744                 :           8 :         state1->sumX = state2->sumX;
    5745                 :             : 
    5746                 :           8 :         MemoryContextSwitchTo(old_context);
    5747                 :             : 
    5748                 :           8 :         PG_RETURN_POINTER(state1);
    5749                 :             :     }
    5750                 :             : 
    5751         [ +  - ]:          12 :     if (state2->N > 0)
    5752                 :             :     {
    5753                 :          12 :         state1->N += state2->N;
    5754                 :          12 :         int128_add_int128(&state1->sumX, state2->sumX);
    5755                 :             :     }
    5756                 :          12 :     PG_RETURN_POINTER(state1);
    5757                 :             : }
    5758                 :             : 
    5759                 :             : /*
    5760                 :             :  * int8_avg_serialize
    5761                 :             :  *      Serialize Int128AggState into bytea for aggregate functions which
    5762                 :             :  *      don't require sumX2.
    5763                 :             :  */
    5764                 :             : Datum
    5765                 :          20 : int8_avg_serialize(PG_FUNCTION_ARGS)
    5766                 :             : {
    5767                 :             :     Int128AggState *state;
    5768                 :             :     StringInfoData buf;
    5769                 :             :     bytea      *result;
    5770                 :             : 
    5771                 :             :     /* Ensure we disallow calling when not in aggregate context */
    5772         [ -  + ]:          20 :     if (!AggCheckCallContext(fcinfo, NULL))
    5773         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5774                 :             : 
    5775                 :          20 :     state = (Int128AggState *) PG_GETARG_POINTER(0);
    5776                 :             : 
    5777                 :          20 :     pq_begintypsend(&buf);
    5778                 :             : 
    5779                 :             :     /* N */
    5780                 :          20 :     pq_sendint64(&buf, state->N);
    5781                 :             : 
    5782                 :             :     /* sumX */
    5783                 :          20 :     int128_serialize(&buf, state->sumX);
    5784                 :             : 
    5785                 :          20 :     result = pq_endtypsend(&buf);
    5786                 :             : 
    5787                 :          20 :     PG_RETURN_BYTEA_P(result);
    5788                 :             : }
    5789                 :             : 
    5790                 :             : /*
    5791                 :             :  * int8_avg_deserialize
    5792                 :             :  *      Deserialize Int128AggState from bytea for aggregate functions which
    5793                 :             :  *      don't require sumX2.
    5794                 :             :  */
    5795                 :             : Datum
    5796                 :          20 : int8_avg_deserialize(PG_FUNCTION_ARGS)
    5797                 :             : {
    5798                 :             :     bytea      *sstate;
    5799                 :             :     Int128AggState *result;
    5800                 :             :     StringInfoData buf;
    5801                 :             : 
    5802         [ -  + ]:          20 :     if (!AggCheckCallContext(fcinfo, NULL))
    5803         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5804                 :             : 
    5805                 :          20 :     sstate = PG_GETARG_BYTEA_PP(0);
    5806                 :             : 
    5807                 :             :     /*
    5808                 :             :      * Initialize a StringInfo so that we can "receive" it using the standard
    5809                 :             :      * recv-function infrastructure.
    5810                 :             :      */
    5811                 :          20 :     initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
    5812                 :          20 :                            VARSIZE_ANY_EXHDR(sstate));
    5813                 :             : 
    5814                 :          20 :     result = makeInt128AggStateCurrentContext(false);
    5815                 :             : 
    5816                 :             :     /* N */
    5817                 :          20 :     result->N = pq_getmsgint64(&buf);
    5818                 :             : 
    5819                 :             :     /* sumX */
    5820                 :          20 :     result->sumX = int128_deserialize(&buf);
    5821                 :             : 
    5822                 :          20 :     pq_getmsgend(&buf);
    5823                 :             : 
    5824                 :          20 :     PG_RETURN_POINTER(result);
    5825                 :             : }
    5826                 :             : 
    5827                 :             : /*
    5828                 :             :  * Inverse transition functions to go with the above.
    5829                 :             :  */
    5830                 :             : 
    5831                 :             : Datum
    5832                 :         108 : int2_accum_inv(PG_FUNCTION_ARGS)
    5833                 :             : {
    5834                 :             :     Int128AggState *state;
    5835                 :             : 
    5836         [ +  - ]:         108 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5837                 :             : 
    5838                 :             :     /* Should not get here with no state */
    5839         [ -  + ]:         108 :     if (state == NULL)
    5840         [ #  # ]:           0 :         elog(ERROR, "int2_accum_inv called with NULL state");
    5841                 :             : 
    5842         [ +  + ]:         108 :     if (!PG_ARGISNULL(1))
    5843                 :          96 :         do_int128_discard(state, PG_GETARG_INT16(1));
    5844                 :             : 
    5845                 :         108 :     PG_RETURN_POINTER(state);
    5846                 :             : }
    5847                 :             : 
    5848                 :             : Datum
    5849                 :         108 : int4_accum_inv(PG_FUNCTION_ARGS)
    5850                 :             : {
    5851                 :             :     Int128AggState *state;
    5852                 :             : 
    5853         [ +  - ]:         108 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5854                 :             : 
    5855                 :             :     /* Should not get here with no state */
    5856         [ -  + ]:         108 :     if (state == NULL)
    5857         [ #  # ]:           0 :         elog(ERROR, "int4_accum_inv called with NULL state");
    5858                 :             : 
    5859         [ +  + ]:         108 :     if (!PG_ARGISNULL(1))
    5860                 :          96 :         do_int128_discard(state, PG_GETARG_INT32(1));
    5861                 :             : 
    5862                 :         108 :     PG_RETURN_POINTER(state);
    5863                 :             : }
    5864                 :             : 
    5865                 :             : Datum
    5866                 :         108 : int8_accum_inv(PG_FUNCTION_ARGS)
    5867                 :             : {
    5868                 :             :     NumericAggState *state;
    5869                 :             : 
    5870         [ +  - ]:         108 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    5871                 :             : 
    5872                 :             :     /* Should not get here with no state */
    5873         [ -  + ]:         108 :     if (state == NULL)
    5874         [ #  # ]:           0 :         elog(ERROR, "int8_accum_inv called with NULL state");
    5875                 :             : 
    5876         [ +  + ]:         108 :     if (!PG_ARGISNULL(1))
    5877                 :             :     {
    5878                 :             :         /* Should never fail, all inputs have dscale 0 */
    5879         [ -  + ]:          96 :         if (!do_numeric_discard(state, int64_to_numeric(PG_GETARG_INT64(1))))
    5880         [ #  # ]:           0 :             elog(ERROR, "do_numeric_discard failed unexpectedly");
    5881                 :             :     }
    5882                 :             : 
    5883                 :         108 :     PG_RETURN_POINTER(state);
    5884                 :             : }
    5885                 :             : 
    5886                 :             : Datum
    5887                 :          24 : int8_avg_accum_inv(PG_FUNCTION_ARGS)
    5888                 :             : {
    5889                 :             :     Int128AggState *state;
    5890                 :             : 
    5891         [ +  - ]:          24 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5892                 :             : 
    5893                 :             :     /* Should not get here with no state */
    5894         [ -  + ]:          24 :     if (state == NULL)
    5895         [ #  # ]:           0 :         elog(ERROR, "int8_avg_accum_inv called with NULL state");
    5896                 :             : 
    5897         [ +  + ]:          24 :     if (!PG_ARGISNULL(1))
    5898                 :          16 :         do_int128_discard(state, PG_GETARG_INT64(1));
    5899                 :             : 
    5900                 :          24 :     PG_RETURN_POINTER(state);
    5901                 :             : }
    5902                 :             : 
    5903                 :             : Datum
    5904                 :         680 : numeric_poly_sum(PG_FUNCTION_ARGS)
    5905                 :             : {
    5906                 :             :     Int128AggState *state;
    5907                 :             :     Numeric     res;
    5908                 :             :     NumericVar  result;
    5909                 :             : 
    5910         [ +  + ]:         680 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5911                 :             : 
    5912                 :             :     /* If there were no non-null inputs, return NULL */
    5913   [ +  +  +  + ]:         680 :     if (state == NULL || state->N == 0)
    5914                 :          16 :         PG_RETURN_NULL();
    5915                 :             : 
    5916                 :         664 :     init_var(&result);
    5917                 :             : 
    5918                 :         664 :     int128_to_numericvar(state->sumX, &result);
    5919                 :             : 
    5920                 :         664 :     res = make_result(&result);
    5921                 :             : 
    5922                 :         664 :     free_var(&result);
    5923                 :             : 
    5924                 :         664 :     PG_RETURN_NUMERIC(res);
    5925                 :             : }
    5926                 :             : 
    5927                 :             : Datum
    5928                 :          24 : numeric_poly_avg(PG_FUNCTION_ARGS)
    5929                 :             : {
    5930                 :             :     Int128AggState *state;
    5931                 :             :     NumericVar  result;
    5932                 :             :     Datum       countd,
    5933                 :             :                 sumd;
    5934                 :             : 
    5935         [ +  - ]:          24 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5936                 :             : 
    5937                 :             :     /* If there were no non-null inputs, return NULL */
    5938   [ +  -  +  + ]:          24 :     if (state == NULL || state->N == 0)
    5939                 :          12 :         PG_RETURN_NULL();
    5940                 :             : 
    5941                 :          12 :     init_var(&result);
    5942                 :             : 
    5943                 :          12 :     int128_to_numericvar(state->sumX, &result);
    5944                 :             : 
    5945                 :          12 :     countd = NumericGetDatum(int64_to_numeric(state->N));
    5946                 :          12 :     sumd = NumericGetDatum(make_result(&result));
    5947                 :             : 
    5948                 :          12 :     free_var(&result);
    5949                 :             : 
    5950                 :          12 :     PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumd, countd));
    5951                 :             : }
    5952                 :             : 
    5953                 :             : Datum
    5954                 :          52 : numeric_avg(PG_FUNCTION_ARGS)
    5955                 :             : {
    5956                 :             :     NumericAggState *state;
    5957                 :             :     Datum       N_datum;
    5958                 :             :     Datum       sumX_datum;
    5959                 :             :     NumericVar  sumX_var;
    5960                 :             : 
    5961         [ +  - ]:          52 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    5962                 :             : 
    5963                 :             :     /* If there were no non-null inputs, return NULL */
    5964   [ +  -  +  + ]:          52 :     if (state == NULL || NA_TOTAL_COUNT(state) == 0)
    5965                 :          12 :         PG_RETURN_NULL();
    5966                 :             : 
    5967         [ +  + ]:          40 :     if (state->NaNcount > 0)  /* there was at least one NaN input */
    5968                 :           4 :         PG_RETURN_NUMERIC(make_result(&const_nan));
    5969                 :             : 
    5970                 :             :     /* adding plus and minus infinities gives NaN */
    5971   [ +  +  +  + ]:          36 :     if (state->pInfcount > 0 && state->nInfcount > 0)
    5972                 :           4 :         PG_RETURN_NUMERIC(make_result(&const_nan));
    5973         [ +  + ]:          32 :     if (state->pInfcount > 0)
    5974                 :          12 :         PG_RETURN_NUMERIC(make_result(&const_pinf));
    5975         [ +  + ]:          20 :     if (state->nInfcount > 0)
    5976                 :           4 :         PG_RETURN_NUMERIC(make_result(&const_ninf));
    5977                 :             : 
    5978                 :          16 :     N_datum = NumericGetDatum(int64_to_numeric(state->N));
    5979                 :             : 
    5980                 :          16 :     init_var(&sumX_var);
    5981                 :          16 :     accum_sum_final(&state->sumX, &sumX_var);
    5982                 :          16 :     sumX_datum = NumericGetDatum(make_result(&sumX_var));
    5983                 :          16 :     free_var(&sumX_var);
    5984                 :             : 
    5985                 :          16 :     PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumX_datum, N_datum));
    5986                 :             : }
    5987                 :             : 
    5988                 :             : Datum
    5989                 :      113926 : numeric_sum(PG_FUNCTION_ARGS)
    5990                 :             : {
    5991                 :             :     NumericAggState *state;
    5992                 :             :     NumericVar  sumX_var;
    5993                 :             :     Numeric     result;
    5994                 :             : 
    5995         [ +  - ]:      113926 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    5996                 :             : 
    5997                 :             :     /* If there were no non-null inputs, return NULL */
    5998   [ +  -  +  + ]:      113926 :     if (state == NULL || NA_TOTAL_COUNT(state) == 0)
    5999                 :          12 :         PG_RETURN_NULL();
    6000                 :             : 
    6001         [ +  + ]:      113914 :     if (state->NaNcount > 0)  /* there was at least one NaN input */
    6002                 :          12 :         PG_RETURN_NUMERIC(make_result(&const_nan));
    6003                 :             : 
    6004                 :             :     /* adding plus and minus infinities gives NaN */
    6005   [ +  +  +  + ]:      113902 :     if (state->pInfcount > 0 && state->nInfcount > 0)
    6006                 :           4 :         PG_RETURN_NUMERIC(make_result(&const_nan));
    6007         [ +  + ]:      113898 :     if (state->pInfcount > 0)
    6008                 :          12 :         PG_RETURN_NUMERIC(make_result(&const_pinf));
    6009         [ +  + ]:      113886 :     if (state->nInfcount > 0)
    6010                 :           4 :         PG_RETURN_NUMERIC(make_result(&const_ninf));
    6011                 :             : 
    6012                 :      113882 :     init_var(&sumX_var);
    6013                 :      113882 :     accum_sum_final(&state->sumX, &sumX_var);
    6014                 :      113882 :     result = make_result(&sumX_var);
    6015                 :      113882 :     free_var(&sumX_var);
    6016                 :             : 
    6017                 :      113882 :     PG_RETURN_NUMERIC(result);
    6018                 :             : }
    6019                 :             : 
    6020                 :             : /*
    6021                 :             :  * Workhorse routine for the standard deviance and variance
    6022                 :             :  * aggregates. 'state' is aggregate's transition state.
    6023                 :             :  * 'variance' specifies whether we should calculate the
    6024                 :             :  * variance or the standard deviation. 'sample' indicates whether the
    6025                 :             :  * caller is interested in the sample or the population
    6026                 :             :  * variance/stddev.
    6027                 :             :  *
    6028                 :             :  * If appropriate variance statistic is undefined for the input,
    6029                 :             :  * *is_null is set to true and NULL is returned.
    6030                 :             :  */
    6031                 :             : static Numeric
    6032                 :         654 : numeric_stddev_internal(NumericAggState *state,
    6033                 :             :                         bool variance, bool sample,
    6034                 :             :                         bool *is_null)
    6035                 :             : {
    6036                 :             :     Numeric     res;
    6037                 :             :     NumericVar  vN,
    6038                 :             :                 vsumX,
    6039                 :             :                 vsumX2,
    6040                 :             :                 vNminus1;
    6041                 :             :     int64       totCount;
    6042                 :             :     int         rscale;
    6043                 :             : 
    6044                 :             :     /*
    6045                 :             :      * Sample stddev and variance are undefined when N <= 1; population stddev
    6046                 :             :      * is undefined when N == 0.  Return NULL in either case (note that NaNs
    6047                 :             :      * and infinities count as normal inputs for this purpose).
    6048                 :             :      */
    6049   [ +  -  -  + ]:         654 :     if (state == NULL || (totCount = NA_TOTAL_COUNT(state)) == 0)
    6050                 :             :     {
    6051                 :           0 :         *is_null = true;
    6052                 :           0 :         return NULL;
    6053                 :             :     }
    6054                 :             : 
    6055   [ +  +  +  + ]:         654 :     if (sample && totCount <= 1)
    6056                 :             :     {
    6057                 :          88 :         *is_null = true;
    6058                 :          88 :         return NULL;
    6059                 :             :     }
    6060                 :             : 
    6061                 :         566 :     *is_null = false;
    6062                 :             : 
    6063                 :             :     /*
    6064                 :             :      * Deal with NaN and infinity cases.  By analogy to the behavior of the
    6065                 :             :      * float8 functions, any infinity input produces NaN output.
    6066                 :             :      */
    6067   [ +  +  +  +  :         566 :     if (state->NaNcount > 0 || state->pInfcount > 0 || state->nInfcount > 0)
                   +  + ]
    6068                 :          36 :         return make_result(&const_nan);
    6069                 :             : 
    6070                 :             :     /* OK, normal calculation applies */
    6071                 :         530 :     init_var(&vN);
    6072                 :         530 :     init_var(&vsumX);
    6073                 :         530 :     init_var(&vsumX2);
    6074                 :             : 
    6075                 :         530 :     int64_to_numericvar(state->N, &vN);
    6076                 :         530 :     accum_sum_final(&(state->sumX), &vsumX);
    6077                 :         530 :     accum_sum_final(&(state->sumX2), &vsumX2);
    6078                 :             : 
    6079                 :         530 :     init_var(&vNminus1);
    6080                 :         530 :     sub_var(&vN, &const_one, &vNminus1);
    6081                 :             : 
    6082                 :             :     /* compute rscale for mul_var calls */
    6083                 :         530 :     rscale = vsumX.dscale * 2;
    6084                 :             : 
    6085                 :         530 :     mul_var(&vsumX, &vsumX, &vsumX, rscale);    /* vsumX = sumX * sumX */
    6086                 :         530 :     mul_var(&vN, &vsumX2, &vsumX2, rscale); /* vsumX2 = N * sumX2 */
    6087                 :         530 :     sub_var(&vsumX2, &vsumX, &vsumX2);  /* N * sumX2 - sumX * sumX */
    6088                 :             : 
    6089         [ +  + ]:         530 :     if (cmp_var(&vsumX2, &const_zero) <= 0)
    6090                 :             :     {
    6091                 :             :         /* Watch out for roundoff error producing a negative numerator */
    6092                 :          50 :         res = make_result(&const_zero);
    6093                 :             :     }
    6094                 :             :     else
    6095                 :             :     {
    6096         [ +  + ]:         480 :         if (sample)
    6097                 :         328 :             mul_var(&vN, &vNminus1, &vNminus1, 0);  /* N * (N - 1) */
    6098                 :             :         else
    6099                 :         152 :             mul_var(&vN, &vN, &vNminus1, 0);    /* N * N */
    6100                 :         480 :         rscale = select_div_scale(&vsumX2, &vNminus1);
    6101                 :         480 :         div_var(&vsumX2, &vNminus1, &vsumX, rscale, true, true);    /* variance */
    6102         [ +  + ]:         480 :         if (!variance)
    6103                 :         252 :             sqrt_var(&vsumX, &vsumX, rscale);   /* stddev */
    6104                 :             : 
    6105                 :         480 :         res = make_result(&vsumX);
    6106                 :             :     }
    6107                 :             : 
    6108                 :         530 :     free_var(&vNminus1);
    6109                 :         530 :     free_var(&vsumX);
    6110                 :         530 :     free_var(&vsumX2);
    6111                 :             : 
    6112                 :         530 :     return res;
    6113                 :             : }
    6114                 :             : 
    6115                 :             : Datum
    6116                 :         120 : numeric_var_samp(PG_FUNCTION_ARGS)
    6117                 :             : {
    6118                 :             :     NumericAggState *state;
    6119                 :             :     Numeric     res;
    6120                 :             :     bool        is_null;
    6121                 :             : 
    6122         [ +  - ]:         120 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    6123                 :             : 
    6124                 :         120 :     res = numeric_stddev_internal(state, true, true, &is_null);
    6125                 :             : 
    6126         [ +  + ]:         120 :     if (is_null)
    6127                 :          28 :         PG_RETURN_NULL();
    6128                 :             :     else
    6129                 :          92 :         PG_RETURN_NUMERIC(res);
    6130                 :             : }
    6131                 :             : 
    6132                 :             : Datum
    6133                 :         116 : numeric_stddev_samp(PG_FUNCTION_ARGS)
    6134                 :             : {
    6135                 :             :     NumericAggState *state;
    6136                 :             :     Numeric     res;
    6137                 :             :     bool        is_null;
    6138                 :             : 
    6139         [ +  - ]:         116 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    6140                 :             : 
    6141                 :         116 :     res = numeric_stddev_internal(state, false, true, &is_null);
    6142                 :             : 
    6143         [ +  + ]:         116 :     if (is_null)
    6144                 :          28 :         PG_RETURN_NULL();
    6145                 :             :     else
    6146                 :          88 :         PG_RETURN_NUMERIC(res);
    6147                 :             : }
    6148                 :             : 
    6149                 :             : Datum
    6150                 :          76 : numeric_var_pop(PG_FUNCTION_ARGS)
    6151                 :             : {
    6152                 :             :     NumericAggState *state;
    6153                 :             :     Numeric     res;
    6154                 :             :     bool        is_null;
    6155                 :             : 
    6156         [ +  - ]:          76 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    6157                 :             : 
    6158                 :          76 :     res = numeric_stddev_internal(state, true, false, &is_null);
    6159                 :             : 
    6160         [ -  + ]:          76 :     if (is_null)
    6161                 :           0 :         PG_RETURN_NULL();
    6162                 :             :     else
    6163                 :          76 :         PG_RETURN_NUMERIC(res);
    6164                 :             : }
    6165                 :             : 
    6166                 :             : Datum
    6167                 :          64 : numeric_stddev_pop(PG_FUNCTION_ARGS)
    6168                 :             : {
    6169                 :             :     NumericAggState *state;
    6170                 :             :     Numeric     res;
    6171                 :             :     bool        is_null;
    6172                 :             : 
    6173         [ +  - ]:          64 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    6174                 :             : 
    6175                 :          64 :     res = numeric_stddev_internal(state, false, false, &is_null);
    6176                 :             : 
    6177         [ -  + ]:          64 :     if (is_null)
    6178                 :           0 :         PG_RETURN_NULL();
    6179                 :             :     else
    6180                 :          64 :         PG_RETURN_NUMERIC(res);
    6181                 :             : }
    6182                 :             : 
    6183                 :             : static Numeric
    6184                 :         278 : numeric_poly_stddev_internal(Int128AggState *state,
    6185                 :             :                              bool variance, bool sample,
    6186                 :             :                              bool *is_null)
    6187                 :             : {
    6188                 :             :     NumericAggState numstate;
    6189                 :             :     Numeric     res;
    6190                 :             : 
    6191                 :             :     /* Initialize an empty agg state */
    6192                 :         278 :     memset(&numstate, 0, sizeof(NumericAggState));
    6193                 :             : 
    6194         [ +  - ]:         278 :     if (state)
    6195                 :             :     {
    6196                 :             :         NumericVar  tmp_var;
    6197                 :             : 
    6198                 :         278 :         numstate.N = state->N;
    6199                 :             : 
    6200                 :         278 :         init_var(&tmp_var);
    6201                 :             : 
    6202                 :         278 :         int128_to_numericvar(state->sumX, &tmp_var);
    6203                 :         278 :         accum_sum_add(&numstate.sumX, &tmp_var);
    6204                 :             : 
    6205                 :         278 :         int128_to_numericvar(state->sumX2, &tmp_var);
    6206                 :         278 :         accum_sum_add(&numstate.sumX2, &tmp_var);
    6207                 :             : 
    6208                 :         278 :         free_var(&tmp_var);
    6209                 :             :     }
    6210                 :             : 
    6211                 :         278 :     res = numeric_stddev_internal(&numstate, variance, sample, is_null);
    6212                 :             : 
    6213         [ +  - ]:         278 :     if (numstate.sumX.ndigits > 0)
    6214                 :             :     {
    6215                 :         278 :         pfree(numstate.sumX.pos_digits);
    6216                 :         278 :         pfree(numstate.sumX.neg_digits);
    6217                 :             :     }
    6218         [ +  - ]:         278 :     if (numstate.sumX2.ndigits > 0)
    6219                 :             :     {
    6220                 :         278 :         pfree(numstate.sumX2.pos_digits);
    6221                 :         278 :         pfree(numstate.sumX2.neg_digits);
    6222                 :             :     }
    6223                 :             : 
    6224                 :         278 :     return res;
    6225                 :             : }
    6226                 :             : 
    6227                 :             : Datum
    6228                 :          84 : numeric_poly_var_samp(PG_FUNCTION_ARGS)
    6229                 :             : {
    6230                 :             :     Int128AggState *state;
    6231                 :             :     Numeric     res;
    6232                 :             :     bool        is_null;
    6233                 :             : 
    6234         [ +  - ]:          84 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    6235                 :             : 
    6236                 :          84 :     res = numeric_poly_stddev_internal(state, true, true, &is_null);
    6237                 :             : 
    6238         [ +  + ]:          84 :     if (is_null)
    6239                 :          16 :         PG_RETURN_NULL();
    6240                 :             :     else
    6241                 :          68 :         PG_RETURN_NUMERIC(res);
    6242                 :             : }
    6243                 :             : 
    6244                 :             : Datum
    6245                 :         106 : numeric_poly_stddev_samp(PG_FUNCTION_ARGS)
    6246                 :             : {
    6247                 :             :     Int128AggState *state;
    6248                 :             :     Numeric     res;
    6249                 :             :     bool        is_null;
    6250                 :             : 
    6251         [ +  - ]:         106 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    6252                 :             : 
    6253                 :         106 :     res = numeric_poly_stddev_internal(state, false, true, &is_null);
    6254                 :             : 
    6255         [ +  + ]:         106 :     if (is_null)
    6256                 :          16 :         PG_RETURN_NULL();
    6257                 :             :     else
    6258                 :          90 :         PG_RETURN_NUMERIC(res);
    6259                 :             : }
    6260                 :             : 
    6261                 :             : Datum
    6262                 :          40 : numeric_poly_var_pop(PG_FUNCTION_ARGS)
    6263                 :             : {
    6264                 :             :     Int128AggState *state;
    6265                 :             :     Numeric     res;
    6266                 :             :     bool        is_null;
    6267                 :             : 
    6268         [ +  - ]:          40 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    6269                 :             : 
    6270                 :          40 :     res = numeric_poly_stddev_internal(state, true, false, &is_null);
    6271                 :             : 
    6272         [ -  + ]:          40 :     if (is_null)
    6273                 :           0 :         PG_RETURN_NULL();
    6274                 :             :     else
    6275                 :          40 :         PG_RETURN_NUMERIC(res);
    6276                 :             : }
    6277                 :             : 
    6278                 :             : Datum
    6279                 :          48 : numeric_poly_stddev_pop(PG_FUNCTION_ARGS)
    6280                 :             : {
    6281                 :             :     Int128AggState *state;
    6282                 :             :     Numeric     res;
    6283                 :             :     bool        is_null;
    6284                 :             : 
    6285         [ +  - ]:          48 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    6286                 :             : 
    6287                 :          48 :     res = numeric_poly_stddev_internal(state, false, false, &is_null);
    6288                 :             : 
    6289         [ -  + ]:          48 :     if (is_null)
    6290                 :           0 :         PG_RETURN_NULL();
    6291                 :             :     else
    6292                 :          48 :         PG_RETURN_NUMERIC(res);
    6293                 :             : }
    6294                 :             : 
    6295                 :             : /*
    6296                 :             :  * SUM transition functions for integer datatypes.
    6297                 :             :  *
    6298                 :             :  * To avoid overflow, we use accumulators wider than the input datatype.
    6299                 :             :  * A Numeric accumulator is needed for int8 input; for int4 and int2
    6300                 :             :  * inputs, we use int8 accumulators which should be sufficient for practical
    6301                 :             :  * purposes.  (The latter two therefore don't really belong in this file,
    6302                 :             :  * but we keep them here anyway.)
    6303                 :             :  *
    6304                 :             :  * Because SQL defines the SUM() of no values to be NULL, not zero,
    6305                 :             :  * the initial condition of the transition data value needs to be NULL. This
    6306                 :             :  * means we can't rely on ExecAgg to automatically insert the first non-null
    6307                 :             :  * data value into the transition data: it doesn't know how to do the type
    6308                 :             :  * conversion.  The upshot is that these routines have to be marked non-strict
    6309                 :             :  * and handle substitution of the first non-null input themselves.
    6310                 :             :  *
    6311                 :             :  * Note: these functions are used only in plain aggregation mode.
    6312                 :             :  * In moving-aggregate mode, we use intX_avg_accum and intX_avg_accum_inv.
    6313                 :             :  */
    6314                 :             : 
    6315                 :             : Datum
    6316                 :          16 : int2_sum(PG_FUNCTION_ARGS)
    6317                 :             : {
    6318                 :             :     int64       oldsum;
    6319                 :             :     int64       newval;
    6320                 :             : 
    6321         [ +  + ]:          16 :     if (PG_ARGISNULL(0))
    6322                 :             :     {
    6323                 :             :         /* No non-null input seen so far... */
    6324         [ -  + ]:           4 :         if (PG_ARGISNULL(1))
    6325                 :           0 :             PG_RETURN_NULL();   /* still no non-null */
    6326                 :             :         /* This is the first non-null input. */
    6327                 :           4 :         newval = (int64) PG_GETARG_INT16(1);
    6328                 :           4 :         PG_RETURN_INT64(newval);
    6329                 :             :     }
    6330                 :             : 
    6331                 :          12 :     oldsum = PG_GETARG_INT64(0);
    6332                 :             : 
    6333                 :             :     /* Leave sum unchanged if new input is null. */
    6334         [ -  + ]:          12 :     if (PG_ARGISNULL(1))
    6335                 :           0 :         PG_RETURN_INT64(oldsum);
    6336                 :             : 
    6337                 :             :     /* OK to do the addition. */
    6338                 :          12 :     newval = oldsum + (int64) PG_GETARG_INT16(1);
    6339                 :             : 
    6340                 :          12 :     PG_RETURN_INT64(newval);
    6341                 :             : }
    6342                 :             : 
    6343                 :             : Datum
    6344                 :     3269520 : int4_sum(PG_FUNCTION_ARGS)
    6345                 :             : {
    6346                 :             :     int64       oldsum;
    6347                 :             :     int64       newval;
    6348                 :             : 
    6349         [ +  + ]:     3269520 :     if (PG_ARGISNULL(0))
    6350                 :             :     {
    6351                 :             :         /* No non-null input seen so far... */
    6352         [ +  + ]:      129114 :         if (PG_ARGISNULL(1))
    6353                 :         654 :             PG_RETURN_NULL();   /* still no non-null */
    6354                 :             :         /* This is the first non-null input. */
    6355                 :      128460 :         newval = (int64) PG_GETARG_INT32(1);
    6356                 :      128460 :         PG_RETURN_INT64(newval);
    6357                 :             :     }
    6358                 :             : 
    6359                 :     3140406 :     oldsum = PG_GETARG_INT64(0);
    6360                 :             : 
    6361                 :             :     /* Leave sum unchanged if new input is null. */
    6362         [ +  + ]:     3140406 :     if (PG_ARGISNULL(1))
    6363                 :       20606 :         PG_RETURN_INT64(oldsum);
    6364                 :             : 
    6365                 :             :     /* OK to do the addition. */
    6366                 :     3119800 :     newval = oldsum + (int64) PG_GETARG_INT32(1);
    6367                 :             : 
    6368                 :     3119800 :     PG_RETURN_INT64(newval);
    6369                 :             : }
    6370                 :             : 
    6371                 :             : /*
    6372                 :             :  * Note: this function is obsolete, it's no longer used for SUM(int8).
    6373                 :             :  */
    6374                 :             : Datum
    6375                 :           0 : int8_sum(PG_FUNCTION_ARGS)
    6376                 :             : {
    6377                 :             :     Numeric     oldsum;
    6378                 :             : 
    6379         [ #  # ]:           0 :     if (PG_ARGISNULL(0))
    6380                 :             :     {
    6381                 :             :         /* No non-null input seen so far... */
    6382         [ #  # ]:           0 :         if (PG_ARGISNULL(1))
    6383                 :           0 :             PG_RETURN_NULL();   /* still no non-null */
    6384                 :             :         /* This is the first non-null input. */
    6385                 :           0 :         PG_RETURN_NUMERIC(int64_to_numeric(PG_GETARG_INT64(1)));
    6386                 :             :     }
    6387                 :             : 
    6388                 :             :     /*
    6389                 :             :      * Note that we cannot special-case the aggregate case here, as we do for
    6390                 :             :      * int2_sum and int4_sum: numeric is of variable size, so we cannot modify
    6391                 :             :      * our first parameter in-place.
    6392                 :             :      */
    6393                 :             : 
    6394                 :           0 :     oldsum = PG_GETARG_NUMERIC(0);
    6395                 :             : 
    6396                 :             :     /* Leave sum unchanged if new input is null. */
    6397         [ #  # ]:           0 :     if (PG_ARGISNULL(1))
    6398                 :           0 :         PG_RETURN_NUMERIC(oldsum);
    6399                 :             : 
    6400                 :             :     /* OK to do the addition. */
    6401                 :           0 :     PG_RETURN_DATUM(DirectFunctionCall2(numeric_add,
    6402                 :             :                                         NumericGetDatum(oldsum),
    6403                 :             :                                         NumericGetDatum(int64_to_numeric(PG_GETARG_INT64(1)))));
    6404                 :             : }
    6405                 :             : 
    6406                 :             : 
    6407                 :             : /*
    6408                 :             :  * Routines for avg(int2) and avg(int4).  The transition datatype
    6409                 :             :  * is a two-element int8 array, holding count and sum.
    6410                 :             :  *
    6411                 :             :  * These functions are also used for sum(int2) and sum(int4) when
    6412                 :             :  * operating in moving-aggregate mode, since for correct inverse transitions
    6413                 :             :  * we need to count the inputs.
    6414                 :             :  */
    6415                 :             : 
    6416                 :             : typedef struct Int8TransTypeData
    6417                 :             : {
    6418                 :             :     int64       count;
    6419                 :             :     int64       sum;
    6420                 :             : } Int8TransTypeData;
    6421                 :             : 
    6422                 :             : Datum
    6423                 :          28 : int2_avg_accum(PG_FUNCTION_ARGS)
    6424                 :             : {
    6425                 :             :     ArrayType  *transarray;
    6426                 :          28 :     int16       newval = PG_GETARG_INT16(1);
    6427                 :             :     Int8TransTypeData *transdata;
    6428                 :             : 
    6429                 :             :     /*
    6430                 :             :      * If we're invoked as an aggregate, we can cheat and modify our first
    6431                 :             :      * parameter in-place to reduce palloc overhead. Otherwise we need to make
    6432                 :             :      * a copy of it before scribbling on it.
    6433                 :             :      */
    6434         [ +  - ]:          28 :     if (AggCheckCallContext(fcinfo, NULL))
    6435                 :          28 :         transarray = PG_GETARG_ARRAYTYPE_P(0);
    6436                 :             :     else
    6437                 :           0 :         transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
    6438                 :             : 
    6439   [ +  -  -  + ]:          56 :     if (ARR_HASNULL(transarray) ||
    6440                 :          28 :         ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6441         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6442                 :             : 
    6443         [ -  + ]:          28 :     transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
    6444                 :          28 :     transdata->count++;
    6445                 :          28 :     transdata->sum += newval;
    6446                 :             : 
    6447                 :          28 :     PG_RETURN_ARRAYTYPE_P(transarray);
    6448                 :             : }
    6449                 :             : 
    6450                 :             : Datum
    6451                 :     1744070 : int4_avg_accum(PG_FUNCTION_ARGS)
    6452                 :             : {
    6453                 :             :     ArrayType  *transarray;
    6454                 :     1744070 :     int32       newval = PG_GETARG_INT32(1);
    6455                 :             :     Int8TransTypeData *transdata;
    6456                 :             : 
    6457                 :             :     /*
    6458                 :             :      * If we're invoked as an aggregate, we can cheat and modify our first
    6459                 :             :      * parameter in-place to reduce palloc overhead. Otherwise we need to make
    6460                 :             :      * a copy of it before scribbling on it.
    6461                 :             :      */
    6462         [ +  - ]:     1744070 :     if (AggCheckCallContext(fcinfo, NULL))
    6463                 :     1744070 :         transarray = PG_GETARG_ARRAYTYPE_P(0);
    6464                 :             :     else
    6465                 :           0 :         transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
    6466                 :             : 
    6467   [ +  -  -  + ]:     3488140 :     if (ARR_HASNULL(transarray) ||
    6468                 :     1744070 :         ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6469         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6470                 :             : 
    6471         [ -  + ]:     1744070 :     transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
    6472                 :     1744070 :     transdata->count++;
    6473                 :     1744070 :     transdata->sum += newval;
    6474                 :             : 
    6475                 :     1744070 :     PG_RETURN_ARRAYTYPE_P(transarray);
    6476                 :             : }
    6477                 :             : 
    6478                 :             : Datum
    6479                 :        6727 : int4_avg_combine(PG_FUNCTION_ARGS)
    6480                 :             : {
    6481                 :             :     ArrayType  *transarray1;
    6482                 :             :     ArrayType  *transarray2;
    6483                 :             :     Int8TransTypeData *state1;
    6484                 :             :     Int8TransTypeData *state2;
    6485                 :             : 
    6486         [ -  + ]:        6727 :     if (!AggCheckCallContext(fcinfo, NULL))
    6487         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    6488                 :             : 
    6489                 :        6727 :     transarray1 = PG_GETARG_ARRAYTYPE_P(0);
    6490                 :        6727 :     transarray2 = PG_GETARG_ARRAYTYPE_P(1);
    6491                 :             : 
    6492   [ +  -  -  + ]:       13454 :     if (ARR_HASNULL(transarray1) ||
    6493                 :        6727 :         ARR_SIZE(transarray1) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6494         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6495                 :             : 
    6496   [ +  -  -  + ]:       13454 :     if (ARR_HASNULL(transarray2) ||
    6497                 :        6727 :         ARR_SIZE(transarray2) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6498         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6499                 :             : 
    6500         [ -  + ]:        6727 :     state1 = (Int8TransTypeData *) ARR_DATA_PTR(transarray1);
    6501         [ -  + ]:        6727 :     state2 = (Int8TransTypeData *) ARR_DATA_PTR(transarray2);
    6502                 :             : 
    6503                 :        6727 :     state1->count += state2->count;
    6504                 :        6727 :     state1->sum += state2->sum;
    6505                 :             : 
    6506                 :        6727 :     PG_RETURN_ARRAYTYPE_P(transarray1);
    6507                 :             : }
    6508                 :             : 
    6509                 :             : Datum
    6510                 :           8 : int2_avg_accum_inv(PG_FUNCTION_ARGS)
    6511                 :             : {
    6512                 :             :     ArrayType  *transarray;
    6513                 :           8 :     int16       newval = PG_GETARG_INT16(1);
    6514                 :             :     Int8TransTypeData *transdata;
    6515                 :             : 
    6516                 :             :     /*
    6517                 :             :      * If we're invoked as an aggregate, we can cheat and modify our first
    6518                 :             :      * parameter in-place to reduce palloc overhead. Otherwise we need to make
    6519                 :             :      * a copy of it before scribbling on it.
    6520                 :             :      */
    6521         [ +  - ]:           8 :     if (AggCheckCallContext(fcinfo, NULL))
    6522                 :           8 :         transarray = PG_GETARG_ARRAYTYPE_P(0);
    6523                 :             :     else
    6524                 :           0 :         transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
    6525                 :             : 
    6526   [ +  -  -  + ]:          16 :     if (ARR_HASNULL(transarray) ||
    6527                 :           8 :         ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6528         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6529                 :             : 
    6530         [ -  + ]:           8 :     transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
    6531                 :           8 :     transdata->count--;
    6532                 :           8 :     transdata->sum -= newval;
    6533                 :             : 
    6534                 :           8 :     PG_RETURN_ARRAYTYPE_P(transarray);
    6535                 :             : }
    6536                 :             : 
    6537                 :             : Datum
    6538                 :        1000 : int4_avg_accum_inv(PG_FUNCTION_ARGS)
    6539                 :             : {
    6540                 :             :     ArrayType  *transarray;
    6541                 :        1000 :     int32       newval = PG_GETARG_INT32(1);
    6542                 :             :     Int8TransTypeData *transdata;
    6543                 :             : 
    6544                 :             :     /*
    6545                 :             :      * If we're invoked as an aggregate, we can cheat and modify our first
    6546                 :             :      * parameter in-place to reduce palloc overhead. Otherwise we need to make
    6547                 :             :      * a copy of it before scribbling on it.
    6548                 :             :      */
    6549         [ +  - ]:        1000 :     if (AggCheckCallContext(fcinfo, NULL))
    6550                 :        1000 :         transarray = PG_GETARG_ARRAYTYPE_P(0);
    6551                 :             :     else
    6552                 :           0 :         transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
    6553                 :             : 
    6554   [ +  -  -  + ]:        2000 :     if (ARR_HASNULL(transarray) ||
    6555                 :        1000 :         ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6556         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6557                 :             : 
    6558         [ -  + ]:        1000 :     transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
    6559                 :        1000 :     transdata->count--;
    6560                 :        1000 :     transdata->sum -= newval;
    6561                 :             : 
    6562                 :        1000 :     PG_RETURN_ARRAYTYPE_P(transarray);
    6563                 :             : }
    6564                 :             : 
    6565                 :             : Datum
    6566                 :        6817 : int8_avg(PG_FUNCTION_ARGS)
    6567                 :             : {
    6568                 :        6817 :     ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    6569                 :             :     Int8TransTypeData *transdata;
    6570                 :             :     Datum       countd,
    6571                 :             :                 sumd;
    6572                 :             : 
    6573   [ +  -  -  + ]:       13634 :     if (ARR_HASNULL(transarray) ||
    6574                 :        6817 :         ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6575         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6576         [ -  + ]:        6817 :     transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
    6577                 :             : 
    6578                 :             :     /* SQL defines AVG of no values to be NULL */
    6579         [ +  + ]:        6817 :     if (transdata->count == 0)
    6580                 :          73 :         PG_RETURN_NULL();
    6581                 :             : 
    6582                 :        6744 :     countd = NumericGetDatum(int64_to_numeric(transdata->count));
    6583                 :        6744 :     sumd = NumericGetDatum(int64_to_numeric(transdata->sum));
    6584                 :             : 
    6585                 :        6744 :     PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumd, countd));
    6586                 :             : }
    6587                 :             : 
    6588                 :             : /*
    6589                 :             :  * SUM(int2) and SUM(int4) both return int8, so we can use this
    6590                 :             :  * final function for both.
    6591                 :             :  */
    6592                 :             : Datum
    6593                 :        2716 : int2int4_sum(PG_FUNCTION_ARGS)
    6594                 :             : {
    6595                 :        2716 :     ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    6596                 :             :     Int8TransTypeData *transdata;
    6597                 :             : 
    6598   [ +  -  -  + ]:        5432 :     if (ARR_HASNULL(transarray) ||
    6599                 :        2716 :         ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6600         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6601         [ -  + ]:        2716 :     transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
    6602                 :             : 
    6603                 :             :     /* SQL defines SUM of no values to be NULL */
    6604         [ +  + ]:        2716 :     if (transdata->count == 0)
    6605                 :         404 :         PG_RETURN_NULL();
    6606                 :             : 
    6607                 :        2312 :     PG_RETURN_DATUM(Int64GetDatumFast(transdata->sum));
    6608                 :             : }
    6609                 :             : 
    6610                 :             : 
    6611                 :             : /* ----------------------------------------------------------------------
    6612                 :             :  *
    6613                 :             :  * Debug support
    6614                 :             :  *
    6615                 :             :  * ----------------------------------------------------------------------
    6616                 :             :  */
    6617                 :             : 
    6618                 :             : #ifdef NUMERIC_DEBUG
    6619                 :             : 
    6620                 :             : /*
    6621                 :             :  * dump_numeric() - Dump a value in the db storage format for debugging
    6622                 :             :  */
    6623                 :             : static void
    6624                 :             : dump_numeric(const char *str, Numeric num)
    6625                 :             : {
    6626                 :             :     NumericDigit *digits = NUMERIC_DIGITS(num);
    6627                 :             :     int         ndigits;
    6628                 :             :     int         i;
    6629                 :             : 
    6630                 :             :     ndigits = NUMERIC_NDIGITS(num);
    6631                 :             : 
    6632                 :             :     printf("%s: NUMERIC w=%d d=%d ", str,
    6633                 :             :            NUMERIC_WEIGHT(num), NUMERIC_DSCALE(num));
    6634                 :             :     switch (NUMERIC_SIGN(num))
    6635                 :             :     {
    6636                 :             :         case NUMERIC_POS:
    6637                 :             :             printf("POS");
    6638                 :             :             break;
    6639                 :             :         case NUMERIC_NEG:
    6640                 :             :             printf("NEG");
    6641                 :             :             break;
    6642                 :             :         case NUMERIC_NAN:
    6643                 :             :             printf("NaN");
    6644                 :             :             break;
    6645                 :             :         case NUMERIC_PINF:
    6646                 :             :             printf("Infinity");
    6647                 :             :             break;
    6648                 :             :         case NUMERIC_NINF:
    6649                 :             :             printf("-Infinity");
    6650                 :             :             break;
    6651                 :             :         default:
    6652                 :             :             printf("SIGN=0x%x", NUMERIC_SIGN(num));
    6653                 :             :             break;
    6654                 :             :     }
    6655                 :             : 
    6656                 :             :     for (i = 0; i < ndigits; i++)
    6657                 :             :         printf(" %0*d", DEC_DIGITS, digits[i]);
    6658                 :             :     printf("\n");
    6659                 :             : }
    6660                 :             : 
    6661                 :             : 
    6662                 :             : /*
    6663                 :             :  * dump_var() - Dump a value in the variable format for debugging
    6664                 :             :  */
    6665                 :             : static void
    6666                 :             : dump_var(const char *str, NumericVar *var)
    6667                 :             : {
    6668                 :             :     int         i;
    6669                 :             : 
    6670                 :             :     printf("%s: VAR w=%d d=%d ", str, var->weight, var->dscale);
    6671                 :             :     switch (var->sign)
    6672                 :             :     {
    6673                 :             :         case NUMERIC_POS:
    6674                 :             :             printf("POS");
    6675                 :             :             break;
    6676                 :             :         case NUMERIC_NEG:
    6677                 :             :             printf("NEG");
    6678                 :             :             break;
    6679                 :             :         case NUMERIC_NAN:
    6680                 :             :             printf("NaN");
    6681                 :             :             break;
    6682                 :             :         case NUMERIC_PINF:
    6683                 :             :             printf("Infinity");
    6684                 :             :             break;
    6685                 :             :         case NUMERIC_NINF:
    6686                 :             :             printf("-Infinity");
    6687                 :             :             break;
    6688                 :             :         default:
    6689                 :             :             printf("SIGN=0x%x", var->sign);
    6690                 :             :             break;
    6691                 :             :     }
    6692                 :             : 
    6693                 :             :     for (i = 0; i < var->ndigits; i++)
    6694                 :             :         printf(" %0*d", DEC_DIGITS, var->digits[i]);
    6695                 :             : 
    6696                 :             :     printf("\n");
    6697                 :             : }
    6698                 :             : #endif                          /* NUMERIC_DEBUG */
    6699                 :             : 
    6700                 :             : 
    6701                 :             : /* ----------------------------------------------------------------------
    6702                 :             :  *
    6703                 :             :  * Local functions follow
    6704                 :             :  *
    6705                 :             :  * In general, these do not support "special" (NaN or infinity) inputs;
    6706                 :             :  * callers should handle those possibilities first.
    6707                 :             :  * (There are one or two exceptions, noted in their header comments.)
    6708                 :             :  *
    6709                 :             :  * ----------------------------------------------------------------------
    6710                 :             :  */
    6711                 :             : 
    6712                 :             : 
    6713                 :             : /*
    6714                 :             :  * alloc_var() -
    6715                 :             :  *
    6716                 :             :  *  Allocate a digit buffer of ndigits digits (plus a spare digit for rounding)
    6717                 :             :  */
    6718                 :             : static void
    6719                 :     1447548 : alloc_var(NumericVar *var, int ndigits)
    6720                 :             : {
    6721         [ +  + ]:     1447548 :     digitbuf_free(var->buf);
    6722                 :     1447548 :     var->buf = digitbuf_alloc(ndigits + 1);
    6723                 :     1447548 :     var->buf[0] = 0;         /* spare digit for rounding */
    6724                 :     1447548 :     var->digits = var->buf + 1;
    6725                 :     1447548 :     var->ndigits = ndigits;
    6726                 :     1447548 : }
    6727                 :             : 
    6728                 :             : 
    6729                 :             : /*
    6730                 :             :  * free_var() -
    6731                 :             :  *
    6732                 :             :  *  Return the digit buffer of a variable to the free pool
    6733                 :             :  */
    6734                 :             : static void
    6735                 :     2784635 : free_var(NumericVar *var)
    6736                 :             : {
    6737         [ +  + ]:     2784635 :     digitbuf_free(var->buf);
    6738                 :     2784635 :     var->buf = NULL;
    6739                 :     2784635 :     var->digits = NULL;
    6740                 :     2784635 :     var->sign = NUMERIC_NAN;
    6741                 :     2784635 : }
    6742                 :             : 
    6743                 :             : 
    6744                 :             : /*
    6745                 :             :  * zero_var() -
    6746                 :             :  *
    6747                 :             :  *  Set a variable to ZERO.
    6748                 :             :  *  Note: its dscale is not touched.
    6749                 :             :  */
    6750                 :             : static void
    6751                 :       38317 : zero_var(NumericVar *var)
    6752                 :             : {
    6753         [ +  + ]:       38317 :     digitbuf_free(var->buf);
    6754                 :       38317 :     var->buf = NULL;
    6755                 :       38317 :     var->digits = NULL;
    6756                 :       38317 :     var->ndigits = 0;
    6757                 :       38317 :     var->weight = 0;         /* by convention; doesn't really matter */
    6758                 :       38317 :     var->sign = NUMERIC_POS; /* anything but NAN... */
    6759                 :       38317 : }
    6760                 :             : 
    6761                 :             : 
    6762                 :             : /*
    6763                 :             :  * set_var_from_str()
    6764                 :             :  *
    6765                 :             :  *  Parse a string and put the number into a variable
    6766                 :             :  *
    6767                 :             :  * This function does not handle leading or trailing spaces.  It returns
    6768                 :             :  * the end+1 position parsed into *endptr, so that caller can check for
    6769                 :             :  * trailing spaces/garbage if deemed necessary.
    6770                 :             :  *
    6771                 :             :  * cp is the place to actually start parsing; str is what to use in error
    6772                 :             :  * reports.  (Typically cp would be the same except advanced over spaces.)
    6773                 :             :  *
    6774                 :             :  * Returns true on success, false on failure (if escontext points to an
    6775                 :             :  * ErrorSaveContext; otherwise errors are thrown).
    6776                 :             :  */
    6777                 :             : static bool
    6778                 :      119403 : set_var_from_str(const char *str, const char *cp,
    6779                 :             :                  NumericVar *dest, const char **endptr,
    6780                 :             :                  Node *escontext)
    6781                 :             : {
    6782                 :      119403 :     bool        have_dp = false;
    6783                 :             :     int         i;
    6784                 :             :     unsigned char *decdigits;
    6785                 :      119403 :     int         sign = NUMERIC_POS;
    6786                 :      119403 :     int         dweight = -1;
    6787                 :             :     int         ddigits;
    6788                 :      119403 :     int         dscale = 0;
    6789                 :             :     int         weight;
    6790                 :             :     int         ndigits;
    6791                 :             :     int         offset;
    6792                 :             :     NumericDigit *digits;
    6793                 :             : 
    6794                 :             :     /*
    6795                 :             :      * We first parse the string to extract decimal digits and determine the
    6796                 :             :      * correct decimal weight.  Then convert to NBASE representation.
    6797                 :             :      */
    6798      [ -  +  + ]:      119403 :     switch (*cp)
    6799                 :             :     {
    6800                 :           0 :         case '+':
    6801                 :           0 :             sign = NUMERIC_POS;
    6802                 :           0 :             cp++;
    6803                 :           0 :             break;
    6804                 :             : 
    6805                 :         183 :         case '-':
    6806                 :         183 :             sign = NUMERIC_NEG;
    6807                 :         183 :             cp++;
    6808                 :         183 :             break;
    6809                 :             :     }
    6810                 :             : 
    6811         [ +  + ]:      119403 :     if (*cp == '.')
    6812                 :             :     {
    6813                 :         252 :         have_dp = true;
    6814                 :         252 :         cp++;
    6815                 :             :     }
    6816                 :             : 
    6817         [ -  + ]:      119403 :     if (!isdigit((unsigned char) *cp))
    6818                 :           0 :         goto invalid_syntax;
    6819                 :             : 
    6820                 :      119403 :     decdigits = (unsigned char *) palloc(strlen(cp) + DEC_DIGITS * 2);
    6821                 :             : 
    6822                 :             :     /* leading padding for digit alignment later */
    6823                 :      119403 :     memset(decdigits, 0, DEC_DIGITS);
    6824                 :      119403 :     i = DEC_DIGITS;
    6825                 :             : 
    6826         [ +  + ]:      501972 :     while (*cp)
    6827                 :             :     {
    6828         [ +  + ]:      383639 :         if (isdigit((unsigned char) *cp))
    6829                 :             :         {
    6830                 :      370478 :             decdigits[i++] = *cp++ - '0';
    6831         [ +  + ]:      370478 :             if (!have_dp)
    6832                 :      314257 :                 dweight++;
    6833                 :             :             else
    6834                 :       56221 :                 dscale++;
    6835                 :             :         }
    6836         [ +  + ]:       13161 :         else if (*cp == '.')
    6837                 :             :         {
    6838         [ -  + ]:       11983 :             if (have_dp)
    6839                 :           0 :                 goto invalid_syntax;
    6840                 :       11983 :             have_dp = true;
    6841                 :       11983 :             cp++;
    6842                 :             :             /* decimal point must not be followed by underscore */
    6843         [ +  + ]:       11983 :             if (*cp == '_')
    6844                 :           4 :                 goto invalid_syntax;
    6845                 :             :         }
    6846         [ +  + ]:        1178 :         else if (*cp == '_')
    6847                 :             :         {
    6848                 :             :             /* underscore must be followed by more digits */
    6849                 :         124 :             cp++;
    6850         [ +  + ]:         124 :             if (!isdigit((unsigned char) *cp))
    6851                 :          12 :                 goto invalid_syntax;
    6852                 :             :         }
    6853                 :             :         else
    6854                 :        1054 :             break;
    6855                 :             :     }
    6856                 :             : 
    6857                 :      119387 :     ddigits = i - DEC_DIGITS;
    6858                 :             :     /* trailing padding for digit alignment later */
    6859                 :      119387 :     memset(decdigits + i, 0, DEC_DIGITS - 1);
    6860                 :             : 
    6861                 :             :     /* Handle exponent, if any */
    6862   [ +  +  +  + ]:      119387 :     if (*cp == 'e' || *cp == 'E')
    6863                 :             :     {
    6864                 :        1022 :         int64       exponent = 0;
    6865                 :        1022 :         bool        neg = false;
    6866                 :             : 
    6867                 :             :         /*
    6868                 :             :          * At this point, dweight and dscale can't be more than about
    6869                 :             :          * INT_MAX/2 due to the MaxAllocSize limit on string length, so
    6870                 :             :          * constraining the exponent similarly should be enough to prevent
    6871                 :             :          * integer overflow in this function.  If the value is too large to
    6872                 :             :          * fit in storage format, make_result() will complain about it later;
    6873                 :             :          * for consistency use the same ereport errcode/text as make_result().
    6874                 :             :          */
    6875                 :             : 
    6876                 :             :         /* exponent sign */
    6877                 :        1022 :         cp++;
    6878         [ +  + ]:        1022 :         if (*cp == '+')
    6879                 :         102 :             cp++;
    6880         [ +  + ]:         920 :         else if (*cp == '-')
    6881                 :             :         {
    6882                 :         444 :             neg = true;
    6883                 :         444 :             cp++;
    6884                 :             :         }
    6885                 :             : 
    6886                 :             :         /* exponent digits */
    6887         [ +  + ]:        1022 :         if (!isdigit((unsigned char) *cp))
    6888                 :           4 :             goto invalid_syntax;
    6889                 :             : 
    6890         [ +  + ]:        3569 :         while (*cp)
    6891                 :             :         {
    6892         [ +  + ]:        2563 :             if (isdigit((unsigned char) *cp))
    6893                 :             :             {
    6894                 :        2535 :                 exponent = exponent * 10 + (*cp++ - '0');
    6895         [ +  + ]:        2535 :                 if (exponent > PG_INT32_MAX / 2)
    6896                 :           4 :                     goto out_of_range;
    6897                 :             :             }
    6898         [ +  - ]:          28 :             else if (*cp == '_')
    6899                 :             :             {
    6900                 :             :                 /* underscore must be followed by more digits */
    6901                 :          28 :                 cp++;
    6902         [ +  + ]:          28 :                 if (!isdigit((unsigned char) *cp))
    6903                 :           8 :                     goto invalid_syntax;
    6904                 :             :             }
    6905                 :             :             else
    6906                 :           0 :                 break;
    6907                 :             :         }
    6908                 :             : 
    6909         [ +  + ]:        1006 :         if (neg)
    6910                 :         444 :             exponent = -exponent;
    6911                 :             : 
    6912                 :        1006 :         dweight += (int) exponent;
    6913                 :        1006 :         dscale -= (int) exponent;
    6914         [ +  + ]:        1006 :         if (dscale < 0)
    6915                 :         426 :             dscale = 0;
    6916                 :             :     }
    6917                 :             : 
    6918                 :             :     /*
    6919                 :             :      * Okay, convert pure-decimal representation to base NBASE.  First we need
    6920                 :             :      * to determine the converted weight and ndigits.  offset is the number of
    6921                 :             :      * decimal zeroes to insert before the first given digit to have a
    6922                 :             :      * correctly aligned first NBASE digit.
    6923                 :             :      */
    6924         [ +  + ]:      119371 :     if (dweight >= 0)
    6925                 :      118743 :         weight = (dweight + 1 + DEC_DIGITS - 1) / DEC_DIGITS - 1;
    6926                 :             :     else
    6927                 :         628 :         weight = -((-dweight - 1) / DEC_DIGITS + 1);
    6928                 :      119371 :     offset = (weight + 1) * DEC_DIGITS - (dweight + 1);
    6929                 :      119371 :     ndigits = (ddigits + offset + DEC_DIGITS - 1) / DEC_DIGITS;
    6930                 :             : 
    6931                 :      119371 :     alloc_var(dest, ndigits);
    6932                 :      119371 :     dest->sign = sign;
    6933                 :      119371 :     dest->weight = weight;
    6934                 :      119371 :     dest->dscale = dscale;
    6935                 :             : 
    6936                 :      119371 :     i = DEC_DIGITS - offset;
    6937                 :      119371 :     digits = dest->digits;
    6938                 :             : 
    6939         [ +  + ]:      284250 :     while (ndigits-- > 0)
    6940                 :             :     {
    6941                 :             : #if DEC_DIGITS == 4
    6942                 :      164879 :         *digits++ = ((decdigits[i] * 10 + decdigits[i + 1]) * 10 +
    6943                 :      164879 :                      decdigits[i + 2]) * 10 + decdigits[i + 3];
    6944                 :             : #elif DEC_DIGITS == 2
    6945                 :             :         *digits++ = decdigits[i] * 10 + decdigits[i + 1];
    6946                 :             : #elif DEC_DIGITS == 1
    6947                 :             :         *digits++ = decdigits[i];
    6948                 :             : #else
    6949                 :             : #error unsupported NBASE
    6950                 :             : #endif
    6951                 :      164879 :         i += DEC_DIGITS;
    6952                 :             :     }
    6953                 :             : 
    6954                 :      119371 :     pfree(decdigits);
    6955                 :             : 
    6956                 :             :     /* Strip any leading/trailing zeroes, and normalize weight if zero */
    6957                 :      119371 :     strip_var(dest);
    6958                 :             : 
    6959                 :             :     /* Return end+1 position for caller */
    6960                 :      119371 :     *endptr = cp;
    6961                 :             : 
    6962                 :      119371 :     return true;
    6963                 :             : 
    6964                 :           4 : out_of_range:
    6965         [ +  - ]:           4 :     ereturn(escontext, false,
    6966                 :             :             (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    6967                 :             :              errmsg("value overflows numeric format")));
    6968                 :             : 
    6969                 :          28 : invalid_syntax:
    6970         [ +  - ]:          28 :     ereturn(escontext, false,
    6971                 :             :             (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    6972                 :             :              errmsg("invalid input syntax for type %s: \"%s\"",
    6973                 :             :                     "numeric", str)));
    6974                 :             : }
    6975                 :             : 
    6976                 :             : 
    6977                 :             : /*
    6978                 :             :  * Return the numeric value of a single hex digit.
    6979                 :             :  */
    6980                 :             : static inline int
    6981                 :         472 : xdigit_value(char dig)
    6982                 :             : {
    6983   [ +  -  +  + ]:         596 :     return dig >= '0' && dig <= '9' ? dig - '0' :
    6984   [ +  +  +  - ]:         196 :         dig >= 'a' && dig <= 'f' ? dig - 'a' + 10 :
    6985   [ +  -  +  - ]:          72 :         dig >= 'A' && dig <= 'F' ? dig - 'A' + 10 : -1;
    6986                 :             : }
    6987                 :             : 
    6988                 :             : /*
    6989                 :             :  * set_var_from_non_decimal_integer_str()
    6990                 :             :  *
    6991                 :             :  *  Parse a string containing a non-decimal integer
    6992                 :             :  *
    6993                 :             :  * This function does not handle leading or trailing spaces.  It returns
    6994                 :             :  * the end+1 position parsed into *endptr, so that caller can check for
    6995                 :             :  * trailing spaces/garbage if deemed necessary.
    6996                 :             :  *
    6997                 :             :  * cp is the place to actually start parsing; str is what to use in error
    6998                 :             :  * reports.  The number's sign and base prefix indicator (e.g., "0x") are
    6999                 :             :  * assumed to have already been parsed, so cp should point to the number's
    7000                 :             :  * first digit in the base specified.
    7001                 :             :  *
    7002                 :             :  * base is expected to be 2, 8 or 16.
    7003                 :             :  *
    7004                 :             :  * Returns true on success, false on failure (if escontext points to an
    7005                 :             :  * ErrorSaveContext; otherwise errors are thrown).
    7006                 :             :  */
    7007                 :             : static bool
    7008                 :         104 : set_var_from_non_decimal_integer_str(const char *str, const char *cp, int sign,
    7009                 :             :                                      int base, NumericVar *dest,
    7010                 :             :                                      const char **endptr, Node *escontext)
    7011                 :             : {
    7012                 :         104 :     const char *firstdigit = cp;
    7013                 :             :     int64       tmp;
    7014                 :             :     int64       mul;
    7015                 :             :     NumericVar  tmp_var;
    7016                 :             : 
    7017                 :         104 :     init_var(&tmp_var);
    7018                 :             : 
    7019                 :         104 :     zero_var(dest);
    7020                 :             : 
    7021                 :             :     /*
    7022                 :             :      * Process input digits in groups that fit in int64.  Here "tmp" is the
    7023                 :             :      * value of the digits in the group, and "mul" is base^n, where n is the
    7024                 :             :      * number of digits in the group.  Thus tmp < mul, and we must start a new
    7025                 :             :      * group when mul * base threatens to overflow PG_INT64_MAX.
    7026                 :             :      */
    7027                 :         104 :     tmp = 0;
    7028                 :         104 :     mul = 1;
    7029                 :             : 
    7030         [ +  + ]:         104 :     if (base == 16)
    7031                 :             :     {
    7032         [ +  + ]:         552 :         while (*cp)
    7033                 :             :         {
    7034         [ +  + ]:         532 :             if (isxdigit((unsigned char) *cp))
    7035                 :             :             {
    7036         [ +  + ]:         472 :                 if (mul > PG_INT64_MAX / 16)
    7037                 :             :                 {
    7038                 :             :                     /* Add the contribution from this group of digits */
    7039                 :          20 :                     int64_to_numericvar(mul, &tmp_var);
    7040                 :          20 :                     mul_var(dest, &tmp_var, dest, 0);
    7041                 :          20 :                     int64_to_numericvar(tmp, &tmp_var);
    7042                 :          20 :                     add_var(dest, &tmp_var, dest);
    7043                 :             : 
    7044                 :             :                     /* Result will overflow if weight overflows int16 */
    7045         [ -  + ]:          20 :                     if (dest->weight > NUMERIC_WEIGHT_MAX)
    7046                 :           0 :                         goto out_of_range;
    7047                 :             : 
    7048                 :             :                     /* Begin a new group */
    7049                 :          20 :                     tmp = 0;
    7050                 :          20 :                     mul = 1;
    7051                 :             :                 }
    7052                 :             : 
    7053                 :         472 :                 tmp = tmp * 16 + xdigit_value(*cp++);
    7054                 :         472 :                 mul = mul * 16;
    7055                 :             :             }
    7056         [ +  + ]:          60 :             else if (*cp == '_')
    7057                 :             :             {
    7058                 :             :                 /* Underscore must be followed by more digits */
    7059                 :          44 :                 cp++;
    7060         [ +  + ]:          44 :                 if (!isxdigit((unsigned char) *cp))
    7061                 :          12 :                     goto invalid_syntax;
    7062                 :             :             }
    7063                 :             :             else
    7064                 :          16 :                 break;
    7065                 :             :         }
    7066                 :             :     }
    7067         [ +  + ]:          56 :     else if (base == 8)
    7068                 :             :     {
    7069         [ +  + ]:         424 :         while (*cp)
    7070                 :             :         {
    7071   [ +  +  +  + ]:         404 :             if (*cp >= '0' && *cp <= '7')
    7072                 :             :             {
    7073         [ +  + ]:         372 :                 if (mul > PG_INT64_MAX / 8)
    7074                 :             :                 {
    7075                 :             :                     /* Add the contribution from this group of digits */
    7076                 :          12 :                     int64_to_numericvar(mul, &tmp_var);
    7077                 :          12 :                     mul_var(dest, &tmp_var, dest, 0);
    7078                 :          12 :                     int64_to_numericvar(tmp, &tmp_var);
    7079                 :          12 :                     add_var(dest, &tmp_var, dest);
    7080                 :             : 
    7081                 :             :                     /* Result will overflow if weight overflows int16 */
    7082         [ -  + ]:          12 :                     if (dest->weight > NUMERIC_WEIGHT_MAX)
    7083                 :           0 :                         goto out_of_range;
    7084                 :             : 
    7085                 :             :                     /* Begin a new group */
    7086                 :          12 :                     tmp = 0;
    7087                 :          12 :                     mul = 1;
    7088                 :             :                 }
    7089                 :             : 
    7090                 :         372 :                 tmp = tmp * 8 + (*cp++ - '0');
    7091                 :         372 :                 mul = mul * 8;
    7092                 :             :             }
    7093         [ +  + ]:          32 :             else if (*cp == '_')
    7094                 :             :             {
    7095                 :             :                 /* Underscore must be followed by more digits */
    7096                 :          24 :                 cp++;
    7097   [ +  -  -  + ]:          24 :                 if (*cp < '0' || *cp > '7')
    7098                 :           0 :                     goto invalid_syntax;
    7099                 :             :             }
    7100                 :             :             else
    7101                 :           8 :                 break;
    7102                 :             :         }
    7103                 :             :     }
    7104         [ +  - ]:          28 :     else if (base == 2)
    7105                 :             :     {
    7106         [ +  + ]:        1040 :         while (*cp)
    7107                 :             :         {
    7108   [ +  +  +  + ]:        1020 :             if (*cp >= '0' && *cp <= '1')
    7109                 :             :             {
    7110         [ +  + ]:         944 :                 if (mul > PG_INT64_MAX / 2)
    7111                 :             :                 {
    7112                 :             :                     /* Add the contribution from this group of digits */
    7113                 :          12 :                     int64_to_numericvar(mul, &tmp_var);
    7114                 :          12 :                     mul_var(dest, &tmp_var, dest, 0);
    7115                 :          12 :                     int64_to_numericvar(tmp, &tmp_var);
    7116                 :          12 :                     add_var(dest, &tmp_var, dest);
    7117                 :             : 
    7118                 :             :                     /* Result will overflow if weight overflows int16 */
    7119         [ -  + ]:          12 :                     if (dest->weight > NUMERIC_WEIGHT_MAX)
    7120                 :           0 :                         goto out_of_range;
    7121                 :             : 
    7122                 :             :                     /* Begin a new group */
    7123                 :          12 :                     tmp = 0;
    7124                 :          12 :                     mul = 1;
    7125                 :             :                 }
    7126                 :             : 
    7127                 :         944 :                 tmp = tmp * 2 + (*cp++ - '0');
    7128                 :         944 :                 mul = mul * 2;
    7129                 :             :             }
    7130         [ +  + ]:          76 :             else if (*cp == '_')
    7131                 :             :             {
    7132                 :             :                 /* Underscore must be followed by more digits */
    7133                 :          68 :                 cp++;
    7134   [ +  -  -  + ]:          68 :                 if (*cp < '0' || *cp > '1')
    7135                 :           0 :                     goto invalid_syntax;
    7136                 :             :             }
    7137                 :             :             else
    7138                 :           8 :                 break;
    7139                 :             :         }
    7140                 :             :     }
    7141                 :             :     else
    7142                 :             :         /* Should never happen; treat as invalid input */
    7143                 :           0 :         goto invalid_syntax;
    7144                 :             : 
    7145                 :             :     /* Check that we got at least one digit */
    7146         [ -  + ]:          92 :     if (unlikely(cp == firstdigit))
    7147                 :           0 :         goto invalid_syntax;
    7148                 :             : 
    7149                 :             :     /* Add the contribution from the final group of digits */
    7150                 :          92 :     int64_to_numericvar(mul, &tmp_var);
    7151                 :          92 :     mul_var(dest, &tmp_var, dest, 0);
    7152                 :          92 :     int64_to_numericvar(tmp, &tmp_var);
    7153                 :          92 :     add_var(dest, &tmp_var, dest);
    7154                 :             : 
    7155         [ -  + ]:          92 :     if (dest->weight > NUMERIC_WEIGHT_MAX)
    7156                 :           0 :         goto out_of_range;
    7157                 :             : 
    7158                 :          92 :     dest->sign = sign;
    7159                 :             : 
    7160                 :          92 :     free_var(&tmp_var);
    7161                 :             : 
    7162                 :             :     /* Return end+1 position for caller */
    7163                 :          92 :     *endptr = cp;
    7164                 :             : 
    7165                 :          92 :     return true;
    7166                 :             : 
    7167                 :           0 : out_of_range:
    7168         [ #  # ]:           0 :     ereturn(escontext, false,
    7169                 :             :             (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    7170                 :             :              errmsg("value overflows numeric format")));
    7171                 :             : 
    7172                 :          12 : invalid_syntax:
    7173         [ +  - ]:          12 :     ereturn(escontext, false,
    7174                 :             :             (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    7175                 :             :              errmsg("invalid input syntax for type %s: \"%s\"",
    7176                 :             :                     "numeric", str)));
    7177                 :             : }
    7178                 :             : 
    7179                 :             : 
    7180                 :             : /*
    7181                 :             :  * set_var_from_num() -
    7182                 :             :  *
    7183                 :             :  *  Convert the packed db format into a variable
    7184                 :             :  */
    7185                 :             : static void
    7186                 :        9099 : set_var_from_num(Numeric num, NumericVar *dest)
    7187                 :             : {
    7188                 :             :     int         ndigits;
    7189                 :             : 
    7190         [ +  + ]:        9099 :     ndigits = NUMERIC_NDIGITS(num);
    7191                 :             : 
    7192                 :        9099 :     alloc_var(dest, ndigits);
    7193                 :             : 
    7194   [ +  +  +  + ]:        9099 :     dest->weight = NUMERIC_WEIGHT(num);
    7195   [ +  +  -  + ]:        9099 :     dest->sign = NUMERIC_SIGN(num);
    7196         [ +  + ]:        9099 :     dest->dscale = NUMERIC_DSCALE(num);
    7197                 :             : 
    7198         [ +  + ]:        9099 :     memcpy(dest->digits, NUMERIC_DIGITS(num), ndigits * sizeof(NumericDigit));
    7199                 :        9099 : }
    7200                 :             : 
    7201                 :             : 
    7202                 :             : /*
    7203                 :             :  * init_var_from_num() -
    7204                 :             :  *
    7205                 :             :  *  Initialize a variable from packed db format. The digits array is not
    7206                 :             :  *  copied, which saves some cycles when the resulting var is not modified.
    7207                 :             :  *  Also, there's no need to call free_var(), as long as you don't assign any
    7208                 :             :  *  other value to it (with set_var_* functions, or by using the var as the
    7209                 :             :  *  destination of a function like add_var())
    7210                 :             :  *
    7211                 :             :  *  CAUTION: Do not modify the digits buffer of a var initialized with this
    7212                 :             :  *  function, e.g by calling round_var() or trunc_var(), as the changes will
    7213                 :             :  *  propagate to the original Numeric! It's OK to use it as the destination
    7214                 :             :  *  argument of one of the calculational functions, though.
    7215                 :             :  */
    7216                 :             : static void
    7217                 :     3892982 : init_var_from_num(Numeric num, NumericVar *dest)
    7218                 :             : {
    7219         [ +  + ]:     3892982 :     dest->ndigits = NUMERIC_NDIGITS(num);
    7220   [ +  +  +  + ]:     3892982 :     dest->weight = NUMERIC_WEIGHT(num);
    7221   [ +  +  -  + ]:     3892982 :     dest->sign = NUMERIC_SIGN(num);
    7222         [ +  + ]:     3892982 :     dest->dscale = NUMERIC_DSCALE(num);
    7223         [ +  + ]:     3892982 :     dest->digits = NUMERIC_DIGITS(num);
    7224                 :     3892982 :     dest->buf = NULL;            /* digits array is not palloc'd */
    7225                 :     3892982 : }
    7226                 :             : 
    7227                 :             : 
    7228                 :             : /*
    7229                 :             :  * set_var_from_var() -
    7230                 :             :  *
    7231                 :             :  *  Copy one variable into another
    7232                 :             :  */
    7233                 :             : static void
    7234                 :       24870 : set_var_from_var(const NumericVar *value, NumericVar *dest)
    7235                 :             : {
    7236                 :             :     NumericDigit *newbuf;
    7237                 :             : 
    7238                 :       24870 :     newbuf = digitbuf_alloc(value->ndigits + 1);
    7239                 :       24870 :     newbuf[0] = 0;              /* spare digit for rounding */
    7240         [ +  + ]:       24870 :     if (value->ndigits > 0)       /* else value->digits might be null */
    7241                 :       24122 :         memcpy(newbuf + 1, value->digits,
    7242                 :       24122 :                value->ndigits * sizeof(NumericDigit));
    7243                 :             : 
    7244         [ +  + ]:       24870 :     digitbuf_free(dest->buf);
    7245                 :             : 
    7246                 :       24870 :     memmove(dest, value, sizeof(NumericVar));
    7247                 :       24870 :     dest->buf = newbuf;
    7248                 :       24870 :     dest->digits = newbuf + 1;
    7249                 :       24870 : }
    7250                 :             : 
    7251                 :             : 
    7252                 :             : /*
    7253                 :             :  * get_str_from_var() -
    7254                 :             :  *
    7255                 :             :  *  Convert a var to text representation (guts of numeric_out).
    7256                 :             :  *  The var is displayed to the number of digits indicated by its dscale.
    7257                 :             :  *  Returns a palloc'd string.
    7258                 :             :  */
    7259                 :             : static char *
    7260                 :      581461 : get_str_from_var(const NumericVar *var)
    7261                 :             : {
    7262                 :             :     int         dscale;
    7263                 :             :     char       *str;
    7264                 :             :     char       *cp;
    7265                 :             :     char       *endcp;
    7266                 :             :     int         i;
    7267                 :             :     int         d;
    7268                 :             :     NumericDigit dig;
    7269                 :             : 
    7270                 :             : #if DEC_DIGITS > 1
    7271                 :             :     NumericDigit d1;
    7272                 :             : #endif
    7273                 :             : 
    7274                 :      581461 :     dscale = var->dscale;
    7275                 :             : 
    7276                 :             :     /*
    7277                 :             :      * Allocate space for the result.
    7278                 :             :      *
    7279                 :             :      * i is set to the # of decimal digits before decimal point. dscale is the
    7280                 :             :      * # of decimal digits we will print after decimal point. We may generate
    7281                 :             :      * as many as DEC_DIGITS-1 excess digits at the end, and in addition we
    7282                 :             :      * need room for sign, decimal point, null terminator.
    7283                 :             :      */
    7284                 :      581461 :     i = (var->weight + 1) * DEC_DIGITS;
    7285         [ +  + ]:      581461 :     if (i <= 0)
    7286                 :       72465 :         i = 1;
    7287                 :             : 
    7288                 :      581461 :     str = palloc(i + dscale + DEC_DIGITS + 2);
    7289                 :      581461 :     cp = str;
    7290                 :             : 
    7291                 :             :     /*
    7292                 :             :      * Output a dash for negative values
    7293                 :             :      */
    7294         [ +  + ]:      581461 :     if (var->sign == NUMERIC_NEG)
    7295                 :        5396 :         *cp++ = '-';
    7296                 :             : 
    7297                 :             :     /*
    7298                 :             :      * Output all digits before the decimal point
    7299                 :             :      */
    7300         [ +  + ]:      581461 :     if (var->weight < 0)
    7301                 :             :     {
    7302                 :       72465 :         d = var->weight + 1;
    7303                 :       72465 :         *cp++ = '0';
    7304                 :             :     }
    7305                 :             :     else
    7306                 :             :     {
    7307         [ +  + ]:     1079586 :         for (d = 0; d <= var->weight; d++)
    7308                 :             :         {
    7309         [ +  + ]:      570590 :             dig = (d < var->ndigits) ? var->digits[d] : 0;
    7310                 :             :             /* In the first digit, suppress extra leading decimal zeroes */
    7311                 :             : #if DEC_DIGITS == 4
    7312                 :             :             {
    7313                 :      570590 :                 bool        putit = (d > 0);
    7314                 :             : 
    7315                 :      570590 :                 d1 = dig / 1000;
    7316                 :      570590 :                 dig -= d1 * 1000;
    7317                 :      570590 :                 putit |= (d1 > 0);
    7318         [ +  + ]:      570590 :                 if (putit)
    7319                 :      102007 :                     *cp++ = d1 + '0';
    7320                 :      570590 :                 d1 = dig / 100;
    7321                 :      570590 :                 dig -= d1 * 100;
    7322                 :      570590 :                 putit |= (d1 > 0);
    7323         [ +  + ]:      570590 :                 if (putit)
    7324                 :      374691 :                     *cp++ = d1 + '0';
    7325                 :      570590 :                 d1 = dig / 10;
    7326                 :      570590 :                 dig -= d1 * 10;
    7327                 :      570590 :                 putit |= (d1 > 0);
    7328         [ +  + ]:      570590 :                 if (putit)
    7329                 :      462393 :                     *cp++ = d1 + '0';
    7330                 :      570590 :                 *cp++ = dig + '0';
    7331                 :             :             }
    7332                 :             : #elif DEC_DIGITS == 2
    7333                 :             :             d1 = dig / 10;
    7334                 :             :             dig -= d1 * 10;
    7335                 :             :             if (d1 > 0 || d > 0)
    7336                 :             :                 *cp++ = d1 + '0';
    7337                 :             :             *cp++ = dig + '0';
    7338                 :             : #elif DEC_DIGITS == 1
    7339                 :             :             *cp++ = dig + '0';
    7340                 :             : #else
    7341                 :             : #error unsupported NBASE
    7342                 :             : #endif
    7343                 :             :         }
    7344                 :             :     }
    7345                 :             : 
    7346                 :             :     /*
    7347                 :             :      * If requested, output a decimal point and all the digits that follow it.
    7348                 :             :      * We initially put out a multiple of DEC_DIGITS digits, then truncate if
    7349                 :             :      * needed.
    7350                 :             :      */
    7351         [ +  + ]:      581461 :     if (dscale > 0)
    7352                 :             :     {
    7353                 :      409492 :         *cp++ = '.';
    7354                 :      409492 :         endcp = cp + dscale;
    7355         [ +  + ]:     1149045 :         for (i = 0; i < dscale; d++, i += DEC_DIGITS)
    7356                 :             :         {
    7357   [ +  +  +  + ]:      739553 :             dig = (d >= 0 && d < var->ndigits) ? var->digits[d] : 0;
    7358                 :             : #if DEC_DIGITS == 4
    7359                 :      739553 :             d1 = dig / 1000;
    7360                 :      739553 :             dig -= d1 * 1000;
    7361                 :      739553 :             *cp++ = d1 + '0';
    7362                 :      739553 :             d1 = dig / 100;
    7363                 :      739553 :             dig -= d1 * 100;
    7364                 :      739553 :             *cp++ = d1 + '0';
    7365                 :      739553 :             d1 = dig / 10;
    7366                 :      739553 :             dig -= d1 * 10;
    7367                 :      739553 :             *cp++ = d1 + '0';
    7368                 :      739553 :             *cp++ = dig + '0';
    7369                 :             : #elif DEC_DIGITS == 2
    7370                 :             :             d1 = dig / 10;
    7371                 :             :             dig -= d1 * 10;
    7372                 :             :             *cp++ = d1 + '0';
    7373                 :             :             *cp++ = dig + '0';
    7374                 :             : #elif DEC_DIGITS == 1
    7375                 :             :             *cp++ = dig + '0';
    7376                 :             : #else
    7377                 :             : #error unsupported NBASE
    7378                 :             : #endif
    7379                 :             :         }
    7380                 :      409492 :         cp = endcp;
    7381                 :             :     }
    7382                 :             : 
    7383                 :             :     /*
    7384                 :             :      * terminate the string and return it
    7385                 :             :      */
    7386                 :      581461 :     *cp = '\0';
    7387                 :      581461 :     return str;
    7388                 :             : }
    7389                 :             : 
    7390                 :             : /*
    7391                 :             :  * get_str_from_var_sci() -
    7392                 :             :  *
    7393                 :             :  *  Convert a var to a normalised scientific notation text representation.
    7394                 :             :  *  This function does the heavy lifting for numeric_out_sci().
    7395                 :             :  *
    7396                 :             :  *  This notation has the general form a * 10^b, where a is known as the
    7397                 :             :  *  "significand" and b is known as the "exponent".
    7398                 :             :  *
    7399                 :             :  *  Because we can't do superscript in ASCII (and because we want to copy
    7400                 :             :  *  printf's behaviour) we display the exponent using E notation, with a
    7401                 :             :  *  minimum of two exponent digits.
    7402                 :             :  *
    7403                 :             :  *  For example, the value 1234 could be output as 1.2e+03.
    7404                 :             :  *
    7405                 :             :  *  We assume that the exponent can fit into an int32.
    7406                 :             :  *
    7407                 :             :  *  rscale is the number of decimal digits desired after the decimal point in
    7408                 :             :  *  the output, negative values will be treated as meaning zero.
    7409                 :             :  *
    7410                 :             :  *  Returns a palloc'd string.
    7411                 :             :  */
    7412                 :             : static char *
    7413                 :         152 : get_str_from_var_sci(const NumericVar *var, int rscale)
    7414                 :             : {
    7415                 :             :     int32       exponent;
    7416                 :             :     NumericVar  tmp_var;
    7417                 :             :     size_t      len;
    7418                 :             :     char       *str;
    7419                 :             :     char       *sig_out;
    7420                 :             : 
    7421         [ -  + ]:         152 :     if (rscale < 0)
    7422                 :           0 :         rscale = 0;
    7423                 :             : 
    7424                 :             :     /*
    7425                 :             :      * Determine the exponent of this number in normalised form.
    7426                 :             :      *
    7427                 :             :      * This is the exponent required to represent the number with only one
    7428                 :             :      * significant digit before the decimal place.
    7429                 :             :      */
    7430         [ +  + ]:         152 :     if (var->ndigits > 0)
    7431                 :             :     {
    7432                 :         140 :         exponent = (var->weight + 1) * DEC_DIGITS;
    7433                 :             : 
    7434                 :             :         /*
    7435                 :             :          * Compensate for leading decimal zeroes in the first numeric digit by
    7436                 :             :          * decrementing the exponent.
    7437                 :             :          */
    7438                 :         140 :         exponent -= DEC_DIGITS - (int) log10(var->digits[0]);
    7439                 :             :     }
    7440                 :             :     else
    7441                 :             :     {
    7442                 :             :         /*
    7443                 :             :          * If var has no digits, then it must be zero.
    7444                 :             :          *
    7445                 :             :          * Zero doesn't technically have a meaningful exponent in normalised
    7446                 :             :          * notation, but we just display the exponent as zero for consistency
    7447                 :             :          * of output.
    7448                 :             :          */
    7449                 :          12 :         exponent = 0;
    7450                 :             :     }
    7451                 :             : 
    7452                 :             :     /*
    7453                 :             :      * Divide var by 10^exponent to get the significand, rounding to rscale
    7454                 :             :      * decimal digits in the process.
    7455                 :             :      */
    7456                 :         152 :     init_var(&tmp_var);
    7457                 :             : 
    7458                 :         152 :     power_ten_int(exponent, &tmp_var);
    7459                 :         152 :     div_var(var, &tmp_var, &tmp_var, rscale, true, true);
    7460                 :         152 :     sig_out = get_str_from_var(&tmp_var);
    7461                 :             : 
    7462                 :         152 :     free_var(&tmp_var);
    7463                 :             : 
    7464                 :             :     /*
    7465                 :             :      * Allocate space for the result.
    7466                 :             :      *
    7467                 :             :      * In addition to the significand, we need room for the exponent
    7468                 :             :      * decoration ("e"), the sign of the exponent, up to 10 digits for the
    7469                 :             :      * exponent itself, and of course the null terminator.
    7470                 :             :      */
    7471                 :         152 :     len = strlen(sig_out) + 13;
    7472                 :         152 :     str = palloc(len);
    7473                 :         152 :     snprintf(str, len, "%se%+03d", sig_out, exponent);
    7474                 :             : 
    7475                 :         152 :     pfree(sig_out);
    7476                 :             : 
    7477                 :         152 :     return str;
    7478                 :             : }
    7479                 :             : 
    7480                 :             : 
    7481                 :             : /*
    7482                 :             :  * numericvar_serialize - serialize NumericVar to binary format
    7483                 :             :  *
    7484                 :             :  * At variable level, no checks are performed on the weight or dscale, allowing
    7485                 :             :  * us to pass around intermediate values with higher precision than supported
    7486                 :             :  * by the numeric type.  Note: this is incompatible with numeric_send/recv(),
    7487                 :             :  * which use 16-bit integers for these fields.
    7488                 :             :  */
    7489                 :             : static void
    7490                 :          64 : numericvar_serialize(StringInfo buf, const NumericVar *var)
    7491                 :             : {
    7492                 :             :     int         i;
    7493                 :             : 
    7494                 :          64 :     pq_sendint32(buf, var->ndigits);
    7495                 :          64 :     pq_sendint32(buf, var->weight);
    7496                 :          64 :     pq_sendint32(buf, var->sign);
    7497                 :          64 :     pq_sendint32(buf, var->dscale);
    7498         [ +  + ]:      425172 :     for (i = 0; i < var->ndigits; i++)
    7499                 :      425108 :         pq_sendint16(buf, var->digits[i]);
    7500                 :          64 : }
    7501                 :             : 
    7502                 :             : /*
    7503                 :             :  * numericvar_deserialize - deserialize binary format to NumericVar
    7504                 :             :  */
    7505                 :             : static void
    7506                 :          64 : numericvar_deserialize(StringInfo buf, NumericVar *var)
    7507                 :             : {
    7508                 :             :     int         len,
    7509                 :             :                 i;
    7510                 :             : 
    7511                 :          64 :     len = pq_getmsgint(buf, sizeof(int32));
    7512                 :             : 
    7513                 :          64 :     alloc_var(var, len);        /* sets var->ndigits */
    7514                 :             : 
    7515                 :          64 :     var->weight = pq_getmsgint(buf, sizeof(int32));
    7516                 :          64 :     var->sign = pq_getmsgint(buf, sizeof(int32));
    7517                 :          64 :     var->dscale = pq_getmsgint(buf, sizeof(int32));
    7518         [ +  + ]:      425172 :     for (i = 0; i < len; i++)
    7519                 :      425108 :         var->digits[i] = pq_getmsgint(buf, sizeof(int16));
    7520                 :          64 : }
    7521                 :             : 
    7522                 :             : 
    7523                 :             : /*
    7524                 :             :  * duplicate_numeric() - copy a packed-format Numeric
    7525                 :             :  *
    7526                 :             :  * This will handle NaN and Infinity cases.
    7527                 :             :  */
    7528                 :             : static Numeric
    7529                 :       18826 : duplicate_numeric(Numeric num)
    7530                 :             : {
    7531                 :             :     Numeric     res;
    7532                 :             : 
    7533                 :       18826 :     res = (Numeric) palloc(VARSIZE(num));
    7534                 :       18826 :     memcpy(res, num, VARSIZE(num));
    7535                 :       18826 :     return res;
    7536                 :             : }
    7537                 :             : 
    7538                 :             : /*
    7539                 :             :  * make_result_safe() -
    7540                 :             :  *
    7541                 :             :  *  Create the packed db numeric format in palloc()'d memory from
    7542                 :             :  *  a variable.  This will handle NaN and Infinity cases.
    7543                 :             :  */
    7544                 :             : static Numeric
    7545                 :     2529744 : make_result_safe(const NumericVar *var, Node *escontext)
    7546                 :             : {
    7547                 :             :     Numeric     result;
    7548                 :     2529744 :     NumericDigit *digits = var->digits;
    7549                 :     2529744 :     int         weight = var->weight;
    7550                 :     2529744 :     int         sign = var->sign;
    7551                 :             :     int         n;
    7552                 :             :     Size        len;
    7553                 :             : 
    7554         [ +  + ]:     2529744 :     if ((sign & NUMERIC_SIGN_MASK) == NUMERIC_SPECIAL)
    7555                 :             :     {
    7556                 :             :         /*
    7557                 :             :          * Verify valid special value.  This could be just an Assert, perhaps,
    7558                 :             :          * but it seems worthwhile to expend a few cycles to ensure that we
    7559                 :             :          * never write any nonzero reserved bits to disk.
    7560                 :             :          */
    7561   [ +  +  +  +  :        2208 :         if (!(sign == NUMERIC_NAN ||
                   -  + ]
    7562                 :             :               sign == NUMERIC_PINF ||
    7563                 :             :               sign == NUMERIC_NINF))
    7564         [ #  # ]:           0 :             elog(ERROR, "invalid numeric sign value 0x%x", sign);
    7565                 :             : 
    7566                 :        2208 :         result = (Numeric) palloc(NUMERIC_HDRSZ_SHORT);
    7567                 :             : 
    7568                 :        2208 :         SET_VARSIZE(result, NUMERIC_HDRSZ_SHORT);
    7569                 :        2208 :         result->choice.n_header = sign;
    7570                 :             :         /* the header word is all we need */
    7571                 :             : 
    7572                 :             :         dump_numeric("make_result()", result);
    7573                 :        2208 :         return result;
    7574                 :             :     }
    7575                 :             : 
    7576                 :     2527536 :     n = var->ndigits;
    7577                 :             : 
    7578                 :             :     /* truncate leading zeroes */
    7579   [ +  +  +  + ]:     2527566 :     while (n > 0 && *digits == 0)
    7580                 :             :     {
    7581                 :          30 :         digits++;
    7582                 :          30 :         weight--;
    7583                 :          30 :         n--;
    7584                 :             :     }
    7585                 :             :     /* truncate trailing zeroes */
    7586   [ +  +  +  + ]:     2579664 :     while (n > 0 && digits[n - 1] == 0)
    7587                 :       52128 :         n--;
    7588                 :             : 
    7589                 :             :     /* If zero result, force to weight=0 and positive sign */
    7590         [ +  + ]:     2527536 :     if (n == 0)
    7591                 :             :     {
    7592                 :       84988 :         weight = 0;
    7593                 :       84988 :         sign = NUMERIC_POS;
    7594                 :             :     }
    7595                 :             : 
    7596                 :             :     /* Build the result */
    7597   [ +  +  +  +  :     2527536 :     if (NUMERIC_CAN_BE_SHORT(var->dscale, weight))
                   +  - ]
    7598                 :             :     {
    7599                 :     2525602 :         len = NUMERIC_HDRSZ_SHORT + n * sizeof(NumericDigit);
    7600                 :     2525602 :         result = (Numeric) palloc(len);
    7601                 :     2525602 :         SET_VARSIZE(result, len);
    7602                 :     2525602 :         result->choice.n_short.n_header =
    7603                 :             :             (sign == NUMERIC_NEG ? (NUMERIC_SHORT | NUMERIC_SHORT_SIGN_MASK)
    7604                 :             :              : NUMERIC_SHORT)
    7605         [ +  + ]:     2525602 :             | (var->dscale << NUMERIC_SHORT_DSCALE_SHIFT)
    7606                 :     2525602 :             | (weight < 0 ? NUMERIC_SHORT_WEIGHT_SIGN_MASK : 0)
    7607                 :     2525602 :             | (weight & NUMERIC_SHORT_WEIGHT_MASK);
    7608                 :             :     }
    7609                 :             :     else
    7610                 :             :     {
    7611                 :        1934 :         len = NUMERIC_HDRSZ + n * sizeof(NumericDigit);
    7612                 :        1934 :         result = (Numeric) palloc(len);
    7613                 :        1934 :         SET_VARSIZE(result, len);
    7614                 :        1934 :         result->choice.n_long.n_sign_dscale =
    7615                 :        1934 :             sign | (var->dscale & NUMERIC_DSCALE_MASK);
    7616                 :        1934 :         result->choice.n_long.n_weight = weight;
    7617                 :             :     }
    7618                 :             : 
    7619                 :             :     Assert(NUMERIC_NDIGITS(result) == n);
    7620         [ +  + ]:     2527536 :     if (n > 0)
    7621         [ +  + ]:     2442548 :         memcpy(NUMERIC_DIGITS(result), digits, n * sizeof(NumericDigit));
    7622                 :             : 
    7623                 :             :     /* Check for overflow of int16 fields */
    7624   [ +  +  +  +  :     2527536 :     if (NUMERIC_WEIGHT(result) != weight ||
                   +  + ]
    7625   [ +  +  -  + ]:     2527516 :         NUMERIC_DSCALE(result) != var->dscale)
    7626         [ +  + ]:          20 :         ereturn(escontext, NULL,
    7627                 :             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    7628                 :             :                  errmsg("value overflows numeric format")));
    7629                 :             : 
    7630                 :             :     dump_numeric("make_result()", result);
    7631                 :     2527516 :     return result;
    7632                 :             : }
    7633                 :             : 
    7634                 :             : 
    7635                 :             : /*
    7636                 :             :  * make_result() -
    7637                 :             :  *
    7638                 :             :  *  An interface to make_result_safe() without "escontext" argument.
    7639                 :             :  */
    7640                 :             : static Numeric
    7641                 :     1506525 : make_result(const NumericVar *var)
    7642                 :             : {
    7643                 :     1506525 :     return make_result_safe(var, NULL);
    7644                 :             : }
    7645                 :             : 
    7646                 :             : 
    7647                 :             : /*
    7648                 :             :  * apply_typmod() -
    7649                 :             :  *
    7650                 :             :  *  Do bounds checking and rounding according to the specified typmod.
    7651                 :             :  *  Note that this is only applied to normal finite values.
    7652                 :             :  *
    7653                 :             :  * Returns true on success, false on failure (if escontext points to an
    7654                 :             :  * ErrorSaveContext; otherwise errors are thrown).
    7655                 :             :  */
    7656                 :             : static bool
    7657                 :      106839 : apply_typmod(NumericVar *var, int32 typmod, Node *escontext)
    7658                 :             : {
    7659                 :             :     int         precision;
    7660                 :             :     int         scale;
    7661                 :             :     int         maxdigits;
    7662                 :             :     int         ddigits;
    7663                 :             :     int         i;
    7664                 :             : 
    7665                 :             :     /* Do nothing if we have an invalid typmod */
    7666         [ +  + ]:      106839 :     if (!is_valid_numeric_typmod(typmod))
    7667                 :       87331 :         return true;
    7668                 :             : 
    7669                 :       19508 :     precision = numeric_typmod_precision(typmod);
    7670                 :       19508 :     scale = numeric_typmod_scale(typmod);
    7671                 :       19508 :     maxdigits = precision - scale;
    7672                 :             : 
    7673                 :             :     /* Round to target scale (and set var->dscale) */
    7674                 :       19508 :     round_var(var, scale);
    7675                 :             : 
    7676                 :             :     /* but don't allow var->dscale to be negative */
    7677         [ +  + ]:       19508 :     if (var->dscale < 0)
    7678                 :         100 :         var->dscale = 0;
    7679                 :             : 
    7680                 :             :     /*
    7681                 :             :      * Check for overflow - note we can't do this before rounding, because
    7682                 :             :      * rounding could raise the weight.  Also note that the var's weight could
    7683                 :             :      * be inflated by leading zeroes, which will be stripped before storage
    7684                 :             :      * but perhaps might not have been yet. In any case, we must recognize a
    7685                 :             :      * true zero, whose weight doesn't mean anything.
    7686                 :             :      */
    7687                 :       19508 :     ddigits = (var->weight + 1) * DEC_DIGITS;
    7688         [ +  + ]:       19508 :     if (ddigits > maxdigits)
    7689                 :             :     {
    7690                 :             :         /* Determine true weight; and check for all-zero result */
    7691         [ +  + ]:        4297 :         for (i = 0; i < var->ndigits; i++)
    7692                 :             :         {
    7693                 :        4286 :             NumericDigit dig = var->digits[i];
    7694                 :             : 
    7695         [ +  - ]:        4286 :             if (dig)
    7696                 :             :             {
    7697                 :             :                 /* Adjust for any high-order decimal zero digits */
    7698                 :             : #if DEC_DIGITS == 4
    7699         [ +  + ]:        4286 :                 if (dig < 10)
    7700                 :         206 :                     ddigits -= 3;
    7701         [ +  + ]:        4080 :                 else if (dig < 100)
    7702                 :         428 :                     ddigits -= 2;
    7703         [ +  + ]:        3652 :                 else if (dig < 1000)
    7704                 :        3640 :                     ddigits -= 1;
    7705                 :             : #elif DEC_DIGITS == 2
    7706                 :             :                 if (dig < 10)
    7707                 :             :                     ddigits -= 1;
    7708                 :             : #elif DEC_DIGITS == 1
    7709                 :             :                 /* no adjustment */
    7710                 :             : #else
    7711                 :             : #error unsupported NBASE
    7712                 :             : #endif
    7713         [ +  + ]:        4286 :                 if (ddigits > maxdigits)
    7714   [ +  +  +  +  :          64 :                     ereturn(escontext, false,
                   +  + ]
    7715                 :             :                             (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    7716                 :             :                              errmsg("numeric field overflow"),
    7717                 :             :                              errdetail("A field with precision %d, scale %d must round to an absolute value less than %s%d.",
    7718                 :             :                                        precision, scale,
    7719                 :             :                     /* Display 10^0 as 1 */
    7720                 :             :                                        maxdigits ? "10^" : "",
    7721                 :             :                                        maxdigits ? maxdigits : 1
    7722                 :             :                                        )));
    7723                 :        4222 :                 break;
    7724                 :             :             }
    7725                 :           0 :             ddigits -= DEC_DIGITS;
    7726                 :             :         }
    7727                 :             :     }
    7728                 :             : 
    7729                 :       19444 :     return true;
    7730                 :             : }
    7731                 :             : 
    7732                 :             : /*
    7733                 :             :  * apply_typmod_special() -
    7734                 :             :  *
    7735                 :             :  *  Do bounds checking according to the specified typmod, for an Inf or NaN.
    7736                 :             :  *  For convenience of most callers, the value is presented in packed form.
    7737                 :             :  *
    7738                 :             :  * Returns true on success, false on failure (if escontext points to an
    7739                 :             :  * ErrorSaveContext; otherwise errors are thrown).
    7740                 :             :  */
    7741                 :             : static bool
    7742                 :        1300 : apply_typmod_special(Numeric num, int32 typmod, Node *escontext)
    7743                 :             : {
    7744                 :             :     int         precision;
    7745                 :             :     int         scale;
    7746                 :             : 
    7747                 :             :     Assert(NUMERIC_IS_SPECIAL(num));    /* caller error if not */
    7748                 :             : 
    7749                 :             :     /*
    7750                 :             :      * NaN is allowed regardless of the typmod; that's rather dubious perhaps,
    7751                 :             :      * but it's a longstanding behavior.  Inf is rejected if we have any
    7752                 :             :      * typmod restriction, since an infinity shouldn't be claimed to fit in
    7753                 :             :      * any finite number of digits.
    7754                 :             :      */
    7755         [ +  + ]:        1300 :     if (NUMERIC_IS_NAN(num))
    7756                 :         557 :         return true;
    7757                 :             : 
    7758                 :             :     /* Do nothing if we have a default typmod (-1) */
    7759         [ +  + ]:         743 :     if (!is_valid_numeric_typmod(typmod))
    7760                 :         731 :         return true;
    7761                 :             : 
    7762                 :          12 :     precision = numeric_typmod_precision(typmod);
    7763                 :          12 :     scale = numeric_typmod_scale(typmod);
    7764                 :             : 
    7765         [ +  - ]:          12 :     ereturn(escontext, false,
    7766                 :             :             (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    7767                 :             :              errmsg("numeric field overflow"),
    7768                 :             :              errdetail("A field with precision %d, scale %d cannot hold an infinite value.",
    7769                 :             :                        precision, scale)));
    7770                 :             : }
    7771                 :             : 
    7772                 :             : 
    7773                 :             : /*
    7774                 :             :  * Convert numeric to int8, rounding if needed.
    7775                 :             :  *
    7776                 :             :  * If overflow, return false (no error is raised).  Return true if okay.
    7777                 :             :  */
    7778                 :             : static bool
    7779                 :        6945 : numericvar_to_int64(const NumericVar *var, int64 *result)
    7780                 :             : {
    7781                 :             :     NumericDigit *digits;
    7782                 :             :     int         ndigits;
    7783                 :             :     int         weight;
    7784                 :             :     int         i;
    7785                 :             :     int64       val;
    7786                 :             :     bool        neg;
    7787                 :             :     NumericVar  rounded;
    7788                 :             : 
    7789                 :             :     /* Round to nearest integer */
    7790                 :        6945 :     init_var(&rounded);
    7791                 :        6945 :     set_var_from_var(var, &rounded);
    7792                 :        6945 :     round_var(&rounded, 0);
    7793                 :             : 
    7794                 :             :     /* Check for zero input */
    7795                 :        6945 :     strip_var(&rounded);
    7796                 :        6945 :     ndigits = rounded.ndigits;
    7797         [ +  + ]:        6945 :     if (ndigits == 0)
    7798                 :             :     {
    7799                 :         420 :         *result = 0;
    7800                 :         420 :         free_var(&rounded);
    7801                 :         420 :         return true;
    7802                 :             :     }
    7803                 :             : 
    7804                 :             :     /*
    7805                 :             :      * For input like 10000000000, we must treat stripped digits as real. So
    7806                 :             :      * the loop assumes there are weight+1 digits before the decimal point.
    7807                 :             :      */
    7808                 :        6525 :     weight = rounded.weight;
    7809                 :             :     Assert(weight >= 0 && ndigits <= weight + 1);
    7810                 :             : 
    7811                 :             :     /*
    7812                 :             :      * Construct the result. To avoid issues with converting a value
    7813                 :             :      * corresponding to INT64_MIN (which can't be represented as a positive 64
    7814                 :             :      * bit two's complement integer), accumulate value as a negative number.
    7815                 :             :      */
    7816                 :        6525 :     digits = rounded.digits;
    7817                 :        6525 :     neg = (rounded.sign == NUMERIC_NEG);
    7818                 :        6525 :     val = -digits[0];
    7819         [ +  + ]:        9010 :     for (i = 1; i <= weight; i++)
    7820                 :             :     {
    7821         [ +  + ]:        2518 :         if (unlikely(pg_mul_s64_overflow(val, NBASE, &val)))
    7822                 :             :         {
    7823                 :          21 :             free_var(&rounded);
    7824                 :          21 :             return false;
    7825                 :             :         }
    7826                 :             : 
    7827         [ +  + ]:        2497 :         if (i < ndigits)
    7828                 :             :         {
    7829         [ +  + ]:        2293 :             if (unlikely(pg_sub_s64_overflow(val, digits[i], &val)))
    7830                 :             :             {
    7831                 :          12 :                 free_var(&rounded);
    7832                 :          12 :                 return false;
    7833                 :             :             }
    7834                 :             :         }
    7835                 :             :     }
    7836                 :             : 
    7837                 :        6492 :     free_var(&rounded);
    7838                 :             : 
    7839         [ +  + ]:        6492 :     if (!neg)
    7840                 :             :     {
    7841         [ +  + ]:        5942 :         if (unlikely(val == PG_INT64_MIN))
    7842                 :          16 :             return false;
    7843                 :        5926 :         val = -val;
    7844                 :             :     }
    7845                 :        6476 :     *result = val;
    7846                 :             : 
    7847                 :        6476 :     return true;
    7848                 :             : }
    7849                 :             : 
    7850                 :             : /*
    7851                 :             :  * Convert int8 value to numeric.
    7852                 :             :  */
    7853                 :             : static void
    7854                 :     1263599 : int64_to_numericvar(int64 val, NumericVar *var)
    7855                 :             : {
    7856                 :             :     uint64      uval,
    7857                 :             :                 newuval;
    7858                 :             :     NumericDigit *ptr;
    7859                 :             :     int         ndigits;
    7860                 :             : 
    7861                 :             :     /* int64 can require at most 19 decimal digits; add one for safety */
    7862                 :     1263599 :     alloc_var(var, 20 / DEC_DIGITS);
    7863         [ +  + ]:     1263599 :     if (val < 0)
    7864                 :             :     {
    7865                 :        1263 :         var->sign = NUMERIC_NEG;
    7866                 :        1263 :         uval = pg_abs_s64(val);
    7867                 :             :     }
    7868                 :             :     else
    7869                 :             :     {
    7870                 :     1262336 :         var->sign = NUMERIC_POS;
    7871                 :     1262336 :         uval = val;
    7872                 :             :     }
    7873                 :     1263599 :     var->dscale = 0;
    7874         [ +  + ]:     1263599 :     if (val == 0)
    7875                 :             :     {
    7876                 :       19431 :         var->ndigits = 0;
    7877                 :       19431 :         var->weight = 0;
    7878                 :       19431 :         return;
    7879                 :             :     }
    7880                 :     1244168 :     ptr = var->digits + var->ndigits;
    7881                 :     1244168 :     ndigits = 0;
    7882                 :             :     do
    7883                 :             :     {
    7884                 :     1441629 :         ptr--;
    7885                 :     1441629 :         ndigits++;
    7886                 :     1441629 :         newuval = uval / NBASE;
    7887                 :     1441629 :         *ptr = uval - newuval * NBASE;
    7888                 :     1441629 :         uval = newuval;
    7889         [ +  + ]:     1441629 :     } while (uval);
    7890                 :     1244168 :     var->digits = ptr;
    7891                 :     1244168 :     var->ndigits = ndigits;
    7892                 :     1244168 :     var->weight = ndigits - 1;
    7893                 :             : }
    7894                 :             : 
    7895                 :             : /*
    7896                 :             :  * Convert numeric to uint64, rounding if needed.
    7897                 :             :  *
    7898                 :             :  * If overflow, return false (no error is raised).  Return true if okay.
    7899                 :             :  */
    7900                 :             : static bool
    7901                 :         100 : numericvar_to_uint64(const NumericVar *var, uint64 *result)
    7902                 :             : {
    7903                 :             :     NumericDigit *digits;
    7904                 :             :     int         ndigits;
    7905                 :             :     int         weight;
    7906                 :             :     int         i;
    7907                 :             :     uint64      val;
    7908                 :             :     NumericVar  rounded;
    7909                 :             : 
    7910                 :             :     /* Round to nearest integer */
    7911                 :         100 :     init_var(&rounded);
    7912                 :         100 :     set_var_from_var(var, &rounded);
    7913                 :         100 :     round_var(&rounded, 0);
    7914                 :             : 
    7915                 :             :     /* Check for zero input */
    7916                 :         100 :     strip_var(&rounded);
    7917                 :         100 :     ndigits = rounded.ndigits;
    7918         [ +  + ]:         100 :     if (ndigits == 0)
    7919                 :             :     {
    7920                 :          15 :         *result = 0;
    7921                 :          15 :         free_var(&rounded);
    7922                 :          15 :         return true;
    7923                 :             :     }
    7924                 :             : 
    7925                 :             :     /* Check for negative input */
    7926         [ +  + ]:          85 :     if (rounded.sign == NUMERIC_NEG)
    7927                 :             :     {
    7928                 :           8 :         free_var(&rounded);
    7929                 :           8 :         return false;
    7930                 :             :     }
    7931                 :             : 
    7932                 :             :     /*
    7933                 :             :      * For input like 10000000000, we must treat stripped digits as real. So
    7934                 :             :      * the loop assumes there are weight+1 digits before the decimal point.
    7935                 :             :      */
    7936                 :          77 :     weight = rounded.weight;
    7937                 :             :     Assert(weight >= 0 && ndigits <= weight + 1);
    7938                 :             : 
    7939                 :             :     /* Construct the result */
    7940                 :          77 :     digits = rounded.digits;
    7941                 :          77 :     val = digits[0];
    7942         [ +  + ]:         218 :     for (i = 1; i <= weight; i++)
    7943                 :             :     {
    7944         [ -  + ]:         149 :         if (unlikely(pg_mul_u64_overflow(val, NBASE, &val)))
    7945                 :             :         {
    7946                 :           0 :             free_var(&rounded);
    7947                 :           0 :             return false;
    7948                 :             :         }
    7949                 :             : 
    7950         [ +  - ]:         149 :         if (i < ndigits)
    7951                 :             :         {
    7952         [ +  + ]:         149 :             if (unlikely(pg_add_u64_overflow(val, digits[i], &val)))
    7953                 :             :             {
    7954                 :           8 :                 free_var(&rounded);
    7955                 :           8 :                 return false;
    7956                 :             :             }
    7957                 :             :         }
    7958                 :             :     }
    7959                 :             : 
    7960                 :          69 :     free_var(&rounded);
    7961                 :             : 
    7962                 :          69 :     *result = val;
    7963                 :             : 
    7964                 :          69 :     return true;
    7965                 :             : }
    7966                 :             : 
    7967                 :             : /*
    7968                 :             :  * Convert 128 bit integer to numeric.
    7969                 :             :  */
    7970                 :             : static void
    7971                 :        6281 : int128_to_numericvar(INT128 val, NumericVar *var)
    7972                 :             : {
    7973                 :             :     int         sign;
    7974                 :             :     NumericDigit *ptr;
    7975                 :             :     int         ndigits;
    7976                 :             :     int32       dig;
    7977                 :             : 
    7978                 :             :     /* int128 can require at most 39 decimal digits; add one for safety */
    7979                 :        6281 :     alloc_var(var, 40 / DEC_DIGITS);
    7980                 :        6281 :     sign = int128_sign(val);
    7981                 :        6281 :     var->sign = sign < 0 ? NUMERIC_NEG : NUMERIC_POS;
    7982                 :        6281 :     var->dscale = 0;
    7983         [ +  + ]:        6281 :     if (sign == 0)
    7984                 :             :     {
    7985                 :         139 :         var->ndigits = 0;
    7986                 :         139 :         var->weight = 0;
    7987                 :         139 :         return;
    7988                 :             :     }
    7989                 :        6142 :     ptr = var->digits + var->ndigits;
    7990                 :        6142 :     ndigits = 0;
    7991                 :             :     do
    7992                 :             :     {
    7993                 :       33048 :         ptr--;
    7994                 :       33048 :         ndigits++;
    7995                 :       33048 :         int128_div_mod_int32(&val, NBASE, &dig);
    7996                 :       33048 :         *ptr = (NumericDigit) abs(dig);
    7997         [ +  + ]:       33048 :     } while (!int128_is_zero(val));
    7998                 :        6142 :     var->digits = ptr;
    7999                 :        6142 :     var->ndigits = ndigits;
    8000                 :        6142 :     var->weight = ndigits - 1;
    8001                 :             : }
    8002                 :             : 
    8003                 :             : /*
    8004                 :             :  * Convert a NumericVar to float8; if out of range, return +/- HUGE_VAL
    8005                 :             :  */
    8006                 :             : static double
    8007                 :         359 : numericvar_to_double_no_overflow(const NumericVar *var)
    8008                 :             : {
    8009                 :             :     char       *tmp;
    8010                 :             :     double      val;
    8011                 :             :     char       *endptr;
    8012                 :             : 
    8013                 :         359 :     tmp = get_str_from_var(var);
    8014                 :             : 
    8015                 :             :     /* unlike float8in, we ignore ERANGE from strtod */
    8016                 :         359 :     val = strtod(tmp, &endptr);
    8017         [ -  + ]:         359 :     if (*endptr != '\0')
    8018                 :             :     {
    8019                 :             :         /* shouldn't happen ... */
    8020         [ #  # ]:           0 :         ereport(ERROR,
    8021                 :             :                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    8022                 :             :                  errmsg("invalid input syntax for type %s: \"%s\"",
    8023                 :             :                         "double precision", tmp)));
    8024                 :             :     }
    8025                 :             : 
    8026                 :         359 :     pfree(tmp);
    8027                 :             : 
    8028                 :         359 :     return val;
    8029                 :             : }
    8030                 :             : 
    8031                 :             : 
    8032                 :             : /*
    8033                 :             :  * cmp_var() -
    8034                 :             :  *
    8035                 :             :  *  Compare two values on variable level.  We assume zeroes have been
    8036                 :             :  *  truncated to no digits.
    8037                 :             :  */
    8038                 :             : static int
    8039                 :      114439 : cmp_var(const NumericVar *var1, const NumericVar *var2)
    8040                 :             : {
    8041                 :      228878 :     return cmp_var_common(var1->digits, var1->ndigits,
    8042                 :      114439 :                           var1->weight, var1->sign,
    8043                 :      114439 :                           var2->digits, var2->ndigits,
    8044                 :      114439 :                           var2->weight, var2->sign);
    8045                 :             : }
    8046                 :             : 
    8047                 :             : /*
    8048                 :             :  * cmp_var_common() -
    8049                 :             :  *
    8050                 :             :  *  Main routine of cmp_var(). This function can be used by both
    8051                 :             :  *  NumericVar and Numeric.
    8052                 :             :  */
    8053                 :             : static int
    8054                 :    18496440 : cmp_var_common(const NumericDigit *var1digits, int var1ndigits,
    8055                 :             :                int var1weight, int var1sign,
    8056                 :             :                const NumericDigit *var2digits, int var2ndigits,
    8057                 :             :                int var2weight, int var2sign)
    8058                 :             : {
    8059         [ +  + ]:    18496440 :     if (var1ndigits == 0)
    8060                 :             :     {
    8061         [ +  + ]:      423025 :         if (var2ndigits == 0)
    8062                 :      334018 :             return 0;
    8063         [ +  + ]:       89007 :         if (var2sign == NUMERIC_NEG)
    8064                 :         362 :             return 1;
    8065                 :       88645 :         return -1;
    8066                 :             :     }
    8067         [ +  + ]:    18073415 :     if (var2ndigits == 0)
    8068                 :             :     {
    8069         [ +  + ]:       69402 :         if (var1sign == NUMERIC_POS)
    8070                 :       63868 :             return 1;
    8071                 :        5534 :         return -1;
    8072                 :             :     }
    8073                 :             : 
    8074         [ +  + ]:    18004013 :     if (var1sign == NUMERIC_POS)
    8075                 :             :     {
    8076         [ +  + ]:    17956837 :         if (var2sign == NUMERIC_NEG)
    8077                 :       15352 :             return 1;
    8078                 :    17941485 :         return cmp_abs_common(var1digits, var1ndigits, var1weight,
    8079                 :             :                               var2digits, var2ndigits, var2weight);
    8080                 :             :     }
    8081                 :             : 
    8082         [ +  + ]:       47176 :     if (var2sign == NUMERIC_POS)
    8083                 :       13763 :         return -1;
    8084                 :             : 
    8085                 :       33413 :     return cmp_abs_common(var2digits, var2ndigits, var2weight,
    8086                 :             :                           var1digits, var1ndigits, var1weight);
    8087                 :             : }
    8088                 :             : 
    8089                 :             : 
    8090                 :             : /*
    8091                 :             :  * add_var() -
    8092                 :             :  *
    8093                 :             :  *  Full version of add functionality on variable level (handling signs).
    8094                 :             :  *  result might point to one of the operands too without danger.
    8095                 :             :  */
    8096                 :             : static void
    8097                 :      414718 : add_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
    8098                 :             : {
    8099                 :             :     /*
    8100                 :             :      * Decide on the signs of the two variables what to do
    8101                 :             :      */
    8102         [ +  + ]:      414718 :     if (var1->sign == NUMERIC_POS)
    8103                 :             :     {
    8104         [ +  + ]:      413463 :         if (var2->sign == NUMERIC_POS)
    8105                 :             :         {
    8106                 :             :             /*
    8107                 :             :              * Both are positive result = +(ABS(var1) + ABS(var2))
    8108                 :             :              */
    8109                 :      279862 :             add_abs(var1, var2, result);
    8110                 :      279862 :             result->sign = NUMERIC_POS;
    8111                 :             :         }
    8112                 :             :         else
    8113                 :             :         {
    8114                 :             :             /*
    8115                 :             :              * var1 is positive, var2 is negative Must compare absolute values
    8116                 :             :              */
    8117   [ +  +  +  - ]:      133601 :             switch (cmp_abs(var1, var2))
    8118                 :             :             {
    8119                 :         134 :                 case 0:
    8120                 :             :                     /* ----------
    8121                 :             :                      * ABS(var1) == ABS(var2)
    8122                 :             :                      * result = ZERO
    8123                 :             :                      * ----------
    8124                 :             :                      */
    8125                 :         134 :                     zero_var(result);
    8126                 :         134 :                     result->dscale = Max(var1->dscale, var2->dscale);
    8127                 :         134 :                     break;
    8128                 :             : 
    8129                 :      124281 :                 case 1:
    8130                 :             :                     /* ----------
    8131                 :             :                      * ABS(var1) > ABS(var2)
    8132                 :             :                      * result = +(ABS(var1) - ABS(var2))
    8133                 :             :                      * ----------
    8134                 :             :                      */
    8135                 :      124281 :                     sub_abs(var1, var2, result);
    8136                 :      124281 :                     result->sign = NUMERIC_POS;
    8137                 :      124281 :                     break;
    8138                 :             : 
    8139                 :        9186 :                 case -1:
    8140                 :             :                     /* ----------
    8141                 :             :                      * ABS(var1) < ABS(var2)
    8142                 :             :                      * result = -(ABS(var2) - ABS(var1))
    8143                 :             :                      * ----------
    8144                 :             :                      */
    8145                 :        9186 :                     sub_abs(var2, var1, result);
    8146                 :        9186 :                     result->sign = NUMERIC_NEG;
    8147                 :        9186 :                     break;
    8148                 :             :             }
    8149                 :             :         }
    8150                 :             :     }
    8151                 :             :     else
    8152                 :             :     {
    8153         [ +  + ]:        1255 :         if (var2->sign == NUMERIC_POS)
    8154                 :             :         {
    8155                 :             :             /* ----------
    8156                 :             :              * var1 is negative, var2 is positive
    8157                 :             :              * Must compare absolute values
    8158                 :             :              * ----------
    8159                 :             :              */
    8160   [ +  +  +  - ]:         318 :             switch (cmp_abs(var1, var2))
    8161                 :             :             {
    8162                 :          20 :                 case 0:
    8163                 :             :                     /* ----------
    8164                 :             :                      * ABS(var1) == ABS(var2)
    8165                 :             :                      * result = ZERO
    8166                 :             :                      * ----------
    8167                 :             :                      */
    8168                 :          20 :                     zero_var(result);
    8169                 :          20 :                     result->dscale = Max(var1->dscale, var2->dscale);
    8170                 :          20 :                     break;
    8171                 :             : 
    8172                 :         197 :                 case 1:
    8173                 :             :                     /* ----------
    8174                 :             :                      * ABS(var1) > ABS(var2)
    8175                 :             :                      * result = -(ABS(var1) - ABS(var2))
    8176                 :             :                      * ----------
    8177                 :             :                      */
    8178                 :         197 :                     sub_abs(var1, var2, result);
    8179                 :         197 :                     result->sign = NUMERIC_NEG;
    8180                 :         197 :                     break;
    8181                 :             : 
    8182                 :         101 :                 case -1:
    8183                 :             :                     /* ----------
    8184                 :             :                      * ABS(var1) < ABS(var2)
    8185                 :             :                      * result = +(ABS(var2) - ABS(var1))
    8186                 :             :                      * ----------
    8187                 :             :                      */
    8188                 :         101 :                     sub_abs(var2, var1, result);
    8189                 :         101 :                     result->sign = NUMERIC_POS;
    8190                 :         101 :                     break;
    8191                 :             :             }
    8192                 :             :         }
    8193                 :             :         else
    8194                 :             :         {
    8195                 :             :             /* ----------
    8196                 :             :              * Both are negative
    8197                 :             :              * result = -(ABS(var1) + ABS(var2))
    8198                 :             :              * ----------
    8199                 :             :              */
    8200                 :         937 :             add_abs(var1, var2, result);
    8201                 :         937 :             result->sign = NUMERIC_NEG;
    8202                 :             :         }
    8203                 :             :     }
    8204                 :      414718 : }
    8205                 :             : 
    8206                 :             : 
    8207                 :             : /*
    8208                 :             :  * sub_var() -
    8209                 :             :  *
    8210                 :             :  *  Full version of sub functionality on variable level (handling signs).
    8211                 :             :  *  result might point to one of the operands too without danger.
    8212                 :             :  */
    8213                 :             : static void
    8214                 :      351637 : sub_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
    8215                 :             : {
    8216                 :             :     /*
    8217                 :             :      * Decide on the signs of the two variables what to do
    8218                 :             :      */
    8219         [ +  + ]:      351637 :     if (var1->sign == NUMERIC_POS)
    8220                 :             :     {
    8221         [ +  + ]:      351028 :         if (var2->sign == NUMERIC_NEG)
    8222                 :             :         {
    8223                 :             :             /* ----------
    8224                 :             :              * var1 is positive, var2 is negative
    8225                 :             :              * result = +(ABS(var1) + ABS(var2))
    8226                 :             :              * ----------
    8227                 :             :              */
    8228                 :       18774 :             add_abs(var1, var2, result);
    8229                 :       18774 :             result->sign = NUMERIC_POS;
    8230                 :             :         }
    8231                 :             :         else
    8232                 :             :         {
    8233                 :             :             /* ----------
    8234                 :             :              * Both are positive
    8235                 :             :              * Must compare absolute values
    8236                 :             :              * ----------
    8237                 :             :              */
    8238   [ +  +  +  - ]:      332254 :             switch (cmp_abs(var1, var2))
    8239                 :             :             {
    8240                 :       29863 :                 case 0:
    8241                 :             :                     /* ----------
    8242                 :             :                      * ABS(var1) == ABS(var2)
    8243                 :             :                      * result = ZERO
    8244                 :             :                      * ----------
    8245                 :             :                      */
    8246                 :       29863 :                     zero_var(result);
    8247                 :       29863 :                     result->dscale = Max(var1->dscale, var2->dscale);
    8248                 :       29863 :                     break;
    8249                 :             : 
    8250                 :      294274 :                 case 1:
    8251                 :             :                     /* ----------
    8252                 :             :                      * ABS(var1) > ABS(var2)
    8253                 :             :                      * result = +(ABS(var1) - ABS(var2))
    8254                 :             :                      * ----------
    8255                 :             :                      */
    8256                 :      294274 :                     sub_abs(var1, var2, result);
    8257                 :      294274 :                     result->sign = NUMERIC_POS;
    8258                 :      294274 :                     break;
    8259                 :             : 
    8260                 :        8117 :                 case -1:
    8261                 :             :                     /* ----------
    8262                 :             :                      * ABS(var1) < ABS(var2)
    8263                 :             :                      * result = -(ABS(var2) - ABS(var1))
    8264                 :             :                      * ----------
    8265                 :             :                      */
    8266                 :        8117 :                     sub_abs(var2, var1, result);
    8267                 :        8117 :                     result->sign = NUMERIC_NEG;
    8268                 :        8117 :                     break;
    8269                 :             :             }
    8270                 :             :         }
    8271                 :             :     }
    8272                 :             :     else
    8273                 :             :     {
    8274         [ +  + ]:         609 :         if (var2->sign == NUMERIC_NEG)
    8275                 :             :         {
    8276                 :             :             /* ----------
    8277                 :             :              * Both are negative
    8278                 :             :              * Must compare absolute values
    8279                 :             :              * ----------
    8280                 :             :              */
    8281   [ +  +  +  - ]:         304 :             switch (cmp_abs(var1, var2))
    8282                 :             :             {
    8283                 :         110 :                 case 0:
    8284                 :             :                     /* ----------
    8285                 :             :                      * ABS(var1) == ABS(var2)
    8286                 :             :                      * result = ZERO
    8287                 :             :                      * ----------
    8288                 :             :                      */
    8289                 :         110 :                     zero_var(result);
    8290                 :         110 :                     result->dscale = Max(var1->dscale, var2->dscale);
    8291                 :         110 :                     break;
    8292                 :             : 
    8293                 :         162 :                 case 1:
    8294                 :             :                     /* ----------
    8295                 :             :                      * ABS(var1) > ABS(var2)
    8296                 :             :                      * result = -(ABS(var1) - ABS(var2))
    8297                 :             :                      * ----------
    8298                 :             :                      */
    8299                 :         162 :                     sub_abs(var1, var2, result);
    8300                 :         162 :                     result->sign = NUMERIC_NEG;
    8301                 :         162 :                     break;
    8302                 :             : 
    8303                 :          32 :                 case -1:
    8304                 :             :                     /* ----------
    8305                 :             :                      * ABS(var1) < ABS(var2)
    8306                 :             :                      * result = +(ABS(var2) - ABS(var1))
    8307                 :             :                      * ----------
    8308                 :             :                      */
    8309                 :          32 :                     sub_abs(var2, var1, result);
    8310                 :          32 :                     result->sign = NUMERIC_POS;
    8311                 :          32 :                     break;
    8312                 :             :             }
    8313                 :             :         }
    8314                 :             :         else
    8315                 :             :         {
    8316                 :             :             /* ----------
    8317                 :             :              * var1 is negative, var2 is positive
    8318                 :             :              * result = -(ABS(var1) + ABS(var2))
    8319                 :             :              * ----------
    8320                 :             :              */
    8321                 :         305 :             add_abs(var1, var2, result);
    8322                 :         305 :             result->sign = NUMERIC_NEG;
    8323                 :             :         }
    8324                 :             :     }
    8325                 :      351637 : }
    8326                 :             : 
    8327                 :             : 
    8328                 :             : /*
    8329                 :             :  * mul_var() -
    8330                 :             :  *
    8331                 :             :  *  Multiplication on variable level. Product of var1 * var2 is stored
    8332                 :             :  *  in result.  Result is rounded to no more than rscale fractional digits.
    8333                 :             :  */
    8334                 :             : static void
    8335                 :      795609 : mul_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result,
    8336                 :             :         int rscale)
    8337                 :             : {
    8338                 :             :     int         res_ndigits;
    8339                 :             :     int         res_ndigitpairs;
    8340                 :             :     int         res_sign;
    8341                 :             :     int         res_weight;
    8342                 :             :     int         pair_offset;
    8343                 :             :     int         maxdigits;
    8344                 :             :     int         maxdigitpairs;
    8345                 :             :     uint64     *dig,
    8346                 :             :                *dig_i1_off;
    8347                 :             :     uint64      maxdig;
    8348                 :             :     uint64      carry;
    8349                 :             :     uint64      newdig;
    8350                 :             :     int         var1ndigits;
    8351                 :             :     int         var2ndigits;
    8352                 :             :     int         var1ndigitpairs;
    8353                 :             :     int         var2ndigitpairs;
    8354                 :             :     NumericDigit *var1digits;
    8355                 :             :     NumericDigit *var2digits;
    8356                 :             :     uint32      var1digitpair;
    8357                 :             :     uint32     *var2digitpairs;
    8358                 :             :     NumericDigit *res_digits;
    8359                 :             :     int         i,
    8360                 :             :                 i1,
    8361                 :             :                 i2,
    8362                 :             :                 i2limit;
    8363                 :             : 
    8364                 :             :     /*
    8365                 :             :      * Arrange for var1 to be the shorter of the two numbers.  This improves
    8366                 :             :      * performance because the inner multiplication loop is much simpler than
    8367                 :             :      * the outer loop, so it's better to have a smaller number of iterations
    8368                 :             :      * of the outer loop.  This also reduces the number of times that the
    8369                 :             :      * accumulator array needs to be normalized.
    8370                 :             :      */
    8371         [ +  + ]:      795609 :     if (var1->ndigits > var2->ndigits)
    8372                 :             :     {
    8373                 :       10374 :         const NumericVar *tmp = var1;
    8374                 :             : 
    8375                 :       10374 :         var1 = var2;
    8376                 :       10374 :         var2 = tmp;
    8377                 :             :     }
    8378                 :             : 
    8379                 :             :     /* copy these values into local vars for speed in inner loop */
    8380                 :      795609 :     var1ndigits = var1->ndigits;
    8381                 :      795609 :     var2ndigits = var2->ndigits;
    8382                 :      795609 :     var1digits = var1->digits;
    8383                 :      795609 :     var2digits = var2->digits;
    8384                 :             : 
    8385         [ +  + ]:      795609 :     if (var1ndigits == 0)
    8386                 :             :     {
    8387                 :             :         /* one or both inputs is zero; so is result */
    8388                 :        1959 :         zero_var(result);
    8389                 :        1959 :         result->dscale = rscale;
    8390                 :        1959 :         return;
    8391                 :             :     }
    8392                 :             : 
    8393                 :             :     /*
    8394                 :             :      * If var1 has 1-6 digits and the exact result was requested, delegate to
    8395                 :             :      * mul_var_short() which uses a faster direct multiplication algorithm.
    8396                 :             :      */
    8397   [ +  +  +  + ]:      793650 :     if (var1ndigits <= 6 && rscale == var1->dscale + var2->dscale)
    8398                 :             :     {
    8399                 :      772981 :         mul_var_short(var1, var2, result);
    8400                 :      772981 :         return;
    8401                 :             :     }
    8402                 :             : 
    8403                 :             :     /* Determine result sign */
    8404         [ +  + ]:       20669 :     if (var1->sign == var2->sign)
    8405                 :       19390 :         res_sign = NUMERIC_POS;
    8406                 :             :     else
    8407                 :        1279 :         res_sign = NUMERIC_NEG;
    8408                 :             : 
    8409                 :             :     /*
    8410                 :             :      * Determine the number of result digits to compute and the (maximum
    8411                 :             :      * possible) result weight.  If the exact result would have more than
    8412                 :             :      * rscale fractional digits, truncate the computation with
    8413                 :             :      * MUL_GUARD_DIGITS guard digits, i.e., ignore input digits that would
    8414                 :             :      * only contribute to the right of that.  (This will give the exact
    8415                 :             :      * rounded-to-rscale answer unless carries out of the ignored positions
    8416                 :             :      * would have propagated through more than MUL_GUARD_DIGITS digits.)
    8417                 :             :      *
    8418                 :             :      * Note: an exact computation could not produce more than var1ndigits +
    8419                 :             :      * var2ndigits digits, but we allocate at least one extra output digit in
    8420                 :             :      * case rscale-driven rounding produces a carry out of the highest exact
    8421                 :             :      * digit.
    8422                 :             :      *
    8423                 :             :      * The computation itself is done using base-NBASE^2 arithmetic, so we
    8424                 :             :      * actually process the input digits in pairs, producing a base-NBASE^2
    8425                 :             :      * intermediate result.  This significantly improves performance, since
    8426                 :             :      * schoolbook multiplication is O(N^2) in the number of input digits, and
    8427                 :             :      * working in base NBASE^2 effectively halves "N".
    8428                 :             :      *
    8429                 :             :      * Note: in a truncated computation, we must compute at least one extra
    8430                 :             :      * output digit to ensure that all the guard digits are fully computed.
    8431                 :             :      */
    8432                 :             :     /* digit pairs in each input */
    8433                 :       20669 :     var1ndigitpairs = (var1ndigits + 1) / 2;
    8434                 :       20669 :     var2ndigitpairs = (var2ndigits + 1) / 2;
    8435                 :             : 
    8436                 :             :     /* digits in exact result */
    8437                 :       20669 :     res_ndigits = var1ndigits + var2ndigits;
    8438                 :             : 
    8439                 :             :     /* digit pairs in exact result with at least one extra output digit */
    8440                 :       20669 :     res_ndigitpairs = res_ndigits / 2 + 1;
    8441                 :             : 
    8442                 :             :     /* pair offset to align result to end of dig[] */
    8443                 :       20669 :     pair_offset = res_ndigitpairs - var1ndigitpairs - var2ndigitpairs + 1;
    8444                 :             : 
    8445                 :             :     /* maximum possible result weight (odd-length inputs shifted up below) */
    8446                 :       20669 :     res_weight = var1->weight + var2->weight + 1 + 2 * res_ndigitpairs -
    8447                 :       20669 :         res_ndigits - (var1ndigits & 1) - (var2ndigits & 1);
    8448                 :             : 
    8449                 :             :     /* rscale-based truncation with at least one extra output digit */
    8450                 :       20669 :     maxdigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS +
    8451                 :             :         MUL_GUARD_DIGITS;
    8452                 :       20669 :     maxdigitpairs = maxdigits / 2 + 1;
    8453                 :             : 
    8454                 :       20669 :     res_ndigitpairs = Min(res_ndigitpairs, maxdigitpairs);
    8455                 :       20669 :     res_ndigits = 2 * res_ndigitpairs;
    8456                 :             : 
    8457                 :             :     /*
    8458                 :             :      * In the computation below, digit pair i1 of var1 and digit pair i2 of
    8459                 :             :      * var2 are multiplied and added to digit i1+i2+pair_offset of dig[]. Thus
    8460                 :             :      * input digit pairs with index >= res_ndigitpairs - pair_offset don't
    8461                 :             :      * contribute to the result, and can be ignored.
    8462                 :             :      */
    8463         [ +  + ]:       20669 :     if (res_ndigitpairs <= pair_offset)
    8464                 :             :     {
    8465                 :             :         /* All input digits will be ignored; so result is zero */
    8466                 :          10 :         zero_var(result);
    8467                 :          10 :         result->dscale = rscale;
    8468                 :          10 :         return;
    8469                 :             :     }
    8470                 :       20659 :     var1ndigitpairs = Min(var1ndigitpairs, res_ndigitpairs - pair_offset);
    8471                 :       20659 :     var2ndigitpairs = Min(var2ndigitpairs, res_ndigitpairs - pair_offset);
    8472                 :             : 
    8473                 :             :     /*
    8474                 :             :      * We do the arithmetic in an array "dig[]" of unsigned 64-bit integers.
    8475                 :             :      * Since PG_UINT64_MAX is much larger than NBASE^4, this gives us a lot of
    8476                 :             :      * headroom to avoid normalizing carries immediately.
    8477                 :             :      *
    8478                 :             :      * maxdig tracks the maximum possible value of any dig[] entry; when this
    8479                 :             :      * threatens to exceed PG_UINT64_MAX, we take the time to propagate
    8480                 :             :      * carries.  Furthermore, we need to ensure that overflow doesn't occur
    8481                 :             :      * during the carry propagation passes either.  The carry values could be
    8482                 :             :      * as much as PG_UINT64_MAX / NBASE^2, so really we must normalize when
    8483                 :             :      * digits threaten to exceed PG_UINT64_MAX - PG_UINT64_MAX / NBASE^2.
    8484                 :             :      *
    8485                 :             :      * To avoid overflow in maxdig itself, it actually represents the maximum
    8486                 :             :      * possible value divided by NBASE^2-1, i.e., at the top of the loop it is
    8487                 :             :      * known that no dig[] entry exceeds maxdig * (NBASE^2-1).
    8488                 :             :      *
    8489                 :             :      * The conversion of var1 to base NBASE^2 is done on the fly, as each new
    8490                 :             :      * digit is required.  The digits of var2 are converted upfront, and
    8491                 :             :      * stored at the end of dig[].  To avoid loss of precision, the input
    8492                 :             :      * digits are aligned with the start of digit pair array, effectively
    8493                 :             :      * shifting them up (multiplying by NBASE) if the inputs have an odd
    8494                 :             :      * number of NBASE digits.
    8495                 :             :      */
    8496                 :       20659 :     dig = (uint64 *) palloc(res_ndigitpairs * sizeof(uint64) +
    8497                 :             :                             var2ndigitpairs * sizeof(uint32));
    8498                 :             : 
    8499                 :             :     /* convert var2 to base NBASE^2, shifting up if its length is odd */
    8500                 :       20659 :     var2digitpairs = (uint32 *) (dig + res_ndigitpairs);
    8501                 :             : 
    8502         [ +  + ]:     1048389 :     for (i2 = 0; i2 < var2ndigitpairs - 1; i2++)
    8503                 :     1027730 :         var2digitpairs[i2] = var2digits[2 * i2] * NBASE + var2digits[2 * i2 + 1];
    8504                 :             : 
    8505         [ +  + ]:       20659 :     if (2 * i2 + 1 < var2ndigits)
    8506                 :       14659 :         var2digitpairs[i2] = var2digits[2 * i2] * NBASE + var2digits[2 * i2 + 1];
    8507                 :             :     else
    8508                 :        6000 :         var2digitpairs[i2] = var2digits[2 * i2] * NBASE;
    8509                 :             : 
    8510                 :             :     /*
    8511                 :             :      * Start by multiplying var2 by the least significant contributing digit
    8512                 :             :      * pair from var1, storing the results at the end of dig[], and filling
    8513                 :             :      * the leading digits with zeros.
    8514                 :             :      *
    8515                 :             :      * The loop here is the same as the inner loop below, except that we set
    8516                 :             :      * the results in dig[], rather than adding to them.  This is the
    8517                 :             :      * performance bottleneck for multiplication, so we want to keep it simple
    8518                 :             :      * enough so that it can be auto-vectorized.  Accordingly, process the
    8519                 :             :      * digits left-to-right even though schoolbook multiplication would
    8520                 :             :      * suggest right-to-left.  Since we aren't propagating carries in this
    8521                 :             :      * loop, the order does not matter.
    8522                 :             :      */
    8523                 :       20659 :     i1 = var1ndigitpairs - 1;
    8524         [ +  + ]:       20659 :     if (2 * i1 + 1 < var1ndigits)
    8525                 :        9183 :         var1digitpair = var1digits[2 * i1] * NBASE + var1digits[2 * i1 + 1];
    8526                 :             :     else
    8527                 :       11476 :         var1digitpair = var1digits[2 * i1] * NBASE;
    8528                 :       20659 :     maxdig = var1digitpair;
    8529                 :             : 
    8530                 :       20659 :     i2limit = Min(var2ndigitpairs, res_ndigitpairs - i1 - pair_offset);
    8531                 :       20659 :     dig_i1_off = &dig[i1 + pair_offset];
    8532                 :             : 
    8533                 :       20659 :     memset(dig, 0, (i1 + pair_offset) * sizeof(uint64));
    8534         [ +  + ]:      930539 :     for (i2 = 0; i2 < i2limit; i2++)
    8535                 :      909880 :         dig_i1_off[i2] = (uint64) var1digitpair * var2digitpairs[i2];
    8536                 :             : 
    8537                 :             :     /*
    8538                 :             :      * Next, multiply var2 by the remaining digit pairs from var1, adding the
    8539                 :             :      * results to dig[] at the appropriate offsets, and normalizing whenever
    8540                 :             :      * there is a risk of any dig[] entry overflowing.
    8541                 :             :      */
    8542         [ +  + ]:     1012436 :     for (i1 = i1 - 1; i1 >= 0; i1--)
    8543                 :             :     {
    8544                 :      991777 :         var1digitpair = var1digits[2 * i1] * NBASE + var1digits[2 * i1 + 1];
    8545         [ +  + ]:      991777 :         if (var1digitpair == 0)
    8546                 :      786344 :             continue;
    8547                 :             : 
    8548                 :             :         /* Time to normalize? */
    8549                 :      205433 :         maxdig += var1digitpair;
    8550         [ +  + ]:      205433 :         if (maxdig > (PG_UINT64_MAX - PG_UINT64_MAX / NBASE_SQR) / (NBASE_SQR - 1))
    8551                 :             :         {
    8552                 :             :             /* Yes, do it (to base NBASE^2) */
    8553                 :          21 :             carry = 0;
    8554         [ +  + ]:       84074 :             for (i = res_ndigitpairs - 1; i >= 0; i--)
    8555                 :             :             {
    8556                 :       84053 :                 newdig = dig[i] + carry;
    8557         [ +  + ]:       84053 :                 if (newdig >= NBASE_SQR)
    8558                 :             :                 {
    8559                 :       80719 :                     carry = newdig / NBASE_SQR;
    8560                 :       80719 :                     newdig -= carry * NBASE_SQR;
    8561                 :             :                 }
    8562                 :             :                 else
    8563                 :        3334 :                     carry = 0;
    8564                 :       84053 :                 dig[i] = newdig;
    8565                 :             :             }
    8566                 :             :             Assert(carry == 0);
    8567                 :             :             /* Reset maxdig to indicate new worst-case */
    8568                 :          21 :             maxdig = 1 + var1digitpair;
    8569                 :             :         }
    8570                 :             : 
    8571                 :             :         /* Multiply and add */
    8572                 :      205433 :         i2limit = Min(var2ndigitpairs, res_ndigitpairs - i1 - pair_offset);
    8573                 :      205433 :         dig_i1_off = &dig[i1 + pair_offset];
    8574                 :             : 
    8575         [ +  + ]:    87005259 :         for (i2 = 0; i2 < i2limit; i2++)
    8576                 :    86799826 :             dig_i1_off[i2] += (uint64) var1digitpair * var2digitpairs[i2];
    8577                 :             :     }
    8578                 :             : 
    8579                 :             :     /*
    8580                 :             :      * Now we do a final carry propagation pass to normalize back to base
    8581                 :             :      * NBASE^2, and construct the base-NBASE result digits.  Note that this is
    8582                 :             :      * still done at full precision w/guard digits.
    8583                 :             :      */
    8584                 :       20659 :     alloc_var(result, res_ndigits);
    8585                 :       20659 :     res_digits = result->digits;
    8586                 :       20659 :     carry = 0;
    8587         [ +  + ]:     1946324 :     for (i = res_ndigitpairs - 1; i >= 0; i--)
    8588                 :             :     {
    8589                 :     1925665 :         newdig = dig[i] + carry;
    8590         [ +  + ]:     1925665 :         if (newdig >= NBASE_SQR)
    8591                 :             :         {
    8592                 :      290140 :             carry = newdig / NBASE_SQR;
    8593                 :      290140 :             newdig -= carry * NBASE_SQR;
    8594                 :             :         }
    8595                 :             :         else
    8596                 :     1635525 :             carry = 0;
    8597                 :     1925665 :         res_digits[2 * i + 1] = (NumericDigit) ((uint32) newdig % NBASE);
    8598                 :     1925665 :         res_digits[2 * i] = (NumericDigit) ((uint32) newdig / NBASE);
    8599                 :             :     }
    8600                 :             :     Assert(carry == 0);
    8601                 :             : 
    8602                 :       20659 :     pfree(dig);
    8603                 :             : 
    8604                 :             :     /*
    8605                 :             :      * Finally, round the result to the requested precision.
    8606                 :             :      */
    8607                 :       20659 :     result->weight = res_weight;
    8608                 :       20659 :     result->sign = res_sign;
    8609                 :             : 
    8610                 :             :     /* Round to target rscale (and set result->dscale) */
    8611                 :       20659 :     round_var(result, rscale);
    8612                 :             : 
    8613                 :             :     /* Strip leading and trailing zeroes */
    8614                 :       20659 :     strip_var(result);
    8615                 :             : }
    8616                 :             : 
    8617                 :             : 
    8618                 :             : /*
    8619                 :             :  * mul_var_short() -
    8620                 :             :  *
    8621                 :             :  *  Special-case multiplication function used when var1 has 1-6 digits, var2
    8622                 :             :  *  has at least as many digits as var1, and the exact product var1 * var2 is
    8623                 :             :  *  requested.
    8624                 :             :  */
    8625                 :             : static void
    8626                 :      772981 : mul_var_short(const NumericVar *var1, const NumericVar *var2,
    8627                 :             :               NumericVar *result)
    8628                 :             : {
    8629                 :      772981 :     int         var1ndigits = var1->ndigits;
    8630                 :      772981 :     int         var2ndigits = var2->ndigits;
    8631                 :      772981 :     NumericDigit *var1digits = var1->digits;
    8632                 :      772981 :     NumericDigit *var2digits = var2->digits;
    8633                 :             :     int         res_sign;
    8634                 :             :     int         res_weight;
    8635                 :             :     int         res_ndigits;
    8636                 :             :     NumericDigit *res_buf;
    8637                 :             :     NumericDigit *res_digits;
    8638                 :      772981 :     uint32      carry = 0;
    8639                 :             :     uint32      term;
    8640                 :             : 
    8641                 :             :     /* Check preconditions */
    8642                 :             :     Assert(var1ndigits >= 1);
    8643                 :             :     Assert(var1ndigits <= 6);
    8644                 :             :     Assert(var2ndigits >= var1ndigits);
    8645                 :             : 
    8646                 :             :     /*
    8647                 :             :      * Determine the result sign, weight, and number of digits to calculate.
    8648                 :             :      * The weight figured here is correct if the product has no leading zero
    8649                 :             :      * digits; otherwise strip_var() will fix things up.  Note that, unlike
    8650                 :             :      * mul_var(), we do not need to allocate an extra output digit, because we
    8651                 :             :      * are not rounding here.
    8652                 :             :      */
    8653         [ +  + ]:      772981 :     if (var1->sign == var2->sign)
    8654                 :      772174 :         res_sign = NUMERIC_POS;
    8655                 :             :     else
    8656                 :         807 :         res_sign = NUMERIC_NEG;
    8657                 :      772981 :     res_weight = var1->weight + var2->weight + 1;
    8658                 :      772981 :     res_ndigits = var1ndigits + var2ndigits;
    8659                 :             : 
    8660                 :             :     /* Allocate result digit array */
    8661                 :      772981 :     res_buf = digitbuf_alloc(res_ndigits + 1);
    8662                 :      772981 :     res_buf[0] = 0;             /* spare digit for later rounding */
    8663                 :      772981 :     res_digits = res_buf + 1;
    8664                 :             : 
    8665                 :             :     /*
    8666                 :             :      * Compute the result digits in reverse, in one pass, propagating the
    8667                 :             :      * carry up as we go.  The i'th result digit consists of the sum of the
    8668                 :             :      * products var1digits[i1] * var2digits[i2] for which i = i1 + i2 + 1.
    8669                 :             :      */
    8670                 :             : #define PRODSUM1(v1,i1,v2,i2) ((v1)[(i1)] * (v2)[(i2)])
    8671                 :             : #define PRODSUM2(v1,i1,v2,i2) (PRODSUM1(v1,i1,v2,i2) + (v1)[(i1)+1] * (v2)[(i2)-1])
    8672                 :             : #define PRODSUM3(v1,i1,v2,i2) (PRODSUM2(v1,i1,v2,i2) + (v1)[(i1)+2] * (v2)[(i2)-2])
    8673                 :             : #define PRODSUM4(v1,i1,v2,i2) (PRODSUM3(v1,i1,v2,i2) + (v1)[(i1)+3] * (v2)[(i2)-3])
    8674                 :             : #define PRODSUM5(v1,i1,v2,i2) (PRODSUM4(v1,i1,v2,i2) + (v1)[(i1)+4] * (v2)[(i2)-4])
    8675                 :             : #define PRODSUM6(v1,i1,v2,i2) (PRODSUM5(v1,i1,v2,i2) + (v1)[(i1)+5] * (v2)[(i2)-5])
    8676                 :             : 
    8677   [ +  +  +  +  :      772981 :     switch (var1ndigits)
                +  +  - ]
    8678                 :             :     {
    8679                 :      768836 :         case 1:
    8680                 :             :             /* ---------
    8681                 :             :              * 1-digit case:
    8682                 :             :              *      var1ndigits = 1
    8683                 :             :              *      var2ndigits >= 1
    8684                 :             :              *      res_ndigits = var2ndigits + 1
    8685                 :             :              * ----------
    8686                 :             :              */
    8687         [ +  + ]:     2406222 :             for (int i = var2ndigits - 1; i >= 0; i--)
    8688                 :             :             {
    8689                 :     1637386 :                 term = PRODSUM1(var1digits, 0, var2digits, i) + carry;
    8690                 :     1637386 :                 res_digits[i + 1] = (NumericDigit) (term % NBASE);
    8691                 :     1637386 :                 carry = term / NBASE;
    8692                 :             :             }
    8693                 :      768836 :             res_digits[0] = (NumericDigit) carry;
    8694                 :      768836 :             break;
    8695                 :             : 
    8696                 :         519 :         case 2:
    8697                 :             :             /* ---------
    8698                 :             :              * 2-digit case:
    8699                 :             :              *      var1ndigits = 2
    8700                 :             :              *      var2ndigits >= 2
    8701                 :             :              *      res_ndigits = var2ndigits + 2
    8702                 :             :              * ----------
    8703                 :             :              */
    8704                 :             :             /* last result digit and carry */
    8705                 :         519 :             term = PRODSUM1(var1digits, 1, var2digits, var2ndigits - 1);
    8706                 :         519 :             res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
    8707                 :         519 :             carry = term / NBASE;
    8708                 :             : 
    8709                 :             :             /* remaining digits, except for the first two */
    8710         [ +  + ]:        1573 :             for (int i = var2ndigits - 1; i >= 1; i--)
    8711                 :             :             {
    8712                 :        1054 :                 term = PRODSUM2(var1digits, 0, var2digits, i) + carry;
    8713                 :        1054 :                 res_digits[i + 1] = (NumericDigit) (term % NBASE);
    8714                 :        1054 :                 carry = term / NBASE;
    8715                 :             :             }
    8716                 :         519 :             break;
    8717                 :             : 
    8718                 :         146 :         case 3:
    8719                 :             :             /* ---------
    8720                 :             :              * 3-digit case:
    8721                 :             :              *      var1ndigits = 3
    8722                 :             :              *      var2ndigits >= 3
    8723                 :             :              *      res_ndigits = var2ndigits + 3
    8724                 :             :              * ----------
    8725                 :             :              */
    8726                 :             :             /* last two result digits */
    8727                 :         146 :             term = PRODSUM1(var1digits, 2, var2digits, var2ndigits - 1);
    8728                 :         146 :             res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
    8729                 :         146 :             carry = term / NBASE;
    8730                 :             : 
    8731                 :         146 :             term = PRODSUM2(var1digits, 1, var2digits, var2ndigits - 1) + carry;
    8732                 :         146 :             res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
    8733                 :         146 :             carry = term / NBASE;
    8734                 :             : 
    8735                 :             :             /* remaining digits, except for the first three */
    8736         [ +  + ]:         387 :             for (int i = var2ndigits - 1; i >= 2; i--)
    8737                 :             :             {
    8738                 :         241 :                 term = PRODSUM3(var1digits, 0, var2digits, i) + carry;
    8739                 :         241 :                 res_digits[i + 1] = (NumericDigit) (term % NBASE);
    8740                 :         241 :                 carry = term / NBASE;
    8741                 :             :             }
    8742                 :         146 :             break;
    8743                 :             : 
    8744                 :        2888 :         case 4:
    8745                 :             :             /* ---------
    8746                 :             :              * 4-digit case:
    8747                 :             :              *      var1ndigits = 4
    8748                 :             :              *      var2ndigits >= 4
    8749                 :             :              *      res_ndigits = var2ndigits + 4
    8750                 :             :              * ----------
    8751                 :             :              */
    8752                 :             :             /* last three result digits */
    8753                 :        2888 :             term = PRODSUM1(var1digits, 3, var2digits, var2ndigits - 1);
    8754                 :        2888 :             res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
    8755                 :        2888 :             carry = term / NBASE;
    8756                 :             : 
    8757                 :        2888 :             term = PRODSUM2(var1digits, 2, var2digits, var2ndigits - 1) + carry;
    8758                 :        2888 :             res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
    8759                 :        2888 :             carry = term / NBASE;
    8760                 :             : 
    8761                 :        2888 :             term = PRODSUM3(var1digits, 1, var2digits, var2ndigits - 1) + carry;
    8762                 :        2888 :             res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
    8763                 :        2888 :             carry = term / NBASE;
    8764                 :             : 
    8765                 :             :             /* remaining digits, except for the first four */
    8766         [ +  + ]:        8058 :             for (int i = var2ndigits - 1; i >= 3; i--)
    8767                 :             :             {
    8768                 :        5170 :                 term = PRODSUM4(var1digits, 0, var2digits, i) + carry;
    8769                 :        5170 :                 res_digits[i + 1] = (NumericDigit) (term % NBASE);
    8770                 :        5170 :                 carry = term / NBASE;
    8771                 :             :             }
    8772                 :        2888 :             break;
    8773                 :             : 
    8774                 :          91 :         case 5:
    8775                 :             :             /* ---------
    8776                 :             :              * 5-digit case:
    8777                 :             :              *      var1ndigits = 5
    8778                 :             :              *      var2ndigits >= 5
    8779                 :             :              *      res_ndigits = var2ndigits + 5
    8780                 :             :              * ----------
    8781                 :             :              */
    8782                 :             :             /* last four result digits */
    8783                 :          91 :             term = PRODSUM1(var1digits, 4, var2digits, var2ndigits - 1);
    8784                 :          91 :             res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
    8785                 :          91 :             carry = term / NBASE;
    8786                 :             : 
    8787                 :          91 :             term = PRODSUM2(var1digits, 3, var2digits, var2ndigits - 1) + carry;
    8788                 :          91 :             res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
    8789                 :          91 :             carry = term / NBASE;
    8790                 :             : 
    8791                 :          91 :             term = PRODSUM3(var1digits, 2, var2digits, var2ndigits - 1) + carry;
    8792                 :          91 :             res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
    8793                 :          91 :             carry = term / NBASE;
    8794                 :             : 
    8795                 :          91 :             term = PRODSUM4(var1digits, 1, var2digits, var2ndigits - 1) + carry;
    8796                 :          91 :             res_digits[res_ndigits - 4] = (NumericDigit) (term % NBASE);
    8797                 :          91 :             carry = term / NBASE;
    8798                 :             : 
    8799                 :             :             /* remaining digits, except for the first five */
    8800         [ +  + ]:         242 :             for (int i = var2ndigits - 1; i >= 4; i--)
    8801                 :             :             {
    8802                 :         151 :                 term = PRODSUM5(var1digits, 0, var2digits, i) + carry;
    8803                 :         151 :                 res_digits[i + 1] = (NumericDigit) (term % NBASE);
    8804                 :         151 :                 carry = term / NBASE;
    8805                 :             :             }
    8806                 :          91 :             break;
    8807                 :             : 
    8808                 :         501 :         case 6:
    8809                 :             :             /* ---------
    8810                 :             :              * 6-digit case:
    8811                 :             :              *      var1ndigits = 6
    8812                 :             :              *      var2ndigits >= 6
    8813                 :             :              *      res_ndigits = var2ndigits + 6
    8814                 :             :              * ----------
    8815                 :             :              */
    8816                 :             :             /* last five result digits */
    8817                 :         501 :             term = PRODSUM1(var1digits, 5, var2digits, var2ndigits - 1);
    8818                 :         501 :             res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
    8819                 :         501 :             carry = term / NBASE;
    8820                 :             : 
    8821                 :         501 :             term = PRODSUM2(var1digits, 4, var2digits, var2ndigits - 1) + carry;
    8822                 :         501 :             res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
    8823                 :         501 :             carry = term / NBASE;
    8824                 :             : 
    8825                 :         501 :             term = PRODSUM3(var1digits, 3, var2digits, var2ndigits - 1) + carry;
    8826                 :         501 :             res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
    8827                 :         501 :             carry = term / NBASE;
    8828                 :             : 
    8829                 :         501 :             term = PRODSUM4(var1digits, 2, var2digits, var2ndigits - 1) + carry;
    8830                 :         501 :             res_digits[res_ndigits - 4] = (NumericDigit) (term % NBASE);
    8831                 :         501 :             carry = term / NBASE;
    8832                 :             : 
    8833                 :         501 :             term = PRODSUM5(var1digits, 1, var2digits, var2ndigits - 1) + carry;
    8834                 :         501 :             res_digits[res_ndigits - 5] = (NumericDigit) (term % NBASE);
    8835                 :         501 :             carry = term / NBASE;
    8836                 :             : 
    8837                 :             :             /* remaining digits, except for the first six */
    8838         [ +  + ]:        1400 :             for (int i = var2ndigits - 1; i >= 5; i--)
    8839                 :             :             {
    8840                 :         899 :                 term = PRODSUM6(var1digits, 0, var2digits, i) + carry;
    8841                 :         899 :                 res_digits[i + 1] = (NumericDigit) (term % NBASE);
    8842                 :         899 :                 carry = term / NBASE;
    8843                 :             :             }
    8844                 :         501 :             break;
    8845                 :             :     }
    8846                 :             : 
    8847                 :             :     /*
    8848                 :             :      * Finally, for var1ndigits > 1, compute the remaining var1ndigits most
    8849                 :             :      * significant result digits.
    8850                 :             :      */
    8851   [ +  +  +  +  :      772981 :     switch (var1ndigits)
                   +  + ]
    8852                 :             :     {
    8853                 :         501 :         case 6:
    8854                 :         501 :             term = PRODSUM5(var1digits, 0, var2digits, 4) + carry;
    8855                 :         501 :             res_digits[5] = (NumericDigit) (term % NBASE);
    8856                 :         501 :             carry = term / NBASE;
    8857                 :             :             pg_fallthrough;
    8858                 :         592 :         case 5:
    8859                 :         592 :             term = PRODSUM4(var1digits, 0, var2digits, 3) + carry;
    8860                 :         592 :             res_digits[4] = (NumericDigit) (term % NBASE);
    8861                 :         592 :             carry = term / NBASE;
    8862                 :             :             pg_fallthrough;
    8863                 :        3480 :         case 4:
    8864                 :        3480 :             term = PRODSUM3(var1digits, 0, var2digits, 2) + carry;
    8865                 :        3480 :             res_digits[3] = (NumericDigit) (term % NBASE);
    8866                 :        3480 :             carry = term / NBASE;
    8867                 :             :             pg_fallthrough;
    8868                 :        3626 :         case 3:
    8869                 :        3626 :             term = PRODSUM2(var1digits, 0, var2digits, 1) + carry;
    8870                 :        3626 :             res_digits[2] = (NumericDigit) (term % NBASE);
    8871                 :        3626 :             carry = term / NBASE;
    8872                 :             :             pg_fallthrough;
    8873                 :        4145 :         case 2:
    8874                 :        4145 :             term = PRODSUM1(var1digits, 0, var2digits, 0) + carry;
    8875                 :        4145 :             res_digits[1] = (NumericDigit) (term % NBASE);
    8876                 :        4145 :             res_digits[0] = (NumericDigit) (term / NBASE);
    8877                 :        4145 :             break;
    8878                 :             :     }
    8879                 :             : 
    8880                 :             :     /* Store the product in result */
    8881         [ +  + ]:      772981 :     digitbuf_free(result->buf);
    8882                 :      772981 :     result->ndigits = res_ndigits;
    8883                 :      772981 :     result->buf = res_buf;
    8884                 :      772981 :     result->digits = res_digits;
    8885                 :      772981 :     result->weight = res_weight;
    8886                 :      772981 :     result->sign = res_sign;
    8887                 :      772981 :     result->dscale = var1->dscale + var2->dscale;
    8888                 :             : 
    8889                 :             :     /* Strip leading and trailing zeroes */
    8890                 :      772981 :     strip_var(result);
    8891                 :      772981 : }
    8892                 :             : 
    8893                 :             : 
    8894                 :             : /*
    8895                 :             :  * div_var() -
    8896                 :             :  *
    8897                 :             :  *  Compute the quotient var1 / var2 to rscale fractional digits.
    8898                 :             :  *
    8899                 :             :  *  If "round" is true, the result is rounded at the rscale'th digit; if
    8900                 :             :  *  false, it is truncated (towards zero) at that digit.
    8901                 :             :  *
    8902                 :             :  *  If "exact" is true, the exact result is computed to the specified rscale;
    8903                 :             :  *  if false, successive quotient digits are approximated up to rscale plus
    8904                 :             :  *  DIV_GUARD_DIGITS extra digits, ignoring all contributions from digits to
    8905                 :             :  *  the right of that, before rounding or truncating to the specified rscale.
    8906                 :             :  *  This can be significantly faster, and usually gives the same result as the
    8907                 :             :  *  exact computation, but it may occasionally be off by one in the final
    8908                 :             :  *  digit, if contributions from the ignored digits would have propagated
    8909                 :             :  *  through the guard digits.  This is good enough for the transcendental
    8910                 :             :  *  functions, where small errors are acceptable.
    8911                 :             :  */
    8912                 :             : static void
    8913                 :      380373 : div_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result,
    8914                 :             :         int rscale, bool round, bool exact)
    8915                 :             : {
    8916                 :      380373 :     int         var1ndigits = var1->ndigits;
    8917                 :      380373 :     int         var2ndigits = var2->ndigits;
    8918                 :             :     int         res_sign;
    8919                 :             :     int         res_weight;
    8920                 :             :     int         res_ndigits;
    8921                 :             :     int         var1ndigitpairs;
    8922                 :             :     int         var2ndigitpairs;
    8923                 :             :     int         res_ndigitpairs;
    8924                 :             :     int         div_ndigitpairs;
    8925                 :             :     int64      *dividend;
    8926                 :             :     int32      *divisor;
    8927                 :             :     double      fdivisor,
    8928                 :             :                 fdivisorinverse,
    8929                 :             :                 fdividend,
    8930                 :             :                 fquotient;
    8931                 :             :     int64       maxdiv;
    8932                 :             :     int         qi;
    8933                 :             :     int32       qdigit;
    8934                 :             :     int64       carry;
    8935                 :             :     int64       newdig;
    8936                 :             :     int64      *remainder;
    8937                 :             :     NumericDigit *res_digits;
    8938                 :             :     int         i;
    8939                 :             : 
    8940                 :             :     /*
    8941                 :             :      * First of all division by zero check; we must not be handed an
    8942                 :             :      * unnormalized divisor.
    8943                 :             :      */
    8944   [ +  +  -  + ]:      380373 :     if (var2ndigits == 0 || var2->digits[0] == 0)
    8945         [ +  - ]:           8 :         ereport(ERROR,
    8946                 :             :                 (errcode(ERRCODE_DIVISION_BY_ZERO),
    8947                 :             :                  errmsg("division by zero")));
    8948                 :             : 
    8949                 :             :     /*
    8950                 :             :      * If the divisor has just one or two digits, delegate to div_var_int(),
    8951                 :             :      * which uses fast short division.
    8952                 :             :      *
    8953                 :             :      * Similarly, on platforms with 128-bit integer support, delegate to
    8954                 :             :      * div_var_int64() for divisors with three or four digits.
    8955                 :             :      */
    8956         [ +  + ]:      380365 :     if (var2ndigits <= 2)
    8957                 :             :     {
    8958                 :             :         int         idivisor;
    8959                 :             :         int         idivisor_weight;
    8960                 :             : 
    8961                 :      376013 :         idivisor = var2->digits[0];
    8962                 :      376013 :         idivisor_weight = var2->weight;
    8963         [ +  + ]:      376013 :         if (var2ndigits == 2)
    8964                 :             :         {
    8965                 :        2219 :             idivisor = idivisor * NBASE + var2->digits[1];
    8966                 :        2219 :             idivisor_weight--;
    8967                 :             :         }
    8968         [ +  + ]:      376013 :         if (var2->sign == NUMERIC_NEG)
    8969                 :         440 :             idivisor = -idivisor;
    8970                 :             : 
    8971                 :      376013 :         div_var_int(var1, idivisor, idivisor_weight, result, rscale, round);
    8972                 :      376013 :         return;
    8973                 :             :     }
    8974                 :             : #ifdef HAVE_INT128
    8975         [ +  + ]:        4352 :     if (var2ndigits <= 4)
    8976                 :             :     {
    8977                 :             :         int64       idivisor;
    8978                 :             :         int         idivisor_weight;
    8979                 :             : 
    8980                 :         360 :         idivisor = var2->digits[0];
    8981                 :         360 :         idivisor_weight = var2->weight;
    8982         [ +  + ]:        1340 :         for (i = 1; i < var2ndigits; i++)
    8983                 :             :         {
    8984                 :         980 :             idivisor = idivisor * NBASE + var2->digits[i];
    8985                 :         980 :             idivisor_weight--;
    8986                 :             :         }
    8987         [ +  + ]:         360 :         if (var2->sign == NUMERIC_NEG)
    8988                 :          80 :             idivisor = -idivisor;
    8989                 :             : 
    8990                 :         360 :         div_var_int64(var1, idivisor, idivisor_weight, result, rscale, round);
    8991                 :         360 :         return;
    8992                 :             :     }
    8993                 :             : #endif
    8994                 :             : 
    8995                 :             :     /*
    8996                 :             :      * Otherwise, perform full long division.
    8997                 :             :      */
    8998                 :             : 
    8999                 :             :     /* Result zero check */
    9000         [ +  + ]:        3992 :     if (var1ndigits == 0)
    9001                 :             :     {
    9002                 :          24 :         zero_var(result);
    9003                 :          24 :         result->dscale = rscale;
    9004                 :          24 :         return;
    9005                 :             :     }
    9006                 :             : 
    9007                 :             :     /*
    9008                 :             :      * The approximate computation can be significantly faster than the exact
    9009                 :             :      * one, since the working dividend is var2ndigitpairs base-NBASE^2 digits
    9010                 :             :      * shorter below.  However, that comes with the tradeoff of computing
    9011                 :             :      * DIV_GUARD_DIGITS extra base-NBASE result digits.  Ignoring all other
    9012                 :             :      * overheads, that suggests that, in theory, the approximate computation
    9013                 :             :      * will only be faster than the exact one when var2ndigits is greater than
    9014                 :             :      * 2 * (DIV_GUARD_DIGITS + 1), independent of the size of var1.
    9015                 :             :      *
    9016                 :             :      * Thus, we're better off doing an exact computation when var2 is shorter
    9017                 :             :      * than this.  Empirically, it has been found that the exact threshold is
    9018                 :             :      * a little higher, due to other overheads in the outer division loop.
    9019                 :             :      */
    9020         [ +  + ]:        3968 :     if (var2ndigits <= 2 * (DIV_GUARD_DIGITS + 2))
    9021                 :        2712 :         exact = true;
    9022                 :             : 
    9023                 :             :     /*
    9024                 :             :      * Determine the result sign, weight and number of digits to calculate.
    9025                 :             :      * The weight figured here is correct if the emitted quotient has no
    9026                 :             :      * leading zero digits; otherwise strip_var() will fix things up.
    9027                 :             :      */
    9028         [ +  + ]:        3968 :     if (var1->sign == var2->sign)
    9029                 :        3866 :         res_sign = NUMERIC_POS;
    9030                 :             :     else
    9031                 :         102 :         res_sign = NUMERIC_NEG;
    9032                 :        3968 :     res_weight = var1->weight - var2->weight + 1;
    9033                 :             :     /* The number of accurate result digits we need to produce: */
    9034                 :        3968 :     res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
    9035                 :             :     /* ... but always at least 1 */
    9036                 :        3968 :     res_ndigits = Max(res_ndigits, 1);
    9037                 :             :     /* If rounding needed, figure one more digit to ensure correct result */
    9038         [ +  + ]:        3968 :     if (round)
    9039                 :         658 :         res_ndigits++;
    9040                 :             :     /* Add guard digits for roundoff error when producing approx result */
    9041         [ +  + ]:        3968 :     if (!exact)
    9042                 :        1246 :         res_ndigits += DIV_GUARD_DIGITS;
    9043                 :             : 
    9044                 :             :     /*
    9045                 :             :      * The computation itself is done using base-NBASE^2 arithmetic, so we
    9046                 :             :      * actually process the input digits in pairs, producing a base-NBASE^2
    9047                 :             :      * intermediate result.  This significantly improves performance, since
    9048                 :             :      * the computation is O(N^2) in the number of input digits, and working in
    9049                 :             :      * base NBASE^2 effectively halves "N".
    9050                 :             :      */
    9051                 :        3968 :     var1ndigitpairs = (var1ndigits + 1) / 2;
    9052                 :        3968 :     var2ndigitpairs = (var2ndigits + 1) / 2;
    9053                 :        3968 :     res_ndigitpairs = (res_ndigits + 1) / 2;
    9054                 :        3968 :     res_ndigits = 2 * res_ndigitpairs;
    9055                 :             : 
    9056                 :             :     /*
    9057                 :             :      * We do the arithmetic in an array "dividend[]" of signed 64-bit
    9058                 :             :      * integers.  Since PG_INT64_MAX is much larger than NBASE^4, this gives
    9059                 :             :      * us a lot of headroom to avoid normalizing carries immediately.
    9060                 :             :      *
    9061                 :             :      * When performing an exact computation, the working dividend requires
    9062                 :             :      * res_ndigitpairs + var2ndigitpairs digits.  If var1 is larger than that,
    9063                 :             :      * the extra digits do not contribute to the result, and are ignored.
    9064                 :             :      *
    9065                 :             :      * When performing an approximate computation, the working dividend only
    9066                 :             :      * requires res_ndigitpairs digits (which includes the extra guard
    9067                 :             :      * digits).  All input digits beyond that are ignored.
    9068                 :             :      */
    9069         [ +  + ]:        3968 :     if (exact)
    9070                 :             :     {
    9071                 :        2722 :         div_ndigitpairs = res_ndigitpairs + var2ndigitpairs;
    9072                 :        2722 :         var1ndigitpairs = Min(var1ndigitpairs, div_ndigitpairs);
    9073                 :             :     }
    9074                 :             :     else
    9075                 :             :     {
    9076                 :        1246 :         div_ndigitpairs = res_ndigitpairs;
    9077                 :        1246 :         var1ndigitpairs = Min(var1ndigitpairs, div_ndigitpairs);
    9078                 :        1246 :         var2ndigitpairs = Min(var2ndigitpairs, div_ndigitpairs);
    9079                 :             :     }
    9080                 :             : 
    9081                 :             :     /*
    9082                 :             :      * Allocate room for the working dividend (div_ndigitpairs 64-bit digits)
    9083                 :             :      * plus the divisor (var2ndigitpairs 32-bit base-NBASE^2 digits).
    9084                 :             :      *
    9085                 :             :      * For convenience, we allocate one extra dividend digit, which is set to
    9086                 :             :      * zero and not counted in div_ndigitpairs, so that the main loop below
    9087                 :             :      * can safely read and write the (qi+1)'th digit in the approximate case.
    9088                 :             :      */
    9089                 :        3968 :     dividend = (int64 *) palloc((div_ndigitpairs + 1) * sizeof(int64) +
    9090                 :             :                                 var2ndigitpairs * sizeof(int32));
    9091                 :        3968 :     divisor = (int32 *) (dividend + div_ndigitpairs + 1);
    9092                 :             : 
    9093                 :             :     /* load var1 into dividend[0 .. var1ndigitpairs-1], zeroing the rest */
    9094         [ +  + ]:       37128 :     for (i = 0; i < var1ndigitpairs - 1; i++)
    9095                 :       33160 :         dividend[i] = var1->digits[2 * i] * NBASE + var1->digits[2 * i + 1];
    9096                 :             : 
    9097         [ +  + ]:        3968 :     if (2 * i + 1 < var1ndigits)
    9098                 :        2341 :         dividend[i] = var1->digits[2 * i] * NBASE + var1->digits[2 * i + 1];
    9099                 :             :     else
    9100                 :        1627 :         dividend[i] = var1->digits[2 * i] * NBASE;
    9101                 :             : 
    9102                 :        3968 :     memset(dividend + i + 1, 0, (div_ndigitpairs - i) * sizeof(int64));
    9103                 :             : 
    9104                 :             :     /* load var2 into divisor[0 .. var2ndigitpairs-1] */
    9105         [ +  + ]:       29424 :     for (i = 0; i < var2ndigitpairs - 1; i++)
    9106                 :       25456 :         divisor[i] = var2->digits[2 * i] * NBASE + var2->digits[2 * i + 1];
    9107                 :             : 
    9108         [ +  + ]:        3968 :     if (2 * i + 1 < var2ndigits)
    9109                 :        2138 :         divisor[i] = var2->digits[2 * i] * NBASE + var2->digits[2 * i + 1];
    9110                 :             :     else
    9111                 :        1830 :         divisor[i] = var2->digits[2 * i] * NBASE;
    9112                 :             : 
    9113                 :             :     /*
    9114                 :             :      * We estimate each quotient digit using floating-point arithmetic, taking
    9115                 :             :      * the first 2 base-NBASE^2 digits of the (current) dividend and divisor.
    9116                 :             :      * This must be float to avoid overflow.
    9117                 :             :      *
    9118                 :             :      * Since the floating-point dividend and divisor use 4 base-NBASE input
    9119                 :             :      * digits, they include roughly 40-53 bits of information from their
    9120                 :             :      * respective inputs (assuming NBASE is 10000), which fits well in IEEE
    9121                 :             :      * double-precision variables.  The relative error in the floating-point
    9122                 :             :      * quotient digit will then be less than around 2/NBASE^3, so the
    9123                 :             :      * estimated base-NBASE^2 quotient digit will typically be correct, and
    9124                 :             :      * should not be off by more than one from the correct value.
    9125                 :             :      */
    9126                 :        3968 :     fdivisor = (double) divisor[0] * NBASE_SQR;
    9127         [ +  - ]:        3968 :     if (var2ndigitpairs > 1)
    9128                 :        3968 :         fdivisor += (double) divisor[1];
    9129                 :        3968 :     fdivisorinverse = 1.0 / fdivisor;
    9130                 :             : 
    9131                 :             :     /*
    9132                 :             :      * maxdiv tracks the maximum possible absolute value of any dividend[]
    9133                 :             :      * entry; when this threatens to exceed PG_INT64_MAX, we take the time to
    9134                 :             :      * propagate carries.  Furthermore, we need to ensure that overflow
    9135                 :             :      * doesn't occur during the carry propagation passes either.  The carry
    9136                 :             :      * values may have an absolute value as high as PG_INT64_MAX/NBASE^2 + 1,
    9137                 :             :      * so really we must normalize when digits threaten to exceed PG_INT64_MAX
    9138                 :             :      * - PG_INT64_MAX/NBASE^2 - 1.
    9139                 :             :      *
    9140                 :             :      * To avoid overflow in maxdiv itself, it represents the max absolute
    9141                 :             :      * value divided by NBASE^2-1, i.e., at the top of the loop it is known
    9142                 :             :      * that no dividend[] entry has an absolute value exceeding maxdiv *
    9143                 :             :      * (NBASE^2-1).
    9144                 :             :      *
    9145                 :             :      * Actually, though, that holds good only for dividend[] entries after
    9146                 :             :      * dividend[qi]; the adjustment done at the bottom of the loop may cause
    9147                 :             :      * dividend[qi + 1] to exceed the maxdiv limit, so that dividend[qi] in
    9148                 :             :      * the next iteration is beyond the limit.  This does not cause problems,
    9149                 :             :      * as explained below.
    9150                 :             :      */
    9151                 :        3968 :     maxdiv = 1;
    9152                 :             : 
    9153                 :             :     /*
    9154                 :             :      * Outer loop computes next quotient digit, which goes in dividend[qi].
    9155                 :             :      */
    9156         [ +  + ]:       36464 :     for (qi = 0; qi < res_ndigitpairs; qi++)
    9157                 :             :     {
    9158                 :             :         /* Approximate the current dividend value */
    9159                 :       32496 :         fdividend = (double) dividend[qi] * NBASE_SQR;
    9160                 :       32496 :         fdividend += (double) dividend[qi + 1];
    9161                 :             : 
    9162                 :             :         /* Compute the (approximate) quotient digit */
    9163                 :       32496 :         fquotient = fdividend * fdivisorinverse;
    9164         [ +  + ]:       32496 :         qdigit = (fquotient >= 0.0) ? ((int32) fquotient) :
    9165                 :           5 :             (((int32) fquotient) - 1);  /* truncate towards -infinity */
    9166                 :             : 
    9167         [ +  + ]:       32496 :         if (qdigit != 0)
    9168                 :             :         {
    9169                 :             :             /* Do we need to normalize now? */
    9170                 :       29863 :             maxdiv += i64abs(qdigit);
    9171         [ +  + ]:       29863 :             if (maxdiv > (PG_INT64_MAX - PG_INT64_MAX / NBASE_SQR - 1) / (NBASE_SQR - 1))
    9172                 :             :             {
    9173                 :             :                 /*
    9174                 :             :                  * Yes, do it.  Note that if var2ndigitpairs is much smaller
    9175                 :             :                  * than div_ndigitpairs, we can save a significant amount of
    9176                 :             :                  * effort here by noting that we only need to normalise those
    9177                 :             :                  * dividend[] entries touched where prior iterations
    9178                 :             :                  * subtracted multiples of the divisor.
    9179                 :             :                  */
    9180                 :           5 :                 carry = 0;
    9181         [ +  + ]:        5625 :                 for (i = Min(qi + var2ndigitpairs - 2, div_ndigitpairs - 1); i > qi; i--)
    9182                 :             :                 {
    9183                 :        5620 :                     newdig = dividend[i] + carry;
    9184         [ +  - ]:        5620 :                     if (newdig < 0)
    9185                 :             :                     {
    9186                 :        5620 :                         carry = -((-newdig - 1) / NBASE_SQR) - 1;
    9187                 :        5620 :                         newdig -= carry * NBASE_SQR;
    9188                 :             :                     }
    9189         [ #  # ]:           0 :                     else if (newdig >= NBASE_SQR)
    9190                 :             :                     {
    9191                 :           0 :                         carry = newdig / NBASE_SQR;
    9192                 :           0 :                         newdig -= carry * NBASE_SQR;
    9193                 :             :                     }
    9194                 :             :                     else
    9195                 :           0 :                         carry = 0;
    9196                 :        5620 :                     dividend[i] = newdig;
    9197                 :             :                 }
    9198                 :           5 :                 dividend[qi] += carry;
    9199                 :             : 
    9200                 :             :                 /*
    9201                 :             :                  * All the dividend[] digits except possibly dividend[qi] are
    9202                 :             :                  * now in the range 0..NBASE^2-1.  We do not need to consider
    9203                 :             :                  * dividend[qi] in the maxdiv value anymore, so we can reset
    9204                 :             :                  * maxdiv to 1.
    9205                 :             :                  */
    9206                 :           5 :                 maxdiv = 1;
    9207                 :             : 
    9208                 :             :                 /*
    9209                 :             :                  * Recompute the quotient digit since new info may have
    9210                 :             :                  * propagated into the top two dividend digits.
    9211                 :             :                  */
    9212                 :           5 :                 fdividend = (double) dividend[qi] * NBASE_SQR;
    9213                 :           5 :                 fdividend += (double) dividend[qi + 1];
    9214                 :           5 :                 fquotient = fdividend * fdivisorinverse;
    9215         [ +  - ]:           5 :                 qdigit = (fquotient >= 0.0) ? ((int32) fquotient) :
    9216                 :           0 :                     (((int32) fquotient) - 1);  /* truncate towards -infinity */
    9217                 :             : 
    9218                 :           5 :                 maxdiv += i64abs(qdigit);
    9219                 :             :             }
    9220                 :             : 
    9221                 :             :             /*
    9222                 :             :              * Subtract off the appropriate multiple of the divisor.
    9223                 :             :              *
    9224                 :             :              * The digits beyond dividend[qi] cannot overflow, because we know
    9225                 :             :              * they will fall within the maxdiv limit.  As for dividend[qi]
    9226                 :             :              * itself, note that qdigit is approximately trunc(dividend[qi] /
    9227                 :             :              * divisor[0]), which would make the new value simply dividend[qi]
    9228                 :             :              * mod divisor[0].  The lower-order terms in qdigit can change
    9229                 :             :              * this result by not more than about twice PG_INT64_MAX/NBASE^2,
    9230                 :             :              * so overflow is impossible.
    9231                 :             :              *
    9232                 :             :              * This inner loop is the performance bottleneck for division, so
    9233                 :             :              * code it in the same way as the inner loop of mul_var() so that
    9234                 :             :              * it can be auto-vectorized.
    9235                 :             :              */
    9236         [ +  - ]:       29863 :             if (qdigit != 0)
    9237                 :             :             {
    9238                 :       29863 :                 int         istop = Min(var2ndigitpairs, div_ndigitpairs - qi);
    9239                 :       29863 :                 int64      *dividend_qi = &dividend[qi];
    9240                 :             : 
    9241         [ +  + ]:     6518873 :                 for (i = 0; i < istop; i++)
    9242                 :     6489010 :                     dividend_qi[i] -= (int64) qdigit * divisor[i];
    9243                 :             :             }
    9244                 :             :         }
    9245                 :             : 
    9246                 :             :         /*
    9247                 :             :          * The dividend digit we are about to replace might still be nonzero.
    9248                 :             :          * Fold it into the next digit position.
    9249                 :             :          *
    9250                 :             :          * There is no risk of overflow here, although proving that requires
    9251                 :             :          * some care.  Much as with the argument for dividend[qi] not
    9252                 :             :          * overflowing, if we consider the first two terms in the numerator
    9253                 :             :          * and denominator of qdigit, we can see that the final value of
    9254                 :             :          * dividend[qi + 1] will be approximately a remainder mod
    9255                 :             :          * (divisor[0]*NBASE^2 + divisor[1]).  Accounting for the lower-order
    9256                 :             :          * terms is a bit complicated but ends up adding not much more than
    9257                 :             :          * PG_INT64_MAX/NBASE^2 to the possible range.  Thus, dividend[qi + 1]
    9258                 :             :          * cannot overflow here, and in its role as dividend[qi] in the next
    9259                 :             :          * loop iteration, it can't be large enough to cause overflow in the
    9260                 :             :          * carry propagation step (if any), either.
    9261                 :             :          *
    9262                 :             :          * But having said that: dividend[qi] can be more than
    9263                 :             :          * PG_INT64_MAX/NBASE^2, as noted above, which means that the product
    9264                 :             :          * dividend[qi] * NBASE^2 *can* overflow.  When that happens, adding
    9265                 :             :          * it to dividend[qi + 1] will always cause a canceling overflow so
    9266                 :             :          * that the end result is correct.  We could avoid the intermediate
    9267                 :             :          * overflow by doing the multiplication and addition using unsigned
    9268                 :             :          * int64 arithmetic, which is modulo 2^64, but so far there appears no
    9269                 :             :          * need.
    9270                 :             :          */
    9271                 :       32496 :         dividend[qi + 1] += dividend[qi] * NBASE_SQR;
    9272                 :             : 
    9273                 :       32496 :         dividend[qi] = qdigit;
    9274                 :             :     }
    9275                 :             : 
    9276                 :             :     /*
    9277                 :             :      * If an exact result was requested, use the remainder to correct the
    9278                 :             :      * approximate quotient.  The remainder is in dividend[], immediately
    9279                 :             :      * after the quotient digits.  Note, however, that although the remainder
    9280                 :             :      * starts at dividend[qi = res_ndigitpairs], the first digit is the result
    9281                 :             :      * of folding two remainder digits into one above, and the remainder
    9282                 :             :      * currently only occupies var2ndigitpairs - 1 digits (the last digit of
    9283                 :             :      * the working dividend was untouched by the computation above).  Thus we
    9284                 :             :      * expand the remainder down by one base-NBASE^2 digit when we normalize
    9285                 :             :      * it, so that it completely fills the last var2ndigitpairs digits of the
    9286                 :             :      * dividend array.
    9287                 :             :      */
    9288         [ +  + ]:        3968 :     if (exact)
    9289                 :             :     {
    9290                 :             :         /* Normalize the remainder, expanding it down by one digit */
    9291                 :        2722 :         remainder = &dividend[qi];
    9292                 :        2722 :         carry = 0;
    9293         [ +  + ]:       15518 :         for (i = var2ndigitpairs - 2; i >= 0; i--)
    9294                 :             :         {
    9295                 :       12796 :             newdig = remainder[i] + carry;
    9296         [ +  + ]:       12796 :             if (newdig < 0)
    9297                 :             :             {
    9298                 :       10044 :                 carry = -((-newdig - 1) / NBASE_SQR) - 1;
    9299                 :       10044 :                 newdig -= carry * NBASE_SQR;
    9300                 :             :             }
    9301         [ +  + ]:        2752 :             else if (newdig >= NBASE_SQR)
    9302                 :             :             {
    9303                 :        2696 :                 carry = newdig / NBASE_SQR;
    9304                 :        2696 :                 newdig -= carry * NBASE_SQR;
    9305                 :             :             }
    9306                 :             :             else
    9307                 :          56 :                 carry = 0;
    9308                 :       12796 :             remainder[i + 1] = newdig;
    9309                 :             :         }
    9310                 :        2722 :         remainder[0] = carry;
    9311                 :             : 
    9312         [ +  + ]:        2722 :         if (remainder[0] < 0)
    9313                 :             :         {
    9314                 :             :             /*
    9315                 :             :              * The remainder is negative, so the approximate quotient is too
    9316                 :             :              * large.  Correct by reducing the quotient by one and adding the
    9317                 :             :              * divisor to the remainder until the remainder is positive.  We
    9318                 :             :              * expect the quotient to be off by at most one, which has been
    9319                 :             :              * borne out in all testing, but not conclusively proven, so we
    9320                 :             :              * allow for larger corrections, just in case.
    9321                 :             :              */
    9322                 :             :             do
    9323                 :             :             {
    9324                 :             :                 /* Add the divisor to the remainder */
    9325                 :           5 :                 carry = 0;
    9326         [ +  + ]:          65 :                 for (i = var2ndigitpairs - 1; i > 0; i--)
    9327                 :             :                 {
    9328                 :          60 :                     newdig = remainder[i] + divisor[i] + carry;
    9329         [ -  + ]:          60 :                     if (newdig >= NBASE_SQR)
    9330                 :             :                     {
    9331                 :           0 :                         remainder[i] = newdig - NBASE_SQR;
    9332                 :           0 :                         carry = 1;
    9333                 :             :                     }
    9334                 :             :                     else
    9335                 :             :                     {
    9336                 :          60 :                         remainder[i] = newdig;
    9337                 :          60 :                         carry = 0;
    9338                 :             :                     }
    9339                 :             :                 }
    9340                 :           5 :                 remainder[0] += divisor[0] + carry;
    9341                 :             : 
    9342                 :             :                 /* Subtract 1 from the quotient (propagating carries later) */
    9343                 :           5 :                 dividend[qi - 1]--;
    9344                 :             : 
    9345         [ -  + ]:           5 :             } while (remainder[0] < 0);
    9346                 :             :         }
    9347                 :             :         else
    9348                 :             :         {
    9349                 :             :             /*
    9350                 :             :              * The remainder is nonnegative.  If it's greater than or equal to
    9351                 :             :              * the divisor, then the approximate quotient is too small and
    9352                 :             :              * must be corrected.  As above, we don't expect to have to apply
    9353                 :             :              * more than one correction, but allow for it just in case.
    9354                 :             :              */
    9355                 :             :             while (true)
    9356                 :           5 :             {
    9357                 :        2722 :                 bool        less = false;
    9358                 :             : 
    9359                 :             :                 /* Is remainder < divisor? */
    9360         [ +  + ]:        2737 :                 for (i = 0; i < var2ndigitpairs; i++)
    9361                 :             :                 {
    9362         [ +  + ]:        2732 :                     if (remainder[i] < divisor[i])
    9363                 :             :                     {
    9364                 :        2717 :                         less = true;
    9365                 :        2717 :                         break;
    9366                 :             :                     }
    9367         [ -  + ]:          15 :                     if (remainder[i] > divisor[i])
    9368                 :           0 :                         break;  /* remainder > divisor */
    9369                 :             :                 }
    9370         [ +  + ]:        2722 :                 if (less)
    9371                 :        2717 :                     break;      /* quotient is correct */
    9372                 :             : 
    9373                 :             :                 /* Subtract the divisor from the remainder */
    9374                 :           5 :                 carry = 0;
    9375         [ +  + ]:          15 :                 for (i = var2ndigitpairs - 1; i > 0; i--)
    9376                 :             :                 {
    9377                 :          10 :                     newdig = remainder[i] - divisor[i] + carry;
    9378         [ -  + ]:          10 :                     if (newdig < 0)
    9379                 :             :                     {
    9380                 :           0 :                         remainder[i] = newdig + NBASE_SQR;
    9381                 :           0 :                         carry = -1;
    9382                 :             :                     }
    9383                 :             :                     else
    9384                 :             :                     {
    9385                 :          10 :                         remainder[i] = newdig;
    9386                 :          10 :                         carry = 0;
    9387                 :             :                     }
    9388                 :             :                 }
    9389                 :           5 :                 remainder[0] = remainder[0] - divisor[0] + carry;
    9390                 :             : 
    9391                 :             :                 /* Add 1 to the quotient (propagating carries later) */
    9392                 :           5 :                 dividend[qi - 1]++;
    9393                 :             :             }
    9394                 :             :         }
    9395                 :             :     }
    9396                 :             : 
    9397                 :             :     /*
    9398                 :             :      * Because the quotient digits were estimates that might have been off by
    9399                 :             :      * one (and we didn't bother propagating carries when adjusting the
    9400                 :             :      * quotient above), some quotient digits might be out of range, so do a
    9401                 :             :      * final carry propagation pass to normalize back to base NBASE^2, and
    9402                 :             :      * construct the base-NBASE result digits.  Note that this is still done
    9403                 :             :      * at full precision w/guard digits.
    9404                 :             :      */
    9405                 :        3968 :     alloc_var(result, res_ndigits);
    9406                 :        3968 :     res_digits = result->digits;
    9407                 :        3968 :     carry = 0;
    9408         [ +  + ]:       36464 :     for (i = res_ndigitpairs - 1; i >= 0; i--)
    9409                 :             :     {
    9410                 :       32496 :         newdig = dividend[i] + carry;
    9411         [ +  + ]:       32496 :         if (newdig < 0)
    9412                 :             :         {
    9413                 :           5 :             carry = -((-newdig - 1) / NBASE_SQR) - 1;
    9414                 :           5 :             newdig -= carry * NBASE_SQR;
    9415                 :             :         }
    9416         [ -  + ]:       32491 :         else if (newdig >= NBASE_SQR)
    9417                 :             :         {
    9418                 :           0 :             carry = newdig / NBASE_SQR;
    9419                 :           0 :             newdig -= carry * NBASE_SQR;
    9420                 :             :         }
    9421                 :             :         else
    9422                 :       32491 :             carry = 0;
    9423                 :       32496 :         res_digits[2 * i + 1] = (NumericDigit) ((uint32) newdig % NBASE);
    9424                 :       32496 :         res_digits[2 * i] = (NumericDigit) ((uint32) newdig / NBASE);
    9425                 :             :     }
    9426                 :             :     Assert(carry == 0);
    9427                 :             : 
    9428                 :        3968 :     pfree(dividend);
    9429                 :             : 
    9430                 :             :     /*
    9431                 :             :      * Finally, round or truncate the result to the requested precision.
    9432                 :             :      */
    9433                 :        3968 :     result->weight = res_weight;
    9434                 :        3968 :     result->sign = res_sign;
    9435                 :             : 
    9436                 :             :     /* Round or truncate to target rscale (and set result->dscale) */
    9437         [ +  + ]:        3968 :     if (round)
    9438                 :         658 :         round_var(result, rscale);
    9439                 :             :     else
    9440                 :        3310 :         trunc_var(result, rscale);
    9441                 :             : 
    9442                 :             :     /* Strip leading and trailing zeroes */
    9443                 :        3968 :     strip_var(result);
    9444                 :             : }
    9445                 :             : 
    9446                 :             : 
    9447                 :             : /*
    9448                 :             :  * div_var_int() -
    9449                 :             :  *
    9450                 :             :  *  Divide a numeric variable by a 32-bit integer with the specified weight.
    9451                 :             :  *  The quotient var / (ival * NBASE^ival_weight) is stored in result.
    9452                 :             :  */
    9453                 :             : static void
    9454                 :      389771 : div_var_int(const NumericVar *var, int ival, int ival_weight,
    9455                 :             :             NumericVar *result, int rscale, bool round)
    9456                 :             : {
    9457                 :      389771 :     NumericDigit *var_digits = var->digits;
    9458                 :      389771 :     int         var_ndigits = var->ndigits;
    9459                 :             :     int         res_sign;
    9460                 :             :     int         res_weight;
    9461                 :             :     int         res_ndigits;
    9462                 :             :     NumericDigit *res_buf;
    9463                 :             :     NumericDigit *res_digits;
    9464                 :             :     uint32      divisor;
    9465                 :             :     int         i;
    9466                 :             : 
    9467                 :             :     /* Guard against division by zero */
    9468         [ -  + ]:      389771 :     if (ival == 0)
    9469         [ #  # ]:           0 :         ereport(ERROR,
    9470                 :             :                 errcode(ERRCODE_DIVISION_BY_ZERO),
    9471                 :             :                 errmsg("division by zero"));
    9472                 :             : 
    9473                 :             :     /* Result zero check */
    9474         [ +  + ]:      389771 :     if (var_ndigits == 0)
    9475                 :             :     {
    9476                 :        1583 :         zero_var(result);
    9477                 :        1583 :         result->dscale = rscale;
    9478                 :        1583 :         return;
    9479                 :             :     }
    9480                 :             : 
    9481                 :             :     /*
    9482                 :             :      * Determine the result sign, weight and number of digits to calculate.
    9483                 :             :      * The weight figured here is correct if the emitted quotient has no
    9484                 :             :      * leading zero digits; otherwise strip_var() will fix things up.
    9485                 :             :      */
    9486         [ +  + ]:      388188 :     if (var->sign == NUMERIC_POS)
    9487         [ +  + ]:      385944 :         res_sign = ival > 0 ? NUMERIC_POS : NUMERIC_NEG;
    9488                 :             :     else
    9489         [ +  + ]:        2244 :         res_sign = ival > 0 ? NUMERIC_NEG : NUMERIC_POS;
    9490                 :      388188 :     res_weight = var->weight - ival_weight;
    9491                 :             :     /* The number of accurate result digits we need to produce: */
    9492                 :      388188 :     res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
    9493                 :             :     /* ... but always at least 1 */
    9494                 :      388188 :     res_ndigits = Max(res_ndigits, 1);
    9495                 :             :     /* If rounding needed, figure one more digit to ensure correct result */
    9496         [ +  + ]:      388188 :     if (round)
    9497                 :      111703 :         res_ndigits++;
    9498                 :             : 
    9499                 :      388188 :     res_buf = digitbuf_alloc(res_ndigits + 1);
    9500                 :      388188 :     res_buf[0] = 0;             /* spare digit for later rounding */
    9501                 :      388188 :     res_digits = res_buf + 1;
    9502                 :             : 
    9503                 :             :     /*
    9504                 :             :      * Now compute the quotient digits.  This is the short division algorithm
    9505                 :             :      * described in Knuth volume 2, section 4.3.1 exercise 16, except that we
    9506                 :             :      * allow the divisor to exceed the internal base.
    9507                 :             :      *
    9508                 :             :      * In this algorithm, the carry from one digit to the next is at most
    9509                 :             :      * divisor - 1.  Therefore, while processing the next digit, carry may
    9510                 :             :      * become as large as divisor * NBASE - 1, and so it requires a 64-bit
    9511                 :             :      * integer if this exceeds UINT_MAX.
    9512                 :             :      */
    9513                 :      388188 :     divisor = abs(ival);
    9514                 :             : 
    9515         [ +  + ]:      388188 :     if (divisor <= UINT_MAX / NBASE)
    9516                 :             :     {
    9517                 :             :         /* carry cannot overflow 32 bits */
    9518                 :      386380 :         uint32      carry = 0;
    9519                 :             : 
    9520         [ +  + ]:     1914304 :         for (i = 0; i < res_ndigits; i++)
    9521                 :             :         {
    9522         [ +  + ]:     1527924 :             carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
    9523                 :     1527924 :             res_digits[i] = (NumericDigit) (carry / divisor);
    9524                 :     1527924 :             carry = carry % divisor;
    9525                 :             :         }
    9526                 :             :     }
    9527                 :             :     else
    9528                 :             :     {
    9529                 :             :         /* carry may exceed 32 bits */
    9530                 :        1808 :         uint64      carry = 0;
    9531                 :             : 
    9532         [ +  + ]:        5873 :         for (i = 0; i < res_ndigits; i++)
    9533                 :             :         {
    9534         [ +  + ]:        4065 :             carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
    9535                 :        4065 :             res_digits[i] = (NumericDigit) (carry / divisor);
    9536                 :        4065 :             carry = carry % divisor;
    9537                 :             :         }
    9538                 :             :     }
    9539                 :             : 
    9540                 :             :     /* Store the quotient in result */
    9541         [ +  + ]:      388188 :     digitbuf_free(result->buf);
    9542                 :      388188 :     result->ndigits = res_ndigits;
    9543                 :      388188 :     result->buf = res_buf;
    9544                 :      388188 :     result->digits = res_digits;
    9545                 :      388188 :     result->weight = res_weight;
    9546                 :      388188 :     result->sign = res_sign;
    9547                 :             : 
    9548                 :             :     /* Round or truncate to target rscale (and set result->dscale) */
    9549         [ +  + ]:      388188 :     if (round)
    9550                 :      111703 :         round_var(result, rscale);
    9551                 :             :     else
    9552                 :      276485 :         trunc_var(result, rscale);
    9553                 :             : 
    9554                 :             :     /* Strip leading/trailing zeroes */
    9555                 :      388188 :     strip_var(result);
    9556                 :             : }
    9557                 :             : 
    9558                 :             : 
    9559                 :             : #ifdef HAVE_INT128
    9560                 :             : /*
    9561                 :             :  * div_var_int64() -
    9562                 :             :  *
    9563                 :             :  *  Divide a numeric variable by a 64-bit integer with the specified weight.
    9564                 :             :  *  The quotient var / (ival * NBASE^ival_weight) is stored in result.
    9565                 :             :  *
    9566                 :             :  *  This duplicates the logic in div_var_int(), so any changes made there
    9567                 :             :  *  should be made here too.
    9568                 :             :  */
    9569                 :             : static void
    9570                 :         360 : div_var_int64(const NumericVar *var, int64 ival, int ival_weight,
    9571                 :             :               NumericVar *result, int rscale, bool round)
    9572                 :             : {
    9573                 :         360 :     NumericDigit *var_digits = var->digits;
    9574                 :         360 :     int         var_ndigits = var->ndigits;
    9575                 :             :     int         res_sign;
    9576                 :             :     int         res_weight;
    9577                 :             :     int         res_ndigits;
    9578                 :             :     NumericDigit *res_buf;
    9579                 :             :     NumericDigit *res_digits;
    9580                 :             :     uint64      divisor;
    9581                 :             :     int         i;
    9582                 :             : 
    9583                 :             :     /* Guard against division by zero */
    9584         [ -  + ]:         360 :     if (ival == 0)
    9585         [ #  # ]:           0 :         ereport(ERROR,
    9586                 :             :                 errcode(ERRCODE_DIVISION_BY_ZERO),
    9587                 :             :                 errmsg("division by zero"));
    9588                 :             : 
    9589                 :             :     /* Result zero check */
    9590         [ +  + ]:         360 :     if (var_ndigits == 0)
    9591                 :             :     {
    9592                 :          64 :         zero_var(result);
    9593                 :          64 :         result->dscale = rscale;
    9594                 :          64 :         return;
    9595                 :             :     }
    9596                 :             : 
    9597                 :             :     /*
    9598                 :             :      * Determine the result sign, weight and number of digits to calculate.
    9599                 :             :      * The weight figured here is correct if the emitted quotient has no
    9600                 :             :      * leading zero digits; otherwise strip_var() will fix things up.
    9601                 :             :      */
    9602         [ +  + ]:         296 :     if (var->sign == NUMERIC_POS)
    9603         [ +  + ]:         175 :         res_sign = ival > 0 ? NUMERIC_POS : NUMERIC_NEG;
    9604                 :             :     else
    9605         [ +  + ]:         121 :         res_sign = ival > 0 ? NUMERIC_NEG : NUMERIC_POS;
    9606                 :         296 :     res_weight = var->weight - ival_weight;
    9607                 :             :     /* The number of accurate result digits we need to produce: */
    9608                 :         296 :     res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
    9609                 :             :     /* ... but always at least 1 */
    9610                 :         296 :     res_ndigits = Max(res_ndigits, 1);
    9611                 :             :     /* If rounding needed, figure one more digit to ensure correct result */
    9612         [ +  + ]:         296 :     if (round)
    9613                 :         291 :         res_ndigits++;
    9614                 :             : 
    9615                 :         296 :     res_buf = digitbuf_alloc(res_ndigits + 1);
    9616                 :         296 :     res_buf[0] = 0;             /* spare digit for later rounding */
    9617                 :         296 :     res_digits = res_buf + 1;
    9618                 :             : 
    9619                 :             :     /*
    9620                 :             :      * Now compute the quotient digits.  This is the short division algorithm
    9621                 :             :      * described in Knuth volume 2, section 4.3.1 exercise 16, except that we
    9622                 :             :      * allow the divisor to exceed the internal base.
    9623                 :             :      *
    9624                 :             :      * In this algorithm, the carry from one digit to the next is at most
    9625                 :             :      * divisor - 1.  Therefore, while processing the next digit, carry may
    9626                 :             :      * become as large as divisor * NBASE - 1, and so it requires a 128-bit
    9627                 :             :      * integer if this exceeds PG_UINT64_MAX.
    9628                 :             :      */
    9629                 :         296 :     divisor = i64abs(ival);
    9630                 :             : 
    9631         [ +  + ]:         296 :     if (divisor <= PG_UINT64_MAX / NBASE)
    9632                 :             :     {
    9633                 :             :         /* carry cannot overflow 64 bits */
    9634                 :         232 :         uint64      carry = 0;
    9635                 :             : 
    9636         [ +  + ]:        2361 :         for (i = 0; i < res_ndigits; i++)
    9637                 :             :         {
    9638         [ +  + ]:        2129 :             carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
    9639                 :        2129 :             res_digits[i] = (NumericDigit) (carry / divisor);
    9640                 :        2129 :             carry = carry % divisor;
    9641                 :             :         }
    9642                 :             :     }
    9643                 :             :     else
    9644                 :             :     {
    9645                 :             :         /* carry may exceed 64 bits */
    9646                 :          64 :         uint128     carry = 0;
    9647                 :             : 
    9648         [ +  + ]:         688 :         for (i = 0; i < res_ndigits; i++)
    9649                 :             :         {
    9650         [ +  + ]:         624 :             carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
    9651                 :         624 :             res_digits[i] = (NumericDigit) (carry / divisor);
    9652                 :         624 :             carry = carry % divisor;
    9653                 :             :         }
    9654                 :             :     }
    9655                 :             : 
    9656                 :             :     /* Store the quotient in result */
    9657         [ +  + ]:         296 :     digitbuf_free(result->buf);
    9658                 :         296 :     result->ndigits = res_ndigits;
    9659                 :         296 :     result->buf = res_buf;
    9660                 :         296 :     result->digits = res_digits;
    9661                 :         296 :     result->weight = res_weight;
    9662                 :         296 :     result->sign = res_sign;
    9663                 :             : 
    9664                 :             :     /* Round or truncate to target rscale (and set result->dscale) */
    9665         [ +  + ]:         296 :     if (round)
    9666                 :         291 :         round_var(result, rscale);
    9667                 :             :     else
    9668                 :           5 :         trunc_var(result, rscale);
    9669                 :             : 
    9670                 :             :     /* Strip leading/trailing zeroes */
    9671                 :         296 :     strip_var(result);
    9672                 :             : }
    9673                 :             : #endif
    9674                 :             : 
    9675                 :             : 
    9676                 :             : /*
    9677                 :             :  * Default scale selection for division
    9678                 :             :  *
    9679                 :             :  * Returns the appropriate result scale for the division result.
    9680                 :             :  */
    9681                 :             : static int
    9682                 :       99382 : select_div_scale(const NumericVar *var1, const NumericVar *var2)
    9683                 :             : {
    9684                 :             :     int         weight1,
    9685                 :             :                 weight2,
    9686                 :             :                 qweight,
    9687                 :             :                 i;
    9688                 :             :     NumericDigit firstdigit1,
    9689                 :             :                 firstdigit2;
    9690                 :             :     int         rscale;
    9691                 :             : 
    9692                 :             :     /*
    9693                 :             :      * The result scale of a division isn't specified in any SQL standard. For
    9694                 :             :      * PostgreSQL we select a result scale that will give at least
    9695                 :             :      * NUMERIC_MIN_SIG_DIGITS significant digits, so that numeric gives a
    9696                 :             :      * result no less accurate than float8; but use a scale not less than
    9697                 :             :      * either input's display scale.
    9698                 :             :      */
    9699                 :             : 
    9700                 :             :     /* Get the actual (normalized) weight and first digit of each input */
    9701                 :             : 
    9702                 :       99382 :     weight1 = 0;                /* values to use if var1 is zero */
    9703                 :       99382 :     firstdigit1 = 0;
    9704         [ +  + ]:       99382 :     for (i = 0; i < var1->ndigits; i++)
    9705                 :             :     {
    9706                 :       98249 :         firstdigit1 = var1->digits[i];
    9707         [ +  - ]:       98249 :         if (firstdigit1 != 0)
    9708                 :             :         {
    9709                 :       98249 :             weight1 = var1->weight - i;
    9710                 :       98249 :             break;
    9711                 :             :         }
    9712                 :             :     }
    9713                 :             : 
    9714                 :       99382 :     weight2 = 0;                /* values to use if var2 is zero */
    9715                 :       99382 :     firstdigit2 = 0;
    9716         [ +  + ]:       99382 :     for (i = 0; i < var2->ndigits; i++)
    9717                 :             :     {
    9718                 :       99349 :         firstdigit2 = var2->digits[i];
    9719         [ +  - ]:       99349 :         if (firstdigit2 != 0)
    9720                 :             :         {
    9721                 :       99349 :             weight2 = var2->weight - i;
    9722                 :       99349 :             break;
    9723                 :             :         }
    9724                 :             :     }
    9725                 :             : 
    9726                 :             :     /*
    9727                 :             :      * Estimate weight of quotient.  If the two first digits are equal, we
    9728                 :             :      * can't be sure, but assume that var1 is less than var2.
    9729                 :             :      */
    9730                 :       99382 :     qweight = weight1 - weight2;
    9731         [ +  + ]:       99382 :     if (firstdigit1 <= firstdigit2)
    9732                 :       88549 :         qweight--;
    9733                 :             : 
    9734                 :             :     /* Select result scale */
    9735                 :       99382 :     rscale = NUMERIC_MIN_SIG_DIGITS - qweight * DEC_DIGITS;
    9736                 :       99382 :     rscale = Max(rscale, var1->dscale);
    9737                 :       99382 :     rscale = Max(rscale, var2->dscale);
    9738                 :       99382 :     rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
    9739                 :       99382 :     rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
    9740                 :             : 
    9741                 :       99382 :     return rscale;
    9742                 :             : }
    9743                 :             : 
    9744                 :             : 
    9745                 :             : /*
    9746                 :             :  * mod_var() -
    9747                 :             :  *
    9748                 :             :  *  Calculate the modulo of two numerics at variable level
    9749                 :             :  */
    9750                 :             : static void
    9751                 :      275449 : mod_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
    9752                 :             : {
    9753                 :             :     NumericVar  tmp;
    9754                 :             : 
    9755                 :      275449 :     init_var(&tmp);
    9756                 :             : 
    9757                 :             :     /* ---------
    9758                 :             :      * We do this using the equation
    9759                 :             :      *      mod(x,y) = x - trunc(x/y)*y
    9760                 :             :      * div_var can be persuaded to give us trunc(x/y) directly.
    9761                 :             :      * ----------
    9762                 :             :      */
    9763                 :      275449 :     div_var(var1, var2, &tmp, 0, false, true);
    9764                 :             : 
    9765                 :      275449 :     mul_var(var2, &tmp, &tmp, var2->dscale);
    9766                 :             : 
    9767                 :      275449 :     sub_var(var1, &tmp, result);
    9768                 :             : 
    9769                 :      275449 :     free_var(&tmp);
    9770                 :      275449 : }
    9771                 :             : 
    9772                 :             : 
    9773                 :             : /*
    9774                 :             :  * div_mod_var() -
    9775                 :             :  *
    9776                 :             :  *  Calculate the truncated integer quotient and numeric remainder of two
    9777                 :             :  *  numeric variables.  The remainder is precise to var2's dscale.
    9778                 :             :  */
    9779                 :             : static void
    9780                 :        3295 : div_mod_var(const NumericVar *var1, const NumericVar *var2,
    9781                 :             :             NumericVar *quot, NumericVar *rem)
    9782                 :             : {
    9783                 :             :     NumericVar  q;
    9784                 :             :     NumericVar  r;
    9785                 :             : 
    9786                 :        3295 :     init_var(&q);
    9787                 :        3295 :     init_var(&r);
    9788                 :             : 
    9789                 :             :     /*
    9790                 :             :      * Use div_var() with exact = false to get an initial estimate for the
    9791                 :             :      * integer quotient (truncated towards zero).  This might be slightly
    9792                 :             :      * inaccurate, but we correct it below.
    9793                 :             :      */
    9794                 :        3295 :     div_var(var1, var2, &q, 0, false, false);
    9795                 :             : 
    9796                 :             :     /* Compute initial estimate of remainder using the quotient estimate. */
    9797                 :        3295 :     mul_var(var2, &q, &r, var2->dscale);
    9798                 :        3295 :     sub_var(var1, &r, &r);
    9799                 :             : 
    9800                 :             :     /*
    9801                 :             :      * Adjust the results if necessary --- the remainder should have the same
    9802                 :             :      * sign as var1, and its absolute value should be less than the absolute
    9803                 :             :      * value of var2.
    9804                 :             :      */
    9805   [ +  -  -  + ]:        3295 :     while (r.ndigits != 0 && r.sign != var1->sign)
    9806                 :             :     {
    9807                 :             :         /* The absolute value of the quotient is too large */
    9808         [ #  # ]:           0 :         if (var1->sign == var2->sign)
    9809                 :             :         {
    9810                 :           0 :             sub_var(&q, &const_one, &q);
    9811                 :           0 :             add_var(&r, var2, &r);
    9812                 :             :         }
    9813                 :             :         else
    9814                 :             :         {
    9815                 :           0 :             add_var(&q, &const_one, &q);
    9816                 :           0 :             sub_var(&r, var2, &r);
    9817                 :             :         }
    9818                 :             :     }
    9819                 :             : 
    9820         [ -  + ]:        3295 :     while (cmp_abs(&r, var2) >= 0)
    9821                 :             :     {
    9822                 :             :         /* The absolute value of the quotient is too small */
    9823         [ #  # ]:           0 :         if (var1->sign == var2->sign)
    9824                 :             :         {
    9825                 :           0 :             add_var(&q, &const_one, &q);
    9826                 :           0 :             sub_var(&r, var2, &r);
    9827                 :             :         }
    9828                 :             :         else
    9829                 :             :         {
    9830                 :           0 :             sub_var(&q, &const_one, &q);
    9831                 :           0 :             add_var(&r, var2, &r);
    9832                 :             :         }
    9833                 :             :     }
    9834                 :             : 
    9835                 :        3295 :     set_var_from_var(&q, quot);
    9836                 :        3295 :     set_var_from_var(&r, rem);
    9837                 :             : 
    9838                 :        3295 :     free_var(&q);
    9839                 :        3295 :     free_var(&r);
    9840                 :        3295 : }
    9841                 :             : 
    9842                 :             : 
    9843                 :             : /*
    9844                 :             :  * ceil_var() -
    9845                 :             :  *
    9846                 :             :  *  Return the smallest integer greater than or equal to the argument
    9847                 :             :  *  on variable level
    9848                 :             :  */
    9849                 :             : static void
    9850                 :         136 : ceil_var(const NumericVar *var, NumericVar *result)
    9851                 :             : {
    9852                 :             :     NumericVar  tmp;
    9853                 :             : 
    9854                 :         136 :     init_var(&tmp);
    9855                 :         136 :     set_var_from_var(var, &tmp);
    9856                 :             : 
    9857                 :         136 :     trunc_var(&tmp, 0);
    9858                 :             : 
    9859   [ +  +  +  + ]:         136 :     if (var->sign == NUMERIC_POS && cmp_var(var, &tmp) != 0)
    9860                 :          40 :         add_var(&tmp, &const_one, &tmp);
    9861                 :             : 
    9862                 :         136 :     set_var_from_var(&tmp, result);
    9863                 :         136 :     free_var(&tmp);
    9864                 :         136 : }
    9865                 :             : 
    9866                 :             : 
    9867                 :             : /*
    9868                 :             :  * floor_var() -
    9869                 :             :  *
    9870                 :             :  *  Return the largest integer equal to or less than the argument
    9871                 :             :  *  on variable level
    9872                 :             :  */
    9873                 :             : static void
    9874                 :          72 : floor_var(const NumericVar *var, NumericVar *result)
    9875                 :             : {
    9876                 :             :     NumericVar  tmp;
    9877                 :             : 
    9878                 :          72 :     init_var(&tmp);
    9879                 :          72 :     set_var_from_var(var, &tmp);
    9880                 :             : 
    9881                 :          72 :     trunc_var(&tmp, 0);
    9882                 :             : 
    9883   [ +  +  +  + ]:          72 :     if (var->sign == NUMERIC_NEG && cmp_var(var, &tmp) != 0)
    9884                 :          20 :         sub_var(&tmp, &const_one, &tmp);
    9885                 :             : 
    9886                 :          72 :     set_var_from_var(&tmp, result);
    9887                 :          72 :     free_var(&tmp);
    9888                 :          72 : }
    9889                 :             : 
    9890                 :             : 
    9891                 :             : /*
    9892                 :             :  * gcd_var() -
    9893                 :             :  *
    9894                 :             :  *  Calculate the greatest common divisor of two numerics at variable level
    9895                 :             :  */
    9896                 :             : static void
    9897                 :         148 : gcd_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
    9898                 :             : {
    9899                 :             :     int         res_dscale;
    9900                 :             :     int         cmp;
    9901                 :             :     NumericVar  tmp_arg;
    9902                 :             :     NumericVar  mod;
    9903                 :             : 
    9904                 :         148 :     res_dscale = Max(var1->dscale, var2->dscale);
    9905                 :             : 
    9906                 :             :     /*
    9907                 :             :      * Arrange for var1 to be the number with the greater absolute value.
    9908                 :             :      *
    9909                 :             :      * This would happen automatically in the loop below, but avoids an
    9910                 :             :      * expensive modulo operation.
    9911                 :             :      */
    9912                 :         148 :     cmp = cmp_abs(var1, var2);
    9913         [ +  + ]:         148 :     if (cmp < 0)
    9914                 :             :     {
    9915                 :          56 :         const NumericVar *tmp = var1;
    9916                 :             : 
    9917                 :          56 :         var1 = var2;
    9918                 :          56 :         var2 = tmp;
    9919                 :             :     }
    9920                 :             : 
    9921                 :             :     /*
    9922                 :             :      * Also avoid the taking the modulo if the inputs have the same absolute
    9923                 :             :      * value, or if the smaller input is zero.
    9924                 :             :      */
    9925   [ +  +  +  + ]:         148 :     if (cmp == 0 || var2->ndigits == 0)
    9926                 :             :     {
    9927                 :          48 :         set_var_from_var(var1, result);
    9928                 :          48 :         result->sign = NUMERIC_POS;
    9929                 :          48 :         result->dscale = res_dscale;
    9930                 :          48 :         return;
    9931                 :             :     }
    9932                 :             : 
    9933                 :         100 :     init_var(&tmp_arg);
    9934                 :         100 :     init_var(&mod);
    9935                 :             : 
    9936                 :             :     /* Use the Euclidean algorithm to find the GCD */
    9937                 :         100 :     set_var_from_var(var1, &tmp_arg);
    9938                 :         100 :     set_var_from_var(var2, result);
    9939                 :             : 
    9940                 :             :     for (;;)
    9941                 :             :     {
    9942                 :             :         /* this loop can take a while, so allow it to be interrupted */
    9943         [ -  + ]:         392 :         CHECK_FOR_INTERRUPTS();
    9944                 :             : 
    9945                 :         392 :         mod_var(&tmp_arg, result, &mod);
    9946         [ +  + ]:         392 :         if (mod.ndigits == 0)
    9947                 :         100 :             break;
    9948                 :         292 :         set_var_from_var(result, &tmp_arg);
    9949                 :         292 :         set_var_from_var(&mod, result);
    9950                 :             :     }
    9951                 :         100 :     result->sign = NUMERIC_POS;
    9952                 :         100 :     result->dscale = res_dscale;
    9953                 :             : 
    9954                 :         100 :     free_var(&tmp_arg);
    9955                 :         100 :     free_var(&mod);
    9956                 :             : }
    9957                 :             : 
    9958                 :             : 
    9959                 :             : /*
    9960                 :             :  * sqrt_var() -
    9961                 :             :  *
    9962                 :             :  *  Compute the square root of x using the Karatsuba Square Root algorithm.
    9963                 :             :  *  NOTE: we allow rscale < 0 here, implying rounding before the decimal
    9964                 :             :  *  point.
    9965                 :             :  */
    9966                 :             : static void
    9967                 :        3048 : sqrt_var(const NumericVar *arg, NumericVar *result, int rscale)
    9968                 :             : {
    9969                 :             :     int         stat;
    9970                 :             :     int         res_weight;
    9971                 :             :     int         res_ndigits;
    9972                 :             :     int         src_ndigits;
    9973                 :             :     int         step;
    9974                 :             :     int         ndigits[32];
    9975                 :             :     int         blen;
    9976                 :             :     int64       arg_int64;
    9977                 :             :     int         src_idx;
    9978                 :             :     int64       s_int64;
    9979                 :             :     int64       r_int64;
    9980                 :             :     NumericVar  s_var;
    9981                 :             :     NumericVar  r_var;
    9982                 :             :     NumericVar  a0_var;
    9983                 :             :     NumericVar  a1_var;
    9984                 :             :     NumericVar  q_var;
    9985                 :             :     NumericVar  u_var;
    9986                 :             : 
    9987                 :        3048 :     stat = cmp_var(arg, &const_zero);
    9988         [ +  + ]:        3048 :     if (stat == 0)
    9989                 :             :     {
    9990                 :          12 :         zero_var(result);
    9991                 :          12 :         result->dscale = rscale;
    9992                 :          12 :         return;
    9993                 :             :     }
    9994                 :             : 
    9995                 :             :     /*
    9996                 :             :      * SQL2003 defines sqrt() in terms of power, so we need to emit the right
    9997                 :             :      * SQLSTATE error code if the operand is negative.
    9998                 :             :      */
    9999         [ +  + ]:        3036 :     if (stat < 0)
   10000         [ +  - ]:           4 :         ereport(ERROR,
   10001                 :             :                 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
   10002                 :             :                  errmsg("cannot take square root of a negative number")));
   10003                 :             : 
   10004                 :        3032 :     init_var(&s_var);
   10005                 :        3032 :     init_var(&r_var);
   10006                 :        3032 :     init_var(&a0_var);
   10007                 :        3032 :     init_var(&a1_var);
   10008                 :        3032 :     init_var(&q_var);
   10009                 :        3032 :     init_var(&u_var);
   10010                 :             : 
   10011                 :             :     /*
   10012                 :             :      * The result weight is half the input weight, rounded towards minus
   10013                 :             :      * infinity --- res_weight = floor(arg->weight / 2).
   10014                 :             :      */
   10015         [ +  + ]:        3032 :     if (arg->weight >= 0)
   10016                 :        2761 :         res_weight = arg->weight / 2;
   10017                 :             :     else
   10018                 :         271 :         res_weight = -((-arg->weight - 1) / 2 + 1);
   10019                 :             : 
   10020                 :             :     /*
   10021                 :             :      * Number of NBASE digits to compute.  To ensure correct rounding, compute
   10022                 :             :      * at least 1 extra decimal digit.  We explicitly allow rscale to be
   10023                 :             :      * negative here, but must always compute at least 1 NBASE digit.  Thus
   10024                 :             :      * res_ndigits = res_weight + 1 + ceil((rscale + 1) / DEC_DIGITS) or 1.
   10025                 :             :      */
   10026         [ +  - ]:        3032 :     if (rscale + 1 >= 0)
   10027                 :        3032 :         res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS) / DEC_DIGITS;
   10028                 :             :     else
   10029                 :           0 :         res_ndigits = res_weight + 1 - (-rscale - 1) / DEC_DIGITS;
   10030                 :        3032 :     res_ndigits = Max(res_ndigits, 1);
   10031                 :             : 
   10032                 :             :     /*
   10033                 :             :      * Number of source NBASE digits logically required to produce a result
   10034                 :             :      * with this precision --- every digit before the decimal point, plus 2
   10035                 :             :      * for each result digit after the decimal point (or minus 2 for each
   10036                 :             :      * result digit we round before the decimal point).
   10037                 :             :      */
   10038                 :        3032 :     src_ndigits = arg->weight + 1 + (res_ndigits - res_weight - 1) * 2;
   10039                 :        3032 :     src_ndigits = Max(src_ndigits, 1);
   10040                 :             : 
   10041                 :             :     /* ----------
   10042                 :             :      * From this point on, we treat the input and the result as integers and
   10043                 :             :      * compute the integer square root and remainder using the Karatsuba
   10044                 :             :      * Square Root algorithm, which may be written recursively as follows:
   10045                 :             :      *
   10046                 :             :      *  SqrtRem(n = a3*b^3 + a2*b^2 + a1*b + a0):
   10047                 :             :      *      [ for some base b, and coefficients a0,a1,a2,a3 chosen so that
   10048                 :             :      *        0 <= a0,a1,a2 < b and a3 >= b/4 ]
   10049                 :             :      *      Let (s,r) = SqrtRem(a3*b + a2)
   10050                 :             :      *      Let (q,u) = DivRem(r*b + a1, 2*s)
   10051                 :             :      *      Let s = s*b + q
   10052                 :             :      *      Let r = u*b + a0 - q^2
   10053                 :             :      *      If r < 0 Then
   10054                 :             :      *          Let r = r + s
   10055                 :             :      *          Let s = s - 1
   10056                 :             :      *          Let r = r + s
   10057                 :             :      *      Return (s,r)
   10058                 :             :      *
   10059                 :             :      * See "Karatsuba Square Root", Paul Zimmermann, INRIA Research Report
   10060                 :             :      * RR-3805, November 1999.  At the time of writing this was available
   10061                 :             :      * on the net at <https://hal.inria.fr/inria-00072854>.
   10062                 :             :      *
   10063                 :             :      * The way to read the assumption "n = a3*b^3 + a2*b^2 + a1*b + a0" is
   10064                 :             :      * "choose a base b such that n requires at least four base-b digits to
   10065                 :             :      * express; then those digits are a3,a2,a1,a0, with a3 possibly larger
   10066                 :             :      * than b".  For optimal performance, b should have approximately a
   10067                 :             :      * quarter the number of digits in the input, so that the outer square
   10068                 :             :      * root computes roughly twice as many digits as the inner one.  For
   10069                 :             :      * simplicity, we choose b = NBASE^blen, an integer power of NBASE.
   10070                 :             :      *
   10071                 :             :      * We implement the algorithm iteratively rather than recursively, to
   10072                 :             :      * allow the working variables to be reused.  With this approach, each
   10073                 :             :      * digit of the input is read precisely once --- src_idx tracks the number
   10074                 :             :      * of input digits used so far.
   10075                 :             :      *
   10076                 :             :      * The array ndigits[] holds the number of NBASE digits of the input that
   10077                 :             :      * will have been used at the end of each iteration, which roughly doubles
   10078                 :             :      * each time.  Note that the array elements are stored in reverse order,
   10079                 :             :      * so if the final iteration requires src_ndigits = 37 input digits, the
   10080                 :             :      * array will contain [37,19,11,7,5,3], and we would start by computing
   10081                 :             :      * the square root of the 3 most significant NBASE digits.
   10082                 :             :      *
   10083                 :             :      * In each iteration, we choose blen to be the largest integer for which
   10084                 :             :      * the input number has a3 >= b/4, when written in the form above.  In
   10085                 :             :      * general, this means blen = src_ndigits / 4 (truncated), but if
   10086                 :             :      * src_ndigits is a multiple of 4, that might lead to the coefficient a3
   10087                 :             :      * being less than b/4 (if the first input digit is less than NBASE/4), in
   10088                 :             :      * which case we choose blen = src_ndigits / 4 - 1.  The number of digits
   10089                 :             :      * in the inner square root is then src_ndigits - 2*blen.  So, for
   10090                 :             :      * example, if we have src_ndigits = 26 initially, the array ndigits[]
   10091                 :             :      * will be either [26,14,8,4] or [26,14,8,6,4], depending on the size of
   10092                 :             :      * the first input digit.
   10093                 :             :      *
   10094                 :             :      * Additionally, we can put an upper bound on the number of steps required
   10095                 :             :      * as follows --- suppose that the number of source digits is an n-bit
   10096                 :             :      * number in the range [2^(n-1), 2^n-1], then blen will be in the range
   10097                 :             :      * [2^(n-3)-1, 2^(n-2)-1] and the number of digits in the inner square
   10098                 :             :      * root will be in the range [2^(n-2), 2^(n-1)+1].  In the next step, blen
   10099                 :             :      * will be in the range [2^(n-4)-1, 2^(n-3)] and the number of digits in
   10100                 :             :      * the next inner square root will be in the range [2^(n-3), 2^(n-2)+1].
   10101                 :             :      * This pattern repeats, and in the worst case the array ndigits[] will
   10102                 :             :      * contain [2^n-1, 2^(n-1)+1, 2^(n-2)+1, ... 9, 5, 3], and the computation
   10103                 :             :      * will require n steps.  Therefore, since all digit array sizes are
   10104                 :             :      * signed 32-bit integers, the number of steps required is guaranteed to
   10105                 :             :      * be less than 32.
   10106                 :             :      * ----------
   10107                 :             :      */
   10108                 :        3032 :     step = 0;
   10109         [ +  + ]:       14531 :     while ((ndigits[step] = src_ndigits) > 4)
   10110                 :             :     {
   10111                 :             :         /* Choose b so that a3 >= b/4, as described above */
   10112                 :       11499 :         blen = src_ndigits / 4;
   10113   [ +  +  +  + ]:       11499 :         if (blen * 4 == src_ndigits && arg->digits[0] < NBASE / 4)
   10114                 :         259 :             blen--;
   10115                 :             : 
   10116                 :             :         /* Number of digits in the next step (inner square root) */
   10117                 :       11499 :         src_ndigits -= 2 * blen;
   10118                 :       11499 :         step++;
   10119                 :             :     }
   10120                 :             : 
   10121                 :             :     /*
   10122                 :             :      * First iteration (innermost square root and remainder):
   10123                 :             :      *
   10124                 :             :      * Here src_ndigits <= 4, and the input fits in an int64.  Its square root
   10125                 :             :      * has at most 9 decimal digits, so estimate it using double precision
   10126                 :             :      * arithmetic, which will in fact almost certainly return the correct
   10127                 :             :      * result with no further correction required.
   10128                 :             :      */
   10129                 :        3032 :     arg_int64 = arg->digits[0];
   10130         [ +  + ]:        9695 :     for (src_idx = 1; src_idx < src_ndigits; src_idx++)
   10131                 :             :     {
   10132                 :        6663 :         arg_int64 *= NBASE;
   10133         [ +  + ]:        6663 :         if (src_idx < arg->ndigits)
   10134                 :        5647 :             arg_int64 += arg->digits[src_idx];
   10135                 :             :     }
   10136                 :             : 
   10137                 :        3032 :     s_int64 = (int64) sqrt((double) arg_int64);
   10138                 :        3032 :     r_int64 = arg_int64 - s_int64 * s_int64;
   10139                 :             : 
   10140                 :             :     /*
   10141                 :             :      * Use Newton's method to correct the result, if necessary.
   10142                 :             :      *
   10143                 :             :      * This uses integer division with truncation to compute the truncated
   10144                 :             :      * integer square root by iterating using the formula x -> (x + n/x) / 2.
   10145                 :             :      * This is known to converge to isqrt(n), unless n+1 is a perfect square.
   10146                 :             :      * If n+1 is a perfect square, the sequence will oscillate between the two
   10147                 :             :      * values isqrt(n) and isqrt(n)+1, so we can be assured of convergence by
   10148                 :             :      * checking the remainder.
   10149                 :             :      */
   10150   [ -  +  -  + ]:        3032 :     while (r_int64 < 0 || r_int64 > 2 * s_int64)
   10151                 :             :     {
   10152                 :           0 :         s_int64 = (s_int64 + arg_int64 / s_int64) / 2;
   10153                 :           0 :         r_int64 = arg_int64 - s_int64 * s_int64;
   10154                 :             :     }
   10155                 :             : 
   10156                 :             :     /*
   10157                 :             :      * Iterations with src_ndigits <= 8:
   10158                 :             :      *
   10159                 :             :      * The next 1 or 2 iterations compute larger (outer) square roots with
   10160                 :             :      * src_ndigits <= 8, so the result still fits in an int64 (even though the
   10161                 :             :      * input no longer does) and we can continue to compute using int64
   10162                 :             :      * variables to avoid more expensive numeric computations.
   10163                 :             :      *
   10164                 :             :      * It is fairly easy to see that there is no risk of the intermediate
   10165                 :             :      * values below overflowing 64-bit integers.  In the worst case, the
   10166                 :             :      * previous iteration will have computed a 3-digit square root (of a
   10167                 :             :      * 6-digit input less than NBASE^6 / 4), so at the start of this
   10168                 :             :      * iteration, s will be less than NBASE^3 / 2 = 10^12 / 2, and r will be
   10169                 :             :      * less than 10^12.  In this case, blen will be 1, so numer will be less
   10170                 :             :      * than 10^17, and denom will be less than 10^12 (and hence u will also be
   10171                 :             :      * less than 10^12).  Finally, since q^2 = u*b + a0 - r, we can also be
   10172                 :             :      * sure that q^2 < 10^17.  Therefore all these quantities fit comfortably
   10173                 :             :      * in 64-bit integers.
   10174                 :             :      */
   10175                 :        3032 :     step--;
   10176   [ +  -  +  + ]:        7672 :     while (step >= 0 && (src_ndigits = ndigits[step]) <= 8)
   10177                 :             :     {
   10178                 :             :         int         b;
   10179                 :             :         int         a0;
   10180                 :             :         int         a1;
   10181                 :             :         int         i;
   10182                 :             :         int64       numer;
   10183                 :             :         int64       denom;
   10184                 :             :         int64       q;
   10185                 :             :         int64       u;
   10186                 :             : 
   10187                 :        4640 :         blen = (src_ndigits - src_idx) / 2;
   10188                 :             : 
   10189                 :             :         /* Extract a1 and a0, and compute b */
   10190                 :        4640 :         a0 = 0;
   10191                 :        4640 :         a1 = 0;
   10192                 :        4640 :         b = 1;
   10193                 :             : 
   10194         [ +  + ]:        9399 :         for (i = 0; i < blen; i++, src_idx++)
   10195                 :             :         {
   10196                 :        4759 :             b *= NBASE;
   10197                 :        4759 :             a1 *= NBASE;
   10198         [ +  + ]:        4759 :             if (src_idx < arg->ndigits)
   10199                 :        3532 :                 a1 += arg->digits[src_idx];
   10200                 :             :         }
   10201                 :             : 
   10202         [ +  + ]:        9399 :         for (i = 0; i < blen; i++, src_idx++)
   10203                 :             :         {
   10204                 :        4759 :             a0 *= NBASE;
   10205         [ +  + ]:        4759 :             if (src_idx < arg->ndigits)
   10206                 :        3420 :                 a0 += arg->digits[src_idx];
   10207                 :             :         }
   10208                 :             : 
   10209                 :             :         /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
   10210                 :        4640 :         numer = r_int64 * b + a1;
   10211                 :        4640 :         denom = 2 * s_int64;
   10212                 :        4640 :         q = numer / denom;
   10213                 :        4640 :         u = numer - q * denom;
   10214                 :             : 
   10215                 :             :         /* Compute s = s*b + q and r = u*b + a0 - q^2 */
   10216                 :        4640 :         s_int64 = s_int64 * b + q;
   10217                 :        4640 :         r_int64 = u * b + a0 - q * q;
   10218                 :             : 
   10219         [ +  + ]:        4640 :         if (r_int64 < 0)
   10220                 :             :         {
   10221                 :             :             /* s is too large by 1; set r += s, s--, r += s */
   10222                 :         161 :             r_int64 += s_int64;
   10223                 :         161 :             s_int64--;
   10224                 :         161 :             r_int64 += s_int64;
   10225                 :             :         }
   10226                 :             : 
   10227                 :             :         Assert(src_idx == src_ndigits); /* All input digits consumed */
   10228                 :        4640 :         step--;
   10229                 :             :     }
   10230                 :             : 
   10231                 :             :     /*
   10232                 :             :      * On platforms with 128-bit integer support, we can further delay the
   10233                 :             :      * need to use numeric variables.
   10234                 :             :      */
   10235                 :             : #ifdef HAVE_INT128
   10236         [ +  - ]:        3032 :     if (step >= 0)
   10237                 :             :     {
   10238                 :             :         int128      s_int128;
   10239                 :             :         int128      r_int128;
   10240                 :             : 
   10241                 :        3032 :         s_int128 = s_int64;
   10242                 :        3032 :         r_int128 = r_int64;
   10243                 :             : 
   10244                 :             :         /*
   10245                 :             :          * Iterations with src_ndigits <= 16:
   10246                 :             :          *
   10247                 :             :          * The result fits in an int128 (even though the input doesn't) so we
   10248                 :             :          * use int128 variables to avoid more expensive numeric computations.
   10249                 :             :          */
   10250   [ +  +  +  + ]:        6596 :         while (step >= 0 && (src_ndigits = ndigits[step]) <= 16)
   10251                 :             :         {
   10252                 :             :             int64       b;
   10253                 :             :             int64       a0;
   10254                 :             :             int64       a1;
   10255                 :             :             int64       i;
   10256                 :             :             int128      numer;
   10257                 :             :             int128      denom;
   10258                 :             :             int128      q;
   10259                 :             :             int128      u;
   10260                 :             : 
   10261                 :        3564 :             blen = (src_ndigits - src_idx) / 2;
   10262                 :             : 
   10263                 :             :             /* Extract a1 and a0, and compute b */
   10264                 :        3564 :             a0 = 0;
   10265                 :        3564 :             a1 = 0;
   10266                 :        3564 :             b = 1;
   10267                 :             : 
   10268         [ +  + ]:       11796 :             for (i = 0; i < blen; i++, src_idx++)
   10269                 :             :             {
   10270                 :        8232 :                 b *= NBASE;
   10271                 :        8232 :                 a1 *= NBASE;
   10272         [ +  + ]:        8232 :                 if (src_idx < arg->ndigits)
   10273                 :        4947 :                     a1 += arg->digits[src_idx];
   10274                 :             :             }
   10275                 :             : 
   10276         [ +  + ]:       11796 :             for (i = 0; i < blen; i++, src_idx++)
   10277                 :             :             {
   10278                 :        8232 :                 a0 *= NBASE;
   10279         [ +  + ]:        8232 :                 if (src_idx < arg->ndigits)
   10280                 :        3407 :                     a0 += arg->digits[src_idx];
   10281                 :             :             }
   10282                 :             : 
   10283                 :             :             /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
   10284                 :        3564 :             numer = r_int128 * b + a1;
   10285                 :        3564 :             denom = 2 * s_int128;
   10286                 :        3564 :             q = numer / denom;
   10287                 :        3564 :             u = numer - q * denom;
   10288                 :             : 
   10289                 :             :             /* Compute s = s*b + q and r = u*b + a0 - q^2 */
   10290                 :        3564 :             s_int128 = s_int128 * b + q;
   10291                 :        3564 :             r_int128 = u * b + a0 - q * q;
   10292                 :             : 
   10293         [ +  + ]:        3564 :             if (r_int128 < 0)
   10294                 :             :             {
   10295                 :             :                 /* s is too large by 1; set r += s, s--, r += s */
   10296                 :         146 :                 r_int128 += s_int128;
   10297                 :         146 :                 s_int128--;
   10298                 :         146 :                 r_int128 += s_int128;
   10299                 :             :             }
   10300                 :             : 
   10301                 :             :             Assert(src_idx == src_ndigits); /* All input digits consumed */
   10302                 :        3564 :             step--;
   10303                 :             :         }
   10304                 :             : 
   10305                 :             :         /*
   10306                 :             :          * All remaining iterations require numeric variables.  Convert the
   10307                 :             :          * integer values to NumericVar and continue.  Note that in the final
   10308                 :             :          * iteration we don't need the remainder, so we can save a few cycles
   10309                 :             :          * there by not fully computing it.
   10310                 :             :          */
   10311                 :        3032 :         int128_to_numericvar(s_int128, &s_var);
   10312         [ +  + ]:        3032 :         if (step >= 0)
   10313                 :        2008 :             int128_to_numericvar(r_int128, &r_var);
   10314                 :             :     }
   10315                 :             :     else
   10316                 :             :     {
   10317                 :           0 :         int64_to_numericvar(s_int64, &s_var);
   10318                 :             :         /* step < 0, so we certainly don't need r */
   10319                 :             :     }
   10320                 :             : #else                           /* !HAVE_INT128 */
   10321                 :             :     int64_to_numericvar(s_int64, &s_var);
   10322                 :             :     if (step >= 0)
   10323                 :             :         int64_to_numericvar(r_int64, &r_var);
   10324                 :             : #endif                          /* HAVE_INT128 */
   10325                 :             : 
   10326                 :             :     /*
   10327                 :             :      * The remaining iterations with src_ndigits > 8 (or 16, if have int128)
   10328                 :             :      * use numeric variables.
   10329                 :             :      */
   10330         [ +  + ]:        6327 :     while (step >= 0)
   10331                 :             :     {
   10332                 :             :         int         tmp_len;
   10333                 :             : 
   10334                 :        3295 :         src_ndigits = ndigits[step];
   10335                 :        3295 :         blen = (src_ndigits - src_idx) / 2;
   10336                 :             : 
   10337                 :             :         /* Extract a1 and a0 */
   10338         [ +  + ]:        3295 :         if (src_idx < arg->ndigits)
   10339                 :             :         {
   10340                 :        1088 :             tmp_len = Min(blen, arg->ndigits - src_idx);
   10341                 :        1088 :             alloc_var(&a1_var, tmp_len);
   10342                 :        1088 :             memcpy(a1_var.digits, arg->digits + src_idx,
   10343                 :             :                    tmp_len * sizeof(NumericDigit));
   10344                 :        1088 :             a1_var.weight = blen - 1;
   10345                 :        1088 :             a1_var.sign = NUMERIC_POS;
   10346                 :        1088 :             a1_var.dscale = 0;
   10347                 :        1088 :             strip_var(&a1_var);
   10348                 :             :         }
   10349                 :             :         else
   10350                 :             :         {
   10351                 :        2207 :             zero_var(&a1_var);
   10352                 :        2207 :             a1_var.dscale = 0;
   10353                 :             :         }
   10354                 :        3295 :         src_idx += blen;
   10355                 :             : 
   10356         [ +  + ]:        3295 :         if (src_idx < arg->ndigits)
   10357                 :             :         {
   10358                 :        1088 :             tmp_len = Min(blen, arg->ndigits - src_idx);
   10359                 :        1088 :             alloc_var(&a0_var, tmp_len);
   10360                 :        1088 :             memcpy(a0_var.digits, arg->digits + src_idx,
   10361                 :             :                    tmp_len * sizeof(NumericDigit));
   10362                 :        1088 :             a0_var.weight = blen - 1;
   10363                 :        1088 :             a0_var.sign = NUMERIC_POS;
   10364                 :        1088 :             a0_var.dscale = 0;
   10365                 :        1088 :             strip_var(&a0_var);
   10366                 :             :         }
   10367                 :             :         else
   10368                 :             :         {
   10369                 :        2207 :             zero_var(&a0_var);
   10370                 :        2207 :             a0_var.dscale = 0;
   10371                 :             :         }
   10372                 :        3295 :         src_idx += blen;
   10373                 :             : 
   10374                 :             :         /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
   10375                 :        3295 :         set_var_from_var(&r_var, &q_var);
   10376                 :        3295 :         q_var.weight += blen;
   10377                 :        3295 :         add_var(&q_var, &a1_var, &q_var);
   10378                 :        3295 :         add_var(&s_var, &s_var, &u_var);
   10379                 :        3295 :         div_mod_var(&q_var, &u_var, &q_var, &u_var);
   10380                 :             : 
   10381                 :             :         /* Compute s = s*b + q */
   10382                 :        3295 :         s_var.weight += blen;
   10383                 :        3295 :         add_var(&s_var, &q_var, &s_var);
   10384                 :             : 
   10385                 :             :         /*
   10386                 :             :          * Compute r = u*b + a0 - q^2.
   10387                 :             :          *
   10388                 :             :          * In the final iteration, we don't actually need r; we just need to
   10389                 :             :          * know whether it is negative, so that we know whether to adjust s.
   10390                 :             :          * So instead of the final subtraction we can just compare.
   10391                 :             :          */
   10392                 :        3295 :         u_var.weight += blen;
   10393                 :        3295 :         add_var(&u_var, &a0_var, &u_var);
   10394                 :        3295 :         mul_var(&q_var, &q_var, &q_var, 0);
   10395                 :             : 
   10396         [ +  + ]:        3295 :         if (step > 0)
   10397                 :             :         {
   10398                 :             :             /* Need r for later iterations */
   10399                 :        1287 :             sub_var(&u_var, &q_var, &r_var);
   10400         [ +  + ]:        1287 :             if (r_var.sign == NUMERIC_NEG)
   10401                 :             :             {
   10402                 :             :                 /* s is too large by 1; set r += s, s--, r += s */
   10403                 :          85 :                 add_var(&r_var, &s_var, &r_var);
   10404                 :          85 :                 sub_var(&s_var, &const_one, &s_var);
   10405                 :          85 :                 add_var(&r_var, &s_var, &r_var);
   10406                 :             :             }
   10407                 :             :         }
   10408                 :             :         else
   10409                 :             :         {
   10410                 :             :             /* Don't need r anymore, except to test if s is too large by 1 */
   10411         [ +  + ]:        2008 :             if (cmp_var(&u_var, &q_var) < 0)
   10412                 :          27 :                 sub_var(&s_var, &const_one, &s_var);
   10413                 :             :         }
   10414                 :             : 
   10415                 :             :         Assert(src_idx == src_ndigits); /* All input digits consumed */
   10416                 :        3295 :         step--;
   10417                 :             :     }
   10418                 :             : 
   10419                 :             :     /*
   10420                 :             :      * Construct the final result, rounding it to the requested precision.
   10421                 :             :      */
   10422                 :        3032 :     set_var_from_var(&s_var, result);
   10423                 :        3032 :     result->weight = res_weight;
   10424                 :        3032 :     result->sign = NUMERIC_POS;
   10425                 :             : 
   10426                 :             :     /* Round to target rscale (and set result->dscale) */
   10427                 :        3032 :     round_var(result, rscale);
   10428                 :             : 
   10429                 :             :     /* Strip leading and trailing zeroes */
   10430                 :        3032 :     strip_var(result);
   10431                 :             : 
   10432                 :        3032 :     free_var(&s_var);
   10433                 :        3032 :     free_var(&r_var);
   10434                 :        3032 :     free_var(&a0_var);
   10435                 :        3032 :     free_var(&a1_var);
   10436                 :        3032 :     free_var(&q_var);
   10437                 :        3032 :     free_var(&u_var);
   10438                 :             : }
   10439                 :             : 
   10440                 :             : 
   10441                 :             : /*
   10442                 :             :  * exp_var() -
   10443                 :             :  *
   10444                 :             :  *  Raise e to the power of x, computed to rscale fractional digits
   10445                 :             :  */
   10446                 :             : static void
   10447                 :         139 : exp_var(const NumericVar *arg, NumericVar *result, int rscale)
   10448                 :             : {
   10449                 :             :     NumericVar  x;
   10450                 :             :     NumericVar  elem;
   10451                 :             :     int         ni;
   10452                 :             :     double      val;
   10453                 :             :     int         dweight;
   10454                 :             :     int         ndiv2;
   10455                 :             :     int         sig_digits;
   10456                 :             :     int         local_rscale;
   10457                 :             : 
   10458                 :         139 :     init_var(&x);
   10459                 :         139 :     init_var(&elem);
   10460                 :             : 
   10461                 :         139 :     set_var_from_var(arg, &x);
   10462                 :             : 
   10463                 :             :     /*
   10464                 :             :      * Estimate the dweight of the result using floating point arithmetic, so
   10465                 :             :      * that we can choose an appropriate local rscale for the calculation.
   10466                 :             :      */
   10467                 :         139 :     val = numericvar_to_double_no_overflow(&x);
   10468                 :             : 
   10469                 :             :     /* Guard against overflow/underflow */
   10470                 :             :     /* If you change this limit, see also power_var()'s limit */
   10471         [ +  + ]:         139 :     if (fabs(val) >= NUMERIC_MAX_RESULT_SCALE * 3)
   10472                 :             :     {
   10473         [ -  + ]:           5 :         if (val > 0)
   10474         [ #  # ]:           0 :             ereport(ERROR,
   10475                 :             :                     (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
   10476                 :             :                      errmsg("value overflows numeric format")));
   10477                 :           5 :         zero_var(result);
   10478                 :           5 :         result->dscale = rscale;
   10479                 :           5 :         return;
   10480                 :             :     }
   10481                 :             : 
   10482                 :             :     /* decimal weight = log10(e^x) = x * log10(e) */
   10483                 :         134 :     dweight = (int) (val * 0.434294481903252);
   10484                 :             : 
   10485                 :             :     /*
   10486                 :             :      * Reduce x to the range -0.01 <= x <= 0.01 (approximately) by dividing by
   10487                 :             :      * 2^ndiv2, to improve the convergence rate of the Taylor series.
   10488                 :             :      *
   10489                 :             :      * Note that the overflow check above ensures that fabs(x) < 6000, which
   10490                 :             :      * means that ndiv2 <= 20 here.
   10491                 :             :      */
   10492         [ +  + ]:         134 :     if (fabs(val) > 0.01)
   10493                 :             :     {
   10494                 :         110 :         ndiv2 = 1;
   10495                 :         110 :         val /= 2;
   10496                 :             : 
   10497         [ +  + ]:        1402 :         while (fabs(val) > 0.01)
   10498                 :             :         {
   10499                 :        1292 :             ndiv2++;
   10500                 :        1292 :             val /= 2;
   10501                 :             :         }
   10502                 :             : 
   10503                 :         110 :         local_rscale = x.dscale + ndiv2;
   10504                 :         110 :         div_var_int(&x, 1 << ndiv2, 0, &x, local_rscale, true);
   10505                 :             :     }
   10506                 :             :     else
   10507                 :          24 :         ndiv2 = 0;
   10508                 :             : 
   10509                 :             :     /*
   10510                 :             :      * Set the scale for the Taylor series expansion.  The final result has
   10511                 :             :      * (dweight + rscale + 1) significant digits.  In addition, we have to
   10512                 :             :      * raise the Taylor series result to the power 2^ndiv2, which introduces
   10513                 :             :      * an error of up to around log10(2^ndiv2) digits, so work with this many
   10514                 :             :      * extra digits of precision (plus a few more for good measure).
   10515                 :             :      */
   10516                 :         134 :     sig_digits = 1 + dweight + rscale + (int) (ndiv2 * 0.301029995663981);
   10517                 :         134 :     sig_digits = Max(sig_digits, 0) + 8;
   10518                 :             : 
   10519                 :         134 :     local_rscale = sig_digits - 1;
   10520                 :             : 
   10521                 :             :     /*
   10522                 :             :      * Use the Taylor series
   10523                 :             :      *
   10524                 :             :      * exp(x) = 1 + x + x^2/2! + x^3/3! + ...
   10525                 :             :      *
   10526                 :             :      * Given the limited range of x, this should converge reasonably quickly.
   10527                 :             :      * We run the series until the terms fall below the local_rscale limit.
   10528                 :             :      */
   10529                 :         134 :     add_var(&const_one, &x, result);
   10530                 :             : 
   10531                 :         134 :     mul_var(&x, &x, &elem, local_rscale);
   10532                 :         134 :     ni = 2;
   10533                 :         134 :     div_var_int(&elem, ni, 0, &elem, local_rscale, true);
   10534                 :             : 
   10535         [ +  + ]:        3639 :     while (elem.ndigits != 0)
   10536                 :             :     {
   10537                 :        3505 :         add_var(result, &elem, result);
   10538                 :             : 
   10539                 :        3505 :         mul_var(&elem, &x, &elem, local_rscale);
   10540                 :        3505 :         ni++;
   10541                 :        3505 :         div_var_int(&elem, ni, 0, &elem, local_rscale, true);
   10542                 :             :     }
   10543                 :             : 
   10544                 :             :     /*
   10545                 :             :      * Compensate for the argument range reduction.  Since the weight of the
   10546                 :             :      * result doubles with each multiplication, we can reduce the local rscale
   10547                 :             :      * as we proceed.
   10548                 :             :      */
   10549         [ +  + ]:        1536 :     while (ndiv2-- > 0)
   10550                 :             :     {
   10551                 :        1402 :         local_rscale = sig_digits - result->weight * 2 * DEC_DIGITS;
   10552                 :        1402 :         local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
   10553                 :        1402 :         mul_var(result, result, result, local_rscale);
   10554                 :             :     }
   10555                 :             : 
   10556                 :             :     /* Round to requested rscale */
   10557                 :         134 :     round_var(result, rscale);
   10558                 :             : 
   10559                 :         134 :     free_var(&x);
   10560                 :         134 :     free_var(&elem);
   10561                 :             : }
   10562                 :             : 
   10563                 :             : 
   10564                 :             : /*
   10565                 :             :  * Estimate the dweight of the most significant decimal digit of the natural
   10566                 :             :  * logarithm of a number.
   10567                 :             :  *
   10568                 :             :  * Essentially, we're approximating log10(abs(ln(var))).  This is used to
   10569                 :             :  * determine the appropriate rscale when computing natural logarithms.
   10570                 :             :  *
   10571                 :             :  * Note: many callers call this before range-checking the input.  Therefore,
   10572                 :             :  * we must be robust against values that are invalid to apply ln() to.
   10573                 :             :  * We don't wish to throw an error here, so just return zero in such cases.
   10574                 :             :  */
   10575                 :             : static int
   10576                 :         534 : estimate_ln_dweight(const NumericVar *var)
   10577                 :             : {
   10578                 :             :     int         ln_dweight;
   10579                 :             : 
   10580                 :             :     /* Caller should fail on ln(negative), but for the moment return zero */
   10581         [ +  + ]:         534 :     if (var->sign != NUMERIC_POS)
   10582                 :          28 :         return 0;
   10583                 :             : 
   10584   [ +  +  +  + ]:         953 :     if (cmp_var(var, &const_zero_point_nine) >= 0 &&
   10585                 :         447 :         cmp_var(var, &const_one_point_one) <= 0)
   10586                 :          70 :     {
   10587                 :             :         /*
   10588                 :             :          * 0.9 <= var <= 1.1
   10589                 :             :          *
   10590                 :             :          * ln(var) has a negative weight (possibly very large).  To get a
   10591                 :             :          * reasonably accurate result, estimate it using ln(1+x) ~= x.
   10592                 :             :          */
   10593                 :             :         NumericVar  x;
   10594                 :             : 
   10595                 :          70 :         init_var(&x);
   10596                 :          70 :         sub_var(var, &const_one, &x);
   10597                 :             : 
   10598         [ +  + ]:          70 :         if (x.ndigits > 0)
   10599                 :             :         {
   10600                 :             :             /* Use weight of most significant decimal digit of x */
   10601                 :          35 :             ln_dweight = x.weight * DEC_DIGITS + (int) log10(x.digits[0]);
   10602                 :             :         }
   10603                 :             :         else
   10604                 :             :         {
   10605                 :             :             /* x = 0.  Since ln(1) = 0 exactly, we don't need extra digits */
   10606                 :          35 :             ln_dweight = 0;
   10607                 :             :         }
   10608                 :             : 
   10609                 :          70 :         free_var(&x);
   10610                 :             :     }
   10611                 :             :     else
   10612                 :             :     {
   10613                 :             :         /*
   10614                 :             :          * Estimate the logarithm using the first couple of digits from the
   10615                 :             :          * input number.  This will give an accurate result whenever the input
   10616                 :             :          * is not too close to 1.
   10617                 :             :          */
   10618         [ +  + ]:         436 :         if (var->ndigits > 0)
   10619                 :             :         {
   10620                 :             :             int         digits;
   10621                 :             :             int         dweight;
   10622                 :             :             double      ln_var;
   10623                 :             : 
   10624                 :         408 :             digits = var->digits[0];
   10625                 :         408 :             dweight = var->weight * DEC_DIGITS;
   10626                 :             : 
   10627         [ +  + ]:         408 :             if (var->ndigits > 1)
   10628                 :             :             {
   10629                 :         250 :                 digits = digits * NBASE + var->digits[1];
   10630                 :         250 :                 dweight -= DEC_DIGITS;
   10631                 :             :             }
   10632                 :             : 
   10633                 :             :             /*----------
   10634                 :             :              * We have var ~= digits * 10^dweight
   10635                 :             :              * so ln(var) ~= ln(digits) + dweight * ln(10)
   10636                 :             :              *----------
   10637                 :             :              */
   10638                 :         408 :             ln_var = log((double) digits) + dweight * 2.302585092994046;
   10639                 :         408 :             ln_dweight = (int) log10(fabs(ln_var));
   10640                 :             :         }
   10641                 :             :         else
   10642                 :             :         {
   10643                 :             :             /* Caller should fail on ln(0), but for the moment return zero */
   10644                 :          28 :             ln_dweight = 0;
   10645                 :             :         }
   10646                 :             :     }
   10647                 :             : 
   10648                 :         506 :     return ln_dweight;
   10649                 :             : }
   10650                 :             : 
   10651                 :             : 
   10652                 :             : /*
   10653                 :             :  * ln_var() -
   10654                 :             :  *
   10655                 :             :  *  Compute the natural log of x
   10656                 :             :  */
   10657                 :             : static void
   10658                 :         607 : ln_var(const NumericVar *arg, NumericVar *result, int rscale)
   10659                 :             : {
   10660                 :             :     NumericVar  x;
   10661                 :             :     NumericVar  xx;
   10662                 :             :     int         ni;
   10663                 :             :     NumericVar  elem;
   10664                 :             :     NumericVar  fact;
   10665                 :             :     int         nsqrt;
   10666                 :             :     int         local_rscale;
   10667                 :             :     int         cmp;
   10668                 :             : 
   10669                 :         607 :     cmp = cmp_var(arg, &const_zero);
   10670         [ +  + ]:         607 :     if (cmp == 0)
   10671         [ +  - ]:          28 :         ereport(ERROR,
   10672                 :             :                 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
   10673                 :             :                  errmsg("cannot take logarithm of zero")));
   10674         [ +  + ]:         579 :     else if (cmp < 0)
   10675         [ +  - ]:          24 :         ereport(ERROR,
   10676                 :             :                 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
   10677                 :             :                  errmsg("cannot take logarithm of a negative number")));
   10678                 :             : 
   10679                 :         555 :     init_var(&x);
   10680                 :         555 :     init_var(&xx);
   10681                 :         555 :     init_var(&elem);
   10682                 :         555 :     init_var(&fact);
   10683                 :             : 
   10684                 :         555 :     set_var_from_var(arg, &x);
   10685                 :         555 :     set_var_from_var(&const_two, &fact);
   10686                 :             : 
   10687                 :             :     /*
   10688                 :             :      * Reduce input into range 0.9 < x < 1.1 with repeated sqrt() operations.
   10689                 :             :      *
   10690                 :             :      * The final logarithm will have up to around rscale+6 significant digits.
   10691                 :             :      * Each sqrt() will roughly halve the weight of x, so adjust the local
   10692                 :             :      * rscale as we work so that we keep this many significant digits at each
   10693                 :             :      * step (plus a few more for good measure).
   10694                 :             :      *
   10695                 :             :      * Note that we allow local_rscale < 0 during this input reduction
   10696                 :             :      * process, which implies rounding before the decimal point.  sqrt_var()
   10697                 :             :      * explicitly supports this, and it significantly reduces the work
   10698                 :             :      * required to reduce very large inputs to the required range.  Once the
   10699                 :             :      * input reduction is complete, x.weight will be 0 and its display scale
   10700                 :             :      * will be non-negative again.
   10701                 :             :      */
   10702                 :         555 :     nsqrt = 0;
   10703         [ +  + ]:         826 :     while (cmp_var(&x, &const_zero_point_nine) <= 0)
   10704                 :             :     {
   10705                 :         271 :         local_rscale = rscale - x.weight * DEC_DIGITS / 2 + 8;
   10706                 :         271 :         sqrt_var(&x, &x, local_rscale);
   10707                 :         271 :         mul_var(&fact, &const_two, &fact, 0);
   10708                 :         271 :         nsqrt++;
   10709                 :             :     }
   10710         [ +  + ]:        2984 :     while (cmp_var(&x, &const_one_point_one) >= 0)
   10711                 :             :     {
   10712                 :        2429 :         local_rscale = rscale - x.weight * DEC_DIGITS / 2 + 8;
   10713                 :        2429 :         sqrt_var(&x, &x, local_rscale);
   10714                 :        2429 :         mul_var(&fact, &const_two, &fact, 0);
   10715                 :        2429 :         nsqrt++;
   10716                 :             :     }
   10717                 :             : 
   10718                 :             :     /*
   10719                 :             :      * We use the Taylor series for 0.5 * ln((1+z)/(1-z)),
   10720                 :             :      *
   10721                 :             :      * z + z^3/3 + z^5/5 + ...
   10722                 :             :      *
   10723                 :             :      * where z = (x-1)/(x+1) is in the range (approximately) -0.053 .. 0.048
   10724                 :             :      * due to the above range-reduction of x.
   10725                 :             :      *
   10726                 :             :      * The convergence of this is not as fast as one would like, but is
   10727                 :             :      * tolerable given that z is small.
   10728                 :             :      *
   10729                 :             :      * The Taylor series result will be multiplied by 2^(nsqrt+1), which has a
   10730                 :             :      * decimal weight of (nsqrt+1) * log10(2), so work with this many extra
   10731                 :             :      * digits of precision (plus a few more for good measure).
   10732                 :             :      */
   10733                 :         555 :     local_rscale = rscale + (int) ((nsqrt + 1) * 0.301029995663981) + 8;
   10734                 :             : 
   10735                 :         555 :     sub_var(&x, &const_one, result);
   10736                 :         555 :     add_var(&x, &const_one, &elem);
   10737                 :         555 :     div_var(result, &elem, result, local_rscale, true, false);
   10738                 :         555 :     set_var_from_var(result, &xx);
   10739                 :         555 :     mul_var(result, result, &x, local_rscale);
   10740                 :             : 
   10741                 :         555 :     ni = 1;
   10742                 :             : 
   10743                 :             :     for (;;)
   10744                 :             :     {
   10745                 :       10009 :         ni += 2;
   10746                 :       10009 :         mul_var(&xx, &x, &xx, local_rscale);
   10747                 :       10009 :         div_var_int(&xx, ni, 0, &elem, local_rscale, true);
   10748                 :             : 
   10749         [ +  + ]:       10009 :         if (elem.ndigits == 0)
   10750                 :         555 :             break;
   10751                 :             : 
   10752                 :        9454 :         add_var(result, &elem, result);
   10753                 :             : 
   10754         [ -  + ]:        9454 :         if (elem.weight < (result->weight - local_rscale * 2 / DEC_DIGITS))
   10755                 :           0 :             break;
   10756                 :             :     }
   10757                 :             : 
   10758                 :             :     /* Compensate for argument range reduction, round to requested rscale */
   10759                 :         555 :     mul_var(result, &fact, result, rscale);
   10760                 :             : 
   10761                 :         555 :     free_var(&x);
   10762                 :         555 :     free_var(&xx);
   10763                 :         555 :     free_var(&elem);
   10764                 :         555 :     free_var(&fact);
   10765                 :         555 : }
   10766                 :             : 
   10767                 :             : 
   10768                 :             : /*
   10769                 :             :  * log_var() -
   10770                 :             :  *
   10771                 :             :  *  Compute the logarithm of num in a given base.
   10772                 :             :  *
   10773                 :             :  *  Note: this routine chooses dscale of the result.
   10774                 :             :  */
   10775                 :             : static void
   10776                 :         156 : log_var(const NumericVar *base, const NumericVar *num, NumericVar *result)
   10777                 :             : {
   10778                 :             :     NumericVar  ln_base;
   10779                 :             :     NumericVar  ln_num;
   10780                 :             :     int         ln_base_dweight;
   10781                 :             :     int         ln_num_dweight;
   10782                 :             :     int         result_dweight;
   10783                 :             :     int         rscale;
   10784                 :             :     int         ln_base_rscale;
   10785                 :             :     int         ln_num_rscale;
   10786                 :             : 
   10787                 :         156 :     init_var(&ln_base);
   10788                 :         156 :     init_var(&ln_num);
   10789                 :             : 
   10790                 :             :     /* Estimated dweights of ln(base), ln(num) and the final result */
   10791                 :         156 :     ln_base_dweight = estimate_ln_dweight(base);
   10792                 :         156 :     ln_num_dweight = estimate_ln_dweight(num);
   10793                 :         156 :     result_dweight = ln_num_dweight - ln_base_dweight;
   10794                 :             : 
   10795                 :             :     /*
   10796                 :             :      * Select the scale of the result so that it will have at least
   10797                 :             :      * NUMERIC_MIN_SIG_DIGITS significant digits and is not less than either
   10798                 :             :      * input's display scale.
   10799                 :             :      */
   10800                 :         156 :     rscale = NUMERIC_MIN_SIG_DIGITS - result_dweight;
   10801                 :         156 :     rscale = Max(rscale, base->dscale);
   10802                 :         156 :     rscale = Max(rscale, num->dscale);
   10803                 :         156 :     rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
   10804                 :         156 :     rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
   10805                 :             : 
   10806                 :             :     /*
   10807                 :             :      * Set the scales for ln(base) and ln(num) so that they each have more
   10808                 :             :      * significant digits than the final result.
   10809                 :             :      */
   10810                 :         156 :     ln_base_rscale = rscale + result_dweight - ln_base_dweight + 8;
   10811                 :         156 :     ln_base_rscale = Max(ln_base_rscale, NUMERIC_MIN_DISPLAY_SCALE);
   10812                 :             : 
   10813                 :         156 :     ln_num_rscale = rscale + result_dweight - ln_num_dweight + 8;
   10814                 :         156 :     ln_num_rscale = Max(ln_num_rscale, NUMERIC_MIN_DISPLAY_SCALE);
   10815                 :             : 
   10816                 :             :     /* Form natural logarithms */
   10817                 :         156 :     ln_var(base, &ln_base, ln_base_rscale);
   10818                 :         140 :     ln_var(num, &ln_num, ln_num_rscale);
   10819                 :             : 
   10820                 :             :     /* Divide and round to the required scale */
   10821                 :         120 :     div_var(&ln_num, &ln_base, result, rscale, true, false);
   10822                 :             : 
   10823                 :         116 :     free_var(&ln_num);
   10824                 :         116 :     free_var(&ln_base);
   10825                 :         116 : }
   10826                 :             : 
   10827                 :             : 
   10828                 :             : /*
   10829                 :             :  * power_var() -
   10830                 :             :  *
   10831                 :             :  *  Raise base to the power of exp
   10832                 :             :  *
   10833                 :             :  *  Note: this routine chooses dscale of the result.
   10834                 :             :  */
   10835                 :             : static void
   10836                 :         968 : power_var(const NumericVar *base, const NumericVar *exp, NumericVar *result)
   10837                 :             : {
   10838                 :             :     int         res_sign;
   10839                 :             :     NumericVar  abs_base;
   10840                 :             :     NumericVar  ln_base;
   10841                 :             :     NumericVar  ln_num;
   10842                 :             :     int         ln_dweight;
   10843                 :             :     int         rscale;
   10844                 :             :     int         sig_digits;
   10845                 :             :     int         local_rscale;
   10846                 :             :     double      val;
   10847                 :             : 
   10848                 :             :     /* If exp can be represented as an integer, use power_var_int */
   10849   [ +  +  +  + ]:         968 :     if (exp->ndigits == 0 || exp->ndigits <= exp->weight + 1)
   10850                 :             :     {
   10851                 :             :         /* exact integer, but does it fit in int? */
   10852                 :             :         int64       expval64;
   10853                 :             : 
   10854         [ +  + ]:         878 :         if (numericvar_to_int64(exp, &expval64))
   10855                 :             :         {
   10856   [ +  -  +  + ]:         873 :             if (expval64 >= PG_INT32_MIN && expval64 <= PG_INT32_MAX)
   10857                 :             :             {
   10858                 :             :                 /* Okay, use power_var_int */
   10859                 :         848 :                 power_var_int(base, (int) expval64, exp->dscale, result);
   10860                 :         840 :                 return;
   10861                 :             :             }
   10862                 :             :         }
   10863                 :             :     }
   10864                 :             : 
   10865                 :             :     /*
   10866                 :             :      * This avoids log(0) for cases of 0 raised to a non-integer.  0 ^ 0 is
   10867                 :             :      * handled by power_var_int().
   10868                 :             :      */
   10869         [ +  + ]:         120 :     if (cmp_var(base, &const_zero) == 0)
   10870                 :             :     {
   10871                 :          14 :         set_var_from_var(&const_zero, result);
   10872                 :          14 :         result->dscale = NUMERIC_MIN_SIG_DIGITS; /* no need to round */
   10873                 :          14 :         return;
   10874                 :             :     }
   10875                 :             : 
   10876                 :         106 :     init_var(&abs_base);
   10877                 :         106 :     init_var(&ln_base);
   10878                 :         106 :     init_var(&ln_num);
   10879                 :             : 
   10880                 :             :     /*
   10881                 :             :      * If base is negative, insist that exp be an integer.  The result is then
   10882                 :             :      * positive if exp is even and negative if exp is odd.
   10883                 :             :      */
   10884         [ +  + ]:         106 :     if (base->sign == NUMERIC_NEG)
   10885                 :             :     {
   10886                 :             :         /*
   10887                 :             :          * Check that exp is an integer.  This error code is defined by the
   10888                 :             :          * SQL standard, and matches other errors in numeric_power().
   10889                 :             :          */
   10890   [ +  -  +  + ]:          27 :         if (exp->ndigits > 0 && exp->ndigits > exp->weight + 1)
   10891         [ +  - ]:          12 :             ereport(ERROR,
   10892                 :             :                     (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
   10893                 :             :                      errmsg("a negative number raised to a non-integer power yields a complex result")));
   10894                 :             : 
   10895                 :             :         /* Test if exp is odd or even */
   10896   [ +  -  +  + ]:          15 :         if (exp->ndigits > 0 && exp->ndigits == exp->weight + 1 &&
   10897         [ +  + ]:          10 :             (exp->digits[exp->ndigits - 1] & 1))
   10898                 :           5 :             res_sign = NUMERIC_NEG;
   10899                 :             :         else
   10900                 :          10 :             res_sign = NUMERIC_POS;
   10901                 :             : 
   10902                 :             :         /* Then work with abs(base) below */
   10903                 :          15 :         set_var_from_var(base, &abs_base);
   10904                 :          15 :         abs_base.sign = NUMERIC_POS;
   10905                 :          15 :         base = &abs_base;
   10906                 :             :     }
   10907                 :             :     else
   10908                 :          79 :         res_sign = NUMERIC_POS;
   10909                 :             : 
   10910                 :             :     /*----------
   10911                 :             :      * Decide on the scale for the ln() calculation.  For this we need an
   10912                 :             :      * estimate of the weight of the result, which we obtain by doing an
   10913                 :             :      * initial low-precision calculation of exp * ln(base).
   10914                 :             :      *
   10915                 :             :      * We want result = e ^ (exp * ln(base))
   10916                 :             :      * so result dweight = log10(result) = exp * ln(base) * log10(e)
   10917                 :             :      *
   10918                 :             :      * We also perform a crude overflow test here so that we can exit early if
   10919                 :             :      * the full-precision result is sure to overflow, and to guard against
   10920                 :             :      * integer overflow when determining the scale for the real calculation.
   10921                 :             :      * exp_var() supports inputs up to NUMERIC_MAX_RESULT_SCALE * 3, so the
   10922                 :             :      * result will overflow if exp * ln(base) >= NUMERIC_MAX_RESULT_SCALE * 3.
   10923                 :             :      * Since the values here are only approximations, we apply a small fuzz
   10924                 :             :      * factor to this overflow test and let exp_var() determine the exact
   10925                 :             :      * overflow threshold so that it is consistent for all inputs.
   10926                 :             :      *----------
   10927                 :             :      */
   10928                 :          94 :     ln_dweight = estimate_ln_dweight(base);
   10929                 :             : 
   10930                 :             :     /*
   10931                 :             :      * Set the scale for the low-precision calculation, computing ln(base) to
   10932                 :             :      * around 8 significant digits.  Note that ln_dweight may be as small as
   10933                 :             :      * -NUMERIC_DSCALE_MAX, so the scale may exceed NUMERIC_MAX_DISPLAY_SCALE
   10934                 :             :      * here.
   10935                 :             :      */
   10936                 :          94 :     local_rscale = 8 - ln_dweight;
   10937                 :          94 :     local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
   10938                 :             : 
   10939                 :          94 :     ln_var(base, &ln_base, local_rscale);
   10940                 :             : 
   10941                 :          94 :     mul_var(&ln_base, exp, &ln_num, local_rscale);
   10942                 :             : 
   10943                 :          94 :     val = numericvar_to_double_no_overflow(&ln_num);
   10944                 :             : 
   10945                 :             :     /* initial overflow/underflow test with fuzz factor */
   10946         [ +  + ]:          94 :     if (fabs(val) > NUMERIC_MAX_RESULT_SCALE * 3.01)
   10947                 :             :     {
   10948         [ -  + ]:           5 :         if (val > 0)
   10949         [ #  # ]:           0 :             ereport(ERROR,
   10950                 :             :                     (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
   10951                 :             :                      errmsg("value overflows numeric format")));
   10952                 :           5 :         zero_var(result);
   10953                 :           5 :         result->dscale = NUMERIC_MAX_DISPLAY_SCALE;
   10954                 :           5 :         return;
   10955                 :             :     }
   10956                 :             : 
   10957                 :          89 :     val *= 0.434294481903252;   /* approximate decimal result weight */
   10958                 :             : 
   10959                 :             :     /* choose the result scale */
   10960                 :          89 :     rscale = NUMERIC_MIN_SIG_DIGITS - (int) val;
   10961                 :          89 :     rscale = Max(rscale, base->dscale);
   10962                 :          89 :     rscale = Max(rscale, exp->dscale);
   10963                 :          89 :     rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
   10964                 :          89 :     rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
   10965                 :             : 
   10966                 :             :     /* significant digits required in the result */
   10967                 :          89 :     sig_digits = rscale + (int) val;
   10968                 :          89 :     sig_digits = Max(sig_digits, 0);
   10969                 :             : 
   10970                 :             :     /* set the scale for the real exp * ln(base) calculation */
   10971                 :          89 :     local_rscale = sig_digits - ln_dweight + 8;
   10972                 :          89 :     local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
   10973                 :             : 
   10974                 :             :     /* and do the real calculation */
   10975                 :             : 
   10976                 :          89 :     ln_var(base, &ln_base, local_rscale);
   10977                 :             : 
   10978                 :          89 :     mul_var(&ln_base, exp, &ln_num, local_rscale);
   10979                 :             : 
   10980                 :          89 :     exp_var(&ln_num, result, rscale);
   10981                 :             : 
   10982   [ +  +  +  - ]:          89 :     if (res_sign == NUMERIC_NEG && result->ndigits > 0)
   10983                 :           5 :         result->sign = NUMERIC_NEG;
   10984                 :             : 
   10985                 :          89 :     free_var(&ln_num);
   10986                 :          89 :     free_var(&ln_base);
   10987                 :          89 :     free_var(&abs_base);
   10988                 :             : }
   10989                 :             : 
   10990                 :             : /*
   10991                 :             :  * power_var_int() -
   10992                 :             :  *
   10993                 :             :  *  Raise base to the power of exp, where exp is an integer.
   10994                 :             :  *
   10995                 :             :  *  Note: this routine chooses dscale of the result.
   10996                 :             :  */
   10997                 :             : static void
   10998                 :         848 : power_var_int(const NumericVar *base, int exp, int exp_dscale,
   10999                 :             :               NumericVar *result)
   11000                 :             : {
   11001                 :             :     double      f;
   11002                 :             :     int         p;
   11003                 :             :     int         i;
   11004                 :             :     int         rscale;
   11005                 :             :     int         sig_digits;
   11006                 :             :     unsigned int mask;
   11007                 :             :     bool        neg;
   11008                 :             :     NumericVar  base_prod;
   11009                 :             :     int         local_rscale;
   11010                 :             : 
   11011                 :             :     /*
   11012                 :             :      * Choose the result scale.  For this we need an estimate of the decimal
   11013                 :             :      * weight of the result, which we obtain by approximating using double
   11014                 :             :      * precision arithmetic.
   11015                 :             :      *
   11016                 :             :      * We also perform crude overflow/underflow tests here so that we can exit
   11017                 :             :      * early if the result is sure to overflow/underflow, and to guard against
   11018                 :             :      * integer overflow when choosing the result scale.
   11019                 :             :      */
   11020         [ +  + ]:         848 :     if (base->ndigits != 0)
   11021                 :             :     {
   11022                 :             :         /*----------
   11023                 :             :          * Choose f (double) and p (int) such that base ~= f * 10^p.
   11024                 :             :          * Then log10(result) = log10(base^exp) ~= exp * (log10(f) + p).
   11025                 :             :          *----------
   11026                 :             :          */
   11027                 :         826 :         f = base->digits[0];
   11028                 :         826 :         p = base->weight * DEC_DIGITS;
   11029                 :             : 
   11030   [ +  +  +  - ]:         891 :         for (i = 1; i < base->ndigits && i * DEC_DIGITS < 16; i++)
   11031                 :             :         {
   11032                 :          65 :             f = f * NBASE + base->digits[i];
   11033                 :          65 :             p -= DEC_DIGITS;
   11034                 :             :         }
   11035                 :             : 
   11036                 :         826 :         f = exp * (log10(f) + p);   /* approximate decimal result weight */
   11037                 :             :     }
   11038                 :             :     else
   11039                 :          22 :         f = 0;                  /* result is 0 or 1 (weight 0), or error */
   11040                 :             : 
   11041                 :             :     /* overflow/underflow tests with fuzz factors */
   11042         [ +  + ]:         848 :     if (f > (NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS)
   11043         [ +  - ]:           8 :         ereport(ERROR,
   11044                 :             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
   11045                 :             :                  errmsg("value overflows numeric format")));
   11046         [ +  + ]:         840 :     if (f + 1 < -NUMERIC_MAX_DISPLAY_SCALE)
   11047                 :             :     {
   11048                 :          10 :         zero_var(result);
   11049                 :          10 :         result->dscale = NUMERIC_MAX_DISPLAY_SCALE;
   11050                 :         151 :         return;
   11051                 :             :     }
   11052                 :             : 
   11053                 :             :     /*
   11054                 :             :      * Choose the result scale in the same way as power_var(), so it has at
   11055                 :             :      * least NUMERIC_MIN_SIG_DIGITS significant digits and is not less than
   11056                 :             :      * either input's display scale.
   11057                 :             :      */
   11058                 :         830 :     rscale = NUMERIC_MIN_SIG_DIGITS - (int) f;
   11059                 :         830 :     rscale = Max(rscale, base->dscale);
   11060                 :         830 :     rscale = Max(rscale, exp_dscale);
   11061                 :         830 :     rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
   11062                 :         830 :     rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
   11063                 :             : 
   11064                 :             :     /* Handle some common special cases, as well as corner cases */
   11065   [ +  +  +  +  :         830 :     switch (exp)
                      + ]
   11066                 :             :     {
   11067                 :          52 :         case 0:
   11068                 :             : 
   11069                 :             :             /*
   11070                 :             :              * While 0 ^ 0 can be either 1 or indeterminate (error), we treat
   11071                 :             :              * it as 1 because most programming languages do this. SQL:2003
   11072                 :             :              * also requires a return value of 1.
   11073                 :             :              * https://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_zero_power
   11074                 :             :              */
   11075                 :          52 :             set_var_from_var(&const_one, result);
   11076                 :          52 :             result->dscale = rscale; /* no need to round */
   11077                 :          52 :             return;
   11078                 :          32 :         case 1:
   11079                 :          32 :             set_var_from_var(base, result);
   11080                 :          32 :             round_var(result, rscale);
   11081                 :          32 :             return;
   11082                 :          21 :         case -1:
   11083                 :          21 :             div_var(&const_one, base, result, rscale, true, true);
   11084                 :          21 :             return;
   11085                 :          36 :         case 2:
   11086                 :          36 :             mul_var(base, base, result, rscale);
   11087                 :          36 :             return;
   11088                 :         689 :         default:
   11089                 :         689 :             break;
   11090                 :             :     }
   11091                 :             : 
   11092                 :             :     /* Handle the special case where the base is zero */
   11093         [ -  + ]:         689 :     if (base->ndigits == 0)
   11094                 :             :     {
   11095         [ #  # ]:           0 :         if (exp < 0)
   11096         [ #  # ]:           0 :             ereport(ERROR,
   11097                 :             :                     (errcode(ERRCODE_DIVISION_BY_ZERO),
   11098                 :             :                      errmsg("division by zero")));
   11099                 :           0 :         zero_var(result);
   11100                 :           0 :         result->dscale = rscale;
   11101                 :           0 :         return;
   11102                 :             :     }
   11103                 :             : 
   11104                 :             :     /*
   11105                 :             :      * The general case repeatedly multiplies base according to the bit
   11106                 :             :      * pattern of exp.
   11107                 :             :      *
   11108                 :             :      * The local rscale used for each multiplication is varied to keep a fixed
   11109                 :             :      * number of significant digits, sufficient to give the required result
   11110                 :             :      * scale.
   11111                 :             :      */
   11112                 :             : 
   11113                 :             :     /*
   11114                 :             :      * Approximate number of significant digits in the result.  Note that the
   11115                 :             :      * underflow test above, together with the choice of rscale, ensures that
   11116                 :             :      * this approximation is necessarily > 0.
   11117                 :             :      */
   11118                 :         689 :     sig_digits = 1 + rscale + (int) f;
   11119                 :             : 
   11120                 :             :     /*
   11121                 :             :      * The multiplications to produce the result may introduce an error of up
   11122                 :             :      * to around log10(abs(exp)) digits, so work with this many extra digits
   11123                 :             :      * of precision (plus a few more for good measure).
   11124                 :             :      */
   11125                 :         689 :     sig_digits += (int) log(fabs((double) exp)) + 8;
   11126                 :             : 
   11127                 :             :     /*
   11128                 :             :      * Now we can proceed with the multiplications.
   11129                 :             :      */
   11130                 :         689 :     neg = (exp < 0);
   11131                 :         689 :     mask = pg_abs_s32(exp);
   11132                 :             : 
   11133                 :         689 :     init_var(&base_prod);
   11134                 :         689 :     set_var_from_var(base, &base_prod);
   11135                 :             : 
   11136         [ +  + ]:         689 :     if (mask & 1)
   11137                 :         343 :         set_var_from_var(base, result);
   11138                 :             :     else
   11139                 :         346 :         set_var_from_var(&const_one, result);
   11140                 :             : 
   11141         [ +  + ]:        3618 :     while ((mask >>= 1) > 0)
   11142                 :             :     {
   11143                 :             :         /*
   11144                 :             :          * Do the multiplications using rscales large enough to hold the
   11145                 :             :          * results to the required number of significant digits, but don't
   11146                 :             :          * waste time by exceeding the scales of the numbers themselves.
   11147                 :             :          */
   11148                 :        2929 :         local_rscale = sig_digits - 2 * base_prod.weight * DEC_DIGITS;
   11149                 :        2929 :         local_rscale = Min(local_rscale, 2 * base_prod.dscale);
   11150                 :        2929 :         local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
   11151                 :             : 
   11152                 :        2929 :         mul_var(&base_prod, &base_prod, &base_prod, local_rscale);
   11153                 :             : 
   11154         [ +  + ]:        2929 :         if (mask & 1)
   11155                 :             :         {
   11156                 :        1932 :             local_rscale = sig_digits -
   11157                 :        1932 :                 (base_prod.weight + result->weight) * DEC_DIGITS;
   11158                 :        1932 :             local_rscale = Min(local_rscale,
   11159                 :             :                                base_prod.dscale + result->dscale);
   11160                 :        1932 :             local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
   11161                 :             : 
   11162                 :        1932 :             mul_var(&base_prod, result, result, local_rscale);
   11163                 :             :         }
   11164                 :             : 
   11165                 :             :         /*
   11166                 :             :          * When abs(base) > 1, the number of digits to the left of the decimal
   11167                 :             :          * point in base_prod doubles at each iteration, so if exp is large we
   11168                 :             :          * could easily spend large amounts of time and memory space doing the
   11169                 :             :          * multiplications.  But once the weight exceeds what will fit in
   11170                 :             :          * int16, the final result is guaranteed to overflow (or underflow, if
   11171                 :             :          * exp < 0), so we can give up before wasting too many cycles.
   11172                 :             :          */
   11173         [ +  - ]:        2929 :         if (base_prod.weight > NUMERIC_WEIGHT_MAX ||
   11174         [ -  + ]:        2929 :             result->weight > NUMERIC_WEIGHT_MAX)
   11175                 :             :         {
   11176                 :             :             /* overflow, unless neg, in which case result should be 0 */
   11177         [ #  # ]:           0 :             if (!neg)
   11178         [ #  # ]:           0 :                 ereport(ERROR,
   11179                 :             :                         (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
   11180                 :             :                          errmsg("value overflows numeric format")));
   11181                 :           0 :             zero_var(result);
   11182                 :           0 :             neg = false;
   11183                 :           0 :             break;
   11184                 :             :         }
   11185                 :             :     }
   11186                 :             : 
   11187                 :         689 :     free_var(&base_prod);
   11188                 :             : 
   11189                 :             :     /* Compensate for input sign, and round to requested rscale */
   11190         [ +  + ]:         689 :     if (neg)
   11191                 :         328 :         div_var(&const_one, result, result, rscale, true, false);
   11192                 :             :     else
   11193                 :         361 :         round_var(result, rscale);
   11194                 :             : }
   11195                 :             : 
   11196                 :             : /*
   11197                 :             :  * power_ten_int() -
   11198                 :             :  *
   11199                 :             :  *  Raise ten to the power of exp, where exp is an integer.  Note that unlike
   11200                 :             :  *  power_var_int(), this does no overflow/underflow checking or rounding.
   11201                 :             :  */
   11202                 :             : static void
   11203                 :         152 : power_ten_int(int exp, NumericVar *result)
   11204                 :             : {
   11205                 :             :     /* Construct the result directly, starting from 10^0 = 1 */
   11206                 :         152 :     set_var_from_var(&const_one, result);
   11207                 :             : 
   11208                 :             :     /* Scale needed to represent the result exactly */
   11209         [ +  + ]:         152 :     result->dscale = exp < 0 ? -exp : 0;
   11210                 :             : 
   11211                 :             :     /* Base-NBASE weight of result and remaining exponent */
   11212         [ +  + ]:         152 :     if (exp >= 0)
   11213                 :         108 :         result->weight = exp / DEC_DIGITS;
   11214                 :             :     else
   11215                 :          44 :         result->weight = (exp + 1) / DEC_DIGITS - 1;
   11216                 :             : 
   11217                 :         152 :     exp -= result->weight * DEC_DIGITS;
   11218                 :             : 
   11219                 :             :     /* Final adjustment of the result's single NBASE digit */
   11220         [ +  + ]:         396 :     while (exp-- > 0)
   11221                 :         244 :         result->digits[0] *= 10;
   11222                 :         152 : }
   11223                 :             : 
   11224                 :             : /*
   11225                 :             :  * random_var() - return a random value in the range [rmin, rmax].
   11226                 :             :  */
   11227                 :             : static void
   11228                 :       22292 : random_var(pg_prng_state *state, const NumericVar *rmin,
   11229                 :             :            const NumericVar *rmax, NumericVar *result)
   11230                 :             : {
   11231                 :             :     int         rscale;
   11232                 :             :     NumericVar  rlen;
   11233                 :             :     int         res_ndigits;
   11234                 :             :     int         n;
   11235                 :             :     int         pow10;
   11236                 :             :     int         i;
   11237                 :             :     uint64      rlen64;
   11238                 :             :     int         rlen64_ndigits;
   11239                 :             : 
   11240                 :       22292 :     rscale = Max(rmin->dscale, rmax->dscale);
   11241                 :             : 
   11242                 :             :     /* Compute rlen = rmax - rmin and check the range bounds */
   11243                 :       22292 :     init_var(&rlen);
   11244                 :       22292 :     sub_var(rmax, rmin, &rlen);
   11245                 :             : 
   11246         [ +  + ]:       22292 :     if (rlen.sign == NUMERIC_NEG)
   11247         [ +  - ]:           4 :         ereport(ERROR,
   11248                 :             :                 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
   11249                 :             :                 errmsg("lower bound must be less than or equal to upper bound"));
   11250                 :             : 
   11251                 :             :     /* Special case for an empty range */
   11252         [ +  + ]:       22288 :     if (rlen.ndigits == 0)
   11253                 :             :     {
   11254                 :           8 :         set_var_from_var(rmin, result);
   11255                 :           8 :         result->dscale = rscale;
   11256                 :           8 :         free_var(&rlen);
   11257                 :           8 :         return;
   11258                 :             :     }
   11259                 :             : 
   11260                 :             :     /*
   11261                 :             :      * Otherwise, select a random value in the range [0, rlen = rmax - rmin],
   11262                 :             :      * and shift it to the required range by adding rmin.
   11263                 :             :      */
   11264                 :             : 
   11265                 :             :     /* Required result digits */
   11266                 :       22280 :     res_ndigits = rlen.weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
   11267                 :             : 
   11268                 :             :     /*
   11269                 :             :      * To get the required rscale, the final result digit must be a multiple
   11270                 :             :      * of pow10 = 10^n, where n = (-rscale) mod DEC_DIGITS.
   11271                 :             :      */
   11272                 :       22280 :     n = ((rscale + DEC_DIGITS - 1) / DEC_DIGITS) * DEC_DIGITS - rscale;
   11273                 :       22280 :     pow10 = 1;
   11274         [ +  + ]:       58600 :     for (i = 0; i < n; i++)
   11275                 :       36320 :         pow10 *= 10;
   11276                 :             : 
   11277                 :             :     /*
   11278                 :             :      * To choose a random value uniformly from the range [0, rlen], we choose
   11279                 :             :      * from the slightly larger range [0, rlen2], where rlen2 is formed from
   11280                 :             :      * rlen by copying the first 4 NBASE digits, and setting all remaining
   11281                 :             :      * decimal digits to "9".
   11282                 :             :      *
   11283                 :             :      * Without loss of generality, we can ignore the weight of rlen2 and treat
   11284                 :             :      * it as a pure integer for the purposes of this discussion.  The process
   11285                 :             :      * above gives rlen2 + 1 = rlen64 * 10^N, for some integer N, where rlen64
   11286                 :             :      * is a 64-bit integer formed from the first 4 NBASE digits copied from
   11287                 :             :      * rlen.  Since this trivially factors into smaller pieces that fit in
   11288                 :             :      * 64-bit integers, the task of choosing a random value uniformly from the
   11289                 :             :      * rlen2 + 1 possible values in [0, rlen2] is much simpler.
   11290                 :             :      *
   11291                 :             :      * If the random value selected is too large, it is rejected, and we try
   11292                 :             :      * again until we get a result <= rlen, ensuring that the overall result
   11293                 :             :      * is uniform (no particular value is any more likely than any other).
   11294                 :             :      *
   11295                 :             :      * Since rlen64 holds 4 NBASE digits from rlen, it contains at least
   11296                 :             :      * DEC_DIGITS * 3 + 1 decimal digits (i.e., at least 13 decimal digits,
   11297                 :             :      * when DEC_DIGITS is 4). Therefore the probability of needing to reject
   11298                 :             :      * the value chosen and retry is less than 1e-13.
   11299                 :             :      */
   11300                 :       22280 :     rlen64 = (uint64) rlen.digits[0];
   11301                 :       22280 :     rlen64_ndigits = 1;
   11302   [ +  +  +  + ]:       50808 :     while (rlen64_ndigits < res_ndigits && rlen64_ndigits < 4)
   11303                 :             :     {
   11304                 :       28528 :         rlen64 *= NBASE;
   11305         [ +  + ]:       28528 :         if (rlen64_ndigits < rlen.ndigits)
   11306                 :        4408 :             rlen64 += rlen.digits[rlen64_ndigits];
   11307                 :       28528 :         rlen64_ndigits++;
   11308                 :             :     }
   11309                 :             : 
   11310                 :             :     /* Loop until we get a result <= rlen */
   11311                 :             :     do
   11312                 :             :     {
   11313                 :             :         NumericDigit *res_digits;
   11314                 :             :         uint64      rand;
   11315                 :             :         int         whole_ndigits;
   11316                 :             : 
   11317                 :       22280 :         alloc_var(result, res_ndigits);
   11318                 :       22280 :         result->sign = NUMERIC_POS;
   11319                 :       22280 :         result->weight = rlen.weight;
   11320                 :       22280 :         result->dscale = rscale;
   11321                 :       22280 :         res_digits = result->digits;
   11322                 :             : 
   11323                 :             :         /*
   11324                 :             :          * Set the first rlen64_ndigits using a random value in [0, rlen64].
   11325                 :             :          *
   11326                 :             :          * If this is the whole result, and rscale is not a multiple of
   11327                 :             :          * DEC_DIGITS (pow10 from above is not 1), then we need this to be a
   11328                 :             :          * multiple of pow10.
   11329                 :             :          */
   11330   [ +  +  +  + ]:       22280 :         if (rlen64_ndigits == res_ndigits && pow10 != 1)
   11331                 :       14088 :             rand = pg_prng_uint64_range(state, 0, rlen64 / pow10) * pow10;
   11332                 :             :         else
   11333                 :        8192 :             rand = pg_prng_uint64_range(state, 0, rlen64);
   11334                 :             : 
   11335         [ +  + ]:       73088 :         for (i = rlen64_ndigits - 1; i >= 0; i--)
   11336                 :             :         {
   11337                 :       50808 :             res_digits[i] = (NumericDigit) (rand % NBASE);
   11338                 :       50808 :             rand = rand / NBASE;
   11339                 :             :         }
   11340                 :             : 
   11341                 :             :         /*
   11342                 :             :          * Set the remaining digits to random values in range [0, NBASE),
   11343                 :             :          * noting that the last digit needs to be a multiple of pow10.
   11344                 :             :          */
   11345                 :       22280 :         whole_ndigits = res_ndigits;
   11346         [ +  + ]:       22280 :         if (pow10 != 1)
   11347                 :       22140 :             whole_ndigits--;
   11348                 :             : 
   11349                 :             :         /* Set whole digits in groups of 4 for best performance */
   11350                 :       22280 :         i = rlen64_ndigits;
   11351         [ +  + ]:       22320 :         while (i < whole_ndigits - 3)
   11352                 :             :         {
   11353                 :          40 :             rand = pg_prng_uint64_range(state, 0,
   11354                 :             :                                         (uint64) NBASE * NBASE * NBASE * NBASE - 1);
   11355                 :          40 :             res_digits[i++] = (NumericDigit) (rand % NBASE);
   11356                 :          40 :             rand = rand / NBASE;
   11357                 :          40 :             res_digits[i++] = (NumericDigit) (rand % NBASE);
   11358                 :          40 :             rand = rand / NBASE;
   11359                 :          40 :             res_digits[i++] = (NumericDigit) (rand % NBASE);
   11360                 :          40 :             rand = rand / NBASE;
   11361                 :          40 :             res_digits[i++] = (NumericDigit) rand;
   11362                 :             :         }
   11363                 :             : 
   11364                 :             :         /* Remaining whole digits */
   11365         [ +  + ]:       22420 :         while (i < whole_ndigits)
   11366                 :             :         {
   11367                 :         140 :             rand = pg_prng_uint64_range(state, 0, NBASE - 1);
   11368                 :         140 :             res_digits[i++] = (NumericDigit) rand;
   11369                 :             :         }
   11370                 :             : 
   11371                 :             :         /* Final partial digit (multiple of pow10) */
   11372         [ +  + ]:       22280 :         if (i < res_ndigits)
   11373                 :             :         {
   11374                 :        8052 :             rand = pg_prng_uint64_range(state, 0, NBASE / pow10 - 1) * pow10;
   11375                 :        8052 :             res_digits[i] = (NumericDigit) rand;
   11376                 :             :         }
   11377                 :             : 
   11378                 :             :         /* Remove leading/trailing zeroes */
   11379                 :       22280 :         strip_var(result);
   11380                 :             : 
   11381                 :             :         /* If result > rlen, try again */
   11382                 :             : 
   11383         [ -  + ]:       22280 :     } while (cmp_var(result, &rlen) > 0);
   11384                 :             : 
   11385                 :             :     /* Offset the result to the required range */
   11386                 :       22280 :     add_var(result, rmin, result);
   11387                 :             : 
   11388                 :       22280 :     free_var(&rlen);
   11389                 :             : }
   11390                 :             : 
   11391                 :             : 
   11392                 :             : /* ----------------------------------------------------------------------
   11393                 :             :  *
   11394                 :             :  * Following are the lowest level functions that operate unsigned
   11395                 :             :  * on the variable level
   11396                 :             :  *
   11397                 :             :  * ----------------------------------------------------------------------
   11398                 :             :  */
   11399                 :             : 
   11400                 :             : 
   11401                 :             : /* ----------
   11402                 :             :  * cmp_abs() -
   11403                 :             :  *
   11404                 :             :  *  Compare the absolute values of var1 and var2
   11405                 :             :  *  Returns:    -1 for ABS(var1) < ABS(var2)
   11406                 :             :  *              0  for ABS(var1) == ABS(var2)
   11407                 :             :  *              1  for ABS(var1) > ABS(var2)
   11408                 :             :  * ----------
   11409                 :             :  */
   11410                 :             : static int
   11411                 :      469920 : cmp_abs(const NumericVar *var1, const NumericVar *var2)
   11412                 :             : {
   11413                 :      939840 :     return cmp_abs_common(var1->digits, var1->ndigits, var1->weight,
   11414                 :      469920 :                           var2->digits, var2->ndigits, var2->weight);
   11415                 :             : }
   11416                 :             : 
   11417                 :             : /* ----------
   11418                 :             :  * cmp_abs_common() -
   11419                 :             :  *
   11420                 :             :  *  Main routine of cmp_abs(). This function can be used by both
   11421                 :             :  *  NumericVar and Numeric.
   11422                 :             :  * ----------
   11423                 :             :  */
   11424                 :             : static int
   11425                 :    18444818 : cmp_abs_common(const NumericDigit *var1digits, int var1ndigits, int var1weight,
   11426                 :             :                const NumericDigit *var2digits, int var2ndigits, int var2weight)
   11427                 :             : {
   11428                 :    18444818 :     int         i1 = 0;
   11429                 :    18444818 :     int         i2 = 0;
   11430                 :             : 
   11431                 :             :     /* Check any digits before the first common digit */
   11432                 :             : 
   11433   [ +  +  +  + ]:    18444818 :     while (var1weight > var2weight && i1 < var1ndigits)
   11434                 :             :     {
   11435         [ +  - ]:       14902 :         if (var1digits[i1++] != 0)
   11436                 :       14902 :             return 1;
   11437                 :           0 :         var1weight--;
   11438                 :             :     }
   11439   [ +  +  +  + ]:    18429916 :     while (var2weight > var1weight && i2 < var2ndigits)
   11440                 :             :     {
   11441         [ +  - ]:      100577 :         if (var2digits[i2++] != 0)
   11442                 :      100577 :             return -1;
   11443                 :           0 :         var2weight--;
   11444                 :             :     }
   11445                 :             : 
   11446                 :             :     /* At this point, either w1 == w2 or we've run out of digits */
   11447                 :             : 
   11448         [ +  + ]:    18329339 :     if (var1weight == var2weight)
   11449                 :             :     {
   11450   [ +  +  +  + ]:    28814727 :         while (i1 < var1ndigits && i2 < var2ndigits)
   11451                 :             :         {
   11452                 :    19350910 :             int         stat = var1digits[i1++] - var2digits[i2++];
   11453                 :             : 
   11454         [ +  + ]:    19350910 :             if (stat)
   11455                 :             :             {
   11456         [ +  + ]:     8861279 :                 if (stat > 0)
   11457                 :     5249221 :                     return 1;
   11458                 :     3612058 :                 return -1;
   11459                 :             :             }
   11460                 :             :         }
   11461                 :             :     }
   11462                 :             : 
   11463                 :             :     /*
   11464                 :             :      * At this point, we've run out of digits on one side or the other; so any
   11465                 :             :      * remaining nonzero digits imply that side is larger
   11466                 :             :      */
   11467         [ +  + ]:     9468160 :     while (i1 < var1ndigits)
   11468                 :             :     {
   11469         [ +  + ]:        6268 :         if (var1digits[i1++] != 0)
   11470                 :        6168 :             return 1;
   11471                 :             :     }
   11472         [ +  + ]:     9462144 :     while (i2 < var2ndigits)
   11473                 :             :     {
   11474         [ +  + ]:         883 :         if (var2digits[i2++] != 0)
   11475                 :         631 :             return -1;
   11476                 :             :     }
   11477                 :             : 
   11478                 :     9461261 :     return 0;
   11479                 :             : }
   11480                 :             : 
   11481                 :             : 
   11482                 :             : /*
   11483                 :             :  * add_abs() -
   11484                 :             :  *
   11485                 :             :  *  Add the absolute values of two variables into result.
   11486                 :             :  *  result might point to one of the operands without danger.
   11487                 :             :  */
   11488                 :             : static void
   11489                 :      299878 : add_abs(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
   11490                 :             : {
   11491                 :             :     NumericDigit *res_buf;
   11492                 :             :     NumericDigit *res_digits;
   11493                 :             :     int         res_ndigits;
   11494                 :             :     int         res_weight;
   11495                 :             :     int         res_rscale,
   11496                 :             :                 rscale1,
   11497                 :             :                 rscale2;
   11498                 :             :     int         res_dscale;
   11499                 :             :     int         i,
   11500                 :             :                 i1,
   11501                 :             :                 i2;
   11502                 :      299878 :     int         carry = 0;
   11503                 :             : 
   11504                 :             :     /* copy these values into local vars for speed in inner loop */
   11505                 :      299878 :     int         var1ndigits = var1->ndigits;
   11506                 :      299878 :     int         var2ndigits = var2->ndigits;
   11507                 :      299878 :     NumericDigit *var1digits = var1->digits;
   11508                 :      299878 :     NumericDigit *var2digits = var2->digits;
   11509                 :             : 
   11510                 :      299878 :     res_weight = Max(var1->weight, var2->weight) + 1;
   11511                 :             : 
   11512                 :      299878 :     res_dscale = Max(var1->dscale, var2->dscale);
   11513                 :             : 
   11514                 :             :     /* Note: here we are figuring rscale in base-NBASE digits */
   11515                 :      299878 :     rscale1 = var1->ndigits - var1->weight - 1;
   11516                 :      299878 :     rscale2 = var2->ndigits - var2->weight - 1;
   11517                 :      299878 :     res_rscale = Max(rscale1, rscale2);
   11518                 :             : 
   11519                 :      299878 :     res_ndigits = res_rscale + res_weight + 1;
   11520         [ -  + ]:      299878 :     if (res_ndigits <= 0)
   11521                 :           0 :         res_ndigits = 1;
   11522                 :             : 
   11523                 :      299878 :     res_buf = digitbuf_alloc(res_ndigits + 1);
   11524                 :      299878 :     res_buf[0] = 0;             /* spare digit for later rounding */
   11525                 :      299878 :     res_digits = res_buf + 1;
   11526                 :             : 
   11527                 :      299878 :     i1 = res_rscale + var1->weight + 1;
   11528                 :      299878 :     i2 = res_rscale + var2->weight + 1;
   11529         [ +  + ]:     2481130 :     for (i = res_ndigits - 1; i >= 0; i--)
   11530                 :             :     {
   11531                 :     2181252 :         i1--;
   11532                 :     2181252 :         i2--;
   11533   [ +  +  +  + ]:     2181252 :         if (i1 >= 0 && i1 < var1ndigits)
   11534                 :      988172 :             carry += var1digits[i1];
   11535   [ +  +  +  + ]:     2181252 :         if (i2 >= 0 && i2 < var2ndigits)
   11536                 :      780173 :             carry += var2digits[i2];
   11537                 :             : 
   11538         [ +  + ]:     2181252 :         if (carry >= NBASE)
   11539                 :             :         {
   11540                 :      159479 :             res_digits[i] = carry - NBASE;
   11541                 :      159479 :             carry = 1;
   11542                 :             :         }
   11543                 :             :         else
   11544                 :             :         {
   11545                 :     2021773 :             res_digits[i] = carry;
   11546                 :     2021773 :             carry = 0;
   11547                 :             :         }
   11548                 :             :     }
   11549                 :             : 
   11550                 :             :     Assert(carry == 0);         /* else we failed to allow for carry out */
   11551                 :             : 
   11552         [ +  + ]:      299878 :     digitbuf_free(result->buf);
   11553                 :      299878 :     result->ndigits = res_ndigits;
   11554                 :      299878 :     result->buf = res_buf;
   11555                 :      299878 :     result->digits = res_digits;
   11556                 :      299878 :     result->weight = res_weight;
   11557                 :      299878 :     result->dscale = res_dscale;
   11558                 :             : 
   11559                 :             :     /* Remove leading/trailing zeroes */
   11560                 :      299878 :     strip_var(result);
   11561                 :      299878 : }
   11562                 :             : 
   11563                 :             : 
   11564                 :             : /*
   11565                 :             :  * sub_abs()
   11566                 :             :  *
   11567                 :             :  *  Subtract the absolute value of var2 from the absolute value of var1
   11568                 :             :  *  and store in result. result might point to one of the operands
   11569                 :             :  *  without danger.
   11570                 :             :  *
   11571                 :             :  *  ABS(var1) MUST BE GREATER OR EQUAL ABS(var2) !!!
   11572                 :             :  */
   11573                 :             : static void
   11574                 :      436350 : sub_abs(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
   11575                 :             : {
   11576                 :             :     NumericDigit *res_buf;
   11577                 :             :     NumericDigit *res_digits;
   11578                 :             :     int         res_ndigits;
   11579                 :             :     int         res_weight;
   11580                 :             :     int         res_rscale,
   11581                 :             :                 rscale1,
   11582                 :             :                 rscale2;
   11583                 :             :     int         res_dscale;
   11584                 :             :     int         i,
   11585                 :             :                 i1,
   11586                 :             :                 i2;
   11587                 :      436350 :     int         borrow = 0;
   11588                 :             : 
   11589                 :             :     /* copy these values into local vars for speed in inner loop */
   11590                 :      436350 :     int         var1ndigits = var1->ndigits;
   11591                 :      436350 :     int         var2ndigits = var2->ndigits;
   11592                 :      436350 :     NumericDigit *var1digits = var1->digits;
   11593                 :      436350 :     NumericDigit *var2digits = var2->digits;
   11594                 :             : 
   11595                 :      436350 :     res_weight = var1->weight;
   11596                 :             : 
   11597                 :      436350 :     res_dscale = Max(var1->dscale, var2->dscale);
   11598                 :             : 
   11599                 :             :     /* Note: here we are figuring rscale in base-NBASE digits */
   11600                 :      436350 :     rscale1 = var1->ndigits - var1->weight - 1;
   11601                 :      436350 :     rscale2 = var2->ndigits - var2->weight - 1;
   11602                 :      436350 :     res_rscale = Max(rscale1, rscale2);
   11603                 :             : 
   11604                 :      436350 :     res_ndigits = res_rscale + res_weight + 1;
   11605         [ -  + ]:      436350 :     if (res_ndigits <= 0)
   11606                 :           0 :         res_ndigits = 1;
   11607                 :             : 
   11608                 :      436350 :     res_buf = digitbuf_alloc(res_ndigits + 1);
   11609                 :      436350 :     res_buf[0] = 0;             /* spare digit for later rounding */
   11610                 :      436350 :     res_digits = res_buf + 1;
   11611                 :             : 
   11612                 :      436350 :     i1 = res_rscale + var1->weight + 1;
   11613                 :      436350 :     i2 = res_rscale + var2->weight + 1;
   11614         [ +  + ]:     3489442 :     for (i = res_ndigits - 1; i >= 0; i--)
   11615                 :             :     {
   11616                 :     3053092 :         i1--;
   11617                 :     3053092 :         i2--;
   11618   [ +  -  +  + ]:     3053092 :         if (i1 >= 0 && i1 < var1ndigits)
   11619                 :     2745695 :             borrow += var1digits[i1];
   11620   [ +  +  +  + ]:     3053092 :         if (i2 >= 0 && i2 < var2ndigits)
   11621                 :     2693462 :             borrow -= var2digits[i2];
   11622                 :             : 
   11623         [ +  + ]:     3053092 :         if (borrow < 0)
   11624                 :             :         {
   11625                 :      330062 :             res_digits[i] = borrow + NBASE;
   11626                 :      330062 :             borrow = -1;
   11627                 :             :         }
   11628                 :             :         else
   11629                 :             :         {
   11630                 :     2723030 :             res_digits[i] = borrow;
   11631                 :     2723030 :             borrow = 0;
   11632                 :             :         }
   11633                 :             :     }
   11634                 :             : 
   11635                 :             :     Assert(borrow == 0);        /* else caller gave us var1 < var2 */
   11636                 :             : 
   11637         [ +  + ]:      436350 :     digitbuf_free(result->buf);
   11638                 :      436350 :     result->ndigits = res_ndigits;
   11639                 :      436350 :     result->buf = res_buf;
   11640                 :      436350 :     result->digits = res_digits;
   11641                 :      436350 :     result->weight = res_weight;
   11642                 :      436350 :     result->dscale = res_dscale;
   11643                 :             : 
   11644                 :             :     /* Remove leading/trailing zeroes */
   11645                 :      436350 :     strip_var(result);
   11646                 :      436350 : }
   11647                 :             : 
   11648                 :             : /*
   11649                 :             :  * round_var
   11650                 :             :  *
   11651                 :             :  * Round the value of a variable to no more than rscale decimal digits
   11652                 :             :  * after the decimal point.  NOTE: we allow rscale < 0 here, implying
   11653                 :             :  * rounding before the decimal point.
   11654                 :             :  */
   11655                 :             : static void
   11656                 :      168581 : round_var(NumericVar *var, int rscale)
   11657                 :             : {
   11658                 :      168581 :     NumericDigit *digits = var->digits;
   11659                 :             :     int         di;
   11660                 :             :     int         ndigits;
   11661                 :             :     int         carry;
   11662                 :             : 
   11663                 :      168581 :     var->dscale = rscale;
   11664                 :             : 
   11665                 :             :     /* decimal digits wanted */
   11666                 :      168581 :     di = (var->weight + 1) * DEC_DIGITS + rscale;
   11667                 :             : 
   11668                 :             :     /*
   11669                 :             :      * If di = 0, the value loses all digits, but could round up to 1 if its
   11670                 :             :      * first extra digit is >= 5.  If di < 0 the result must be 0.
   11671                 :             :      */
   11672         [ +  + ]:      168581 :     if (di < 0)
   11673                 :             :     {
   11674                 :          71 :         var->ndigits = 0;
   11675                 :          71 :         var->weight = 0;
   11676                 :          71 :         var->sign = NUMERIC_POS;
   11677                 :             :     }
   11678                 :             :     else
   11679                 :             :     {
   11680                 :             :         /* NBASE digits wanted */
   11681                 :      168510 :         ndigits = (di + DEC_DIGITS - 1) / DEC_DIGITS;
   11682                 :             : 
   11683                 :             :         /* 0, or number of decimal digits to keep in last NBASE digit */
   11684                 :      168510 :         di %= DEC_DIGITS;
   11685                 :             : 
   11686         [ +  + ]:      168510 :         if (ndigits < var->ndigits ||
   11687   [ +  +  +  + ]:       30974 :             (ndigits == var->ndigits && di > 0))
   11688                 :             :         {
   11689                 :      140005 :             var->ndigits = ndigits;
   11690                 :             : 
   11691                 :             : #if DEC_DIGITS == 1
   11692                 :             :             /* di must be zero */
   11693                 :             :             carry = (digits[ndigits] >= HALF_NBASE) ? 1 : 0;
   11694                 :             : #else
   11695         [ +  + ]:      140005 :             if (di == 0)
   11696                 :      109933 :                 carry = (digits[ndigits] >= HALF_NBASE) ? 1 : 0;
   11697                 :             :             else
   11698                 :             :             {
   11699                 :             :                 /* Must round within last NBASE digit */
   11700                 :             :                 int         extra,
   11701                 :             :                             pow10;
   11702                 :             : 
   11703                 :             : #if DEC_DIGITS == 4
   11704                 :       30072 :                 pow10 = round_powers[di];
   11705                 :             : #elif DEC_DIGITS == 2
   11706                 :             :                 pow10 = 10;
   11707                 :             : #else
   11708                 :             : #error unsupported NBASE
   11709                 :             : #endif
   11710                 :       30072 :                 extra = digits[--ndigits] % pow10;
   11711                 :       30072 :                 digits[ndigits] -= extra;
   11712                 :       30072 :                 carry = 0;
   11713         [ +  + ]:       30072 :                 if (extra >= pow10 / 2)
   11714                 :             :                 {
   11715                 :       14019 :                     pow10 += digits[ndigits];
   11716         [ +  + ]:       14019 :                     if (pow10 >= NBASE)
   11717                 :             :                     {
   11718                 :         595 :                         pow10 -= NBASE;
   11719                 :         595 :                         carry = 1;
   11720                 :             :                     }
   11721                 :       14019 :                     digits[ndigits] = pow10;
   11722                 :             :                 }
   11723                 :             :             }
   11724                 :             : #endif
   11725                 :             : 
   11726                 :             :             /* Propagate carry if needed */
   11727         [ +  + ]:      166895 :             while (carry)
   11728                 :             :             {
   11729                 :       26890 :                 carry += digits[--ndigits];
   11730         [ +  + ]:       26890 :                 if (carry >= NBASE)
   11731                 :             :                 {
   11732                 :       20528 :                     digits[ndigits] = carry - NBASE;
   11733                 :       20528 :                     carry = 1;
   11734                 :             :                 }
   11735                 :             :                 else
   11736                 :             :                 {
   11737                 :        6362 :                     digits[ndigits] = carry;
   11738                 :        6362 :                     carry = 0;
   11739                 :             :                 }
   11740                 :             :             }
   11741                 :             : 
   11742         [ +  + ]:      140005 :             if (ndigits < 0)
   11743                 :             :             {
   11744                 :             :                 Assert(ndigits == -1);  /* better not have added > 1 digit */
   11745                 :             :                 Assert(var->digits > var->buf);
   11746                 :          65 :                 var->digits--;
   11747                 :          65 :                 var->ndigits++;
   11748                 :          65 :                 var->weight++;
   11749                 :             :             }
   11750                 :             :         }
   11751                 :             :     }
   11752                 :      168581 : }
   11753                 :             : 
   11754                 :             : /*
   11755                 :             :  * trunc_var
   11756                 :             :  *
   11757                 :             :  * Truncate (towards zero) the value of a variable at rscale decimal digits
   11758                 :             :  * after the decimal point.  NOTE: we allow rscale < 0 here, implying
   11759                 :             :  * truncation before the decimal point.
   11760                 :             :  */
   11761                 :             : static void
   11762                 :      280784 : trunc_var(NumericVar *var, int rscale)
   11763                 :             : {
   11764                 :             :     int         di;
   11765                 :             :     int         ndigits;
   11766                 :             : 
   11767                 :      280784 :     var->dscale = rscale;
   11768                 :             : 
   11769                 :             :     /* decimal digits wanted */
   11770                 :      280784 :     di = (var->weight + 1) * DEC_DIGITS + rscale;
   11771                 :             : 
   11772                 :             :     /*
   11773                 :             :      * If di <= 0, the value loses all digits.
   11774                 :             :      */
   11775         [ +  + ]:      280784 :     if (di <= 0)
   11776                 :             :     {
   11777                 :          66 :         var->ndigits = 0;
   11778                 :          66 :         var->weight = 0;
   11779                 :          66 :         var->sign = NUMERIC_POS;
   11780                 :             :     }
   11781                 :             :     else
   11782                 :             :     {
   11783                 :             :         /* NBASE digits wanted */
   11784                 :      280718 :         ndigits = (di + DEC_DIGITS - 1) / DEC_DIGITS;
   11785                 :             : 
   11786         [ +  + ]:      280718 :         if (ndigits <= var->ndigits)
   11787                 :             :         {
   11788                 :      280458 :             var->ndigits = ndigits;
   11789                 :             : 
   11790                 :             : #if DEC_DIGITS == 1
   11791                 :             :             /* no within-digit stuff to worry about */
   11792                 :             : #else
   11793                 :             :             /* 0, or number of decimal digits to keep in last NBASE digit */
   11794                 :      280458 :             di %= DEC_DIGITS;
   11795                 :             : 
   11796         [ +  + ]:      280458 :             if (di > 0)
   11797                 :             :             {
   11798                 :             :                 /* Must truncate within last NBASE digit */
   11799                 :          63 :                 NumericDigit *digits = var->digits;
   11800                 :             :                 int         extra,
   11801                 :             :                             pow10;
   11802                 :             : 
   11803                 :             : #if DEC_DIGITS == 4
   11804                 :          63 :                 pow10 = round_powers[di];
   11805                 :             : #elif DEC_DIGITS == 2
   11806                 :             :                 pow10 = 10;
   11807                 :             : #else
   11808                 :             : #error unsupported NBASE
   11809                 :             : #endif
   11810                 :          63 :                 extra = digits[--ndigits] % pow10;
   11811                 :          63 :                 digits[ndigits] -= extra;
   11812                 :             :             }
   11813                 :             : #endif
   11814                 :             :         }
   11815                 :             :     }
   11816                 :      280784 : }
   11817                 :             : 
   11818                 :             : /*
   11819                 :             :  * strip_var
   11820                 :             :  *
   11821                 :             :  * Strip any leading and trailing zeroes from a numeric variable
   11822                 :             :  */
   11823                 :             : static void
   11824                 :     2191282 : strip_var(NumericVar *var)
   11825                 :             : {
   11826                 :     2191282 :     NumericDigit *digits = var->digits;
   11827                 :     2191282 :     int         ndigits = var->ndigits;
   11828                 :             : 
   11829                 :             :     /* Strip leading zeroes */
   11830   [ +  +  +  + ]:     3766135 :     while (ndigits > 0 && *digits == 0)
   11831                 :             :     {
   11832                 :     1574853 :         digits++;
   11833                 :     1574853 :         var->weight--;
   11834                 :     1574853 :         ndigits--;
   11835                 :             :     }
   11836                 :             : 
   11837                 :             :     /* Strip trailing zeroes */
   11838   [ +  +  +  + ]:     2643083 :     while (ndigits > 0 && digits[ndigits - 1] == 0)
   11839                 :      451801 :         ndigits--;
   11840                 :             : 
   11841                 :             :     /* If it's zero, normalize the sign and weight */
   11842         [ +  + ]:     2191282 :     if (ndigits == 0)
   11843                 :             :     {
   11844                 :       34612 :         var->sign = NUMERIC_POS;
   11845                 :       34612 :         var->weight = 0;
   11846                 :             :     }
   11847                 :             : 
   11848                 :     2191282 :     var->digits = digits;
   11849                 :     2191282 :     var->ndigits = ndigits;
   11850                 :     2191282 : }
   11851                 :             : 
   11852                 :             : 
   11853                 :             : /* ----------------------------------------------------------------------
   11854                 :             :  *
   11855                 :             :  * Fast sum accumulator functions
   11856                 :             :  *
   11857                 :             :  * ----------------------------------------------------------------------
   11858                 :             :  */
   11859                 :             : 
   11860                 :             : /*
   11861                 :             :  * Reset the accumulator's value to zero.  The buffers to hold the digits
   11862                 :             :  * are not free'd.
   11863                 :             :  */
   11864                 :             : static void
   11865                 :          12 : accum_sum_reset(NumericSumAccum *accum)
   11866                 :             : {
   11867                 :             :     int         i;
   11868                 :             : 
   11869                 :          12 :     accum->dscale = 0;
   11870         [ +  + ]:          44 :     for (i = 0; i < accum->ndigits; i++)
   11871                 :             :     {
   11872                 :          32 :         accum->pos_digits[i] = 0;
   11873                 :          32 :         accum->neg_digits[i] = 0;
   11874                 :             :     }
   11875                 :          12 : }
   11876                 :             : 
   11877                 :             : /*
   11878                 :             :  * Accumulate a new value.
   11879                 :             :  */
   11880                 :             : static void
   11881                 :     1570448 : accum_sum_add(NumericSumAccum *accum, const NumericVar *val)
   11882                 :             : {
   11883                 :             :     int32      *accum_digits;
   11884                 :             :     int         i,
   11885                 :             :                 val_i;
   11886                 :             :     int         val_ndigits;
   11887                 :             :     NumericDigit *val_digits;
   11888                 :             : 
   11889                 :             :     /*
   11890                 :             :      * If we have accumulated too many values since the last carry
   11891                 :             :      * propagation, do it now, to avoid overflowing.  (We could allow more
   11892                 :             :      * than NBASE - 1, if we reserved two extra digits, rather than one, for
   11893                 :             :      * carry propagation.  But even with NBASE - 1, this needs to be done so
   11894                 :             :      * seldom, that the performance difference is negligible.)
   11895                 :             :      */
   11896         [ +  + ]:     1570448 :     if (accum->num_uncarried == NBASE - 1)
   11897                 :         104 :         accum_sum_carry(accum);
   11898                 :             : 
   11899                 :             :     /*
   11900                 :             :      * Adjust the weight or scale of the old value, so that it can accommodate
   11901                 :             :      * the new value.
   11902                 :             :      */
   11903                 :     1570448 :     accum_sum_rescale(accum, val);
   11904                 :             : 
   11905                 :             :     /* */
   11906         [ +  + ]:     1570448 :     if (val->sign == NUMERIC_POS)
   11907                 :     1169996 :         accum_digits = accum->pos_digits;
   11908                 :             :     else
   11909                 :      400452 :         accum_digits = accum->neg_digits;
   11910                 :             : 
   11911                 :             :     /* copy these values into local vars for speed in loop */
   11912                 :     1570448 :     val_ndigits = val->ndigits;
   11913                 :     1570448 :     val_digits = val->digits;
   11914                 :             : 
   11915                 :     1570448 :     i = accum->weight - val->weight;
   11916         [ +  + ]:     7926592 :     for (val_i = 0; val_i < val_ndigits; val_i++)
   11917                 :             :     {
   11918                 :     6356144 :         accum_digits[i] += (int32) val_digits[val_i];
   11919                 :     6356144 :         i++;
   11920                 :             :     }
   11921                 :             : 
   11922                 :     1570448 :     accum->num_uncarried++;
   11923                 :     1570448 : }
   11924                 :             : 
   11925                 :             : /*
   11926                 :             :  * Propagate carries.
   11927                 :             :  */
   11928                 :             : static void
   11929                 :      115162 : accum_sum_carry(NumericSumAccum *accum)
   11930                 :             : {
   11931                 :             :     int         i;
   11932                 :             :     int         ndigits;
   11933                 :             :     int32      *dig;
   11934                 :             :     int32       carry;
   11935                 :      115162 :     int32       newdig = 0;
   11936                 :             : 
   11937                 :             :     /*
   11938                 :             :      * If no new values have been added since last carry propagation, nothing
   11939                 :             :      * to do.
   11940                 :             :      */
   11941         [ +  + ]:      115162 :     if (accum->num_uncarried == 0)
   11942                 :          48 :         return;
   11943                 :             : 
   11944                 :             :     /*
   11945                 :             :      * We maintain that the weight of the accumulator is always one larger
   11946                 :             :      * than needed to hold the current value, before carrying, to make sure
   11947                 :             :      * there is enough space for the possible extra digit when carry is
   11948                 :             :      * propagated.  We cannot expand the buffer here, unless we require
   11949                 :             :      * callers of accum_sum_final() to switch to the right memory context.
   11950                 :             :      */
   11951                 :             :     Assert(accum->pos_digits[0] == 0 && accum->neg_digits[0] == 0);
   11952                 :             : 
   11953                 :      115114 :     ndigits = accum->ndigits;
   11954                 :             : 
   11955                 :             :     /* Propagate carry in the positive sum */
   11956                 :      115114 :     dig = accum->pos_digits;
   11957                 :      115114 :     carry = 0;
   11958         [ +  + ]:     1736994 :     for (i = ndigits - 1; i >= 0; i--)
   11959                 :             :     {
   11960                 :     1621880 :         newdig = dig[i] + carry;
   11961         [ +  + ]:     1621880 :         if (newdig >= NBASE)
   11962                 :             :         {
   11963                 :       73876 :             carry = newdig / NBASE;
   11964                 :       73876 :             newdig -= carry * NBASE;
   11965                 :             :         }
   11966                 :             :         else
   11967                 :     1548004 :             carry = 0;
   11968                 :     1621880 :         dig[i] = newdig;
   11969                 :             :     }
   11970                 :             :     /* Did we use up the digit reserved for carry propagation? */
   11971         [ +  + ]:      115114 :     if (newdig > 0)
   11972                 :        1760 :         accum->have_carry_space = false;
   11973                 :             : 
   11974                 :             :     /* And the same for the negative sum */
   11975                 :      115114 :     dig = accum->neg_digits;
   11976                 :      115114 :     carry = 0;
   11977         [ +  + ]:     1736994 :     for (i = ndigits - 1; i >= 0; i--)
   11978                 :             :     {
   11979                 :     1621880 :         newdig = dig[i] + carry;
   11980         [ +  + ]:     1621880 :         if (newdig >= NBASE)
   11981                 :             :         {
   11982                 :         132 :             carry = newdig / NBASE;
   11983                 :         132 :             newdig -= carry * NBASE;
   11984                 :             :         }
   11985                 :             :         else
   11986                 :     1621748 :             carry = 0;
   11987                 :     1621880 :         dig[i] = newdig;
   11988                 :             :     }
   11989         [ +  + ]:      115114 :     if (newdig > 0)
   11990                 :          20 :         accum->have_carry_space = false;
   11991                 :             : 
   11992                 :      115114 :     accum->num_uncarried = 0;
   11993                 :             : }
   11994                 :             : 
   11995                 :             : /*
   11996                 :             :  * Re-scale accumulator to accommodate new value.
   11997                 :             :  *
   11998                 :             :  * If the new value has more digits than the current digit buffers in the
   11999                 :             :  * accumulator, enlarge the buffers.
   12000                 :             :  */
   12001                 :             : static void
   12002                 :     1570448 : accum_sum_rescale(NumericSumAccum *accum, const NumericVar *val)
   12003                 :             : {
   12004                 :     1570448 :     int         old_weight = accum->weight;
   12005                 :     1570448 :     int         old_ndigits = accum->ndigits;
   12006                 :             :     int         accum_ndigits;
   12007                 :             :     int         accum_weight;
   12008                 :             :     int         accum_rscale;
   12009                 :             :     int         val_rscale;
   12010                 :             : 
   12011                 :     1570448 :     accum_weight = old_weight;
   12012                 :     1570448 :     accum_ndigits = old_ndigits;
   12013                 :             : 
   12014                 :             :     /*
   12015                 :             :      * Does the new value have a larger weight? If so, enlarge the buffers,
   12016                 :             :      * and shift the existing value to the new weight, by adding leading
   12017                 :             :      * zeros.
   12018                 :             :      *
   12019                 :             :      * We enforce that the accumulator always has a weight one larger than
   12020                 :             :      * needed for the inputs, so that we have space for an extra digit at the
   12021                 :             :      * final carry-propagation phase, if necessary.
   12022                 :             :      */
   12023         [ +  + ]:     1570448 :     if (val->weight >= accum_weight)
   12024                 :             :     {
   12025                 :      174806 :         accum_weight = val->weight + 1;
   12026                 :      174806 :         accum_ndigits = accum_ndigits + (accum_weight - old_weight);
   12027                 :             :     }
   12028                 :             : 
   12029                 :             :     /*
   12030                 :             :      * Even though the new value is small, we might've used up the space
   12031                 :             :      * reserved for the carry digit in the last call to accum_sum_carry().  If
   12032                 :             :      * so, enlarge to make room for another one.
   12033                 :             :      */
   12034         [ +  + ]:     1395642 :     else if (!accum->have_carry_space)
   12035                 :             :     {
   12036                 :          56 :         accum_weight++;
   12037                 :          56 :         accum_ndigits++;
   12038                 :             :     }
   12039                 :             : 
   12040                 :             :     /* Is the new value wider on the right side? */
   12041                 :     1570448 :     accum_rscale = accum_ndigits - accum_weight - 1;
   12042                 :     1570448 :     val_rscale = val->ndigits - val->weight - 1;
   12043         [ +  + ]:     1570448 :     if (val_rscale > accum_rscale)
   12044                 :      114822 :         accum_ndigits = accum_ndigits + (val_rscale - accum_rscale);
   12045                 :             : 
   12046   [ +  +  -  + ]:     1570448 :     if (accum_ndigits != old_ndigits ||
   12047                 :             :         accum_weight != old_weight)
   12048                 :             :     {
   12049                 :             :         int32      *new_pos_digits;
   12050                 :             :         int32      *new_neg_digits;
   12051                 :             :         int         weightdiff;
   12052                 :             : 
   12053                 :      175069 :         weightdiff = accum_weight - old_weight;
   12054                 :             : 
   12055                 :      175069 :         new_pos_digits = palloc0(accum_ndigits * sizeof(int32));
   12056                 :      175069 :         new_neg_digits = palloc0(accum_ndigits * sizeof(int32));
   12057                 :             : 
   12058         [ +  + ]:      175069 :         if (accum->pos_digits)
   12059                 :             :         {
   12060                 :       60295 :             memcpy(&new_pos_digits[weightdiff], accum->pos_digits,
   12061                 :             :                    old_ndigits * sizeof(int32));
   12062                 :       60295 :             pfree(accum->pos_digits);
   12063                 :             : 
   12064                 :       60295 :             memcpy(&new_neg_digits[weightdiff], accum->neg_digits,
   12065                 :             :                    old_ndigits * sizeof(int32));
   12066                 :       60295 :             pfree(accum->neg_digits);
   12067                 :             :         }
   12068                 :             : 
   12069                 :      175069 :         accum->pos_digits = new_pos_digits;
   12070                 :      175069 :         accum->neg_digits = new_neg_digits;
   12071                 :             : 
   12072                 :      175069 :         accum->weight = accum_weight;
   12073                 :      175069 :         accum->ndigits = accum_ndigits;
   12074                 :             : 
   12075                 :             :         Assert(accum->pos_digits[0] == 0 && accum->neg_digits[0] == 0);
   12076                 :      175069 :         accum->have_carry_space = true;
   12077                 :             :     }
   12078                 :             : 
   12079         [ +  + ]:     1570448 :     if (val->dscale > accum->dscale)
   12080                 :         200 :         accum->dscale = val->dscale;
   12081                 :     1570448 : }
   12082                 :             : 
   12083                 :             : /*
   12084                 :             :  * Return the current value of the accumulator.  This perform final carry
   12085                 :             :  * propagation, and adds together the positive and negative sums.
   12086                 :             :  *
   12087                 :             :  * Unlike all the other routines, the caller is not required to switch to
   12088                 :             :  * the memory context that holds the accumulator.
   12089                 :             :  */
   12090                 :             : static void
   12091                 :      115058 : accum_sum_final(NumericSumAccum *accum, NumericVar *result)
   12092                 :             : {
   12093                 :             :     int         i;
   12094                 :             :     NumericVar  pos_var;
   12095                 :             :     NumericVar  neg_var;
   12096                 :             : 
   12097         [ -  + ]:      115058 :     if (accum->ndigits == 0)
   12098                 :             :     {
   12099                 :           0 :         set_var_from_var(&const_zero, result);
   12100                 :           0 :         return;
   12101                 :             :     }
   12102                 :             : 
   12103                 :             :     /* Perform final carry */
   12104                 :      115058 :     accum_sum_carry(accum);
   12105                 :             : 
   12106                 :             :     /* Create NumericVars representing the positive and negative sums */
   12107                 :      115058 :     init_var(&pos_var);
   12108                 :      115058 :     init_var(&neg_var);
   12109                 :             : 
   12110                 :      115058 :     pos_var.ndigits = neg_var.ndigits = accum->ndigits;
   12111                 :      115058 :     pos_var.weight = neg_var.weight = accum->weight;
   12112                 :      115058 :     pos_var.dscale = neg_var.dscale = accum->dscale;
   12113                 :      115058 :     pos_var.sign = NUMERIC_POS;
   12114                 :      115058 :     neg_var.sign = NUMERIC_NEG;
   12115                 :             : 
   12116                 :      115058 :     pos_var.buf = pos_var.digits = digitbuf_alloc(accum->ndigits);
   12117                 :      115058 :     neg_var.buf = neg_var.digits = digitbuf_alloc(accum->ndigits);
   12118                 :             : 
   12119         [ +  + ]:     1736706 :     for (i = 0; i < accum->ndigits; i++)
   12120                 :             :     {
   12121                 :             :         Assert(accum->pos_digits[i] < NBASE);
   12122                 :     1621648 :         pos_var.digits[i] = (int16) accum->pos_digits[i];
   12123                 :             : 
   12124                 :             :         Assert(accum->neg_digits[i] < NBASE);
   12125                 :     1621648 :         neg_var.digits[i] = (int16) accum->neg_digits[i];
   12126                 :             :     }
   12127                 :             : 
   12128                 :             :     /* And add them together */
   12129                 :      115058 :     add_var(&pos_var, &neg_var, result);
   12130                 :             : 
   12131                 :             :     /* Remove leading/trailing zeroes */
   12132                 :      115058 :     strip_var(result);
   12133                 :             : }
   12134                 :             : 
   12135                 :             : /*
   12136                 :             :  * Copy an accumulator's state.
   12137                 :             :  *
   12138                 :             :  * 'dst' is assumed to be uninitialized beforehand.  No attempt is made at
   12139                 :             :  * freeing old values.
   12140                 :             :  */
   12141                 :             : static void
   12142                 :          28 : accum_sum_copy(NumericSumAccum *dst, NumericSumAccum *src)
   12143                 :             : {
   12144                 :          28 :     dst->pos_digits = palloc(src->ndigits * sizeof(int32));
   12145                 :          28 :     dst->neg_digits = palloc(src->ndigits * sizeof(int32));
   12146                 :             : 
   12147                 :          28 :     memcpy(dst->pos_digits, src->pos_digits, src->ndigits * sizeof(int32));
   12148                 :          28 :     memcpy(dst->neg_digits, src->neg_digits, src->ndigits * sizeof(int32));
   12149                 :          28 :     dst->num_uncarried = src->num_uncarried;
   12150                 :          28 :     dst->ndigits = src->ndigits;
   12151                 :          28 :     dst->weight = src->weight;
   12152                 :          28 :     dst->dscale = src->dscale;
   12153                 :          28 : }
   12154                 :             : 
   12155                 :             : /*
   12156                 :             :  * Add the current value of 'accum2' into 'accum'.
   12157                 :             :  */
   12158                 :             : static void
   12159                 :          36 : accum_sum_combine(NumericSumAccum *accum, NumericSumAccum *accum2)
   12160                 :             : {
   12161                 :             :     NumericVar  tmp_var;
   12162                 :             : 
   12163                 :          36 :     init_var(&tmp_var);
   12164                 :             : 
   12165                 :          36 :     accum_sum_final(accum2, &tmp_var);
   12166                 :          36 :     accum_sum_add(accum, &tmp_var);
   12167                 :             : 
   12168                 :          36 :     free_var(&tmp_var);
   12169                 :          36 : }
        

Generated by: LCOV version 2.0-1