LCOV - code coverage report
Current view: top level - src/backend/utils/adt - numeric.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 94.4 % 4000 3777
Test Date: 2026-08-11 06:15:55 Functions: 99.1 % 212 210
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 78.7 % 2461 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                 :      103190 : numeric_in(PG_FUNCTION_ARGS)
     627                 :             : {
     628                 :      103190 :     char       *str = PG_GETARG_CSTRING(0);
     629                 :             : #ifdef NOT_USED
     630                 :             :     Oid         typelem = PG_GETARG_OID(1);
     631                 :             : #endif
     632                 :      103190 :     int32       typmod = PG_GETARG_INT32(2);
     633                 :      103190 :     Node       *escontext = fcinfo->context;
     634                 :             :     Numeric     res;
     635                 :             :     const char *cp;
     636                 :             :     const char *numstart;
     637                 :             :     int         sign;
     638                 :             : 
     639                 :             :     /* Skip leading spaces */
     640                 :      103190 :     cp = str;
     641         [ +  + ]:      119470 :     while (*cp)
     642                 :             :     {
     643         [ +  + ]:      119458 :         if (!isspace((unsigned char) *cp))
     644                 :      103178 :             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                 :      103190 :     numstart = cp;
     654                 :      103190 :     sign = NUMERIC_POS;
     655                 :             : 
     656         [ +  + ]:      103190 :     if (*cp == '+')
     657                 :          32 :         cp++;
     658         [ +  + ]:      103158 :     else if (*cp == '-')
     659                 :             :     {
     660                 :        2501 :         sign = NUMERIC_NEG;
     661                 :        2501 :         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   [ +  +  +  + ]:      103190 :     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                 :      101989 :         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         [ +  + ]:      101989 :         if (cp[0] == '0')
     728                 :             :         {
     729   [ +  +  +  + ]:       31740 :             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                 :       31636 :                 default:
     744                 :       31636 :                     base = 10;
     745                 :             :             }
     746                 :             :         }
     747                 :             :         else
     748                 :       70249 :             base = 10;
     749                 :             : 
     750                 :             :         /* Parse the rest of the number and apply the sign */
     751         [ +  + ]:      101989 :         if (base == 10)
     752                 :             :         {
     753         [ -  + ]:      101885 :             if (!set_var_from_str(str, cp, &value, &cp, escontext))
     754                 :          16 :                 PG_RETURN_NULL();
     755                 :      101853 :             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         [ +  + ]:      101997 :         while (*cp)
     769                 :             :         {
     770         [ +  + ]:         100 :             if (!isspace((unsigned char) *cp))
     771                 :          48 :                 goto invalid_syntax;
     772                 :          52 :             cp++;
     773                 :             :         }
     774                 :             : 
     775         [ +  + ]:      101897 :         if (!apply_typmod(&value, typmod, escontext))
     776                 :          16 :             PG_RETURN_NULL();
     777                 :             : 
     778                 :      101881 :         res = make_result_safe(&value, escontext);
     779                 :             : 
     780                 :      101881 :         free_var(&value);
     781                 :             :     }
     782                 :             : 
     783                 :      103009 :     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                 :      536972 : numeric_out(PG_FUNCTION_ARGS)
     800                 :             : {
     801                 :      536972 :     Numeric     num = PG_GETARG_NUMERIC(0);
     802                 :             :     NumericVar  x;
     803                 :             :     char       *str;
     804                 :             : 
     805                 :             :     /*
     806                 :             :      * Handle NaN and infinities
     807                 :             :      */
     808         [ +  + ]:      536972 :     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                 :      534628 :     init_var_from_num(num, &x);
     822                 :             : 
     823                 :      534628 :     str = get_str_from_var(&x);
     824                 :             : 
     825                 :      534628 :     PG_RETURN_CSTRING(str);
     826                 :             : }
     827                 :             : 
     828                 :             : /*
     829                 :             :  * numeric_is_nan() -
     830                 :             :  *
     831                 :             :  *  Is Numeric value a NaN?
     832                 :             :  */
     833                 :             : bool
     834                 :        4490 : numeric_is_nan(Numeric num)
     835                 :             : {
     836                 :        4490 :     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                 :      119188 : is_valid_numeric_typmod(int32 typmod)
     900                 :             : {
     901                 :      119188 :     return typmod >= (int32) VARHDRSZ;
     902                 :             : }
     903                 :             : 
     904                 :             : /*
     905                 :             :  * numeric_typmod_precision() -
     906                 :             :  *
     907                 :             :  *  Extract the precision from a numeric typmod --- see make_numeric_typmod().
     908                 :             :  */
     909                 :             : static inline int
     910                 :       32945 : numeric_typmod_precision(int32 typmod)
     911                 :             : {
     912                 :       32945 :     return ((typmod - VARHDRSZ) >> 16) & 0xffff;
     913                 :             : }
     914                 :             : 
     915                 :             : /*
     916                 :             :  * numeric_typmod_scale() -
     917                 :             :  *
     918                 :             :  *  Extract the scale from a numeric typmod --- see make_numeric_typmod().
     919                 :             :  *
     920                 :             :  *  Note that the scale may be negative, so we must do sign extension when
     921                 :             :  *  unpacking it.  We do this using the bit hack (x^1024)-1024, which sign
     922                 :             :  *  extends an 11-bit two's complement number x.
     923                 :             :  */
     924                 :             : static inline int
     925                 :       28030 : numeric_typmod_scale(int32 typmod)
     926                 :             : {
     927                 :       28030 :     return (((typmod - VARHDRSZ) & 0x7ff) ^ 1024) - 1024;
     928                 :             : }
     929                 :             : 
     930                 :             : /*
     931                 :             :  * numeric_maximum_size() -
     932                 :             :  *
     933                 :             :  *  Maximum size of a numeric with given typmod, or -1 if unlimited/unknown.
     934                 :             :  */
     935                 :             : int32
     936                 :        4915 : numeric_maximum_size(int32 typmod)
     937                 :             : {
     938                 :             :     int         precision;
     939                 :             :     int         numeric_digits;
     940                 :             : 
     941         [ -  + ]:        4915 :     if (!is_valid_numeric_typmod(typmod))
     942                 :           0 :         return -1;
     943                 :             : 
     944                 :             :     /* precision (ie, max # of digits) is in upper bits of typmod */
     945                 :        4915 :     precision = numeric_typmod_precision(typmod);
     946                 :             : 
     947                 :             :     /*
     948                 :             :      * This formula computes the maximum number of NumericDigits we could need
     949                 :             :      * in order to store the specified number of decimal digits. Because the
     950                 :             :      * weight is stored as a number of NumericDigits rather than a number of
     951                 :             :      * decimal digits, it's possible that the first NumericDigit will contain
     952                 :             :      * only a single decimal digit.  Thus, the first two decimal digits can
     953                 :             :      * require two NumericDigits to store, but it isn't until we reach
     954                 :             :      * DEC_DIGITS + 2 decimal digits that we potentially need a third
     955                 :             :      * NumericDigit.
     956                 :             :      */
     957                 :        4915 :     numeric_digits = (precision + 2 * (DEC_DIGITS - 1)) / DEC_DIGITS;
     958                 :             : 
     959                 :             :     /*
     960                 :             :      * In most cases, the size of a numeric will be smaller than the value
     961                 :             :      * computed below, because the varlena header will typically get toasted
     962                 :             :      * down to a single byte before being stored on disk, and it may also be
     963                 :             :      * possible to use a short numeric header.  But our job here is to compute
     964                 :             :      * the worst case.
     965                 :             :      */
     966                 :        4915 :     return NUMERIC_HDRSZ + (numeric_digits * sizeof(NumericDigit));
     967                 :             : }
     968                 :             : 
     969                 :             : /*
     970                 :             :  * numeric_out_sci() -
     971                 :             :  *
     972                 :             :  *  Output function for numeric data type in scientific notation.
     973                 :             :  */
     974                 :             : char *
     975                 :         164 : numeric_out_sci(Numeric num, int scale)
     976                 :             : {
     977                 :             :     NumericVar  x;
     978                 :             :     char       *str;
     979                 :             : 
     980                 :             :     /*
     981                 :             :      * Handle NaN and infinities
     982                 :             :      */
     983         [ +  + ]:         164 :     if (NUMERIC_IS_SPECIAL(num))
     984                 :             :     {
     985         [ +  + ]:          12 :         if (NUMERIC_IS_PINF(num))
     986                 :           4 :             return pstrdup("Infinity");
     987         [ +  + ]:           8 :         else if (NUMERIC_IS_NINF(num))
     988                 :           4 :             return pstrdup("-Infinity");
     989                 :             :         else
     990                 :           4 :             return pstrdup("NaN");
     991                 :             :     }
     992                 :             : 
     993                 :         152 :     init_var_from_num(num, &x);
     994                 :             : 
     995                 :         152 :     str = get_str_from_var_sci(&x, scale);
     996                 :             : 
     997                 :         152 :     return str;
     998                 :             : }
     999                 :             : 
    1000                 :             : /*
    1001                 :             :  * numeric_normalize() -
    1002                 :             :  *
    1003                 :             :  *  Output function for numeric data type, suppressing insignificant trailing
    1004                 :             :  *  zeroes and then any trailing decimal point.  The intent of this is to
    1005                 :             :  *  produce strings that are equal if and only if the input numeric values
    1006                 :             :  *  compare equal.
    1007                 :             :  */
    1008                 :             : char *
    1009                 :       27344 : numeric_normalize(Numeric num)
    1010                 :             : {
    1011                 :             :     NumericVar  x;
    1012                 :             :     char       *str;
    1013                 :             :     int         last;
    1014                 :             : 
    1015                 :             :     /*
    1016                 :             :      * Handle NaN and infinities
    1017                 :             :      */
    1018         [ -  + ]:       27344 :     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                 :       27344 :     init_var_from_num(num, &x);
    1029                 :             : 
    1030                 :       27344 :     str = get_str_from_var(&x);
    1031                 :             : 
    1032                 :             :     /* If there's no decimal point, there's certainly nothing to remove. */
    1033         [ +  + ]:       27344 :     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                 :       27344 :     return str;
    1052                 :             : }
    1053                 :             : 
    1054                 :             : /*
    1055                 :             :  *      numeric_recv            - converts external binary format to numeric
    1056                 :             :  *
    1057                 :             :  * External format is a sequence of int16's:
    1058                 :             :  * ndigits, weight, sign, dscale, NumericDigits.
    1059                 :             :  */
    1060                 :             : Datum
    1061                 :          51 : numeric_recv(PG_FUNCTION_ARGS)
    1062                 :             : {
    1063                 :          51 :     StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
    1064                 :             : 
    1065                 :             : #ifdef NOT_USED
    1066                 :             :     Oid         typelem = PG_GETARG_OID(1);
    1067                 :             : #endif
    1068                 :          51 :     int32       typmod = PG_GETARG_INT32(2);
    1069                 :             :     NumericVar  value;
    1070                 :             :     Numeric     res;
    1071                 :             :     int         len,
    1072                 :             :                 i;
    1073                 :             : 
    1074                 :          51 :     init_var(&value);
    1075                 :             : 
    1076                 :          51 :     len = (uint16) pq_getmsgint(buf, sizeof(uint16));
    1077                 :             : 
    1078                 :          51 :     alloc_var(&value, len);
    1079                 :             : 
    1080                 :          51 :     value.weight = (int16) pq_getmsgint(buf, sizeof(int16));
    1081                 :             :     /* we allow any int16 for weight --- OK? */
    1082                 :             : 
    1083                 :          51 :     value.sign = (uint16) pq_getmsgint(buf, sizeof(uint16));
    1084         [ -  + ]:          51 :     if (!(value.sign == NUMERIC_POS ||
    1085         [ #  # ]:           0 :           value.sign == NUMERIC_NEG ||
    1086         [ #  # ]:           0 :           value.sign == NUMERIC_NAN ||
    1087         [ #  # ]:           0 :           value.sign == NUMERIC_PINF ||
    1088         [ #  # ]:           0 :           value.sign == NUMERIC_NINF))
    1089         [ #  # ]:           0 :         ereport(ERROR,
    1090                 :             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
    1091                 :             :                  errmsg("invalid sign in external \"numeric\" value")));
    1092                 :             : 
    1093                 :          51 :     value.dscale = (uint16) pq_getmsgint(buf, sizeof(uint16));
    1094         [ -  + ]:          51 :     if ((value.dscale & NUMERIC_DSCALE_MASK) != value.dscale)
    1095         [ #  # ]:           0 :         ereport(ERROR,
    1096                 :             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
    1097                 :             :                  errmsg("invalid scale in external \"numeric\" value")));
    1098                 :             : 
    1099         [ +  + ]:         137 :     for (i = 0; i < len; i++)
    1100                 :             :     {
    1101                 :          86 :         NumericDigit d = pq_getmsgint(buf, sizeof(NumericDigit));
    1102                 :             : 
    1103   [ +  -  -  + ]:          86 :         if (d < 0 || d >= NBASE)
    1104         [ #  # ]:           0 :             ereport(ERROR,
    1105                 :             :                     (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
    1106                 :             :                      errmsg("invalid digit in external \"numeric\" value")));
    1107                 :          86 :         value.digits[i] = d;
    1108                 :             :     }
    1109                 :             : 
    1110                 :             :     /*
    1111                 :             :      * If the given dscale would hide any digits, truncate those digits away.
    1112                 :             :      * We could alternatively throw an error, but that would take a bunch of
    1113                 :             :      * extra code (about as much as trunc_var involves), and it might cause
    1114                 :             :      * client compatibility issues.  Be careful not to apply trunc_var to
    1115                 :             :      * special values, as it could do the wrong thing; we don't need it
    1116                 :             :      * anyway, since make_result will ignore all but the sign field.
    1117                 :             :      *
    1118                 :             :      * After doing that, be sure to check the typmod restriction.
    1119                 :             :      */
    1120         [ -  + ]:          51 :     if (value.sign == NUMERIC_POS ||
    1121         [ #  # ]:           0 :         value.sign == NUMERIC_NEG)
    1122                 :             :     {
    1123                 :          51 :         trunc_var(&value, value.dscale);
    1124                 :             : 
    1125                 :          51 :         (void) apply_typmod(&value, typmod, NULL);
    1126                 :             : 
    1127                 :          51 :         res = make_result(&value);
    1128                 :             :     }
    1129                 :             :     else
    1130                 :             :     {
    1131                 :             :         /* apply_typmod_special wants us to make the Numeric first */
    1132                 :           0 :         res = make_result(&value);
    1133                 :             : 
    1134                 :           0 :         (void) apply_typmod_special(res, typmod, NULL);
    1135                 :             :     }
    1136                 :             : 
    1137                 :          51 :     free_var(&value);
    1138                 :             : 
    1139                 :          51 :     PG_RETURN_NUMERIC(res);
    1140                 :             : }
    1141                 :             : 
    1142                 :             : /*
    1143                 :             :  *      numeric_send            - converts numeric to binary format
    1144                 :             :  */
    1145                 :             : Datum
    1146                 :          35 : numeric_send(PG_FUNCTION_ARGS)
    1147                 :             : {
    1148                 :          35 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1149                 :             :     NumericVar  x;
    1150                 :             :     StringInfoData buf;
    1151                 :             :     int         i;
    1152                 :             : 
    1153                 :          35 :     init_var_from_num(num, &x);
    1154                 :             : 
    1155                 :          35 :     pq_begintypsend(&buf);
    1156                 :             : 
    1157                 :          35 :     pq_sendint16(&buf, x.ndigits);
    1158                 :          35 :     pq_sendint16(&buf, x.weight);
    1159                 :          35 :     pq_sendint16(&buf, x.sign);
    1160                 :          35 :     pq_sendint16(&buf, x.dscale);
    1161         [ +  + ]:          97 :     for (i = 0; i < x.ndigits; i++)
    1162                 :          62 :         pq_sendint16(&buf, x.digits[i]);
    1163                 :             : 
    1164                 :          35 :     PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
    1165                 :             : }
    1166                 :             : 
    1167                 :             : 
    1168                 :             : /*
    1169                 :             :  * numeric_support()
    1170                 :             :  *
    1171                 :             :  * Planner support function for the numeric() length coercion function.
    1172                 :             :  *
    1173                 :             :  * Flatten calls that solely represent increases in allowable precision.
    1174                 :             :  * Scale changes mutate every datum, so they are unoptimizable.  Some values,
    1175                 :             :  * e.g. 1E-1001, can only fit into an unconstrained numeric, so a change from
    1176                 :             :  * an unconstrained numeric to any constrained numeric is also unoptimizable.
    1177                 :             :  */
    1178                 :             : Datum
    1179                 :         427 : numeric_support(PG_FUNCTION_ARGS)
    1180                 :             : {
    1181                 :         427 :     Node       *rawreq = (Node *) PG_GETARG_POINTER(0);
    1182                 :         427 :     Node       *ret = NULL;
    1183                 :             : 
    1184         [ +  + ]:         427 :     if (IsA(rawreq, SupportRequestSimplify))
    1185                 :             :     {
    1186                 :         187 :         SupportRequestSimplify *req = (SupportRequestSimplify *) rawreq;
    1187                 :         187 :         FuncExpr   *expr = req->fcall;
    1188                 :             :         Node       *typmod;
    1189                 :             : 
    1190                 :             :         Assert(list_length(expr->args) >= 2);
    1191                 :             : 
    1192                 :         187 :         typmod = (Node *) lsecond(expr->args);
    1193                 :             : 
    1194   [ +  -  +  - ]:         187 :         if (IsA(typmod, Const) && !((Const *) typmod)->constisnull)
    1195                 :             :         {
    1196                 :         187 :             Node       *source = (Node *) linitial(expr->args);
    1197                 :         187 :             int32       old_typmod = exprTypmod(source);
    1198                 :         187 :             int32       new_typmod = DatumGetInt32(((Const *) typmod)->constvalue);
    1199                 :         187 :             int32       old_scale = numeric_typmod_scale(old_typmod);
    1200                 :         187 :             int32       new_scale = numeric_typmod_scale(new_typmod);
    1201                 :         187 :             int32       old_precision = numeric_typmod_precision(old_typmod);
    1202                 :         187 :             int32       new_precision = numeric_typmod_precision(new_typmod);
    1203                 :             : 
    1204                 :             :             /*
    1205                 :             :              * If new_typmod is invalid, the destination is unconstrained;
    1206                 :             :              * that's always OK.  If old_typmod is valid, the source is
    1207                 :             :              * constrained, and we're OK if the scale is unchanged and the
    1208                 :             :              * precision is not decreasing.  See further notes in function
    1209                 :             :              * header comment.
    1210                 :             :              */
    1211   [ +  -  +  + ]:         374 :             if (!is_valid_numeric_typmod(new_typmod) ||
    1212         [ +  + ]:         196 :                 (is_valid_numeric_typmod(old_typmod) &&
    1213         [ +  - ]:           4 :                  new_scale == old_scale && new_precision >= old_precision))
    1214                 :           4 :                 ret = relabel_to_typmod(source, new_typmod);
    1215                 :             :         }
    1216                 :             :     }
    1217                 :             : 
    1218                 :         427 :     PG_RETURN_POINTER(ret);
    1219                 :             : }
    1220                 :             : 
    1221                 :             : /*
    1222                 :             :  * numeric() -
    1223                 :             :  *
    1224                 :             :  *  This is a special function called by the Postgres database system
    1225                 :             :  *  before a value is stored in a tuple's attribute. The precision and
    1226                 :             :  *  scale of the attribute have to be applied on the value.
    1227                 :             :  */
    1228                 :             : Datum
    1229                 :        8091 : numeric     (PG_FUNCTION_ARGS)
    1230                 :             : {
    1231                 :        8091 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1232                 :        8091 :     int32       typmod = PG_GETARG_INT32(1);
    1233                 :             :     Numeric     new;
    1234                 :             :     int         precision;
    1235                 :             :     int         scale;
    1236                 :             :     int         ddigits;
    1237                 :             :     int         maxdigits;
    1238                 :             :     int         dscale;
    1239                 :             :     NumericVar  var;
    1240                 :             : 
    1241                 :             :     /*
    1242                 :             :      * Handle NaN and infinities: if apply_typmod_special doesn't complain,
    1243                 :             :      * just return a copy of the input.
    1244                 :             :      */
    1245         [ +  + ]:        8091 :     if (NUMERIC_IS_SPECIAL(num))
    1246                 :             :     {
    1247         [ -  + ]:         172 :         if (!apply_typmod_special(num, typmod, fcinfo->context))
    1248                 :           0 :             PG_RETURN_NULL();
    1249                 :         160 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    1250                 :             :     }
    1251                 :             : 
    1252                 :             :     /*
    1253                 :             :      * If the value isn't a valid type modifier, simply return a copy of the
    1254                 :             :      * input value
    1255                 :             :      */
    1256         [ -  + ]:        7919 :     if (!is_valid_numeric_typmod(typmod))
    1257                 :           0 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    1258                 :             : 
    1259                 :             :     /*
    1260                 :             :      * Get the precision and scale out of the typmod value
    1261                 :             :      */
    1262                 :        7919 :     precision = numeric_typmod_precision(typmod);
    1263                 :        7919 :     scale = numeric_typmod_scale(typmod);
    1264                 :        7919 :     maxdigits = precision - scale;
    1265                 :             : 
    1266                 :             :     /* The target display scale is non-negative */
    1267                 :        7919 :     dscale = Max(scale, 0);
    1268                 :             : 
    1269                 :             :     /*
    1270                 :             :      * If the number is certainly in bounds and due to the target scale no
    1271                 :             :      * rounding could be necessary, just make a copy of the input and modify
    1272                 :             :      * its scale fields, unless the larger scale forces us to abandon the
    1273                 :             :      * short representation.  (Note we assume the existing dscale is
    1274                 :             :      * honest...)
    1275                 :             :      */
    1276   [ +  +  +  + ]:        7919 :     ddigits = (NUMERIC_WEIGHT(num) + 1) * DEC_DIGITS;
    1277   [ +  +  +  +  :        7919 :     if (ddigits <= maxdigits && scale >= NUMERIC_DSCALE(num)
                   +  + ]
    1278   [ +  -  +  -  :        4839 :         && (NUMERIC_CAN_BE_SHORT(dscale, NUMERIC_WEIGHT(num))
          +  +  +  -  -  
          -  +  -  +  +  
             -  +  -  - ]
    1279         [ #  # ]:           0 :             || !NUMERIC_IS_SHORT(num)))
    1280                 :             :     {
    1281                 :        4839 :         new = duplicate_numeric(num);
    1282         [ +  - ]:        4839 :         if (NUMERIC_IS_SHORT(num))
    1283                 :        4839 :             new->choice.n_short.n_header =
    1284                 :        4839 :                 (num->choice.n_short.n_header & ~NUMERIC_SHORT_DSCALE_MASK)
    1285                 :        4839 :                 | (dscale << NUMERIC_SHORT_DSCALE_SHIFT);
    1286                 :             :         else
    1287   [ #  #  #  # ]:           0 :             new->choice.n_long.n_sign_dscale = NUMERIC_SIGN(new) |
    1288                 :           0 :                 ((uint16) dscale & NUMERIC_DSCALE_MASK);
    1289                 :        4839 :         PG_RETURN_NUMERIC(new);
    1290                 :             :     }
    1291                 :             : 
    1292                 :             :     /*
    1293                 :             :      * We really need to fiddle with things - unpack the number into a
    1294                 :             :      * variable and let apply_typmod() do it.
    1295                 :             :      */
    1296                 :        3080 :     init_var(&var);
    1297                 :             : 
    1298                 :        3080 :     set_var_from_num(num, &var);
    1299         [ -  + ]:        3080 :     if (!apply_typmod(&var, typmod, fcinfo->context))
    1300                 :           0 :         PG_RETURN_NULL();
    1301                 :        3032 :     new = make_result_safe(&var, fcinfo->context);
    1302                 :             : 
    1303                 :        3032 :     free_var(&var);
    1304                 :             : 
    1305                 :        3032 :     PG_RETURN_NUMERIC(new);
    1306                 :             : }
    1307                 :             : 
    1308                 :             : /*
    1309                 :             :  * make_numeric_typmod_safe() -
    1310                 :             :  *
    1311                 :             :  *  Validate a numeric precision/scale and pack them into a typmod value,
    1312                 :             :  *  with soft error handling.
    1313                 :             :  */
    1314                 :             : int32
    1315                 :        1132 : make_numeric_typmod_safe(int32 precision, int32 scale, Node *escontext)
    1316                 :             : {
    1317   [ +  +  +  + ]:        1132 :     if (precision < 1 || precision > NUMERIC_MAX_PRECISION)
    1318         [ +  + ]:          29 :         ereturn(escontext, -1,
    1319                 :             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1320                 :             :                  errmsg("NUMERIC precision %d must be between 1 and %d",
    1321                 :             :                         precision, NUMERIC_MAX_PRECISION)));
    1322   [ +  +  +  + ]:        1103 :     if (scale < NUMERIC_MIN_SCALE || scale > NUMERIC_MAX_SCALE)
    1323         [ +  + ]:          16 :         ereturn(escontext, -1,
    1324                 :             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1325                 :             :                  errmsg("NUMERIC scale %d must be between %d and %d",
    1326                 :             :                         scale, NUMERIC_MIN_SCALE, NUMERIC_MAX_SCALE)));
    1327                 :             : 
    1328                 :        1087 :     return make_numeric_typmod(precision, scale);
    1329                 :             : }
    1330                 :             : 
    1331                 :             : Datum
    1332                 :        1055 : numerictypmodin(PG_FUNCTION_ARGS)
    1333                 :             : {
    1334                 :        1055 :     ArrayType  *ta = PG_GETARG_ARRAYTYPE_P(0);
    1335                 :             :     int32      *tl;
    1336                 :             :     int         n;
    1337                 :             :     int32       typmod;
    1338                 :             : 
    1339                 :        1055 :     tl = ArrayGetIntegerTypmods(ta, &n);
    1340                 :             : 
    1341         [ +  + ]:        1055 :     if (n == 2)
    1342                 :        1043 :         typmod = make_numeric_typmod_safe(tl[0], tl[1], NULL);
    1343         [ +  + ]:          12 :     else if (n == 1)
    1344                 :             :     {
    1345                 :             :         /* scale defaults to zero */
    1346                 :           4 :         typmod = make_numeric_typmod_safe(tl[0], 0, NULL);
    1347                 :             :     }
    1348                 :             :     else
    1349                 :             :     {
    1350         [ +  - ]:           8 :         ereport(ERROR,
    1351                 :             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1352                 :             :                  errmsg("invalid NUMERIC type modifier")));
    1353                 :             :         typmod = 0;             /* keep compiler quiet */
    1354                 :             :     }
    1355                 :             : 
    1356                 :        1047 :     PG_RETURN_INT32(typmod);
    1357                 :             : }
    1358                 :             : 
    1359                 :             : Datum
    1360                 :         209 : numerictypmodout(PG_FUNCTION_ARGS)
    1361                 :             : {
    1362                 :         209 :     int32       typmod = PG_GETARG_INT32(0);
    1363                 :         209 :     char       *res = (char *) palloc(64);
    1364                 :             : 
    1365         [ +  - ]:         209 :     if (is_valid_numeric_typmod(typmod))
    1366                 :         209 :         snprintf(res, 64, "(%d,%d)",
    1367                 :             :                  numeric_typmod_precision(typmod),
    1368                 :             :                  numeric_typmod_scale(typmod));
    1369                 :             :     else
    1370                 :           0 :         *res = '\0';
    1371                 :             : 
    1372                 :         209 :     PG_RETURN_CSTRING(res);
    1373                 :             : }
    1374                 :             : 
    1375                 :             : 
    1376                 :             : /* ----------------------------------------------------------------------
    1377                 :             :  *
    1378                 :             :  * Sign manipulation, rounding and the like
    1379                 :             :  *
    1380                 :             :  * ----------------------------------------------------------------------
    1381                 :             :  */
    1382                 :             : 
    1383                 :             : Datum
    1384                 :       13004 : numeric_abs(PG_FUNCTION_ARGS)
    1385                 :             : {
    1386                 :       13004 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1387                 :             :     Numeric     res;
    1388                 :             : 
    1389                 :             :     /*
    1390                 :             :      * Do it the easy way directly on the packed format
    1391                 :             :      */
    1392                 :       13004 :     res = duplicate_numeric(num);
    1393                 :             : 
    1394         [ +  + ]:       13004 :     if (NUMERIC_IS_SHORT(num))
    1395                 :       12960 :         res->choice.n_short.n_header =
    1396                 :       12960 :             num->choice.n_short.n_header & ~NUMERIC_SHORT_SIGN_MASK;
    1397         [ +  + ]:          44 :     else if (NUMERIC_IS_SPECIAL(num))
    1398                 :             :     {
    1399                 :             :         /* This changes -Inf to Inf, and doesn't affect NaN */
    1400                 :          12 :         res->choice.n_short.n_header =
    1401                 :          12 :             num->choice.n_short.n_header & ~NUMERIC_INF_SIGN_MASK;
    1402                 :             :     }
    1403                 :             :     else
    1404         [ -  + ]:          32 :         res->choice.n_long.n_sign_dscale = NUMERIC_POS | NUMERIC_DSCALE(num);
    1405                 :             : 
    1406                 :       13004 :     PG_RETURN_NUMERIC(res);
    1407                 :             : }
    1408                 :             : 
    1409                 :             : 
    1410                 :             : Datum
    1411                 :         631 : numeric_uminus(PG_FUNCTION_ARGS)
    1412                 :             : {
    1413                 :         631 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1414                 :             :     Numeric     res;
    1415                 :             : 
    1416                 :             :     /*
    1417                 :             :      * Do it the easy way directly on the packed format
    1418                 :             :      */
    1419                 :         631 :     res = duplicate_numeric(num);
    1420                 :             : 
    1421         [ +  + ]:         631 :     if (NUMERIC_IS_SPECIAL(num))
    1422                 :             :     {
    1423                 :             :         /* Flip the sign, if it's Inf or -Inf */
    1424         [ +  + ]:          84 :         if (!NUMERIC_IS_NAN(num))
    1425                 :          56 :             res->choice.n_short.n_header =
    1426                 :          56 :                 num->choice.n_short.n_header ^ NUMERIC_INF_SIGN_MASK;
    1427                 :             :     }
    1428                 :             : 
    1429                 :             :     /*
    1430                 :             :      * The packed format is known to be totally zero digit trimmed always. So
    1431                 :             :      * once we've eliminated specials, we can identify a zero by the fact that
    1432                 :             :      * there are no digits at all. Do nothing to a zero.
    1433                 :             :      */
    1434   [ +  -  +  + ]:         547 :     else if (NUMERIC_NDIGITS(num) != 0)
    1435                 :             :     {
    1436                 :             :         /* Else, flip the sign */
    1437         [ +  - ]:         471 :         if (NUMERIC_IS_SHORT(num))
    1438                 :         471 :             res->choice.n_short.n_header =
    1439                 :         471 :                 num->choice.n_short.n_header ^ NUMERIC_SHORT_SIGN_MASK;
    1440   [ #  #  #  #  :           0 :         else if (NUMERIC_SIGN(num) == NUMERIC_POS)
                   #  # ]
    1441                 :           0 :             res->choice.n_long.n_sign_dscale =
    1442         [ #  # ]:           0 :                 NUMERIC_NEG | NUMERIC_DSCALE(num);
    1443                 :             :         else
    1444                 :           0 :             res->choice.n_long.n_sign_dscale =
    1445         [ #  # ]:           0 :                 NUMERIC_POS | NUMERIC_DSCALE(num);
    1446                 :             :     }
    1447                 :             : 
    1448                 :         631 :     PG_RETURN_NUMERIC(res);
    1449                 :             : }
    1450                 :             : 
    1451                 :             : 
    1452                 :             : Datum
    1453                 :           0 : numeric_uplus(PG_FUNCTION_ARGS)
    1454                 :             : {
    1455                 :           0 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1456                 :             : 
    1457                 :           0 :     PG_RETURN_NUMERIC(duplicate_numeric(num));
    1458                 :             : }
    1459                 :             : 
    1460                 :             : 
    1461                 :             : /*
    1462                 :             :  * numeric_sign_internal() -
    1463                 :             :  *
    1464                 :             :  * Returns -1 if the argument is less than 0, 0 if the argument is equal
    1465                 :             :  * to 0, and 1 if the argument is greater than zero.  Caller must have
    1466                 :             :  * taken care of the NaN case, but we can handle infinities here.
    1467                 :             :  */
    1468                 :             : static int
    1469                 :        2476 : numeric_sign_internal(Numeric num)
    1470                 :             : {
    1471         [ +  + ]:        2476 :     if (NUMERIC_IS_SPECIAL(num))
    1472                 :             :     {
    1473                 :             :         Assert(!NUMERIC_IS_NAN(num));
    1474                 :             :         /* Must be Inf or -Inf */
    1475         [ +  + ]:         223 :         if (NUMERIC_IS_PINF(num))
    1476                 :         129 :             return 1;
    1477                 :             :         else
    1478                 :          94 :             return -1;
    1479                 :             :     }
    1480                 :             : 
    1481                 :             :     /*
    1482                 :             :      * The packed format is known to be totally zero digit trimmed always. So
    1483                 :             :      * once we've eliminated specials, we can identify a zero by the fact that
    1484                 :             :      * there are no digits at all.
    1485                 :             :      */
    1486   [ +  +  +  + ]:        2253 :     else if (NUMERIC_NDIGITS(num) == 0)
    1487                 :         161 :         return 0;
    1488   [ +  +  -  +  :        2092 :     else if (NUMERIC_SIGN(num) == NUMERIC_NEG)
                   +  + ]
    1489                 :         511 :         return -1;
    1490                 :             :     else
    1491                 :        1581 :         return 1;
    1492                 :             : }
    1493                 :             : 
    1494                 :             : /*
    1495                 :             :  * numeric_sign() -
    1496                 :             :  *
    1497                 :             :  * returns -1 if the argument is less than 0, 0 if the argument is equal
    1498                 :             :  * to 0, and 1 if the argument is greater than zero.
    1499                 :             :  */
    1500                 :             : Datum
    1501                 :          32 : numeric_sign(PG_FUNCTION_ARGS)
    1502                 :             : {
    1503                 :          32 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1504                 :             : 
    1505                 :             :     /*
    1506                 :             :      * Handle NaN (infinities can be handled normally)
    1507                 :             :      */
    1508         [ +  + ]:          32 :     if (NUMERIC_IS_NAN(num))
    1509                 :           4 :         PG_RETURN_NUMERIC(make_result(&const_nan));
    1510                 :             : 
    1511   [ +  +  +  - ]:          28 :     switch (numeric_sign_internal(num))
    1512                 :             :     {
    1513                 :           4 :         case 0:
    1514                 :           4 :             PG_RETURN_NUMERIC(make_result(&const_zero));
    1515                 :          12 :         case 1:
    1516                 :          12 :             PG_RETURN_NUMERIC(make_result(&const_one));
    1517                 :          12 :         case -1:
    1518                 :          12 :             PG_RETURN_NUMERIC(make_result(&const_minus_one));
    1519                 :             :     }
    1520                 :             : 
    1521                 :             :     Assert(false);
    1522                 :           0 :     return (Datum) 0;
    1523                 :             : }
    1524                 :             : 
    1525                 :             : 
    1526                 :             : /*
    1527                 :             :  * numeric_round() -
    1528                 :             :  *
    1529                 :             :  *  Round a value to have 'scale' digits after the decimal point.
    1530                 :             :  *  We allow negative 'scale', implying rounding before the decimal
    1531                 :             :  *  point --- Oracle interprets rounding that way.
    1532                 :             :  */
    1533                 :             : Datum
    1534                 :        5217 : numeric_round(PG_FUNCTION_ARGS)
    1535                 :             : {
    1536                 :        5217 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1537                 :        5217 :     int32       scale = PG_GETARG_INT32(1);
    1538                 :             :     Numeric     res;
    1539                 :             :     NumericVar  arg;
    1540                 :             : 
    1541                 :             :     /*
    1542                 :             :      * Handle NaN and infinities
    1543                 :             :      */
    1544         [ +  + ]:        5217 :     if (NUMERIC_IS_SPECIAL(num))
    1545                 :          64 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    1546                 :             : 
    1547                 :             :     /*
    1548                 :             :      * Limit the scale value to avoid possible overflow in calculations.
    1549                 :             :      *
    1550                 :             :      * These limits are based on the maximum number of digits a Numeric value
    1551                 :             :      * can have before and after the decimal point, but we must allow for one
    1552                 :             :      * extra digit before the decimal point, in case the most significant
    1553                 :             :      * digit rounds up; we must check if that causes Numeric overflow.
    1554                 :             :      */
    1555                 :        5153 :     scale = Max(scale, -(NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS - 1);
    1556                 :        5153 :     scale = Min(scale, NUMERIC_DSCALE_MAX);
    1557                 :             : 
    1558                 :             :     /*
    1559                 :             :      * Unpack the argument and round it at the proper digit position
    1560                 :             :      */
    1561                 :        5153 :     init_var(&arg);
    1562                 :        5153 :     set_var_from_num(num, &arg);
    1563                 :             : 
    1564                 :        5153 :     round_var(&arg, scale);
    1565                 :             : 
    1566                 :             :     /* We don't allow negative output dscale */
    1567         [ +  + ]:        5153 :     if (scale < 0)
    1568                 :         149 :         arg.dscale = 0;
    1569                 :             : 
    1570                 :             :     /*
    1571                 :             :      * Return the rounded result
    1572                 :             :      */
    1573                 :        5153 :     res = make_result(&arg);
    1574                 :             : 
    1575                 :        5149 :     free_var(&arg);
    1576                 :        5149 :     PG_RETURN_NUMERIC(res);
    1577                 :             : }
    1578                 :             : 
    1579                 :             : 
    1580                 :             : /*
    1581                 :             :  * numeric_trunc() -
    1582                 :             :  *
    1583                 :             :  *  Truncate a value to have 'scale' digits after the decimal point.
    1584                 :             :  *  We allow negative 'scale', implying a truncation before the decimal
    1585                 :             :  *  point --- Oracle interprets truncation that way.
    1586                 :             :  */
    1587                 :             : Datum
    1588                 :         442 : numeric_trunc(PG_FUNCTION_ARGS)
    1589                 :             : {
    1590                 :         442 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1591                 :         442 :     int32       scale = PG_GETARG_INT32(1);
    1592                 :             :     Numeric     res;
    1593                 :             :     NumericVar  arg;
    1594                 :             : 
    1595                 :             :     /*
    1596                 :             :      * Handle NaN and infinities
    1597                 :             :      */
    1598         [ +  + ]:         442 :     if (NUMERIC_IS_SPECIAL(num))
    1599                 :          24 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    1600                 :             : 
    1601                 :             :     /*
    1602                 :             :      * Limit the scale value to avoid possible overflow in calculations.
    1603                 :             :      *
    1604                 :             :      * These limits are based on the maximum number of digits a Numeric value
    1605                 :             :      * can have before and after the decimal point.
    1606                 :             :      */
    1607                 :         418 :     scale = Max(scale, -(NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS);
    1608                 :         418 :     scale = Min(scale, NUMERIC_DSCALE_MAX);
    1609                 :             : 
    1610                 :             :     /*
    1611                 :             :      * Unpack the argument and truncate it at the proper digit position
    1612                 :             :      */
    1613                 :         418 :     init_var(&arg);
    1614                 :         418 :     set_var_from_num(num, &arg);
    1615                 :             : 
    1616                 :         418 :     trunc_var(&arg, scale);
    1617                 :             : 
    1618                 :             :     /* We don't allow negative output dscale */
    1619         [ +  + ]:         418 :     if (scale < 0)
    1620                 :          20 :         arg.dscale = 0;
    1621                 :             : 
    1622                 :             :     /*
    1623                 :             :      * Return the truncated result
    1624                 :             :      */
    1625                 :         418 :     res = make_result(&arg);
    1626                 :             : 
    1627                 :         418 :     free_var(&arg);
    1628                 :         418 :     PG_RETURN_NUMERIC(res);
    1629                 :             : }
    1630                 :             : 
    1631                 :             : 
    1632                 :             : /*
    1633                 :             :  * numeric_ceil() -
    1634                 :             :  *
    1635                 :             :  *  Return the smallest integer greater than or equal to the argument
    1636                 :             :  */
    1637                 :             : Datum
    1638                 :         148 : numeric_ceil(PG_FUNCTION_ARGS)
    1639                 :             : {
    1640                 :         148 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1641                 :             :     Numeric     res;
    1642                 :             :     NumericVar  result;
    1643                 :             : 
    1644                 :             :     /*
    1645                 :             :      * Handle NaN and infinities
    1646                 :             :      */
    1647         [ +  + ]:         148 :     if (NUMERIC_IS_SPECIAL(num))
    1648                 :          12 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    1649                 :             : 
    1650                 :         136 :     init_var_from_num(num, &result);
    1651                 :         136 :     ceil_var(&result, &result);
    1652                 :             : 
    1653                 :         136 :     res = make_result(&result);
    1654                 :         136 :     free_var(&result);
    1655                 :             : 
    1656                 :         136 :     PG_RETURN_NUMERIC(res);
    1657                 :             : }
    1658                 :             : 
    1659                 :             : 
    1660                 :             : /*
    1661                 :             :  * numeric_floor() -
    1662                 :             :  *
    1663                 :             :  *  Return the largest integer equal to or less than the argument
    1664                 :             :  */
    1665                 :             : Datum
    1666                 :          84 : numeric_floor(PG_FUNCTION_ARGS)
    1667                 :             : {
    1668                 :          84 :     Numeric     num = PG_GETARG_NUMERIC(0);
    1669                 :             :     Numeric     res;
    1670                 :             :     NumericVar  result;
    1671                 :             : 
    1672                 :             :     /*
    1673                 :             :      * Handle NaN and infinities
    1674                 :             :      */
    1675         [ +  + ]:          84 :     if (NUMERIC_IS_SPECIAL(num))
    1676                 :          12 :         PG_RETURN_NUMERIC(duplicate_numeric(num));
    1677                 :             : 
    1678                 :          72 :     init_var_from_num(num, &result);
    1679                 :          72 :     floor_var(&result, &result);
    1680                 :             : 
    1681                 :          72 :     res = make_result(&result);
    1682                 :          72 :     free_var(&result);
    1683                 :             : 
    1684                 :          72 :     PG_RETURN_NUMERIC(res);
    1685                 :             : }
    1686                 :             : 
    1687                 :             : 
    1688                 :             : /*
    1689                 :             :  * generate_series_numeric() -
    1690                 :             :  *
    1691                 :             :  *  Generate series of numeric.
    1692                 :             :  */
    1693                 :             : Datum
    1694                 :       80256 : generate_series_numeric(PG_FUNCTION_ARGS)
    1695                 :             : {
    1696                 :       80256 :     return generate_series_step_numeric(fcinfo);
    1697                 :             : }
    1698                 :             : 
    1699                 :             : Datum
    1700                 :       80556 : generate_series_step_numeric(PG_FUNCTION_ARGS)
    1701                 :             : {
    1702                 :             :     generate_series_numeric_fctx *fctx;
    1703                 :             :     FuncCallContext *funcctx;
    1704                 :             :     MemoryContext oldcontext;
    1705                 :             : 
    1706         [ +  + ]:       80556 :     if (SRF_IS_FIRSTCALL())
    1707                 :             :     {
    1708                 :         116 :         Numeric     start_num = PG_GETARG_NUMERIC(0);
    1709                 :         116 :         Numeric     stop_num = PG_GETARG_NUMERIC(1);
    1710                 :         116 :         NumericVar  steploc = const_one;
    1711                 :             : 
    1712                 :             :         /* Reject NaN and infinities in start and stop values */
    1713         [ +  + ]:         116 :         if (NUMERIC_IS_SPECIAL(start_num))
    1714                 :             :         {
    1715         [ +  + ]:           8 :             if (NUMERIC_IS_NAN(start_num))
    1716         [ +  - ]:           4 :                 ereport(ERROR,
    1717                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1718                 :             :                          errmsg("start value cannot be NaN")));
    1719                 :             :             else
    1720         [ +  - ]:           4 :                 ereport(ERROR,
    1721                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1722                 :             :                          errmsg("start value cannot be infinity")));
    1723                 :             :         }
    1724         [ +  + ]:         108 :         if (NUMERIC_IS_SPECIAL(stop_num))
    1725                 :             :         {
    1726         [ +  + ]:           8 :             if (NUMERIC_IS_NAN(stop_num))
    1727         [ +  - ]:           4 :                 ereport(ERROR,
    1728                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1729                 :             :                          errmsg("stop value cannot be NaN")));
    1730                 :             :             else
    1731         [ +  - ]:           4 :                 ereport(ERROR,
    1732                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1733                 :             :                          errmsg("stop value cannot be infinity")));
    1734                 :             :         }
    1735                 :             : 
    1736                 :             :         /* see if we were given an explicit step size */
    1737         [ +  + ]:         100 :         if (PG_NARGS() == 3)
    1738                 :             :         {
    1739                 :          48 :             Numeric     step_num = PG_GETARG_NUMERIC(2);
    1740                 :             : 
    1741         [ +  + ]:          48 :             if (NUMERIC_IS_SPECIAL(step_num))
    1742                 :             :             {
    1743         [ +  + ]:           8 :                 if (NUMERIC_IS_NAN(step_num))
    1744         [ +  - ]:           4 :                     ereport(ERROR,
    1745                 :             :                             (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1746                 :             :                              errmsg("step size cannot be NaN")));
    1747                 :             :                 else
    1748         [ +  - ]:           4 :                     ereport(ERROR,
    1749                 :             :                             (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1750                 :             :                              errmsg("step size cannot be infinity")));
    1751                 :             :             }
    1752                 :             : 
    1753                 :          40 :             init_var_from_num(step_num, &steploc);
    1754                 :             : 
    1755         [ +  + ]:          40 :             if (cmp_var(&steploc, &const_zero) == 0)
    1756         [ +  - ]:           4 :                 ereport(ERROR,
    1757                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1758                 :             :                          errmsg("step size cannot equal zero")));
    1759                 :             :         }
    1760                 :             : 
    1761                 :             :         /* create a function context for cross-call persistence */
    1762                 :          88 :         funcctx = SRF_FIRSTCALL_INIT();
    1763                 :             : 
    1764                 :             :         /*
    1765                 :             :          * Switch to memory context appropriate for multiple function calls.
    1766                 :             :          */
    1767                 :          88 :         oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
    1768                 :             : 
    1769                 :             :         /* allocate memory for user context */
    1770                 :          88 :         fctx = palloc_object(generate_series_numeric_fctx);
    1771                 :             : 
    1772                 :             :         /*
    1773                 :             :          * Use fctx to keep state from call to call. Seed current with the
    1774                 :             :          * original start value. We must copy the start_num and stop_num
    1775                 :             :          * values rather than pointing to them, since we may have detoasted
    1776                 :             :          * them in the per-call context.
    1777                 :             :          */
    1778                 :          88 :         init_var(&fctx->current);
    1779                 :          88 :         init_var(&fctx->stop);
    1780                 :          88 :         init_var(&fctx->step);
    1781                 :             : 
    1782                 :          88 :         set_var_from_num(start_num, &fctx->current);
    1783                 :          88 :         set_var_from_num(stop_num, &fctx->stop);
    1784                 :          88 :         set_var_from_var(&steploc, &fctx->step);
    1785                 :             : 
    1786                 :          88 :         funcctx->user_fctx = fctx;
    1787                 :          88 :         MemoryContextSwitchTo(oldcontext);
    1788                 :             :     }
    1789                 :             : 
    1790                 :             :     /* stuff done on every call of the function */
    1791                 :       80528 :     funcctx = SRF_PERCALL_SETUP();
    1792                 :             : 
    1793                 :             :     /*
    1794                 :             :      * Get the saved state and use current state as the result of this
    1795                 :             :      * iteration.
    1796                 :             :      */
    1797                 :       80528 :     fctx = funcctx->user_fctx;
    1798                 :             : 
    1799   [ +  +  +  + ]:      160936 :     if ((fctx->step.sign == NUMERIC_POS &&
    1800                 :       80408 :          cmp_var(&fctx->current, &fctx->stop) <= 0) ||
    1801   [ +  +  +  + ]:         320 :         (fctx->step.sign == NUMERIC_NEG &&
    1802                 :         120 :          cmp_var(&fctx->current, &fctx->stop) >= 0))
    1803                 :             :     {
    1804                 :       80440 :         Numeric     result = make_result(&fctx->current);
    1805                 :             : 
    1806                 :             :         /* switch to memory context appropriate for iteration calculation */
    1807                 :       80440 :         oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
    1808                 :             : 
    1809                 :             :         /* increment current in preparation for next iteration */
    1810                 :       80440 :         add_var(&fctx->current, &fctx->step, &fctx->current);
    1811                 :       80440 :         MemoryContextSwitchTo(oldcontext);
    1812                 :             : 
    1813                 :             :         /* do when there is more left to send */
    1814                 :       80440 :         SRF_RETURN_NEXT(funcctx, NumericGetDatum(result));
    1815                 :             :     }
    1816                 :             :     else
    1817                 :             :         /* do when there is no more left */
    1818                 :          88 :         SRF_RETURN_DONE(funcctx);
    1819                 :             : }
    1820                 :             : 
    1821                 :             : /*
    1822                 :             :  * Planner support function for generate_series(numeric, numeric [, numeric])
    1823                 :             :  */
    1824                 :             : Datum
    1825                 :         535 : generate_series_numeric_support(PG_FUNCTION_ARGS)
    1826                 :             : {
    1827                 :         535 :     Node       *rawreq = (Node *) PG_GETARG_POINTER(0);
    1828                 :         535 :     Node       *ret = NULL;
    1829                 :             : 
    1830         [ +  + ]:         535 :     if (IsA(rawreq, SupportRequestRows))
    1831                 :             :     {
    1832                 :             :         /* Try to estimate the number of rows returned */
    1833                 :         130 :         SupportRequestRows *req = (SupportRequestRows *) rawreq;
    1834                 :             : 
    1835         [ +  - ]:         130 :         if (is_funcclause(req->node))    /* be paranoid */
    1836                 :             :         {
    1837                 :         130 :             List       *args = ((FuncExpr *) req->node)->args;
    1838                 :             :             Node       *arg1,
    1839                 :             :                        *arg2,
    1840                 :             :                        *arg3;
    1841                 :             : 
    1842                 :             :             /* We can use estimated argument values here */
    1843                 :         130 :             arg1 = estimate_expression_value(req->root, linitial(args));
    1844                 :         130 :             arg2 = estimate_expression_value(req->root, lsecond(args));
    1845         [ +  + ]:         130 :             if (list_length(args) >= 3)
    1846                 :          85 :                 arg3 = estimate_expression_value(req->root, lthird(args));
    1847                 :             :             else
    1848                 :          45 :                 arg3 = NULL;
    1849                 :             : 
    1850                 :             :             /*
    1851                 :             :              * If any argument is constant NULL, we can safely assume that
    1852                 :             :              * zero rows are returned.  Otherwise, if they're all non-NULL
    1853                 :             :              * constants, we can calculate the number of rows that will be
    1854                 :             :              * returned.
    1855                 :             :              */
    1856         [ +  + ]:         130 :             if ((IsA(arg1, Const) &&
    1857         [ +  - ]:         125 :                  ((Const *) arg1)->constisnull) ||
    1858         [ +  + ]:         130 :                 (IsA(arg2, Const) &&
    1859   [ +  -  +  + ]:         130 :                  ((Const *) arg2)->constisnull) ||
    1860         [ +  + ]:          85 :                 (arg3 != NULL && IsA(arg3, Const) &&
    1861         [ -  + ]:          80 :                  ((Const *) arg3)->constisnull))
    1862                 :             :             {
    1863                 :           0 :                 req->rows = 0;
    1864                 :           0 :                 ret = (Node *) req;
    1865                 :             :             }
    1866         [ +  + ]:         130 :             else if (IsA(arg1, Const) &&
    1867   [ +  +  +  + ]:         125 :                      IsA(arg2, Const) &&
    1868         [ +  + ]:          85 :                      (arg3 == NULL || IsA(arg3, Const)))
    1869                 :             :             {
    1870                 :             :                 Numeric     start_num;
    1871                 :             :                 Numeric     stop_num;
    1872                 :         115 :                 NumericVar  step = const_one;
    1873                 :             : 
    1874                 :             :                 /*
    1875                 :             :                  * If any argument is NaN or infinity, generate_series() will
    1876                 :             :                  * error out, so we needn't produce an estimate.
    1877                 :             :                  */
    1878                 :         115 :                 start_num = DatumGetNumeric(((Const *) arg1)->constvalue);
    1879                 :         115 :                 stop_num = DatumGetNumeric(((Const *) arg2)->constvalue);
    1880                 :             : 
    1881         [ +  + ]:         115 :                 if (NUMERIC_IS_SPECIAL(start_num) ||
    1882         [ +  + ]:         100 :                     NUMERIC_IS_SPECIAL(stop_num))
    1883                 :          40 :                     PG_RETURN_POINTER(NULL);
    1884                 :             : 
    1885         [ +  + ]:          90 :                 if (arg3)
    1886                 :             :                 {
    1887                 :             :                     Numeric     step_num;
    1888                 :             : 
    1889                 :          55 :                     step_num = DatumGetNumeric(((Const *) arg3)->constvalue);
    1890                 :             : 
    1891         [ +  + ]:          55 :                     if (NUMERIC_IS_SPECIAL(step_num))
    1892                 :          15 :                         PG_RETURN_POINTER(NULL);
    1893                 :             : 
    1894                 :          40 :                     init_var_from_num(step_num, &step);
    1895                 :             :                 }
    1896                 :             : 
    1897                 :             :                 /*
    1898                 :             :                  * The number of rows that will be returned is given by
    1899                 :             :                  * floor((stop - start) / step) + 1, if the sign of step
    1900                 :             :                  * matches the sign of stop - start.  Otherwise, no rows will
    1901                 :             :                  * be returned.
    1902                 :             :                  */
    1903         [ +  + ]:          75 :                 if (cmp_var(&step, &const_zero) != 0)
    1904                 :             :                 {
    1905                 :             :                     NumericVar  start;
    1906                 :             :                     NumericVar  stop;
    1907                 :             :                     NumericVar  res;
    1908                 :             : 
    1909                 :          65 :                     init_var_from_num(start_num, &start);
    1910                 :          65 :                     init_var_from_num(stop_num, &stop);
    1911                 :             : 
    1912                 :          65 :                     init_var(&res);
    1913                 :          65 :                     sub_var(&stop, &start, &res);
    1914                 :             : 
    1915         [ +  + ]:          65 :                     if (step.sign != res.sign)
    1916                 :             :                     {
    1917                 :             :                         /* no rows will be returned */
    1918                 :           5 :                         req->rows = 0;
    1919                 :           5 :                         ret = (Node *) req;
    1920                 :             :                     }
    1921                 :             :                     else
    1922                 :             :                     {
    1923         [ +  + ]:          60 :                         if (arg3)
    1924                 :          25 :                             div_var(&res, &step, &res, 0, false, false);
    1925                 :             :                         else
    1926                 :          35 :                             trunc_var(&res, 0); /* step = 1 */
    1927                 :             : 
    1928                 :          60 :                         req->rows = numericvar_to_double_no_overflow(&res) + 1;
    1929                 :          60 :                         ret = (Node *) req;
    1930                 :             :                     }
    1931                 :             : 
    1932                 :          65 :                     free_var(&res);
    1933                 :             :                 }
    1934                 :             :             }
    1935                 :             :         }
    1936                 :             :     }
    1937                 :             : 
    1938                 :         495 :     PG_RETURN_POINTER(ret);
    1939                 :             : }
    1940                 :             : 
    1941                 :             : 
    1942                 :             : /*
    1943                 :             :  * Implements the numeric version of the width_bucket() function
    1944                 :             :  * defined by SQL2003. See also width_bucket_float8().
    1945                 :             :  *
    1946                 :             :  * 'bound1' and 'bound2' are the lower and upper bounds of the
    1947                 :             :  * histogram's range, respectively. 'count' is the number of buckets
    1948                 :             :  * in the histogram. width_bucket() returns an integer indicating the
    1949                 :             :  * bucket number that 'operand' belongs to in an equiwidth histogram
    1950                 :             :  * with the specified characteristics. An operand smaller than the
    1951                 :             :  * lower bound is assigned to bucket 0. An operand greater than or equal
    1952                 :             :  * to the upper bound is assigned to an additional bucket (with number
    1953                 :             :  * count+1). We don't allow the histogram bounds to be NaN or +/- infinity,
    1954                 :             :  * but we do allow those values for the operand (taking NaN to be larger
    1955                 :             :  * than any other value, as we do in comparisons).
    1956                 :             :  */
    1957                 :             : Datum
    1958                 :         529 : width_bucket_numeric(PG_FUNCTION_ARGS)
    1959                 :             : {
    1960                 :         529 :     Numeric     operand = PG_GETARG_NUMERIC(0);
    1961                 :         529 :     Numeric     bound1 = PG_GETARG_NUMERIC(1);
    1962                 :         529 :     Numeric     bound2 = PG_GETARG_NUMERIC(2);
    1963                 :         529 :     int32       count = PG_GETARG_INT32(3);
    1964                 :             :     NumericVar  count_var;
    1965                 :             :     NumericVar  result_var;
    1966                 :             :     int32       result;
    1967                 :             : 
    1968         [ +  + ]:         529 :     if (count <= 0)
    1969         [ +  - ]:           8 :         ereport(ERROR,
    1970                 :             :                 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
    1971                 :             :                  errmsg("count must be greater than zero")));
    1972                 :             : 
    1973   [ +  +  +  + ]:         521 :     if (NUMERIC_IS_SPECIAL(bound1) || NUMERIC_IS_SPECIAL(bound2))
    1974                 :             :     {
    1975   [ +  +  -  + ]:          16 :         if (NUMERIC_IS_NAN(bound1) || NUMERIC_IS_NAN(bound2))
    1976         [ +  - ]:           4 :             ereport(ERROR,
    1977                 :             :                     (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
    1978                 :             :                      errmsg("lower and upper bounds cannot be NaN")));
    1979                 :             : 
    1980   [ +  +  +  - ]:          12 :         if (NUMERIC_IS_INF(bound1) || NUMERIC_IS_INF(bound2))
    1981         [ +  - ]:          12 :             ereport(ERROR,
    1982                 :             :                     (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
    1983                 :             :                      errmsg("lower and upper bounds must be finite")));
    1984                 :             :     }
    1985                 :             : 
    1986                 :         505 :     init_var(&result_var);
    1987                 :         505 :     init_var(&count_var);
    1988                 :             : 
    1989                 :             :     /* Convert 'count' to a numeric, for ease of use later */
    1990                 :         505 :     int64_to_numericvar((int64) count, &count_var);
    1991                 :             : 
    1992   [ +  +  +  - ]:         505 :     switch (cmp_numerics(bound1, bound2))
    1993                 :             :     {
    1994                 :           4 :         case 0:
    1995         [ +  - ]:           4 :             ereport(ERROR,
    1996                 :             :                     (errcode(ERRCODE_INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION),
    1997                 :             :                      errmsg("lower bound cannot equal upper bound")));
    1998                 :             :             break;
    1999                 :             : 
    2000                 :             :             /* bound1 < bound2 */
    2001                 :         372 :         case -1:
    2002         [ +  + ]:         372 :             if (cmp_numerics(operand, bound1) < 0)
    2003                 :          77 :                 set_var_from_var(&const_zero, &result_var);
    2004         [ +  + ]:         295 :             else if (cmp_numerics(operand, bound2) >= 0)
    2005                 :          78 :                 add_var(&count_var, &const_one, &result_var);
    2006                 :             :             else
    2007                 :         217 :                 compute_bucket(operand, bound1, bound2, &count_var,
    2008                 :             :                                &result_var);
    2009                 :         372 :             break;
    2010                 :             : 
    2011                 :             :             /* bound1 > bound2 */
    2012                 :         129 :         case 1:
    2013         [ +  + ]:         129 :             if (cmp_numerics(operand, bound1) > 0)
    2014                 :           8 :                 set_var_from_var(&const_zero, &result_var);
    2015         [ +  + ]:         121 :             else if (cmp_numerics(operand, bound2) <= 0)
    2016                 :          16 :                 add_var(&count_var, &const_one, &result_var);
    2017                 :             :             else
    2018                 :         105 :                 compute_bucket(operand, bound1, bound2, &count_var,
    2019                 :             :                                &result_var);
    2020                 :         129 :             break;
    2021                 :             :     }
    2022                 :             : 
    2023                 :             :     /* if result exceeds the range of a legal int4, we ereport here */
    2024         [ -  + ]:         501 :     if (!numericvar_to_int32(&result_var, &result))
    2025         [ #  # ]:           0 :         ereport(ERROR,
    2026                 :             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    2027                 :             :                  errmsg("integer out of range")));
    2028                 :             : 
    2029                 :         501 :     free_var(&count_var);
    2030                 :         501 :     free_var(&result_var);
    2031                 :             : 
    2032                 :         501 :     PG_RETURN_INT32(result);
    2033                 :             : }
    2034                 :             : 
    2035                 :             : /*
    2036                 :             :  * 'operand' is inside the bucket range, so determine the correct
    2037                 :             :  * bucket for it to go in. The calculations performed by this function
    2038                 :             :  * are derived directly from the SQL2003 spec. Note however that we
    2039                 :             :  * multiply by count before dividing, to avoid unnecessary roundoff error.
    2040                 :             :  */
    2041                 :             : static void
    2042                 :         322 : compute_bucket(Numeric operand, Numeric bound1, Numeric bound2,
    2043                 :             :                const NumericVar *count_var, NumericVar *result_var)
    2044                 :             : {
    2045                 :             :     NumericVar  bound1_var;
    2046                 :             :     NumericVar  bound2_var;
    2047                 :             :     NumericVar  operand_var;
    2048                 :             : 
    2049                 :         322 :     init_var_from_num(bound1, &bound1_var);
    2050                 :         322 :     init_var_from_num(bound2, &bound2_var);
    2051                 :         322 :     init_var_from_num(operand, &operand_var);
    2052                 :             : 
    2053                 :             :     /*
    2054                 :             :      * Per spec, bound1 is inclusive and bound2 is exclusive, and so we have
    2055                 :             :      * bound1 <= operand < bound2 or bound1 >= operand > bound2.  Either way,
    2056                 :             :      * the result is ((operand - bound1) * count) / (bound2 - bound1) + 1,
    2057                 :             :      * where the quotient is computed using floor division (i.e., division to
    2058                 :             :      * zero decimal places with truncation), which guarantees that the result
    2059                 :             :      * is in the range [1, count].  Reversing the bounds doesn't affect the
    2060                 :             :      * computation, because the signs cancel out when dividing.
    2061                 :             :      */
    2062                 :         322 :     sub_var(&operand_var, &bound1_var, &operand_var);
    2063                 :         322 :     sub_var(&bound2_var, &bound1_var, &bound2_var);
    2064                 :             : 
    2065                 :         322 :     mul_var(&operand_var, count_var, &operand_var,
    2066                 :         322 :             operand_var.dscale + count_var->dscale);
    2067                 :         322 :     div_var(&operand_var, &bound2_var, result_var, 0, false, true);
    2068                 :         322 :     add_var(result_var, &const_one, result_var);
    2069                 :             : 
    2070                 :         322 :     free_var(&bound1_var);
    2071                 :         322 :     free_var(&bound2_var);
    2072                 :         322 :     free_var(&operand_var);
    2073                 :         322 : }
    2074                 :             : 
    2075                 :             : /* ----------------------------------------------------------------------
    2076                 :             :  *
    2077                 :             :  * Comparison functions
    2078                 :             :  *
    2079                 :             :  * Note: btree indexes need these routines not to leak memory; therefore,
    2080                 :             :  * be careful to free working copies of toasted datums.  Most places don't
    2081                 :             :  * need to be so careful.
    2082                 :             :  *
    2083                 :             :  * Sort support:
    2084                 :             :  *
    2085                 :             :  * We implement the sortsupport strategy routine in order to get the benefit of
    2086                 :             :  * abbreviation. The ordinary numeric comparison can be quite slow as a result
    2087                 :             :  * of palloc/pfree cycles (due to detoasting packed values for alignment);
    2088                 :             :  * while this could be worked on itself, the abbreviation strategy gives more
    2089                 :             :  * speedup in many common cases.
    2090                 :             :  *
    2091                 :             :  * The abbreviated format is an int64. The representation is negated relative
    2092                 :             :  * to the original value, because we use the largest negative value for NaN,
    2093                 :             :  * which sorts higher than other values. We convert the absolute value of the
    2094                 :             :  * numeric to a 63-bit positive value, and then negate it if the original
    2095                 :             :  * number was positive.
    2096                 :             :  *
    2097                 :             :  * We abort the abbreviation process if the abbreviation cardinality is below
    2098                 :             :  * 0.01% of the row count (1 per 10k non-null rows).  The actual break-even
    2099                 :             :  * point is somewhat below that, perhaps 1 per 30k (at 1 per 100k there's a
    2100                 :             :  * very small penalty), but we don't want to build up too many abbreviated
    2101                 :             :  * values before first testing for abort, so we take the slightly pessimistic
    2102                 :             :  * number.  We make no attempt to estimate the cardinality of the real values,
    2103                 :             :  * since it plays no part in the cost model here (if the abbreviation is equal,
    2104                 :             :  * the cost of comparing equal and unequal underlying values is comparable).
    2105                 :             :  * We discontinue even checking for abort (saving us the hashing overhead) if
    2106                 :             :  * the estimated cardinality gets to 100k; that would be enough to support many
    2107                 :             :  * billions of rows while doing no worse than breaking even.
    2108                 :             :  *
    2109                 :             :  * ----------------------------------------------------------------------
    2110                 :             :  */
    2111                 :             : 
    2112                 :             : /*
    2113                 :             :  * Sort support strategy routine.
    2114                 :             :  */
    2115                 :             : Datum
    2116                 :         800 : numeric_sortsupport(PG_FUNCTION_ARGS)
    2117                 :             : {
    2118                 :         800 :     SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
    2119                 :             : 
    2120                 :         800 :     ssup->comparator = numeric_fast_cmp;
    2121                 :             : 
    2122         [ +  + ]:         800 :     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                 :         800 :     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                 :    17212321 : numeric_fast_cmp(Datum x, Datum y, SortSupport ssup)
    2287                 :             : {
    2288                 :    17212321 :     Numeric     nx = DatumGetNumeric(x);
    2289                 :    17212321 :     Numeric     ny = DatumGetNumeric(y);
    2290                 :             :     int         result;
    2291                 :             : 
    2292                 :    17212321 :     result = cmp_numerics(nx, ny);
    2293                 :             : 
    2294         [ +  + ]:    17212321 :     if (nx != DatumGetPointer(x))
    2295                 :     7409856 :         pfree(nx);
    2296         [ +  + ]:    17212321 :     if (ny != DatumGetPointer(y))
    2297                 :     7409852 :         pfree(ny);
    2298                 :             : 
    2299                 :    17212321 :     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                 :      125883 : 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         [ +  + ]:      125883 :     if (DatumGetNumericAbbrev(x) < DatumGetNumericAbbrev(y))
    2315                 :       65911 :         return 1;
    2316         [ +  + ]:       59972 :     if (DatumGetNumericAbbrev(x) > DatumGetNumericAbbrev(y))
    2317                 :       59825 :         return -1;
    2318                 :         147 :     return 0;
    2319                 :             : }
    2320                 :             : 
    2321                 :             : /*
    2322                 :             :  * Abbreviate a NumericVar into the 64-bit sortsupport size.
    2323                 :             :  *
    2324                 :             :  * The 31-bit value is constructed as:
    2325                 :             :  *
    2326                 :             :  *  0 + 7bits digit weight + 24 bits digit value
    2327                 :             :  *
    2328                 :             :  * where the digit weight is in single decimal digits, not digit words, and
    2329                 :             :  * stored in excess-44 representation[1]. The 24-bit digit value is the 7 most
    2330                 :             :  * significant decimal digits of the value converted to binary. Values whose
    2331                 :             :  * weights would fall outside the representable range are rounded off to zero
    2332                 :             :  * (which is also used to represent actual zeros) or to 0x7FFFFFFF (which
    2333                 :             :  * otherwise cannot occur). Abbreviation therefore fails to gain any advantage
    2334                 :             :  * where values are outside the range 10^-44 to 10^83, which is not considered
    2335                 :             :  * to be a serious limitation, or when values are of the same magnitude and
    2336                 :             :  * equal in the first 7 decimal digits, which is considered to be an
    2337                 :             :  * unavoidable limitation given the available bits. (Stealing three more bits
    2338                 :             :  * to compare another digit would narrow the range of representable weights by
    2339                 :             :  * a factor of 8, which starts to look like a real limiting factor.)
    2340                 :             :  *
    2341                 :             :  * (The value 44 for the excess is essentially arbitrary)
    2342                 :             :  *
    2343                 :             :  * The 63-bit value is constructed as:
    2344                 :             :  *
    2345                 :             :  *  0 + 7bits weight + 4 x 14-bit packed digit words
    2346                 :             :  *
    2347                 :             :  * The weight in this case is again stored in excess-44, but this time it is
    2348                 :             :  * the original weight in digit words (i.e. powers of 10000). The first four
    2349                 :             :  * digit words of the value (if present; trailing zeros are assumed as needed)
    2350                 :             :  * are packed into 14 bits each to form the rest of the value. Again,
    2351                 :             :  * out-of-range values are rounded off to 0 or 0x7FFFFFFFFFFFFFFF. The
    2352                 :             :  * representable range in this case is 10^-176 to 10^332, which is considered
    2353                 :             :  * to be good enough for all practical purposes, and comparison of 4 words
    2354                 :             :  * means that at least 13 decimal digits are compared, which is considered to
    2355                 :             :  * be a reasonable compromise between effectiveness and efficiency in computing
    2356                 :             :  * the abbreviation.
    2357                 :             :  *
    2358                 :             :  * (The value 44 for the excess is even more arbitrary here, it was chosen just
    2359                 :             :  * to match the value used in the 31-bit case)
    2360                 :             :  *
    2361                 :             :  * [1] - Excess-k representation means that the value is offset by adding 'k'
    2362                 :             :  * and then treated as unsigned, so the smallest representable value is stored
    2363                 :             :  * with all bits zero. This allows simple comparisons to work on the composite
    2364                 :             :  * value.
    2365                 :             :  */
    2366                 :             : static Datum
    2367                 :       12679 : numeric_abbrev_convert_var(const NumericVar *var, NumericSortSupport *nss)
    2368                 :             : {
    2369                 :       12679 :     int         ndigits = var->ndigits;
    2370                 :       12679 :     int         weight = var->weight;
    2371                 :             :     int64       result;
    2372                 :             : 
    2373   [ +  +  -  + ]:       12679 :     if (ndigits == 0 || weight < -44)
    2374                 :             :     {
    2375                 :          34 :         result = 0;
    2376                 :             :     }
    2377         [ +  + ]:       12645 :     else if (weight > 83)
    2378                 :             :     {
    2379                 :           8 :         result = PG_INT64_MAX;
    2380                 :             :     }
    2381                 :             :     else
    2382                 :             :     {
    2383                 :       12637 :         result = ((int64) (weight + 44) << 56);
    2384                 :             : 
    2385   [ -  +  +  + ]:       12637 :         switch (ndigits)
    2386                 :             :         {
    2387                 :           0 :             default:
    2388                 :           0 :                 result |= ((int64) var->digits[3]);
    2389                 :             :                 pg_fallthrough;
    2390                 :        4137 :             case 3:
    2391                 :        4137 :                 result |= ((int64) var->digits[2]) << 14;
    2392                 :             :                 pg_fallthrough;
    2393                 :       12212 :             case 2:
    2394                 :       12212 :                 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                 :      488753 : numeric_cmp(PG_FUNCTION_ARGS)
    2424                 :             : {
    2425                 :      488753 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    2426                 :      488753 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    2427                 :             :     int         result;
    2428                 :             : 
    2429                 :      488753 :     result = cmp_numerics(num1, num2);
    2430                 :             : 
    2431         [ +  + ]:      488753 :     PG_FREE_IF_COPY(num1, 0);
    2432         [ +  + ]:      488753 :     PG_FREE_IF_COPY(num2, 1);
    2433                 :             : 
    2434                 :      488753 :     PG_RETURN_INT32(result);
    2435                 :             : }
    2436                 :             : 
    2437                 :             : 
    2438                 :             : Datum
    2439                 :      428577 : numeric_eq(PG_FUNCTION_ARGS)
    2440                 :             : {
    2441                 :      428577 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    2442                 :      428577 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    2443                 :             :     bool        result;
    2444                 :             : 
    2445                 :      428577 :     result = cmp_numerics(num1, num2) == 0;
    2446                 :             : 
    2447         [ +  + ]:      428577 :     PG_FREE_IF_COPY(num1, 0);
    2448         [ +  + ]:      428577 :     PG_FREE_IF_COPY(num2, 1);
    2449                 :             : 
    2450                 :      428577 :     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                 :       33640 : numeric_gt(PG_FUNCTION_ARGS)
    2470                 :             : {
    2471                 :       33640 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    2472                 :       33640 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    2473                 :             :     bool        result;
    2474                 :             : 
    2475                 :       33640 :     result = cmp_numerics(num1, num2) > 0;
    2476                 :             : 
    2477         [ +  + ]:       33640 :     PG_FREE_IF_COPY(num1, 0);
    2478         [ +  + ]:       33640 :     PG_FREE_IF_COPY(num2, 1);
    2479                 :             : 
    2480                 :       33640 :     PG_RETURN_BOOL(result);
    2481                 :             : }
    2482                 :             : 
    2483                 :             : Datum
    2484                 :        7945 : numeric_ge(PG_FUNCTION_ARGS)
    2485                 :             : {
    2486                 :        7945 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    2487                 :        7945 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    2488                 :             :     bool        result;
    2489                 :             : 
    2490                 :        7945 :     result = cmp_numerics(num1, num2) >= 0;
    2491                 :             : 
    2492         [ +  + ]:        7945 :     PG_FREE_IF_COPY(num1, 0);
    2493         [ -  + ]:        7945 :     PG_FREE_IF_COPY(num2, 1);
    2494                 :             : 
    2495                 :        7945 :     PG_RETURN_BOOL(result);
    2496                 :             : }
    2497                 :             : 
    2498                 :             : Datum
    2499                 :      198916 : numeric_lt(PG_FUNCTION_ARGS)
    2500                 :             : {
    2501                 :      198916 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    2502                 :      198916 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    2503                 :             :     bool        result;
    2504                 :             : 
    2505                 :      198916 :     result = cmp_numerics(num1, num2) < 0;
    2506                 :             : 
    2507         [ +  + ]:      198916 :     PG_FREE_IF_COPY(num1, 0);
    2508         [ +  + ]:      198916 :     PG_FREE_IF_COPY(num2, 1);
    2509                 :             : 
    2510                 :      198916 :     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                 :    18398059 : 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         [ +  + ]:    18398059 :     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         [ +  + ]:    18395955 :     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   [ +  +  +  + ]:    36776694 :         result = cmp_var_common(NUMERIC_DIGITS(num1), NUMERIC_NDIGITS(num1),
    2574   [ +  +  -  +  :    18388233 :                                 NUMERIC_WEIGHT(num1), NUMERIC_SIGN(num1),
             +  +  +  + ]
    2575   [ +  +  +  + ]:    18388035 :                                 NUMERIC_DIGITS(num2), NUMERIC_NDIGITS(num2),
    2576   [ +  +  -  +  :    18388461 :                                 NUMERIC_WEIGHT(num2), NUMERIC_SIGN(num2));
             +  +  +  + ]
    2577                 :             :     }
    2578                 :             : 
    2579                 :    18398059 :     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                 :      405122 : hash_numeric(PG_FUNCTION_ARGS)
    2722                 :             : {
    2723                 :      405122 :     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         [ -  + ]:      405122 :     if (NUMERIC_IS_SPECIAL(key))
    2735                 :           0 :         PG_RETURN_UINT32(0);
    2736                 :             : 
    2737   [ +  -  +  + ]:      405122 :     weight = NUMERIC_WEIGHT(key);
    2738                 :      405122 :     start_offset = 0;
    2739                 :      405122 :     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         [ +  - ]:      405122 :     digits = NUMERIC_DIGITS(key);
    2748   [ +  -  +  + ]:      405122 :     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   [ +  -  +  + ]:      405122 :     if (NUMERIC_NDIGITS(key) == start_offset)
    2767                 :        1104 :         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                 :      169142 : 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   [ +  +  +  + ]:      169142 :     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                 :      169010 :     init_var_from_num(num1, &arg1);
    2928                 :      169010 :     init_var_from_num(num2, &arg2);
    2929                 :             : 
    2930                 :      169010 :     init_var(&result);
    2931                 :      169010 :     add_var(&arg1, &arg2, &result);
    2932                 :             : 
    2933                 :      169010 :     res = make_result_safe(&result, escontext);
    2934                 :             : 
    2935                 :      169010 :     free_var(&result);
    2936                 :             : 
    2937                 :      169010 :     return res;
    2938                 :             : }
    2939                 :             : 
    2940                 :             : 
    2941                 :             : /*
    2942                 :             :  * numeric_sub() -
    2943                 :             :  *
    2944                 :             :  *  Subtract one numeric from another
    2945                 :             :  */
    2946                 :             : Datum
    2947                 :       46361 : numeric_sub(PG_FUNCTION_ARGS)
    2948                 :             : {
    2949                 :       46361 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    2950                 :       46361 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    2951                 :             :     Numeric     res;
    2952                 :             : 
    2953                 :       46361 :     res = numeric_sub_safe(num1, num2, NULL);
    2954                 :             : 
    2955                 :       46361 :     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                 :       46465 : 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   [ +  +  +  + ]:       46465 :     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                 :       46333 :     init_var_from_num(num1, &arg1);
    3004                 :       46333 :     init_var_from_num(num2, &arg2);
    3005                 :             : 
    3006                 :       46333 :     init_var(&result);
    3007                 :       46333 :     sub_var(&arg1, &arg2, &result);
    3008                 :             : 
    3009                 :       46333 :     res = make_result_safe(&result, escontext);
    3010                 :             : 
    3011                 :       46333 :     free_var(&result);
    3012                 :             : 
    3013                 :       46333 :     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                 :       98472 : numeric_div(PG_FUNCTION_ARGS)
    3146                 :             : {
    3147                 :       98472 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    3148                 :       98472 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    3149                 :             :     Numeric     res;
    3150                 :             : 
    3151                 :       98472 :     res = numeric_div_safe(num1, num2, NULL);
    3152                 :             : 
    3153                 :       98451 :     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                 :       99033 : 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   [ +  +  +  + ]:       99033 :     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                 :       98900 :     init_var_from_num(num1, &arg1);
    3222                 :       98900 :     init_var_from_num(num2, &arg2);
    3223                 :             : 
    3224                 :       98900 :     init_var(&result);
    3225                 :             : 
    3226                 :             :     /*
    3227                 :             :      * Select scale for division result
    3228                 :             :      */
    3229                 :       98900 :     rscale = select_div_scale(&arg1, &arg2);
    3230                 :             : 
    3231                 :             :     /* Check for division by zero */
    3232   [ +  +  -  + ]:       98900 :     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                 :       98867 :     div_var(&arg1, &arg2, &result, rscale, true, true);
    3239                 :             : 
    3240                 :       98867 :     res = make_result_safe(&result, escontext);
    3241                 :             : 
    3242                 :       98867 :     free_var(&result);
    3243                 :             : 
    3244                 :       98867 :     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                 :      275179 : numeric_mod(PG_FUNCTION_ARGS)
    3349                 :             : {
    3350                 :      275179 :     Numeric     num1 = PG_GETARG_NUMERIC(0);
    3351                 :      275179 :     Numeric     num2 = PG_GETARG_NUMERIC(1);
    3352                 :             :     Numeric     res;
    3353                 :             : 
    3354                 :      275179 :     res = numeric_mod_safe(num1, num2, NULL);
    3355                 :             : 
    3356                 :      275167 :     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                 :      275187 : 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   [ +  +  +  + ]:      275187 :     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                 :      275054 :     init_var_from_num(num1, &arg1);
    3395                 :      275054 :     init_var_from_num(num2, &arg2);
    3396                 :             : 
    3397                 :      275054 :     init_var(&result);
    3398                 :             : 
    3399                 :             :     /* Check for division by zero */
    3400   [ +  +  -  + ]:      275054 :     if (arg2.ndigits == 0 || arg2.digits[0] == 0)
    3401                 :           8 :         goto division_by_zero;
    3402                 :             : 
    3403                 :      275046 :     mod_var(&arg1, &arg2, &result);
    3404                 :             : 
    3405                 :      275046 :     res = make_result_safe(&result, escontext);
    3406                 :             : 
    3407                 :      275046 :     free_var(&result);
    3408                 :             : 
    3409                 :      275046 :     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                 :         435 :         PG_RETURN_NUMERIC(num1);
    3468                 :             :     else
    3469                 :         108 :         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                 :       11768 :         PG_RETURN_NUMERIC(num1);
    3490                 :             :     else
    3491                 :         652 :         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                 :     1245659 : int64_to_numeric(int64 val)
    4271                 :             : {
    4272                 :             :     Numeric     res;
    4273                 :             :     NumericVar  result;
    4274                 :             : 
    4275                 :     1245659 :     init_var(&result);
    4276                 :             : 
    4277                 :     1245659 :     int64_to_numericvar(val, &result);
    4278                 :             : 
    4279                 :     1245659 :     res = make_result(&result);
    4280                 :             : 
    4281                 :     1245659 :     free_var(&result);
    4282                 :             : 
    4283                 :     1245659 :     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                 :     1037875 : int4_numeric(PG_FUNCTION_ARGS)
    4365                 :             : {
    4366                 :     1037875 :     int32       val = PG_GETARG_INT32(0);
    4367                 :             : 
    4368                 :     1037875 :     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                 :        4859 : numeric_int4_safe(Numeric num, Node *escontext)
    4376                 :             : {
    4377                 :             :     NumericVar  x;
    4378                 :             :     int32       result;
    4379                 :             : 
    4380         [ +  + ]:        4859 :     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                 :        4847 :     init_var_from_num(num, &x);
    4394                 :             : 
    4395         [ +  + ]:        4847 :     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                 :        4777 :     return result;
    4401                 :             : }
    4402                 :             : 
    4403                 :             : Datum
    4404                 :        3716 : numeric_int4(PG_FUNCTION_ARGS)
    4405                 :             : {
    4406                 :        3716 :     Numeric     num = PG_GETARG_NUMERIC(0);
    4407                 :             :     int32       result;
    4408                 :             : 
    4409                 :        3716 :     result = numeric_int4_safe(num, fcinfo->context);
    4410                 :             : 
    4411   [ -  +  -  -  :        3696 :     if (unlikely(SOFT_ERROR_OCCURRED(fcinfo->context)))
          -  +  -  -  -  
                      + ]
    4412                 :           0 :         PG_RETURN_NULL();
    4413                 :             : 
    4414                 :        3696 :     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                 :        5348 : numericvar_to_int32(const NumericVar *var, int32 *result)
    4424                 :             : {
    4425                 :             :     int64       val;
    4426                 :             : 
    4427         [ +  + ]:        5348 :     if (!numericvar_to_int64(var, &val))
    4428                 :           4 :         return false;
    4429                 :             : 
    4430   [ +  +  +  + ]:        5344 :     if (unlikely(val < PG_INT32_MIN) || unlikely(val > PG_INT32_MAX))
    4431                 :          66 :         return false;
    4432                 :             : 
    4433                 :             :     /* Down-convert to int4 */
    4434                 :        5278 :     *result = (int32) val;
    4435                 :             : 
    4436                 :        5278 :     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                 :      347591 : numeric_float8(PG_FUNCTION_ARGS)
    4581                 :             : {
    4582                 :      347591 :     Numeric     num = PG_GETARG_NUMERIC(0);
    4583                 :             :     char       *tmp;
    4584                 :             :     Datum       result;
    4585                 :             : 
    4586         [ +  + ]:      347591 :     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                 :      347535 :     tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
    4597                 :             :                                               NumericGetDatum(num)));
    4598         [ -  + ]:      347535 :     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                 :      347535 :     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                 :          14 : numeric_float8_no_overflow(PG_FUNCTION_ARGS)
    4618                 :             : {
    4619                 :          14 :     Numeric     num = PG_GETARG_NUMERIC(0);
    4620                 :             :     double      val;
    4621                 :             : 
    4622         [ -  + ]:          14 :     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                 :          14 :         init_var_from_num(num, &x);
    4636                 :          14 :         val = numericvar_to_double_no_overflow(&x);
    4637                 :             :     }
    4638                 :             : 
    4639                 :          14 :     PG_RETURN_FLOAT8(val);
    4640                 :             : }
    4641                 :             : 
    4642                 :             : Datum
    4643                 :       15063 : float4_numeric(PG_FUNCTION_ARGS)
    4644                 :             : {
    4645                 :       15063 :     float4      val = PG_GETARG_FLOAT4(0);
    4646                 :             :     Numeric     res;
    4647                 :             :     NumericVar  result;
    4648                 :             :     char        buf[FLT_DIG + 100];
    4649                 :             :     const char *endptr;
    4650                 :             : 
    4651         [ +  + ]:       15063 :     if (isnan(val))
    4652                 :           5 :         PG_RETURN_NUMERIC(make_result(&const_nan));
    4653                 :             : 
    4654         [ +  + ]:       15058 :     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                 :       15048 :     snprintf(buf, sizeof(buf), "%.*g", FLT_DIG, val);
    4663                 :             : 
    4664                 :       15048 :     init_var(&result);
    4665                 :             : 
    4666                 :             :     /* Assume we need not worry about leading/trailing spaces */
    4667         [ -  + ]:       15048 :     if (!set_var_from_str(buf, buf, &result, &endptr, fcinfo->context))
    4668                 :           0 :         PG_RETURN_NULL();
    4669                 :             : 
    4670                 :       15048 :     res = make_result(&result);
    4671                 :             : 
    4672                 :       15048 :     free_var(&result);
    4673                 :             : 
    4674                 :       15048 :     PG_RETURN_NUMERIC(res);
    4675                 :             : }
    4676                 :             : 
    4677                 :             : 
    4678                 :             : Datum
    4679                 :        1733 : numeric_float4(PG_FUNCTION_ARGS)
    4680                 :             : {
    4681                 :        1733 :     Numeric     num = PG_GETARG_NUMERIC(0);
    4682                 :             :     char       *tmp;
    4683                 :             :     Datum       result;
    4684                 :             : 
    4685         [ +  + ]:        1733 :     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                 :        1677 :     tmp = DatumGetCString(DirectFunctionCall1(numeric_out,
    4696                 :             :                                               NumericGetDatum(num)));
    4697                 :             : 
    4698         [ -  + ]:        1677 :     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                 :        1677 :     pfree(tmp);
    4708                 :             : 
    4709                 :        1677 :     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                 :      114080 : makeNumericAggState(FunctionCallInfo fcinfo, bool calcSumX2)
    4782                 :             : {
    4783                 :             :     NumericAggState *state;
    4784                 :             :     MemoryContext agg_context;
    4785                 :             :     MemoryContext old_context;
    4786                 :             : 
    4787         [ -  + ]:      114080 :     if (!AggCheckCallContext(fcinfo, &agg_context))
    4788         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    4789                 :             : 
    4790                 :      114080 :     old_context = MemoryContextSwitchTo(agg_context);
    4791                 :             : 
    4792                 :      114080 :     state = palloc0_object(NumericAggState);
    4793                 :      114080 :     state->calcSumX2 = calcSumX2;
    4794                 :      114080 :     state->agg_context = agg_context;
    4795                 :             : 
    4796                 :      114080 :     MemoryContextSwitchTo(old_context);
    4797                 :             : 
    4798                 :      114080 :     return state;
    4799                 :             : }
    4800                 :             : 
    4801                 :             : /*
    4802                 :             :  * Like makeNumericAggState(), but allocate the state in the current memory
    4803                 :             :  * context.
    4804                 :             :  */
    4805                 :             : static NumericAggState *
    4806                 :          54 : makeNumericAggStateCurrentContext(bool calcSumX2)
    4807                 :             : {
    4808                 :             :     NumericAggState *state;
    4809                 :             : 
    4810                 :          54 :     state = palloc0_object(NumericAggState);
    4811                 :          54 :     state->calcSumX2 = calcSumX2;
    4812                 :          54 :     state->agg_context = CurrentMemoryContext;
    4813                 :             : 
    4814                 :          54 :     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                 :          23 : numeric_combine(PG_FUNCTION_ARGS)
    5005                 :             : {
    5006                 :             :     NumericAggState *state1;
    5007                 :             :     NumericAggState *state2;
    5008                 :             :     MemoryContext agg_context;
    5009                 :             :     MemoryContext old_context;
    5010                 :             : 
    5011         [ -  + ]:          23 :     if (!AggCheckCallContext(fcinfo, &agg_context))
    5012         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5013                 :             : 
    5014         [ +  + ]:          23 :     state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    5015         [ +  - ]:          23 :     state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
    5016                 :             : 
    5017         [ -  + ]:          23 :     if (state2 == NULL)
    5018                 :             :     {
    5019                 :             :         /*
    5020                 :             :          * NULL state2 is easy, just return state1, which we know is already
    5021                 :             :          * in the agg_context
    5022                 :             :          */
    5023         [ #  # ]:           0 :         if (state1 == NULL)
    5024                 :           0 :             PG_RETURN_NULL();
    5025                 :           0 :         PG_RETURN_POINTER(state1);
    5026                 :             :     }
    5027                 :             : 
    5028                 :             :     /* manually copy all fields from state2 to state1 */
    5029         [ +  + ]:          23 :     if (state1 == NULL)
    5030                 :             :     {
    5031                 :          12 :         old_context = MemoryContextSwitchTo(agg_context);
    5032                 :             : 
    5033                 :          12 :         state1 = makeNumericAggStateCurrentContext(true);
    5034                 :          12 :         state1->N = state2->N;
    5035                 :          12 :         state1->NaNcount = state2->NaNcount;
    5036                 :          12 :         state1->pInfcount = state2->pInfcount;
    5037                 :          12 :         state1->nInfcount = state2->nInfcount;
    5038                 :          12 :         state1->maxScale = state2->maxScale;
    5039                 :          12 :         state1->maxScaleCount = state2->maxScaleCount;
    5040                 :             : 
    5041                 :          12 :         accum_sum_copy(&state1->sumX, &state2->sumX);
    5042                 :          12 :         accum_sum_copy(&state1->sumX2, &state2->sumX2);
    5043                 :             : 
    5044                 :          12 :         MemoryContextSwitchTo(old_context);
    5045                 :             : 
    5046                 :          12 :         PG_RETURN_POINTER(state1);
    5047                 :             :     }
    5048                 :             : 
    5049                 :          11 :     state1->N += state2->N;
    5050                 :          11 :     state1->NaNcount += state2->NaNcount;
    5051                 :          11 :     state1->pInfcount += state2->pInfcount;
    5052                 :          11 :     state1->nInfcount += state2->nInfcount;
    5053                 :             : 
    5054         [ +  - ]:          11 :     if (state2->N > 0)
    5055                 :             :     {
    5056                 :             :         /*
    5057                 :             :          * These are currently only needed for moving aggregates, but let's do
    5058                 :             :          * the right thing anyway...
    5059                 :             :          */
    5060         [ -  + ]:          11 :         if (state2->maxScale > state1->maxScale)
    5061                 :             :         {
    5062                 :           0 :             state1->maxScale = state2->maxScale;
    5063                 :           0 :             state1->maxScaleCount = state2->maxScaleCount;
    5064                 :             :         }
    5065         [ +  - ]:          11 :         else if (state2->maxScale == state1->maxScale)
    5066                 :          11 :             state1->maxScaleCount += state2->maxScaleCount;
    5067                 :             : 
    5068                 :             :         /* The rest of this needs to work in the aggregate context */
    5069                 :          11 :         old_context = MemoryContextSwitchTo(agg_context);
    5070                 :             : 
    5071                 :             :         /* Accumulate sums */
    5072                 :          11 :         accum_sum_combine(&state1->sumX, &state2->sumX);
    5073                 :          11 :         accum_sum_combine(&state1->sumX2, &state2->sumX2);
    5074                 :             : 
    5075                 :          11 :         MemoryContextSwitchTo(old_context);
    5076                 :             :     }
    5077                 :          11 :     PG_RETURN_POINTER(state1);
    5078                 :             : }
    5079                 :             : 
    5080                 :             : /*
    5081                 :             :  * Generic transition function for numeric aggregates that don't require sumX2.
    5082                 :             :  */
    5083                 :             : Datum
    5084                 :     1248516 : numeric_avg_accum(PG_FUNCTION_ARGS)
    5085                 :             : {
    5086                 :             :     NumericAggState *state;
    5087                 :             : 
    5088         [ +  + ]:     1248516 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    5089                 :             : 
    5090                 :             :     /* Create the state data on the first call */
    5091         [ +  + ]:     1248516 :     if (state == NULL)
    5092                 :      113925 :         state = makeNumericAggState(fcinfo, false);
    5093                 :             : 
    5094         [ +  + ]:     1248516 :     if (!PG_ARGISNULL(1))
    5095                 :     1248476 :         do_numeric_accum(state, PG_GETARG_NUMERIC(1));
    5096                 :             : 
    5097                 :     1248516 :     PG_RETURN_POINTER(state);
    5098                 :             : }
    5099                 :             : 
    5100                 :             : /*
    5101                 :             :  * Combine function for numeric aggregates which don't require sumX2
    5102                 :             :  */
    5103                 :             : Datum
    5104                 :          15 : numeric_avg_combine(PG_FUNCTION_ARGS)
    5105                 :             : {
    5106                 :             :     NumericAggState *state1;
    5107                 :             :     NumericAggState *state2;
    5108                 :             :     MemoryContext agg_context;
    5109                 :             :     MemoryContext old_context;
    5110                 :             : 
    5111         [ -  + ]:          15 :     if (!AggCheckCallContext(fcinfo, &agg_context))
    5112         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5113                 :             : 
    5114         [ +  + ]:          15 :     state1 = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    5115         [ +  - ]:          15 :     state2 = PG_ARGISNULL(1) ? NULL : (NumericAggState *) PG_GETARG_POINTER(1);
    5116                 :             : 
    5117         [ -  + ]:          15 :     if (state2 == NULL)
    5118                 :             :     {
    5119                 :             :         /*
    5120                 :             :          * NULL state2 is easy, just return state1, which we know is already
    5121                 :             :          * in the agg_context
    5122                 :             :          */
    5123         [ #  # ]:           0 :         if (state1 == NULL)
    5124                 :           0 :             PG_RETURN_NULL();
    5125                 :           0 :         PG_RETURN_POINTER(state1);
    5126                 :             :     }
    5127                 :             : 
    5128                 :             :     /* manually copy all fields from state2 to state1 */
    5129         [ +  + ]:          15 :     if (state1 == NULL)
    5130                 :             :     {
    5131                 :           4 :         old_context = MemoryContextSwitchTo(agg_context);
    5132                 :             : 
    5133                 :           4 :         state1 = makeNumericAggStateCurrentContext(false);
    5134                 :           4 :         state1->N = state2->N;
    5135                 :           4 :         state1->NaNcount = state2->NaNcount;
    5136                 :           4 :         state1->pInfcount = state2->pInfcount;
    5137                 :           4 :         state1->nInfcount = state2->nInfcount;
    5138                 :           4 :         state1->maxScale = state2->maxScale;
    5139                 :           4 :         state1->maxScaleCount = state2->maxScaleCount;
    5140                 :             : 
    5141                 :           4 :         accum_sum_copy(&state1->sumX, &state2->sumX);
    5142                 :             : 
    5143                 :           4 :         MemoryContextSwitchTo(old_context);
    5144                 :             : 
    5145                 :           4 :         PG_RETURN_POINTER(state1);
    5146                 :             :     }
    5147                 :             : 
    5148                 :          11 :     state1->N += state2->N;
    5149                 :          11 :     state1->NaNcount += state2->NaNcount;
    5150                 :          11 :     state1->pInfcount += state2->pInfcount;
    5151                 :          11 :     state1->nInfcount += state2->nInfcount;
    5152                 :             : 
    5153         [ +  - ]:          11 :     if (state2->N > 0)
    5154                 :             :     {
    5155                 :             :         /*
    5156                 :             :          * These are currently only needed for moving aggregates, but let's do
    5157                 :             :          * the right thing anyway...
    5158                 :             :          */
    5159         [ -  + ]:          11 :         if (state2->maxScale > state1->maxScale)
    5160                 :             :         {
    5161                 :           0 :             state1->maxScale = state2->maxScale;
    5162                 :           0 :             state1->maxScaleCount = state2->maxScaleCount;
    5163                 :             :         }
    5164         [ +  - ]:          11 :         else if (state2->maxScale == state1->maxScale)
    5165                 :          11 :             state1->maxScaleCount += state2->maxScaleCount;
    5166                 :             : 
    5167                 :             :         /* The rest of this needs to work in the aggregate context */
    5168                 :          11 :         old_context = MemoryContextSwitchTo(agg_context);
    5169                 :             : 
    5170                 :             :         /* Accumulate sums */
    5171                 :          11 :         accum_sum_combine(&state1->sumX, &state2->sumX);
    5172                 :             : 
    5173                 :          11 :         MemoryContextSwitchTo(old_context);
    5174                 :             :     }
    5175                 :          11 :     PG_RETURN_POINTER(state1);
    5176                 :             : }
    5177                 :             : 
    5178                 :             : /*
    5179                 :             :  * numeric_avg_serialize
    5180                 :             :  *      Serialize NumericAggState for numeric aggregates that don't require
    5181                 :             :  *      sumX2.
    5182                 :             :  */
    5183                 :             : Datum
    5184                 :          15 : numeric_avg_serialize(PG_FUNCTION_ARGS)
    5185                 :             : {
    5186                 :             :     NumericAggState *state;
    5187                 :             :     StringInfoData buf;
    5188                 :             :     bytea      *result;
    5189                 :             :     NumericVar  tmp_var;
    5190                 :             : 
    5191                 :             :     /* Ensure we disallow calling when not in aggregate context */
    5192         [ -  + ]:          15 :     if (!AggCheckCallContext(fcinfo, NULL))
    5193         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5194                 :             : 
    5195                 :          15 :     state = (NumericAggState *) PG_GETARG_POINTER(0);
    5196                 :             : 
    5197                 :          15 :     init_var(&tmp_var);
    5198                 :             : 
    5199                 :          15 :     pq_begintypsend(&buf);
    5200                 :             : 
    5201                 :             :     /* N */
    5202                 :          15 :     pq_sendint64(&buf, state->N);
    5203                 :             : 
    5204                 :             :     /* sumX */
    5205                 :          15 :     accum_sum_final(&state->sumX, &tmp_var);
    5206                 :          15 :     numericvar_serialize(&buf, &tmp_var);
    5207                 :             : 
    5208                 :             :     /* maxScale */
    5209                 :          15 :     pq_sendint32(&buf, state->maxScale);
    5210                 :             : 
    5211                 :             :     /* maxScaleCount */
    5212                 :          15 :     pq_sendint64(&buf, state->maxScaleCount);
    5213                 :             : 
    5214                 :             :     /* NaNcount */
    5215                 :          15 :     pq_sendint64(&buf, state->NaNcount);
    5216                 :             : 
    5217                 :             :     /* pInfcount */
    5218                 :          15 :     pq_sendint64(&buf, state->pInfcount);
    5219                 :             : 
    5220                 :             :     /* nInfcount */
    5221                 :          15 :     pq_sendint64(&buf, state->nInfcount);
    5222                 :             : 
    5223                 :          15 :     result = pq_endtypsend(&buf);
    5224                 :             : 
    5225                 :          15 :     free_var(&tmp_var);
    5226                 :             : 
    5227                 :          15 :     PG_RETURN_BYTEA_P(result);
    5228                 :             : }
    5229                 :             : 
    5230                 :             : /*
    5231                 :             :  * numeric_avg_deserialize
    5232                 :             :  *      Deserialize bytea into NumericAggState for numeric aggregates that
    5233                 :             :  *      don't require sumX2.
    5234                 :             :  */
    5235                 :             : Datum
    5236                 :          15 : numeric_avg_deserialize(PG_FUNCTION_ARGS)
    5237                 :             : {
    5238                 :             :     bytea      *sstate;
    5239                 :             :     NumericAggState *result;
    5240                 :             :     StringInfoData buf;
    5241                 :             :     NumericVar  tmp_var;
    5242                 :             : 
    5243         [ -  + ]:          15 :     if (!AggCheckCallContext(fcinfo, NULL))
    5244         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5245                 :             : 
    5246                 :          15 :     sstate = PG_GETARG_BYTEA_PP(0);
    5247                 :             : 
    5248                 :          15 :     init_var(&tmp_var);
    5249                 :             : 
    5250                 :             :     /*
    5251                 :             :      * Initialize a StringInfo so that we can "receive" it using the standard
    5252                 :             :      * recv-function infrastructure.
    5253                 :             :      */
    5254                 :          15 :     initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
    5255                 :          15 :                            VARSIZE_ANY_EXHDR(sstate));
    5256                 :             : 
    5257                 :          15 :     result = makeNumericAggStateCurrentContext(false);
    5258                 :             : 
    5259                 :             :     /* N */
    5260                 :          15 :     result->N = pq_getmsgint64(&buf);
    5261                 :             : 
    5262                 :             :     /* sumX */
    5263                 :          15 :     numericvar_deserialize(&buf, &tmp_var);
    5264                 :          15 :     accum_sum_add(&(result->sumX), &tmp_var);
    5265                 :             : 
    5266                 :             :     /* maxScale */
    5267                 :          15 :     result->maxScale = pq_getmsgint(&buf, 4);
    5268                 :             : 
    5269                 :             :     /* maxScaleCount */
    5270                 :          15 :     result->maxScaleCount = pq_getmsgint64(&buf);
    5271                 :             : 
    5272                 :             :     /* NaNcount */
    5273                 :          15 :     result->NaNcount = pq_getmsgint64(&buf);
    5274                 :             : 
    5275                 :             :     /* pInfcount */
    5276                 :          15 :     result->pInfcount = pq_getmsgint64(&buf);
    5277                 :             : 
    5278                 :             :     /* nInfcount */
    5279                 :          15 :     result->nInfcount = pq_getmsgint64(&buf);
    5280                 :             : 
    5281                 :          15 :     pq_getmsgend(&buf);
    5282                 :             : 
    5283                 :          15 :     free_var(&tmp_var);
    5284                 :             : 
    5285                 :          15 :     PG_RETURN_POINTER(result);
    5286                 :             : }
    5287                 :             : 
    5288                 :             : /*
    5289                 :             :  * numeric_serialize
    5290                 :             :  *      Serialization function for NumericAggState for numeric aggregates that
    5291                 :             :  *      require sumX2.
    5292                 :             :  */
    5293                 :             : Datum
    5294                 :          23 : numeric_serialize(PG_FUNCTION_ARGS)
    5295                 :             : {
    5296                 :             :     NumericAggState *state;
    5297                 :             :     StringInfoData buf;
    5298                 :             :     bytea      *result;
    5299                 :             :     NumericVar  tmp_var;
    5300                 :             : 
    5301                 :             :     /* Ensure we disallow calling when not in aggregate context */
    5302         [ -  + ]:          23 :     if (!AggCheckCallContext(fcinfo, NULL))
    5303         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5304                 :             : 
    5305                 :          23 :     state = (NumericAggState *) PG_GETARG_POINTER(0);
    5306                 :             : 
    5307                 :          23 :     init_var(&tmp_var);
    5308                 :             : 
    5309                 :          23 :     pq_begintypsend(&buf);
    5310                 :             : 
    5311                 :             :     /* N */
    5312                 :          23 :     pq_sendint64(&buf, state->N);
    5313                 :             : 
    5314                 :             :     /* sumX */
    5315                 :          23 :     accum_sum_final(&state->sumX, &tmp_var);
    5316                 :          23 :     numericvar_serialize(&buf, &tmp_var);
    5317                 :             : 
    5318                 :             :     /* sumX2 */
    5319                 :          23 :     accum_sum_final(&state->sumX2, &tmp_var);
    5320                 :          23 :     numericvar_serialize(&buf, &tmp_var);
    5321                 :             : 
    5322                 :             :     /* maxScale */
    5323                 :          23 :     pq_sendint32(&buf, state->maxScale);
    5324                 :             : 
    5325                 :             :     /* maxScaleCount */
    5326                 :          23 :     pq_sendint64(&buf, state->maxScaleCount);
    5327                 :             : 
    5328                 :             :     /* NaNcount */
    5329                 :          23 :     pq_sendint64(&buf, state->NaNcount);
    5330                 :             : 
    5331                 :             :     /* pInfcount */
    5332                 :          23 :     pq_sendint64(&buf, state->pInfcount);
    5333                 :             : 
    5334                 :             :     /* nInfcount */
    5335                 :          23 :     pq_sendint64(&buf, state->nInfcount);
    5336                 :             : 
    5337                 :          23 :     result = pq_endtypsend(&buf);
    5338                 :             : 
    5339                 :          23 :     free_var(&tmp_var);
    5340                 :             : 
    5341                 :          23 :     PG_RETURN_BYTEA_P(result);
    5342                 :             : }
    5343                 :             : 
    5344                 :             : /*
    5345                 :             :  * numeric_deserialize
    5346                 :             :  *      Deserialization function for NumericAggState for numeric aggregates that
    5347                 :             :  *      require sumX2.
    5348                 :             :  */
    5349                 :             : Datum
    5350                 :          23 : numeric_deserialize(PG_FUNCTION_ARGS)
    5351                 :             : {
    5352                 :             :     bytea      *sstate;
    5353                 :             :     NumericAggState *result;
    5354                 :             :     StringInfoData buf;
    5355                 :             :     NumericVar  tmp_var;
    5356                 :             : 
    5357         [ -  + ]:          23 :     if (!AggCheckCallContext(fcinfo, NULL))
    5358         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5359                 :             : 
    5360                 :          23 :     sstate = PG_GETARG_BYTEA_PP(0);
    5361                 :             : 
    5362                 :          23 :     init_var(&tmp_var);
    5363                 :             : 
    5364                 :             :     /*
    5365                 :             :      * Initialize a StringInfo so that we can "receive" it using the standard
    5366                 :             :      * recv-function infrastructure.
    5367                 :             :      */
    5368                 :          23 :     initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
    5369                 :          23 :                            VARSIZE_ANY_EXHDR(sstate));
    5370                 :             : 
    5371                 :          23 :     result = makeNumericAggStateCurrentContext(false);
    5372                 :             : 
    5373                 :             :     /* N */
    5374                 :          23 :     result->N = pq_getmsgint64(&buf);
    5375                 :             : 
    5376                 :             :     /* sumX */
    5377                 :          23 :     numericvar_deserialize(&buf, &tmp_var);
    5378                 :          23 :     accum_sum_add(&(result->sumX), &tmp_var);
    5379                 :             : 
    5380                 :             :     /* sumX2 */
    5381                 :          23 :     numericvar_deserialize(&buf, &tmp_var);
    5382                 :          23 :     accum_sum_add(&(result->sumX2), &tmp_var);
    5383                 :             : 
    5384                 :             :     /* maxScale */
    5385                 :          23 :     result->maxScale = pq_getmsgint(&buf, 4);
    5386                 :             : 
    5387                 :             :     /* maxScaleCount */
    5388                 :          23 :     result->maxScaleCount = pq_getmsgint64(&buf);
    5389                 :             : 
    5390                 :             :     /* NaNcount */
    5391                 :          23 :     result->NaNcount = pq_getmsgint64(&buf);
    5392                 :             : 
    5393                 :             :     /* pInfcount */
    5394                 :          23 :     result->pInfcount = pq_getmsgint64(&buf);
    5395                 :             : 
    5396                 :             :     /* nInfcount */
    5397                 :          23 :     result->nInfcount = pq_getmsgint64(&buf);
    5398                 :             : 
    5399                 :          23 :     pq_getmsgend(&buf);
    5400                 :             : 
    5401                 :          23 :     free_var(&tmp_var);
    5402                 :             : 
    5403                 :          23 :     PG_RETURN_POINTER(result);
    5404                 :             : }
    5405                 :             : 
    5406                 :             : /*
    5407                 :             :  * Generic inverse transition function for numeric aggregates
    5408                 :             :  * (with or without requirement for X^2).
    5409                 :             :  */
    5410                 :             : Datum
    5411                 :         152 : numeric_accum_inv(PG_FUNCTION_ARGS)
    5412                 :             : {
    5413                 :             :     NumericAggState *state;
    5414                 :             : 
    5415         [ +  - ]:         152 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    5416                 :             : 
    5417                 :             :     /* Should not get here with no state */
    5418         [ -  + ]:         152 :     if (state == NULL)
    5419         [ #  # ]:           0 :         elog(ERROR, "numeric_accum_inv called with NULL state");
    5420                 :             : 
    5421         [ +  + ]:         152 :     if (!PG_ARGISNULL(1))
    5422                 :             :     {
    5423                 :             :         /* If we fail to perform the inverse transition, return NULL */
    5424         [ +  + ]:         132 :         if (!do_numeric_discard(state, PG_GETARG_NUMERIC(1)))
    5425                 :           4 :             PG_RETURN_NULL();
    5426                 :             :     }
    5427                 :             : 
    5428                 :         148 :     PG_RETURN_POINTER(state);
    5429                 :             : }
    5430                 :             : 
    5431                 :             : 
    5432                 :             : /*
    5433                 :             :  * Integer data types in general use Numeric accumulators to share code and
    5434                 :             :  * avoid risk of overflow.  However for performance reasons optimized
    5435                 :             :  * special-purpose accumulator routines are used when possible:
    5436                 :             :  *
    5437                 :             :  * For 16-bit and 32-bit inputs, N and sum(X) fit into 64-bit, so 64-bit
    5438                 :             :  * accumulators are used for SUM and AVG of these data types.
    5439                 :             :  *
    5440                 :             :  * For 16-bit and 32-bit inputs, sum(X^2) fits into 128-bit, so 128-bit
    5441                 :             :  * accumulators are used for STDDEV_POP, STDDEV_SAMP, VAR_POP, and VAR_SAMP of
    5442                 :             :  * these data types.
    5443                 :             :  *
    5444                 :             :  * For 64-bit inputs, sum(X) fits into 128-bit, so a 128-bit accumulator is
    5445                 :             :  * used for SUM(int8) and AVG(int8).
    5446                 :             :  */
    5447                 :             : 
    5448                 :             : typedef struct Int128AggState
    5449                 :             : {
    5450                 :             :     bool        calcSumX2;      /* if true, calculate sumX2 */
    5451                 :             :     int64       N;              /* count of processed numbers */
    5452                 :             :     INT128      sumX;           /* sum of processed numbers */
    5453                 :             :     INT128      sumX2;          /* sum of squares of processed numbers */
    5454                 :             : } Int128AggState;
    5455                 :             : 
    5456                 :             : /*
    5457                 :             :  * Prepare state data for a 128-bit aggregate function that needs to compute
    5458                 :             :  * sum, count and optionally sum of squares of the input.
    5459                 :             :  */
    5460                 :             : static Int128AggState *
    5461                 :         619 : makeInt128AggState(FunctionCallInfo fcinfo, bool calcSumX2)
    5462                 :             : {
    5463                 :             :     Int128AggState *state;
    5464                 :             :     MemoryContext agg_context;
    5465                 :             :     MemoryContext old_context;
    5466                 :             : 
    5467         [ -  + ]:         619 :     if (!AggCheckCallContext(fcinfo, &agg_context))
    5468         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5469                 :             : 
    5470                 :         619 :     old_context = MemoryContextSwitchTo(agg_context);
    5471                 :             : 
    5472                 :         619 :     state = palloc0_object(Int128AggState);
    5473                 :         619 :     state->calcSumX2 = calcSumX2;
    5474                 :             : 
    5475                 :         619 :     MemoryContextSwitchTo(old_context);
    5476                 :             : 
    5477                 :         619 :     return state;
    5478                 :             : }
    5479                 :             : 
    5480                 :             : /*
    5481                 :             :  * Like makeInt128AggState(), but allocate the state in the current memory
    5482                 :             :  * context.
    5483                 :             :  */
    5484                 :             : static Int128AggState *
    5485                 :          33 : makeInt128AggStateCurrentContext(bool calcSumX2)
    5486                 :             : {
    5487                 :             :     Int128AggState *state;
    5488                 :             : 
    5489                 :          33 :     state = palloc0_object(Int128AggState);
    5490                 :          33 :     state->calcSumX2 = calcSumX2;
    5491                 :             : 
    5492                 :          33 :     return state;
    5493                 :             : }
    5494                 :             : 
    5495                 :             : /*
    5496                 :             :  * Accumulate a new input value for 128-bit aggregate functions.
    5497                 :             :  */
    5498                 :             : static void
    5499                 :      371066 : do_int128_accum(Int128AggState *state, int64 newval)
    5500                 :             : {
    5501         [ +  + ]:      371066 :     if (state->calcSumX2)
    5502                 :      161240 :         int128_add_int64_mul_int64(&state->sumX2, newval, newval);
    5503                 :             : 
    5504                 :      371066 :     int128_add_int64(&state->sumX, newval);
    5505                 :      371066 :     state->N++;
    5506                 :      371066 : }
    5507                 :             : 
    5508                 :             : /*
    5509                 :             :  * Remove an input value from the aggregated state.
    5510                 :             :  */
    5511                 :             : static void
    5512                 :         208 : do_int128_discard(Int128AggState *state, int64 newval)
    5513                 :             : {
    5514         [ +  + ]:         208 :     if (state->calcSumX2)
    5515                 :         192 :         int128_sub_int64_mul_int64(&state->sumX2, newval, newval);
    5516                 :             : 
    5517                 :         208 :     int128_sub_int64(&state->sumX, newval);
    5518                 :         208 :     state->N--;
    5519                 :         208 : }
    5520                 :             : 
    5521                 :             : Datum
    5522                 :         132 : int2_accum(PG_FUNCTION_ARGS)
    5523                 :             : {
    5524                 :             :     Int128AggState *state;
    5525                 :             : 
    5526         [ +  + ]:         132 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5527                 :             : 
    5528                 :             :     /* Create the state data on the first call */
    5529         [ +  + ]:         132 :     if (state == NULL)
    5530                 :          24 :         state = makeInt128AggState(fcinfo, true);
    5531                 :             : 
    5532         [ +  + ]:         132 :     if (!PG_ARGISNULL(1))
    5533                 :         120 :         do_int128_accum(state, PG_GETARG_INT16(1));
    5534                 :             : 
    5535                 :         132 :     PG_RETURN_POINTER(state);
    5536                 :             : }
    5537                 :             : 
    5538                 :             : Datum
    5539                 :      161132 : int4_accum(PG_FUNCTION_ARGS)
    5540                 :             : {
    5541                 :             :     Int128AggState *state;
    5542                 :             : 
    5543         [ +  + ]:      161132 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5544                 :             : 
    5545                 :             :     /* Create the state data on the first call */
    5546         [ +  + ]:      161132 :     if (state == NULL)
    5547                 :          48 :         state = makeInt128AggState(fcinfo, true);
    5548                 :             : 
    5549         [ +  + ]:      161132 :     if (!PG_ARGISNULL(1))
    5550                 :      161120 :         do_int128_accum(state, PG_GETARG_INT32(1));
    5551                 :             : 
    5552                 :      161132 :     PG_RETURN_POINTER(state);
    5553                 :             : }
    5554                 :             : 
    5555                 :             : Datum
    5556                 :      160132 : int8_accum(PG_FUNCTION_ARGS)
    5557                 :             : {
    5558                 :             :     NumericAggState *state;
    5559                 :             : 
    5560         [ +  + ]:      160132 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    5561                 :             : 
    5562                 :             :     /* Create the state data on the first call */
    5563         [ +  + ]:      160132 :     if (state == NULL)
    5564                 :          39 :         state = makeNumericAggState(fcinfo, true);
    5565                 :             : 
    5566         [ +  + ]:      160132 :     if (!PG_ARGISNULL(1))
    5567                 :      160120 :         do_numeric_accum(state, int64_to_numeric(PG_GETARG_INT64(1)));
    5568                 :             : 
    5569                 :      160132 :     PG_RETURN_POINTER(state);
    5570                 :             : }
    5571                 :             : 
    5572                 :             : /*
    5573                 :             :  * Combine function for Int128AggState for aggregates which require sumX2
    5574                 :             :  */
    5575                 :             : Datum
    5576                 :          14 : numeric_poly_combine(PG_FUNCTION_ARGS)
    5577                 :             : {
    5578                 :             :     Int128AggState *state1;
    5579                 :             :     Int128AggState *state2;
    5580                 :             :     MemoryContext agg_context;
    5581                 :             :     MemoryContext old_context;
    5582                 :             : 
    5583         [ -  + ]:          14 :     if (!AggCheckCallContext(fcinfo, &agg_context))
    5584         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5585                 :             : 
    5586         [ +  + ]:          14 :     state1 = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5587         [ +  - ]:          14 :     state2 = PG_ARGISNULL(1) ? NULL : (Int128AggState *) PG_GETARG_POINTER(1);
    5588                 :             : 
    5589         [ -  + ]:          14 :     if (state2 == NULL)
    5590                 :             :     {
    5591                 :             :         /*
    5592                 :             :          * NULL state2 is easy, just return state1, which we know is already
    5593                 :             :          * in the agg_context
    5594                 :             :          */
    5595         [ #  # ]:           0 :         if (state1 == NULL)
    5596                 :           0 :             PG_RETURN_NULL();
    5597                 :           0 :         PG_RETURN_POINTER(state1);
    5598                 :             :     }
    5599                 :             : 
    5600                 :             :     /* manually copy all fields from state2 to state1 */
    5601         [ +  + ]:          14 :     if (state1 == NULL)
    5602                 :             :     {
    5603                 :           4 :         old_context = MemoryContextSwitchTo(agg_context);
    5604                 :             : 
    5605                 :           4 :         state1 = makeInt128AggState(fcinfo, true);
    5606                 :           4 :         state1->N = state2->N;
    5607                 :           4 :         state1->sumX = state2->sumX;
    5608                 :           4 :         state1->sumX2 = state2->sumX2;
    5609                 :             : 
    5610                 :           4 :         MemoryContextSwitchTo(old_context);
    5611                 :             : 
    5612                 :           4 :         PG_RETURN_POINTER(state1);
    5613                 :             :     }
    5614                 :             : 
    5615         [ +  - ]:          10 :     if (state2->N > 0)
    5616                 :             :     {
    5617                 :          10 :         state1->N += state2->N;
    5618                 :          10 :         int128_add_int128(&state1->sumX, state2->sumX);
    5619                 :          10 :         int128_add_int128(&state1->sumX2, state2->sumX2);
    5620                 :             :     }
    5621                 :          10 :     PG_RETURN_POINTER(state1);
    5622                 :             : }
    5623                 :             : 
    5624                 :             : /*
    5625                 :             :  * int128_serialize - serialize a 128-bit integer to binary format
    5626                 :             :  */
    5627                 :             : static inline void
    5628                 :          47 : int128_serialize(StringInfo buf, INT128 val)
    5629                 :             : {
    5630                 :          47 :     pq_sendint64(buf, PG_INT128_HI_INT64(val));
    5631                 :          47 :     pq_sendint64(buf, PG_INT128_LO_UINT64(val));
    5632                 :          47 : }
    5633                 :             : 
    5634                 :             : /*
    5635                 :             :  * int128_deserialize - deserialize binary format to a 128-bit integer.
    5636                 :             :  */
    5637                 :             : static inline INT128
    5638                 :          47 : int128_deserialize(StringInfo buf)
    5639                 :             : {
    5640                 :          47 :     int64       hi = pq_getmsgint64(buf);
    5641                 :          47 :     uint64      lo = pq_getmsgint64(buf);
    5642                 :             : 
    5643                 :          47 :     return make_int128(hi, lo);
    5644                 :             : }
    5645                 :             : 
    5646                 :             : /*
    5647                 :             :  * numeric_poly_serialize
    5648                 :             :  *      Serialize Int128AggState into bytea for aggregate functions which
    5649                 :             :  *      require sumX2.
    5650                 :             :  */
    5651                 :             : Datum
    5652                 :          14 : numeric_poly_serialize(PG_FUNCTION_ARGS)
    5653                 :             : {
    5654                 :             :     Int128AggState *state;
    5655                 :             :     StringInfoData buf;
    5656                 :             :     bytea      *result;
    5657                 :             : 
    5658                 :             :     /* Ensure we disallow calling when not in aggregate context */
    5659         [ -  + ]:          14 :     if (!AggCheckCallContext(fcinfo, NULL))
    5660         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5661                 :             : 
    5662                 :          14 :     state = (Int128AggState *) PG_GETARG_POINTER(0);
    5663                 :             : 
    5664                 :          14 :     pq_begintypsend(&buf);
    5665                 :             : 
    5666                 :             :     /* N */
    5667                 :          14 :     pq_sendint64(&buf, state->N);
    5668                 :             : 
    5669                 :             :     /* sumX */
    5670                 :          14 :     int128_serialize(&buf, state->sumX);
    5671                 :             : 
    5672                 :             :     /* sumX2 */
    5673                 :          14 :     int128_serialize(&buf, state->sumX2);
    5674                 :             : 
    5675                 :          14 :     result = pq_endtypsend(&buf);
    5676                 :             : 
    5677                 :          14 :     PG_RETURN_BYTEA_P(result);
    5678                 :             : }
    5679                 :             : 
    5680                 :             : /*
    5681                 :             :  * numeric_poly_deserialize
    5682                 :             :  *      Deserialize Int128AggState from bytea for aggregate functions which
    5683                 :             :  *      require sumX2.
    5684                 :             :  */
    5685                 :             : Datum
    5686                 :          14 : numeric_poly_deserialize(PG_FUNCTION_ARGS)
    5687                 :             : {
    5688                 :             :     bytea      *sstate;
    5689                 :             :     Int128AggState *result;
    5690                 :             :     StringInfoData buf;
    5691                 :             : 
    5692         [ -  + ]:          14 :     if (!AggCheckCallContext(fcinfo, NULL))
    5693         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5694                 :             : 
    5695                 :          14 :     sstate = PG_GETARG_BYTEA_PP(0);
    5696                 :             : 
    5697                 :             :     /*
    5698                 :             :      * Initialize a StringInfo so that we can "receive" it using the standard
    5699                 :             :      * recv-function infrastructure.
    5700                 :             :      */
    5701                 :          14 :     initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
    5702                 :          14 :                            VARSIZE_ANY_EXHDR(sstate));
    5703                 :             : 
    5704                 :          14 :     result = makeInt128AggStateCurrentContext(false);
    5705                 :             : 
    5706                 :             :     /* N */
    5707                 :          14 :     result->N = pq_getmsgint64(&buf);
    5708                 :             : 
    5709                 :             :     /* sumX */
    5710                 :          14 :     result->sumX = int128_deserialize(&buf);
    5711                 :             : 
    5712                 :             :     /* sumX2 */
    5713                 :          14 :     result->sumX2 = int128_deserialize(&buf);
    5714                 :             : 
    5715                 :          14 :     pq_getmsgend(&buf);
    5716                 :             : 
    5717                 :          14 :     PG_RETURN_POINTER(result);
    5718                 :             : }
    5719                 :             : 
    5720                 :             : /*
    5721                 :             :  * Transition function for int8 input when we don't need sumX2.
    5722                 :             :  */
    5723                 :             : Datum
    5724                 :      212605 : int8_avg_accum(PG_FUNCTION_ARGS)
    5725                 :             : {
    5726                 :             :     Int128AggState *state;
    5727                 :             : 
    5728         [ +  + ]:      212605 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5729                 :             : 
    5730                 :             :     /* Create the state data on the first call */
    5731         [ +  + ]:      212605 :     if (state == NULL)
    5732                 :         535 :         state = makeInt128AggState(fcinfo, false);
    5733                 :             : 
    5734         [ +  + ]:      212605 :     if (!PG_ARGISNULL(1))
    5735                 :      209826 :         do_int128_accum(state, PG_GETARG_INT64(1));
    5736                 :             : 
    5737                 :      212605 :     PG_RETURN_POINTER(state);
    5738                 :             : }
    5739                 :             : 
    5740                 :             : /*
    5741                 :             :  * Combine function for Int128AggState for aggregates which don't require
    5742                 :             :  * sumX2
    5743                 :             :  */
    5744                 :             : Datum
    5745                 :          19 : int8_avg_combine(PG_FUNCTION_ARGS)
    5746                 :             : {
    5747                 :             :     Int128AggState *state1;
    5748                 :             :     Int128AggState *state2;
    5749                 :             :     MemoryContext agg_context;
    5750                 :             :     MemoryContext old_context;
    5751                 :             : 
    5752         [ -  + ]:          19 :     if (!AggCheckCallContext(fcinfo, &agg_context))
    5753         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5754                 :             : 
    5755         [ +  + ]:          19 :     state1 = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5756         [ +  - ]:          19 :     state2 = PG_ARGISNULL(1) ? NULL : (Int128AggState *) PG_GETARG_POINTER(1);
    5757                 :             : 
    5758         [ -  + ]:          19 :     if (state2 == NULL)
    5759                 :             :     {
    5760                 :             :         /*
    5761                 :             :          * NULL state2 is easy, just return state1, which we know is already
    5762                 :             :          * in the agg_context
    5763                 :             :          */
    5764         [ #  # ]:           0 :         if (state1 == NULL)
    5765                 :           0 :             PG_RETURN_NULL();
    5766                 :           0 :         PG_RETURN_POINTER(state1);
    5767                 :             :     }
    5768                 :             : 
    5769                 :             :     /* manually copy all fields from state2 to state1 */
    5770         [ +  + ]:          19 :     if (state1 == NULL)
    5771                 :             :     {
    5772                 :           8 :         old_context = MemoryContextSwitchTo(agg_context);
    5773                 :             : 
    5774                 :           8 :         state1 = makeInt128AggState(fcinfo, false);
    5775                 :           8 :         state1->N = state2->N;
    5776                 :           8 :         state1->sumX = state2->sumX;
    5777                 :             : 
    5778                 :           8 :         MemoryContextSwitchTo(old_context);
    5779                 :             : 
    5780                 :           8 :         PG_RETURN_POINTER(state1);
    5781                 :             :     }
    5782                 :             : 
    5783         [ +  - ]:          11 :     if (state2->N > 0)
    5784                 :             :     {
    5785                 :          11 :         state1->N += state2->N;
    5786                 :          11 :         int128_add_int128(&state1->sumX, state2->sumX);
    5787                 :             :     }
    5788                 :          11 :     PG_RETURN_POINTER(state1);
    5789                 :             : }
    5790                 :             : 
    5791                 :             : /*
    5792                 :             :  * int8_avg_serialize
    5793                 :             :  *      Serialize Int128AggState into bytea for aggregate functions which
    5794                 :             :  *      don't require sumX2.
    5795                 :             :  */
    5796                 :             : Datum
    5797                 :          19 : int8_avg_serialize(PG_FUNCTION_ARGS)
    5798                 :             : {
    5799                 :             :     Int128AggState *state;
    5800                 :             :     StringInfoData buf;
    5801                 :             :     bytea      *result;
    5802                 :             : 
    5803                 :             :     /* Ensure we disallow calling when not in aggregate context */
    5804         [ -  + ]:          19 :     if (!AggCheckCallContext(fcinfo, NULL))
    5805         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5806                 :             : 
    5807                 :          19 :     state = (Int128AggState *) PG_GETARG_POINTER(0);
    5808                 :             : 
    5809                 :          19 :     pq_begintypsend(&buf);
    5810                 :             : 
    5811                 :             :     /* N */
    5812                 :          19 :     pq_sendint64(&buf, state->N);
    5813                 :             : 
    5814                 :             :     /* sumX */
    5815                 :          19 :     int128_serialize(&buf, state->sumX);
    5816                 :             : 
    5817                 :          19 :     result = pq_endtypsend(&buf);
    5818                 :             : 
    5819                 :          19 :     PG_RETURN_BYTEA_P(result);
    5820                 :             : }
    5821                 :             : 
    5822                 :             : /*
    5823                 :             :  * int8_avg_deserialize
    5824                 :             :  *      Deserialize Int128AggState from bytea for aggregate functions which
    5825                 :             :  *      don't require sumX2.
    5826                 :             :  */
    5827                 :             : Datum
    5828                 :          19 : int8_avg_deserialize(PG_FUNCTION_ARGS)
    5829                 :             : {
    5830                 :             :     bytea      *sstate;
    5831                 :             :     Int128AggState *result;
    5832                 :             :     StringInfoData buf;
    5833                 :             : 
    5834         [ -  + ]:          19 :     if (!AggCheckCallContext(fcinfo, NULL))
    5835         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    5836                 :             : 
    5837                 :          19 :     sstate = PG_GETARG_BYTEA_PP(0);
    5838                 :             : 
    5839                 :             :     /*
    5840                 :             :      * Initialize a StringInfo so that we can "receive" it using the standard
    5841                 :             :      * recv-function infrastructure.
    5842                 :             :      */
    5843                 :          19 :     initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
    5844                 :          19 :                            VARSIZE_ANY_EXHDR(sstate));
    5845                 :             : 
    5846                 :          19 :     result = makeInt128AggStateCurrentContext(false);
    5847                 :             : 
    5848                 :             :     /* N */
    5849                 :          19 :     result->N = pq_getmsgint64(&buf);
    5850                 :             : 
    5851                 :             :     /* sumX */
    5852                 :          19 :     result->sumX = int128_deserialize(&buf);
    5853                 :             : 
    5854                 :          19 :     pq_getmsgend(&buf);
    5855                 :             : 
    5856                 :          19 :     PG_RETURN_POINTER(result);
    5857                 :             : }
    5858                 :             : 
    5859                 :             : /*
    5860                 :             :  * Inverse transition functions to go with the above.
    5861                 :             :  */
    5862                 :             : 
    5863                 :             : Datum
    5864                 :         108 : int2_accum_inv(PG_FUNCTION_ARGS)
    5865                 :             : {
    5866                 :             :     Int128AggState *state;
    5867                 :             : 
    5868         [ +  - ]:         108 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5869                 :             : 
    5870                 :             :     /* Should not get here with no state */
    5871         [ -  + ]:         108 :     if (state == NULL)
    5872         [ #  # ]:           0 :         elog(ERROR, "int2_accum_inv called with NULL state");
    5873                 :             : 
    5874         [ +  + ]:         108 :     if (!PG_ARGISNULL(1))
    5875                 :          96 :         do_int128_discard(state, PG_GETARG_INT16(1));
    5876                 :             : 
    5877                 :         108 :     PG_RETURN_POINTER(state);
    5878                 :             : }
    5879                 :             : 
    5880                 :             : Datum
    5881                 :         108 : int4_accum_inv(PG_FUNCTION_ARGS)
    5882                 :             : {
    5883                 :             :     Int128AggState *state;
    5884                 :             : 
    5885         [ +  - ]:         108 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5886                 :             : 
    5887                 :             :     /* Should not get here with no state */
    5888         [ -  + ]:         108 :     if (state == NULL)
    5889         [ #  # ]:           0 :         elog(ERROR, "int4_accum_inv called with NULL state");
    5890                 :             : 
    5891         [ +  + ]:         108 :     if (!PG_ARGISNULL(1))
    5892                 :          96 :         do_int128_discard(state, PG_GETARG_INT32(1));
    5893                 :             : 
    5894                 :         108 :     PG_RETURN_POINTER(state);
    5895                 :             : }
    5896                 :             : 
    5897                 :             : Datum
    5898                 :         108 : int8_accum_inv(PG_FUNCTION_ARGS)
    5899                 :             : {
    5900                 :             :     NumericAggState *state;
    5901                 :             : 
    5902         [ +  - ]:         108 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    5903                 :             : 
    5904                 :             :     /* Should not get here with no state */
    5905         [ -  + ]:         108 :     if (state == NULL)
    5906         [ #  # ]:           0 :         elog(ERROR, "int8_accum_inv called with NULL state");
    5907                 :             : 
    5908         [ +  + ]:         108 :     if (!PG_ARGISNULL(1))
    5909                 :             :     {
    5910                 :             :         /* Should never fail, all inputs have dscale 0 */
    5911         [ -  + ]:          96 :         if (!do_numeric_discard(state, int64_to_numeric(PG_GETARG_INT64(1))))
    5912         [ #  # ]:           0 :             elog(ERROR, "do_numeric_discard failed unexpectedly");
    5913                 :             :     }
    5914                 :             : 
    5915                 :         108 :     PG_RETURN_POINTER(state);
    5916                 :             : }
    5917                 :             : 
    5918                 :             : Datum
    5919                 :          24 : int8_avg_accum_inv(PG_FUNCTION_ARGS)
    5920                 :             : {
    5921                 :             :     Int128AggState *state;
    5922                 :             : 
    5923         [ +  - ]:          24 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5924                 :             : 
    5925                 :             :     /* Should not get here with no state */
    5926         [ -  + ]:          24 :     if (state == NULL)
    5927         [ #  # ]:           0 :         elog(ERROR, "int8_avg_accum_inv called with NULL state");
    5928                 :             : 
    5929         [ +  + ]:          24 :     if (!PG_ARGISNULL(1))
    5930                 :          16 :         do_int128_discard(state, PG_GETARG_INT64(1));
    5931                 :             : 
    5932                 :          24 :     PG_RETURN_POINTER(state);
    5933                 :             : }
    5934                 :             : 
    5935                 :             : Datum
    5936                 :         680 : numeric_poly_sum(PG_FUNCTION_ARGS)
    5937                 :             : {
    5938                 :             :     Int128AggState *state;
    5939                 :             :     Numeric     res;
    5940                 :             :     NumericVar  result;
    5941                 :             : 
    5942         [ +  + ]:         680 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5943                 :             : 
    5944                 :             :     /* If there were no non-null inputs, return NULL */
    5945   [ +  +  +  + ]:         680 :     if (state == NULL || state->N == 0)
    5946                 :          16 :         PG_RETURN_NULL();
    5947                 :             : 
    5948                 :         664 :     init_var(&result);
    5949                 :             : 
    5950                 :         664 :     int128_to_numericvar(state->sumX, &result);
    5951                 :             : 
    5952                 :         664 :     res = make_result(&result);
    5953                 :             : 
    5954                 :         664 :     free_var(&result);
    5955                 :             : 
    5956                 :         664 :     PG_RETURN_NUMERIC(res);
    5957                 :             : }
    5958                 :             : 
    5959                 :             : Datum
    5960                 :          24 : numeric_poly_avg(PG_FUNCTION_ARGS)
    5961                 :             : {
    5962                 :             :     Int128AggState *state;
    5963                 :             :     NumericVar  result;
    5964                 :             :     Datum       countd,
    5965                 :             :                 sumd;
    5966                 :             : 
    5967         [ +  - ]:          24 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    5968                 :             : 
    5969                 :             :     /* If there were no non-null inputs, return NULL */
    5970   [ +  -  +  + ]:          24 :     if (state == NULL || state->N == 0)
    5971                 :          12 :         PG_RETURN_NULL();
    5972                 :             : 
    5973                 :          12 :     init_var(&result);
    5974                 :             : 
    5975                 :          12 :     int128_to_numericvar(state->sumX, &result);
    5976                 :             : 
    5977                 :          12 :     countd = NumericGetDatum(int64_to_numeric(state->N));
    5978                 :          12 :     sumd = NumericGetDatum(make_result(&result));
    5979                 :             : 
    5980                 :          12 :     free_var(&result);
    5981                 :             : 
    5982                 :          12 :     PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumd, countd));
    5983                 :             : }
    5984                 :             : 
    5985                 :             : Datum
    5986                 :          52 : numeric_avg(PG_FUNCTION_ARGS)
    5987                 :             : {
    5988                 :             :     NumericAggState *state;
    5989                 :             :     Datum       N_datum;
    5990                 :             :     Datum       sumX_datum;
    5991                 :             :     NumericVar  sumX_var;
    5992                 :             : 
    5993         [ +  - ]:          52 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    5994                 :             : 
    5995                 :             :     /* If there were no non-null inputs, return NULL */
    5996   [ +  -  +  + ]:          52 :     if (state == NULL || NA_TOTAL_COUNT(state) == 0)
    5997                 :          12 :         PG_RETURN_NULL();
    5998                 :             : 
    5999         [ +  + ]:          40 :     if (state->NaNcount > 0)  /* there was at least one NaN input */
    6000                 :           4 :         PG_RETURN_NUMERIC(make_result(&const_nan));
    6001                 :             : 
    6002                 :             :     /* adding plus and minus infinities gives NaN */
    6003   [ +  +  +  + ]:          36 :     if (state->pInfcount > 0 && state->nInfcount > 0)
    6004                 :           4 :         PG_RETURN_NUMERIC(make_result(&const_nan));
    6005         [ +  + ]:          32 :     if (state->pInfcount > 0)
    6006                 :          12 :         PG_RETURN_NUMERIC(make_result(&const_pinf));
    6007         [ +  + ]:          20 :     if (state->nInfcount > 0)
    6008                 :           4 :         PG_RETURN_NUMERIC(make_result(&const_ninf));
    6009                 :             : 
    6010                 :          16 :     N_datum = NumericGetDatum(int64_to_numeric(state->N));
    6011                 :             : 
    6012                 :          16 :     init_var(&sumX_var);
    6013                 :          16 :     accum_sum_final(&state->sumX, &sumX_var);
    6014                 :          16 :     sumX_datum = NumericGetDatum(make_result(&sumX_var));
    6015                 :          16 :     free_var(&sumX_var);
    6016                 :             : 
    6017                 :          16 :     PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumX_datum, N_datum));
    6018                 :             : }
    6019                 :             : 
    6020                 :             : Datum
    6021                 :      113926 : numeric_sum(PG_FUNCTION_ARGS)
    6022                 :             : {
    6023                 :             :     NumericAggState *state;
    6024                 :             :     NumericVar  sumX_var;
    6025                 :             :     Numeric     result;
    6026                 :             : 
    6027         [ +  - ]:      113926 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    6028                 :             : 
    6029                 :             :     /* If there were no non-null inputs, return NULL */
    6030   [ +  -  +  + ]:      113926 :     if (state == NULL || NA_TOTAL_COUNT(state) == 0)
    6031                 :          12 :         PG_RETURN_NULL();
    6032                 :             : 
    6033         [ +  + ]:      113914 :     if (state->NaNcount > 0)  /* there was at least one NaN input */
    6034                 :          12 :         PG_RETURN_NUMERIC(make_result(&const_nan));
    6035                 :             : 
    6036                 :             :     /* adding plus and minus infinities gives NaN */
    6037   [ +  +  +  + ]:      113902 :     if (state->pInfcount > 0 && state->nInfcount > 0)
    6038                 :           4 :         PG_RETURN_NUMERIC(make_result(&const_nan));
    6039         [ +  + ]:      113898 :     if (state->pInfcount > 0)
    6040                 :          12 :         PG_RETURN_NUMERIC(make_result(&const_pinf));
    6041         [ +  + ]:      113886 :     if (state->nInfcount > 0)
    6042                 :           4 :         PG_RETURN_NUMERIC(make_result(&const_ninf));
    6043                 :             : 
    6044                 :      113882 :     init_var(&sumX_var);
    6045                 :      113882 :     accum_sum_final(&state->sumX, &sumX_var);
    6046                 :      113882 :     result = make_result(&sumX_var);
    6047                 :      113882 :     free_var(&sumX_var);
    6048                 :             : 
    6049                 :      113882 :     PG_RETURN_NUMERIC(result);
    6050                 :             : }
    6051                 :             : 
    6052                 :             : /*
    6053                 :             :  * Workhorse routine for the standard deviance and variance
    6054                 :             :  * aggregates. 'state' is aggregate's transition state.
    6055                 :             :  * 'variance' specifies whether we should calculate the
    6056                 :             :  * variance or the standard deviation. 'sample' indicates whether the
    6057                 :             :  * caller is interested in the sample or the population
    6058                 :             :  * variance/stddev.
    6059                 :             :  *
    6060                 :             :  * If appropriate variance statistic is undefined for the input,
    6061                 :             :  * *is_null is set to true and NULL is returned.
    6062                 :             :  */
    6063                 :             : static Numeric
    6064                 :         654 : numeric_stddev_internal(NumericAggState *state,
    6065                 :             :                         bool variance, bool sample,
    6066                 :             :                         bool *is_null)
    6067                 :             : {
    6068                 :             :     Numeric     res;
    6069                 :             :     NumericVar  vN,
    6070                 :             :                 vsumX,
    6071                 :             :                 vsumX2,
    6072                 :             :                 vNminus1;
    6073                 :             :     int64       totCount;
    6074                 :             :     int         rscale;
    6075                 :             : 
    6076                 :             :     /*
    6077                 :             :      * Sample stddev and variance are undefined when N <= 1; population stddev
    6078                 :             :      * is undefined when N == 0.  Return NULL in either case (note that NaNs
    6079                 :             :      * and infinities count as normal inputs for this purpose).
    6080                 :             :      */
    6081   [ +  -  -  + ]:         654 :     if (state == NULL || (totCount = NA_TOTAL_COUNT(state)) == 0)
    6082                 :             :     {
    6083                 :           0 :         *is_null = true;
    6084                 :           0 :         return NULL;
    6085                 :             :     }
    6086                 :             : 
    6087   [ +  +  +  + ]:         654 :     if (sample && totCount <= 1)
    6088                 :             :     {
    6089                 :          88 :         *is_null = true;
    6090                 :          88 :         return NULL;
    6091                 :             :     }
    6092                 :             : 
    6093                 :         566 :     *is_null = false;
    6094                 :             : 
    6095                 :             :     /*
    6096                 :             :      * Deal with NaN and infinity cases.  By analogy to the behavior of the
    6097                 :             :      * float8 functions, any infinity input produces NaN output.
    6098                 :             :      */
    6099   [ +  +  +  +  :         566 :     if (state->NaNcount > 0 || state->pInfcount > 0 || state->nInfcount > 0)
                   +  + ]
    6100                 :          36 :         return make_result(&const_nan);
    6101                 :             : 
    6102                 :             :     /* OK, normal calculation applies */
    6103                 :         530 :     init_var(&vN);
    6104                 :         530 :     init_var(&vsumX);
    6105                 :         530 :     init_var(&vsumX2);
    6106                 :             : 
    6107                 :         530 :     int64_to_numericvar(state->N, &vN);
    6108                 :         530 :     accum_sum_final(&(state->sumX), &vsumX);
    6109                 :         530 :     accum_sum_final(&(state->sumX2), &vsumX2);
    6110                 :             : 
    6111                 :         530 :     init_var(&vNminus1);
    6112                 :         530 :     sub_var(&vN, &const_one, &vNminus1);
    6113                 :             : 
    6114                 :             :     /* compute rscale for mul_var calls */
    6115                 :         530 :     rscale = vsumX.dscale * 2;
    6116                 :             : 
    6117                 :         530 :     mul_var(&vsumX, &vsumX, &vsumX, rscale);    /* vsumX = sumX * sumX */
    6118                 :         530 :     mul_var(&vN, &vsumX2, &vsumX2, rscale); /* vsumX2 = N * sumX2 */
    6119                 :         530 :     sub_var(&vsumX2, &vsumX, &vsumX2);  /* N * sumX2 - sumX * sumX */
    6120                 :             : 
    6121         [ +  + ]:         530 :     if (cmp_var(&vsumX2, &const_zero) <= 0)
    6122                 :             :     {
    6123                 :             :         /* Watch out for roundoff error producing a negative numerator */
    6124                 :          50 :         res = make_result(&const_zero);
    6125                 :             :     }
    6126                 :             :     else
    6127                 :             :     {
    6128         [ +  + ]:         480 :         if (sample)
    6129                 :         328 :             mul_var(&vN, &vNminus1, &vNminus1, 0);  /* N * (N - 1) */
    6130                 :             :         else
    6131                 :         152 :             mul_var(&vN, &vN, &vNminus1, 0);    /* N * N */
    6132                 :         480 :         rscale = select_div_scale(&vsumX2, &vNminus1);
    6133                 :         480 :         div_var(&vsumX2, &vNminus1, &vsumX, rscale, true, true);    /* variance */
    6134         [ +  + ]:         480 :         if (!variance)
    6135                 :         252 :             sqrt_var(&vsumX, &vsumX, rscale);   /* stddev */
    6136                 :             : 
    6137                 :         480 :         res = make_result(&vsumX);
    6138                 :             :     }
    6139                 :             : 
    6140                 :         530 :     free_var(&vNminus1);
    6141                 :         530 :     free_var(&vsumX);
    6142                 :         530 :     free_var(&vsumX2);
    6143                 :             : 
    6144                 :         530 :     return res;
    6145                 :             : }
    6146                 :             : 
    6147                 :             : Datum
    6148                 :         120 : numeric_var_samp(PG_FUNCTION_ARGS)
    6149                 :             : {
    6150                 :             :     NumericAggState *state;
    6151                 :             :     Numeric     res;
    6152                 :             :     bool        is_null;
    6153                 :             : 
    6154         [ +  - ]:         120 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    6155                 :             : 
    6156                 :         120 :     res = numeric_stddev_internal(state, true, true, &is_null);
    6157                 :             : 
    6158         [ +  + ]:         120 :     if (is_null)
    6159                 :          28 :         PG_RETURN_NULL();
    6160                 :             :     else
    6161                 :          92 :         PG_RETURN_NUMERIC(res);
    6162                 :             : }
    6163                 :             : 
    6164                 :             : Datum
    6165                 :         116 : numeric_stddev_samp(PG_FUNCTION_ARGS)
    6166                 :             : {
    6167                 :             :     NumericAggState *state;
    6168                 :             :     Numeric     res;
    6169                 :             :     bool        is_null;
    6170                 :             : 
    6171         [ +  - ]:         116 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    6172                 :             : 
    6173                 :         116 :     res = numeric_stddev_internal(state, false, true, &is_null);
    6174                 :             : 
    6175         [ +  + ]:         116 :     if (is_null)
    6176                 :          28 :         PG_RETURN_NULL();
    6177                 :             :     else
    6178                 :          88 :         PG_RETURN_NUMERIC(res);
    6179                 :             : }
    6180                 :             : 
    6181                 :             : Datum
    6182                 :          76 : numeric_var_pop(PG_FUNCTION_ARGS)
    6183                 :             : {
    6184                 :             :     NumericAggState *state;
    6185                 :             :     Numeric     res;
    6186                 :             :     bool        is_null;
    6187                 :             : 
    6188         [ +  - ]:          76 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    6189                 :             : 
    6190                 :          76 :     res = numeric_stddev_internal(state, true, false, &is_null);
    6191                 :             : 
    6192         [ -  + ]:          76 :     if (is_null)
    6193                 :           0 :         PG_RETURN_NULL();
    6194                 :             :     else
    6195                 :          76 :         PG_RETURN_NUMERIC(res);
    6196                 :             : }
    6197                 :             : 
    6198                 :             : Datum
    6199                 :          64 : numeric_stddev_pop(PG_FUNCTION_ARGS)
    6200                 :             : {
    6201                 :             :     NumericAggState *state;
    6202                 :             :     Numeric     res;
    6203                 :             :     bool        is_null;
    6204                 :             : 
    6205         [ +  - ]:          64 :     state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
    6206                 :             : 
    6207                 :          64 :     res = numeric_stddev_internal(state, false, false, &is_null);
    6208                 :             : 
    6209         [ -  + ]:          64 :     if (is_null)
    6210                 :           0 :         PG_RETURN_NULL();
    6211                 :             :     else
    6212                 :          64 :         PG_RETURN_NUMERIC(res);
    6213                 :             : }
    6214                 :             : 
    6215                 :             : static Numeric
    6216                 :         278 : numeric_poly_stddev_internal(Int128AggState *state,
    6217                 :             :                              bool variance, bool sample,
    6218                 :             :                              bool *is_null)
    6219                 :             : {
    6220                 :             :     NumericAggState numstate;
    6221                 :             :     Numeric     res;
    6222                 :             : 
    6223                 :             :     /* Initialize an empty agg state */
    6224                 :         278 :     memset(&numstate, 0, sizeof(NumericAggState));
    6225                 :             : 
    6226         [ +  - ]:         278 :     if (state)
    6227                 :             :     {
    6228                 :             :         NumericVar  tmp_var;
    6229                 :             : 
    6230                 :         278 :         numstate.N = state->N;
    6231                 :             : 
    6232                 :         278 :         init_var(&tmp_var);
    6233                 :             : 
    6234                 :         278 :         int128_to_numericvar(state->sumX, &tmp_var);
    6235                 :         278 :         accum_sum_add(&numstate.sumX, &tmp_var);
    6236                 :             : 
    6237                 :         278 :         int128_to_numericvar(state->sumX2, &tmp_var);
    6238                 :         278 :         accum_sum_add(&numstate.sumX2, &tmp_var);
    6239                 :             : 
    6240                 :         278 :         free_var(&tmp_var);
    6241                 :             :     }
    6242                 :             : 
    6243                 :         278 :     res = numeric_stddev_internal(&numstate, variance, sample, is_null);
    6244                 :             : 
    6245         [ +  - ]:         278 :     if (numstate.sumX.ndigits > 0)
    6246                 :             :     {
    6247                 :         278 :         pfree(numstate.sumX.pos_digits);
    6248                 :         278 :         pfree(numstate.sumX.neg_digits);
    6249                 :             :     }
    6250         [ +  - ]:         278 :     if (numstate.sumX2.ndigits > 0)
    6251                 :             :     {
    6252                 :         278 :         pfree(numstate.sumX2.pos_digits);
    6253                 :         278 :         pfree(numstate.sumX2.neg_digits);
    6254                 :             :     }
    6255                 :             : 
    6256                 :         278 :     return res;
    6257                 :             : }
    6258                 :             : 
    6259                 :             : Datum
    6260                 :          84 : numeric_poly_var_samp(PG_FUNCTION_ARGS)
    6261                 :             : {
    6262                 :             :     Int128AggState *state;
    6263                 :             :     Numeric     res;
    6264                 :             :     bool        is_null;
    6265                 :             : 
    6266         [ +  - ]:          84 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    6267                 :             : 
    6268                 :          84 :     res = numeric_poly_stddev_internal(state, true, true, &is_null);
    6269                 :             : 
    6270         [ +  + ]:          84 :     if (is_null)
    6271                 :          16 :         PG_RETURN_NULL();
    6272                 :             :     else
    6273                 :          68 :         PG_RETURN_NUMERIC(res);
    6274                 :             : }
    6275                 :             : 
    6276                 :             : Datum
    6277                 :         106 : numeric_poly_stddev_samp(PG_FUNCTION_ARGS)
    6278                 :             : {
    6279                 :             :     Int128AggState *state;
    6280                 :             :     Numeric     res;
    6281                 :             :     bool        is_null;
    6282                 :             : 
    6283         [ +  - ]:         106 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    6284                 :             : 
    6285                 :         106 :     res = numeric_poly_stddev_internal(state, false, true, &is_null);
    6286                 :             : 
    6287         [ +  + ]:         106 :     if (is_null)
    6288                 :          16 :         PG_RETURN_NULL();
    6289                 :             :     else
    6290                 :          90 :         PG_RETURN_NUMERIC(res);
    6291                 :             : }
    6292                 :             : 
    6293                 :             : Datum
    6294                 :          40 : numeric_poly_var_pop(PG_FUNCTION_ARGS)
    6295                 :             : {
    6296                 :             :     Int128AggState *state;
    6297                 :             :     Numeric     res;
    6298                 :             :     bool        is_null;
    6299                 :             : 
    6300         [ +  - ]:          40 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    6301                 :             : 
    6302                 :          40 :     res = numeric_poly_stddev_internal(state, true, false, &is_null);
    6303                 :             : 
    6304         [ -  + ]:          40 :     if (is_null)
    6305                 :           0 :         PG_RETURN_NULL();
    6306                 :             :     else
    6307                 :          40 :         PG_RETURN_NUMERIC(res);
    6308                 :             : }
    6309                 :             : 
    6310                 :             : Datum
    6311                 :          48 : numeric_poly_stddev_pop(PG_FUNCTION_ARGS)
    6312                 :             : {
    6313                 :             :     Int128AggState *state;
    6314                 :             :     Numeric     res;
    6315                 :             :     bool        is_null;
    6316                 :             : 
    6317         [ +  - ]:          48 :     state = PG_ARGISNULL(0) ? NULL : (Int128AggState *) PG_GETARG_POINTER(0);
    6318                 :             : 
    6319                 :          48 :     res = numeric_poly_stddev_internal(state, false, false, &is_null);
    6320                 :             : 
    6321         [ -  + ]:          48 :     if (is_null)
    6322                 :           0 :         PG_RETURN_NULL();
    6323                 :             :     else
    6324                 :          48 :         PG_RETURN_NUMERIC(res);
    6325                 :             : }
    6326                 :             : 
    6327                 :             : /*
    6328                 :             :  * SUM transition functions for integer datatypes.
    6329                 :             :  *
    6330                 :             :  * To avoid overflow, we use accumulators wider than the input datatype.
    6331                 :             :  * A Numeric accumulator is needed for int8 input; for int4 and int2
    6332                 :             :  * inputs, we use int8 accumulators which should be sufficient for practical
    6333                 :             :  * purposes.  (The latter two therefore don't really belong in this file,
    6334                 :             :  * but we keep them here anyway.)
    6335                 :             :  *
    6336                 :             :  * Because SQL defines the SUM() of no values to be NULL, not zero,
    6337                 :             :  * the initial condition of the transition data value needs to be NULL. This
    6338                 :             :  * means we can't rely on ExecAgg to automatically insert the first non-null
    6339                 :             :  * data value into the transition data: it doesn't know how to do the type
    6340                 :             :  * conversion.  The upshot is that these routines have to be marked non-strict
    6341                 :             :  * and handle substitution of the first non-null input themselves.
    6342                 :             :  *
    6343                 :             :  * Note: these functions are used only in plain aggregation mode.
    6344                 :             :  * In moving-aggregate mode, we use intX_avg_accum and intX_avg_accum_inv.
    6345                 :             :  */
    6346                 :             : 
    6347                 :             : Datum
    6348                 :          16 : int2_sum(PG_FUNCTION_ARGS)
    6349                 :             : {
    6350                 :             :     int64       oldsum;
    6351                 :             :     int64       newval;
    6352                 :             : 
    6353         [ +  + ]:          16 :     if (PG_ARGISNULL(0))
    6354                 :             :     {
    6355                 :             :         /* No non-null input seen so far... */
    6356         [ -  + ]:           4 :         if (PG_ARGISNULL(1))
    6357                 :           0 :             PG_RETURN_NULL();   /* still no non-null */
    6358                 :             :         /* This is the first non-null input. */
    6359                 :           4 :         newval = (int64) PG_GETARG_INT16(1);
    6360                 :           4 :         PG_RETURN_INT64(newval);
    6361                 :             :     }
    6362                 :             : 
    6363                 :          12 :     oldsum = PG_GETARG_INT64(0);
    6364                 :             : 
    6365                 :             :     /* Leave sum unchanged if new input is null. */
    6366         [ -  + ]:          12 :     if (PG_ARGISNULL(1))
    6367                 :           0 :         PG_RETURN_INT64(oldsum);
    6368                 :             : 
    6369                 :             :     /* OK to do the addition. */
    6370                 :          12 :     newval = oldsum + (int64) PG_GETARG_INT16(1);
    6371                 :             : 
    6372                 :          12 :     PG_RETURN_INT64(newval);
    6373                 :             : }
    6374                 :             : 
    6375                 :             : Datum
    6376                 :     3269520 : int4_sum(PG_FUNCTION_ARGS)
    6377                 :             : {
    6378                 :             :     int64       oldsum;
    6379                 :             :     int64       newval;
    6380                 :             : 
    6381         [ +  + ]:     3269520 :     if (PG_ARGISNULL(0))
    6382                 :             :     {
    6383                 :             :         /* No non-null input seen so far... */
    6384         [ +  + ]:      128945 :         if (PG_ARGISNULL(1))
    6385                 :         654 :             PG_RETURN_NULL();   /* still no non-null */
    6386                 :             :         /* This is the first non-null input. */
    6387                 :      128291 :         newval = (int64) PG_GETARG_INT32(1);
    6388                 :      128291 :         PG_RETURN_INT64(newval);
    6389                 :             :     }
    6390                 :             : 
    6391                 :     3140575 :     oldsum = PG_GETARG_INT64(0);
    6392                 :             : 
    6393                 :             :     /* Leave sum unchanged if new input is null. */
    6394         [ +  + ]:     3140575 :     if (PG_ARGISNULL(1))
    6395                 :       20606 :         PG_RETURN_INT64(oldsum);
    6396                 :             : 
    6397                 :             :     /* OK to do the addition. */
    6398                 :     3119969 :     newval = oldsum + (int64) PG_GETARG_INT32(1);
    6399                 :             : 
    6400                 :     3119969 :     PG_RETURN_INT64(newval);
    6401                 :             : }
    6402                 :             : 
    6403                 :             : /*
    6404                 :             :  * Note: this function is obsolete, it's no longer used for SUM(int8).
    6405                 :             :  */
    6406                 :             : Datum
    6407                 :           0 : int8_sum(PG_FUNCTION_ARGS)
    6408                 :             : {
    6409                 :             :     Numeric     oldsum;
    6410                 :             : 
    6411         [ #  # ]:           0 :     if (PG_ARGISNULL(0))
    6412                 :             :     {
    6413                 :             :         /* No non-null input seen so far... */
    6414         [ #  # ]:           0 :         if (PG_ARGISNULL(1))
    6415                 :           0 :             PG_RETURN_NULL();   /* still no non-null */
    6416                 :             :         /* This is the first non-null input. */
    6417                 :           0 :         PG_RETURN_NUMERIC(int64_to_numeric(PG_GETARG_INT64(1)));
    6418                 :             :     }
    6419                 :             : 
    6420                 :             :     /*
    6421                 :             :      * Note that we cannot special-case the aggregate case here, as we do for
    6422                 :             :      * int2_sum and int4_sum: numeric is of variable size, so we cannot modify
    6423                 :             :      * our first parameter in-place.
    6424                 :             :      */
    6425                 :             : 
    6426                 :           0 :     oldsum = PG_GETARG_NUMERIC(0);
    6427                 :             : 
    6428                 :             :     /* Leave sum unchanged if new input is null. */
    6429         [ #  # ]:           0 :     if (PG_ARGISNULL(1))
    6430                 :           0 :         PG_RETURN_NUMERIC(oldsum);
    6431                 :             : 
    6432                 :             :     /* OK to do the addition. */
    6433                 :           0 :     PG_RETURN_DATUM(DirectFunctionCall2(numeric_add,
    6434                 :             :                                         NumericGetDatum(oldsum),
    6435                 :             :                                         NumericGetDatum(int64_to_numeric(PG_GETARG_INT64(1)))));
    6436                 :             : }
    6437                 :             : 
    6438                 :             : 
    6439                 :             : /*
    6440                 :             :  * Routines for avg(int2) and avg(int4).  The transition datatype
    6441                 :             :  * is a two-element int8 array, holding count and sum.
    6442                 :             :  *
    6443                 :             :  * These functions are also used for sum(int2) and sum(int4) when
    6444                 :             :  * operating in moving-aggregate mode, since for correct inverse transitions
    6445                 :             :  * we need to count the inputs.
    6446                 :             :  */
    6447                 :             : 
    6448                 :             : typedef struct Int8TransTypeData
    6449                 :             : {
    6450                 :             :     int64       count;
    6451                 :             :     int64       sum;
    6452                 :             : } Int8TransTypeData;
    6453                 :             : 
    6454                 :             : Datum
    6455                 :          28 : int2_avg_accum(PG_FUNCTION_ARGS)
    6456                 :             : {
    6457                 :             :     ArrayType  *transarray;
    6458                 :          28 :     int16       newval = PG_GETARG_INT16(1);
    6459                 :             :     Int8TransTypeData *transdata;
    6460                 :             : 
    6461                 :             :     /*
    6462                 :             :      * If we're invoked as an aggregate, we can cheat and modify our first
    6463                 :             :      * parameter in-place to reduce palloc overhead. Otherwise we need to make
    6464                 :             :      * a copy of it before scribbling on it.
    6465                 :             :      */
    6466         [ +  - ]:          28 :     if (AggCheckCallContext(fcinfo, NULL))
    6467                 :          28 :         transarray = PG_GETARG_ARRAYTYPE_P(0);
    6468                 :             :     else
    6469                 :           0 :         transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
    6470                 :             : 
    6471   [ +  -  -  + ]:          56 :     if (ARR_HASNULL(transarray) ||
    6472                 :          28 :         ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6473         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6474                 :             : 
    6475         [ -  + ]:          28 :     transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
    6476                 :          28 :     transdata->count++;
    6477                 :          28 :     transdata->sum += newval;
    6478                 :             : 
    6479                 :          28 :     PG_RETURN_ARRAYTYPE_P(transarray);
    6480                 :             : }
    6481                 :             : 
    6482                 :             : Datum
    6483                 :     1744070 : int4_avg_accum(PG_FUNCTION_ARGS)
    6484                 :             : {
    6485                 :             :     ArrayType  *transarray;
    6486                 :     1744070 :     int32       newval = PG_GETARG_INT32(1);
    6487                 :             :     Int8TransTypeData *transdata;
    6488                 :             : 
    6489                 :             :     /*
    6490                 :             :      * If we're invoked as an aggregate, we can cheat and modify our first
    6491                 :             :      * parameter in-place to reduce palloc overhead. Otherwise we need to make
    6492                 :             :      * a copy of it before scribbling on it.
    6493                 :             :      */
    6494         [ +  - ]:     1744070 :     if (AggCheckCallContext(fcinfo, NULL))
    6495                 :     1744070 :         transarray = PG_GETARG_ARRAYTYPE_P(0);
    6496                 :             :     else
    6497                 :           0 :         transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
    6498                 :             : 
    6499   [ +  -  -  + ]:     3488140 :     if (ARR_HASNULL(transarray) ||
    6500                 :     1744070 :         ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6501         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6502                 :             : 
    6503         [ -  + ]:     1744070 :     transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
    6504                 :     1744070 :     transdata->count++;
    6505                 :     1744070 :     transdata->sum += newval;
    6506                 :             : 
    6507                 :     1744070 :     PG_RETURN_ARRAYTYPE_P(transarray);
    6508                 :             : }
    6509                 :             : 
    6510                 :             : Datum
    6511                 :        6559 : int4_avg_combine(PG_FUNCTION_ARGS)
    6512                 :             : {
    6513                 :             :     ArrayType  *transarray1;
    6514                 :             :     ArrayType  *transarray2;
    6515                 :             :     Int8TransTypeData *state1;
    6516                 :             :     Int8TransTypeData *state2;
    6517                 :             : 
    6518         [ -  + ]:        6559 :     if (!AggCheckCallContext(fcinfo, NULL))
    6519         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    6520                 :             : 
    6521                 :        6559 :     transarray1 = PG_GETARG_ARRAYTYPE_P(0);
    6522                 :        6559 :     transarray2 = PG_GETARG_ARRAYTYPE_P(1);
    6523                 :             : 
    6524   [ +  -  -  + ]:       13118 :     if (ARR_HASNULL(transarray1) ||
    6525                 :        6559 :         ARR_SIZE(transarray1) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6526         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6527                 :             : 
    6528   [ +  -  -  + ]:       13118 :     if (ARR_HASNULL(transarray2) ||
    6529                 :        6559 :         ARR_SIZE(transarray2) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6530         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6531                 :             : 
    6532         [ -  + ]:        6559 :     state1 = (Int8TransTypeData *) ARR_DATA_PTR(transarray1);
    6533         [ -  + ]:        6559 :     state2 = (Int8TransTypeData *) ARR_DATA_PTR(transarray2);
    6534                 :             : 
    6535                 :        6559 :     state1->count += state2->count;
    6536                 :        6559 :     state1->sum += state2->sum;
    6537                 :             : 
    6538                 :        6559 :     PG_RETURN_ARRAYTYPE_P(transarray1);
    6539                 :             : }
    6540                 :             : 
    6541                 :             : Datum
    6542                 :           8 : int2_avg_accum_inv(PG_FUNCTION_ARGS)
    6543                 :             : {
    6544                 :             :     ArrayType  *transarray;
    6545                 :           8 :     int16       newval = PG_GETARG_INT16(1);
    6546                 :             :     Int8TransTypeData *transdata;
    6547                 :             : 
    6548                 :             :     /*
    6549                 :             :      * If we're invoked as an aggregate, we can cheat and modify our first
    6550                 :             :      * parameter in-place to reduce palloc overhead. Otherwise we need to make
    6551                 :             :      * a copy of it before scribbling on it.
    6552                 :             :      */
    6553         [ +  - ]:           8 :     if (AggCheckCallContext(fcinfo, NULL))
    6554                 :           8 :         transarray = PG_GETARG_ARRAYTYPE_P(0);
    6555                 :             :     else
    6556                 :           0 :         transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
    6557                 :             : 
    6558   [ +  -  -  + ]:          16 :     if (ARR_HASNULL(transarray) ||
    6559                 :           8 :         ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6560         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6561                 :             : 
    6562         [ -  + ]:           8 :     transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
    6563                 :           8 :     transdata->count--;
    6564                 :           8 :     transdata->sum -= newval;
    6565                 :             : 
    6566                 :           8 :     PG_RETURN_ARRAYTYPE_P(transarray);
    6567                 :             : }
    6568                 :             : 
    6569                 :             : Datum
    6570                 :        1000 : int4_avg_accum_inv(PG_FUNCTION_ARGS)
    6571                 :             : {
    6572                 :             :     ArrayType  *transarray;
    6573                 :        1000 :     int32       newval = PG_GETARG_INT32(1);
    6574                 :             :     Int8TransTypeData *transdata;
    6575                 :             : 
    6576                 :             :     /*
    6577                 :             :      * If we're invoked as an aggregate, we can cheat and modify our first
    6578                 :             :      * parameter in-place to reduce palloc overhead. Otherwise we need to make
    6579                 :             :      * a copy of it before scribbling on it.
    6580                 :             :      */
    6581         [ +  - ]:        1000 :     if (AggCheckCallContext(fcinfo, NULL))
    6582                 :        1000 :         transarray = PG_GETARG_ARRAYTYPE_P(0);
    6583                 :             :     else
    6584                 :           0 :         transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
    6585                 :             : 
    6586   [ +  -  -  + ]:        2000 :     if (ARR_HASNULL(transarray) ||
    6587                 :        1000 :         ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6588         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6589                 :             : 
    6590         [ -  + ]:        1000 :     transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
    6591                 :        1000 :     transdata->count--;
    6592                 :        1000 :     transdata->sum -= newval;
    6593                 :             : 
    6594                 :        1000 :     PG_RETURN_ARRAYTYPE_P(transarray);
    6595                 :             : }
    6596                 :             : 
    6597                 :             : Datum
    6598                 :        6817 : int8_avg(PG_FUNCTION_ARGS)
    6599                 :             : {
    6600                 :        6817 :     ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    6601                 :             :     Int8TransTypeData *transdata;
    6602                 :             :     Datum       countd,
    6603                 :             :                 sumd;
    6604                 :             : 
    6605   [ +  -  -  + ]:       13634 :     if (ARR_HASNULL(transarray) ||
    6606                 :        6817 :         ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6607         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6608         [ -  + ]:        6817 :     transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
    6609                 :             : 
    6610                 :             :     /* SQL defines AVG of no values to be NULL */
    6611         [ +  + ]:        6817 :     if (transdata->count == 0)
    6612                 :          73 :         PG_RETURN_NULL();
    6613                 :             : 
    6614                 :        6744 :     countd = NumericGetDatum(int64_to_numeric(transdata->count));
    6615                 :        6744 :     sumd = NumericGetDatum(int64_to_numeric(transdata->sum));
    6616                 :             : 
    6617                 :        6744 :     PG_RETURN_DATUM(DirectFunctionCall2(numeric_div, sumd, countd));
    6618                 :             : }
    6619                 :             : 
    6620                 :             : /*
    6621                 :             :  * SUM(int2) and SUM(int4) both return int8, so we can use this
    6622                 :             :  * final function for both.
    6623                 :             :  */
    6624                 :             : Datum
    6625                 :        2716 : int2int4_sum(PG_FUNCTION_ARGS)
    6626                 :             : {
    6627                 :        2716 :     ArrayType  *transarray = PG_GETARG_ARRAYTYPE_P(0);
    6628                 :             :     Int8TransTypeData *transdata;
    6629                 :             : 
    6630   [ +  -  -  + ]:        5432 :     if (ARR_HASNULL(transarray) ||
    6631                 :        2716 :         ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
    6632         [ #  # ]:           0 :         elog(ERROR, "expected 2-element int8 array");
    6633         [ -  + ]:        2716 :     transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
    6634                 :             : 
    6635                 :             :     /* SQL defines SUM of no values to be NULL */
    6636         [ +  + ]:        2716 :     if (transdata->count == 0)
    6637                 :         404 :         PG_RETURN_NULL();
    6638                 :             : 
    6639                 :        2312 :     PG_RETURN_DATUM(Int64GetDatumFast(transdata->sum));
    6640                 :             : }
    6641                 :             : 
    6642                 :             : 
    6643                 :             : /* ----------------------------------------------------------------------
    6644                 :             :  *
    6645                 :             :  * Debug support
    6646                 :             :  *
    6647                 :             :  * ----------------------------------------------------------------------
    6648                 :             :  */
    6649                 :             : 
    6650                 :             : #ifdef NUMERIC_DEBUG
    6651                 :             : 
    6652                 :             : /*
    6653                 :             :  * dump_numeric() - Dump a value in the db storage format for debugging
    6654                 :             :  */
    6655                 :             : static void
    6656                 :             : dump_numeric(const char *str, Numeric num)
    6657                 :             : {
    6658                 :             :     NumericDigit *digits = NUMERIC_DIGITS(num);
    6659                 :             :     int         ndigits;
    6660                 :             :     int         i;
    6661                 :             : 
    6662                 :             :     ndigits = NUMERIC_NDIGITS(num);
    6663                 :             : 
    6664                 :             :     printf("%s: NUMERIC w=%d d=%d ", str,
    6665                 :             :            NUMERIC_WEIGHT(num), NUMERIC_DSCALE(num));
    6666                 :             :     switch (NUMERIC_SIGN(num))
    6667                 :             :     {
    6668                 :             :         case NUMERIC_POS:
    6669                 :             :             printf("POS");
    6670                 :             :             break;
    6671                 :             :         case NUMERIC_NEG:
    6672                 :             :             printf("NEG");
    6673                 :             :             break;
    6674                 :             :         case NUMERIC_NAN:
    6675                 :             :             printf("NaN");
    6676                 :             :             break;
    6677                 :             :         case NUMERIC_PINF:
    6678                 :             :             printf("Infinity");
    6679                 :             :             break;
    6680                 :             :         case NUMERIC_NINF:
    6681                 :             :             printf("-Infinity");
    6682                 :             :             break;
    6683                 :             :         default:
    6684                 :             :             printf("SIGN=0x%x", NUMERIC_SIGN(num));
    6685                 :             :             break;
    6686                 :             :     }
    6687                 :             : 
    6688                 :             :     for (i = 0; i < ndigits; i++)
    6689                 :             :         printf(" %0*d", DEC_DIGITS, digits[i]);
    6690                 :             :     printf("\n");
    6691                 :             : }
    6692                 :             : 
    6693                 :             : 
    6694                 :             : /*
    6695                 :             :  * dump_var() - Dump a value in the variable format for debugging
    6696                 :             :  */
    6697                 :             : static void
    6698                 :             : dump_var(const char *str, NumericVar *var)
    6699                 :             : {
    6700                 :             :     int         i;
    6701                 :             : 
    6702                 :             :     printf("%s: VAR w=%d d=%d ", str, var->weight, var->dscale);
    6703                 :             :     switch (var->sign)
    6704                 :             :     {
    6705                 :             :         case NUMERIC_POS:
    6706                 :             :             printf("POS");
    6707                 :             :             break;
    6708                 :             :         case NUMERIC_NEG:
    6709                 :             :             printf("NEG");
    6710                 :             :             break;
    6711                 :             :         case NUMERIC_NAN:
    6712                 :             :             printf("NaN");
    6713                 :             :             break;
    6714                 :             :         case NUMERIC_PINF:
    6715                 :             :             printf("Infinity");
    6716                 :             :             break;
    6717                 :             :         case NUMERIC_NINF:
    6718                 :             :             printf("-Infinity");
    6719                 :             :             break;
    6720                 :             :         default:
    6721                 :             :             printf("SIGN=0x%x", var->sign);
    6722                 :             :             break;
    6723                 :             :     }
    6724                 :             : 
    6725                 :             :     for (i = 0; i < var->ndigits; i++)
    6726                 :             :         printf(" %0*d", DEC_DIGITS, var->digits[i]);
    6727                 :             : 
    6728                 :             :     printf("\n");
    6729                 :             : }
    6730                 :             : #endif                          /* NUMERIC_DEBUG */
    6731                 :             : 
    6732                 :             : 
    6733                 :             : /* ----------------------------------------------------------------------
    6734                 :             :  *
    6735                 :             :  * Local functions follow
    6736                 :             :  *
    6737                 :             :  * In general, these do not support "special" (NaN or infinity) inputs;
    6738                 :             :  * callers should handle those possibilities first.
    6739                 :             :  * (There are one or two exceptions, noted in their header comments.)
    6740                 :             :  *
    6741                 :             :  * ----------------------------------------------------------------------
    6742                 :             :  */
    6743                 :             : 
    6744                 :             : 
    6745                 :             : /*
    6746                 :             :  * alloc_var() -
    6747                 :             :  *
    6748                 :             :  *  Allocate a digit buffer of ndigits digits (plus a spare digit for rounding)
    6749                 :             :  */
    6750                 :             : static void
    6751                 :     1444196 : alloc_var(NumericVar *var, int ndigits)
    6752                 :             : {
    6753         [ +  + ]:     1444196 :     digitbuf_free(var->buf);
    6754                 :     1444196 :     var->buf = digitbuf_alloc(ndigits + 1);
    6755                 :     1444196 :     var->buf[0] = 0;         /* spare digit for rounding */
    6756                 :     1444196 :     var->digits = var->buf + 1;
    6757                 :     1444196 :     var->ndigits = ndigits;
    6758                 :     1444196 : }
    6759                 :             : 
    6760                 :             : 
    6761                 :             : /*
    6762                 :             :  * free_var() -
    6763                 :             :  *
    6764                 :             :  *  Return the digit buffer of a variable to the free pool
    6765                 :             :  */
    6766                 :             : static void
    6767                 :     2780405 : free_var(NumericVar *var)
    6768                 :             : {
    6769         [ +  + ]:     2780405 :     digitbuf_free(var->buf);
    6770                 :     2780405 :     var->buf = NULL;
    6771                 :     2780405 :     var->digits = NULL;
    6772                 :     2780405 :     var->sign = NUMERIC_NAN;
    6773                 :     2780405 : }
    6774                 :             : 
    6775                 :             : 
    6776                 :             : /*
    6777                 :             :  * zero_var() -
    6778                 :             :  *
    6779                 :             :  *  Set a variable to ZERO.
    6780                 :             :  *  Note: its dscale is not touched.
    6781                 :             :  */
    6782                 :             : static void
    6783                 :       37827 : zero_var(NumericVar *var)
    6784                 :             : {
    6785         [ +  + ]:       37827 :     digitbuf_free(var->buf);
    6786                 :       37827 :     var->buf = NULL;
    6787                 :       37827 :     var->digits = NULL;
    6788                 :       37827 :     var->ndigits = 0;
    6789                 :       37827 :     var->weight = 0;         /* by convention; doesn't really matter */
    6790                 :       37827 :     var->sign = NUMERIC_POS; /* anything but NAN... */
    6791                 :       37827 : }
    6792                 :             : 
    6793                 :             : 
    6794                 :             : /*
    6795                 :             :  * set_var_from_str()
    6796                 :             :  *
    6797                 :             :  *  Parse a string and put the number into a variable
    6798                 :             :  *
    6799                 :             :  * This function does not handle leading or trailing spaces.  It returns
    6800                 :             :  * the end+1 position parsed into *endptr, so that caller can check for
    6801                 :             :  * trailing spaces/garbage if deemed necessary.
    6802                 :             :  *
    6803                 :             :  * cp is the place to actually start parsing; str is what to use in error
    6804                 :             :  * reports.  (Typically cp would be the same except advanced over spaces.)
    6805                 :             :  *
    6806                 :             :  * Returns true on success, false on failure (if escontext points to an
    6807                 :             :  * ErrorSaveContext; otherwise errors are thrown).
    6808                 :             :  */
    6809                 :             : static bool
    6810                 :      117572 : set_var_from_str(const char *str, const char *cp,
    6811                 :             :                  NumericVar *dest, const char **endptr,
    6812                 :             :                  Node *escontext)
    6813                 :             : {
    6814                 :      117572 :     bool        have_dp = false;
    6815                 :             :     int         i;
    6816                 :             :     unsigned char *decdigits;
    6817                 :      117572 :     int         sign = NUMERIC_POS;
    6818                 :      117572 :     int         dweight = -1;
    6819                 :             :     int         ddigits;
    6820                 :      117572 :     int         dscale = 0;
    6821                 :             :     int         weight;
    6822                 :             :     int         ndigits;
    6823                 :             :     int         offset;
    6824                 :             :     NumericDigit *digits;
    6825                 :             : 
    6826                 :             :     /*
    6827                 :             :      * We first parse the string to extract decimal digits and determine the
    6828                 :             :      * correct decimal weight.  Then convert to NBASE representation.
    6829                 :             :      */
    6830      [ -  +  + ]:      117572 :     switch (*cp)
    6831                 :             :     {
    6832                 :           0 :         case '+':
    6833                 :           0 :             sign = NUMERIC_POS;
    6834                 :           0 :             cp++;
    6835                 :           0 :             break;
    6836                 :             : 
    6837                 :         183 :         case '-':
    6838                 :         183 :             sign = NUMERIC_NEG;
    6839                 :         183 :             cp++;
    6840                 :         183 :             break;
    6841                 :             :     }
    6842                 :             : 
    6843         [ +  + ]:      117572 :     if (*cp == '.')
    6844                 :             :     {
    6845                 :         252 :         have_dp = true;
    6846                 :         252 :         cp++;
    6847                 :             :     }
    6848                 :             : 
    6849         [ -  + ]:      117572 :     if (!isdigit((unsigned char) *cp))
    6850                 :           0 :         goto invalid_syntax;
    6851                 :             : 
    6852                 :      117572 :     decdigits = (unsigned char *) palloc(strlen(cp) + DEC_DIGITS * 2);
    6853                 :             : 
    6854                 :             :     /* leading padding for digit alignment later */
    6855                 :      117572 :     memset(decdigits, 0, DEC_DIGITS);
    6856                 :      117572 :     i = DEC_DIGITS;
    6857                 :             : 
    6858         [ +  + ]:      513097 :     while (*cp)
    6859                 :             :     {
    6860         [ +  + ]:      396595 :         if (isdigit((unsigned char) *cp))
    6861                 :             :         {
    6862                 :      383214 :             decdigits[i++] = *cp++ - '0';
    6863         [ +  + ]:      383214 :             if (!have_dp)
    6864                 :      320900 :                 dweight++;
    6865                 :             :             else
    6866                 :       62314 :                 dscale++;
    6867                 :             :         }
    6868         [ +  + ]:       13381 :         else if (*cp == '.')
    6869                 :             :         {
    6870         [ -  + ]:       12203 :             if (have_dp)
    6871                 :           0 :                 goto invalid_syntax;
    6872                 :       12203 :             have_dp = true;
    6873                 :       12203 :             cp++;
    6874                 :             :             /* decimal point must not be followed by underscore */
    6875         [ +  + ]:       12203 :             if (*cp == '_')
    6876                 :           4 :                 goto invalid_syntax;
    6877                 :             :         }
    6878         [ +  + ]:        1178 :         else if (*cp == '_')
    6879                 :             :         {
    6880                 :             :             /* underscore must be followed by more digits */
    6881                 :         124 :             cp++;
    6882         [ +  + ]:         124 :             if (!isdigit((unsigned char) *cp))
    6883                 :          12 :                 goto invalid_syntax;
    6884                 :             :         }
    6885                 :             :         else
    6886                 :        1054 :             break;
    6887                 :             :     }
    6888                 :             : 
    6889                 :      117556 :     ddigits = i - DEC_DIGITS;
    6890                 :             :     /* trailing padding for digit alignment later */
    6891                 :      117556 :     memset(decdigits + i, 0, DEC_DIGITS - 1);
    6892                 :             : 
    6893                 :             :     /* Handle exponent, if any */
    6894   [ +  +  +  + ]:      117556 :     if (*cp == 'e' || *cp == 'E')
    6895                 :             :     {
    6896                 :        1022 :         int64       exponent = 0;
    6897                 :        1022 :         bool        neg = false;
    6898                 :             : 
    6899                 :             :         /*
    6900                 :             :          * At this point, dweight and dscale can't be more than about
    6901                 :             :          * INT_MAX/2 due to the MaxAllocSize limit on string length, so
    6902                 :             :          * constraining the exponent similarly should be enough to prevent
    6903                 :             :          * integer overflow in this function.  If the value is too large to
    6904                 :             :          * fit in storage format, make_result() will complain about it later;
    6905                 :             :          * for consistency use the same ereport errcode/text as make_result().
    6906                 :             :          */
    6907                 :             : 
    6908                 :             :         /* exponent sign */
    6909                 :        1022 :         cp++;
    6910         [ +  + ]:        1022 :         if (*cp == '+')
    6911                 :         102 :             cp++;
    6912         [ +  + ]:         920 :         else if (*cp == '-')
    6913                 :             :         {
    6914                 :         444 :             neg = true;
    6915                 :         444 :             cp++;
    6916                 :             :         }
    6917                 :             : 
    6918                 :             :         /* exponent digits */
    6919         [ +  + ]:        1022 :         if (!isdigit((unsigned char) *cp))
    6920                 :           4 :             goto invalid_syntax;
    6921                 :             : 
    6922         [ +  + ]:        3569 :         while (*cp)
    6923                 :             :         {
    6924         [ +  + ]:        2563 :             if (isdigit((unsigned char) *cp))
    6925                 :             :             {
    6926                 :        2535 :                 exponent = exponent * 10 + (*cp++ - '0');
    6927         [ +  + ]:        2535 :                 if (exponent > PG_INT32_MAX / 2)
    6928                 :           4 :                     goto out_of_range;
    6929                 :             :             }
    6930         [ +  - ]:          28 :             else if (*cp == '_')
    6931                 :             :             {
    6932                 :             :                 /* underscore must be followed by more digits */
    6933                 :          28 :                 cp++;
    6934         [ +  + ]:          28 :                 if (!isdigit((unsigned char) *cp))
    6935                 :           8 :                     goto invalid_syntax;
    6936                 :             :             }
    6937                 :             :             else
    6938                 :           0 :                 break;
    6939                 :             :         }
    6940                 :             : 
    6941         [ +  + ]:        1006 :         if (neg)
    6942                 :         444 :             exponent = -exponent;
    6943                 :             : 
    6944                 :        1006 :         dweight += (int) exponent;
    6945                 :        1006 :         dscale -= (int) exponent;
    6946         [ +  + ]:        1006 :         if (dscale < 0)
    6947                 :         426 :             dscale = 0;
    6948                 :             :     }
    6949                 :             : 
    6950                 :             :     /*
    6951                 :             :      * Okay, convert pure-decimal representation to base NBASE.  First we need
    6952                 :             :      * to determine the converted weight and ndigits.  offset is the number of
    6953                 :             :      * decimal zeroes to insert before the first given digit to have a
    6954                 :             :      * correctly aligned first NBASE digit.
    6955                 :             :      */
    6956         [ +  + ]:      117540 :     if (dweight >= 0)
    6957                 :      116912 :         weight = (dweight + 1 + DEC_DIGITS - 1) / DEC_DIGITS - 1;
    6958                 :             :     else
    6959                 :         628 :         weight = -((-dweight - 1) / DEC_DIGITS + 1);
    6960                 :      117540 :     offset = (weight + 1) * DEC_DIGITS - (dweight + 1);
    6961                 :      117540 :     ndigits = (ddigits + offset + DEC_DIGITS - 1) / DEC_DIGITS;
    6962                 :             : 
    6963                 :      117540 :     alloc_var(dest, ndigits);
    6964                 :      117540 :     dest->sign = sign;
    6965                 :      117540 :     dest->weight = weight;
    6966                 :      117540 :     dest->dscale = dscale;
    6967                 :             : 
    6968                 :      117540 :     i = DEC_DIGITS - offset;
    6969                 :      117540 :     digits = dest->digits;
    6970                 :             : 
    6971         [ +  + ]:      284051 :     while (ndigits-- > 0)
    6972                 :             :     {
    6973                 :             : #if DEC_DIGITS == 4
    6974                 :      166511 :         *digits++ = ((decdigits[i] * 10 + decdigits[i + 1]) * 10 +
    6975                 :      166511 :                      decdigits[i + 2]) * 10 + decdigits[i + 3];
    6976                 :             : #elif DEC_DIGITS == 2
    6977                 :             :         *digits++ = decdigits[i] * 10 + decdigits[i + 1];
    6978                 :             : #elif DEC_DIGITS == 1
    6979                 :             :         *digits++ = decdigits[i];
    6980                 :             : #else
    6981                 :             : #error unsupported NBASE
    6982                 :             : #endif
    6983                 :      166511 :         i += DEC_DIGITS;
    6984                 :             :     }
    6985                 :             : 
    6986                 :      117540 :     pfree(decdigits);
    6987                 :             : 
    6988                 :             :     /* Strip any leading/trailing zeroes, and normalize weight if zero */
    6989                 :      117540 :     strip_var(dest);
    6990                 :             : 
    6991                 :             :     /* Return end+1 position for caller */
    6992                 :      117540 :     *endptr = cp;
    6993                 :             : 
    6994                 :      117540 :     return true;
    6995                 :             : 
    6996                 :           4 : out_of_range:
    6997         [ +  - ]:           4 :     ereturn(escontext, false,
    6998                 :             :             (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    6999                 :             :              errmsg("value overflows numeric format")));
    7000                 :             : 
    7001                 :          28 : invalid_syntax:
    7002         [ +  - ]:          28 :     ereturn(escontext, false,
    7003                 :             :             (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    7004                 :             :              errmsg("invalid input syntax for type %s: \"%s\"",
    7005                 :             :                     "numeric", str)));
    7006                 :             : }
    7007                 :             : 
    7008                 :             : 
    7009                 :             : /*
    7010                 :             :  * Return the numeric value of a single hex digit.
    7011                 :             :  */
    7012                 :             : static inline int
    7013                 :         472 : xdigit_value(char dig)
    7014                 :             : {
    7015   [ +  -  +  + ]:         596 :     return dig >= '0' && dig <= '9' ? dig - '0' :
    7016   [ +  +  +  - ]:         196 :         dig >= 'a' && dig <= 'f' ? dig - 'a' + 10 :
    7017   [ +  -  +  - ]:          72 :         dig >= 'A' && dig <= 'F' ? dig - 'A' + 10 : -1;
    7018                 :             : }
    7019                 :             : 
    7020                 :             : /*
    7021                 :             :  * set_var_from_non_decimal_integer_str()
    7022                 :             :  *
    7023                 :             :  *  Parse a string containing a non-decimal integer
    7024                 :             :  *
    7025                 :             :  * This function does not handle leading or trailing spaces.  It returns
    7026                 :             :  * the end+1 position parsed into *endptr, so that caller can check for
    7027                 :             :  * trailing spaces/garbage if deemed necessary.
    7028                 :             :  *
    7029                 :             :  * cp is the place to actually start parsing; str is what to use in error
    7030                 :             :  * reports.  The number's sign and base prefix indicator (e.g., "0x") are
    7031                 :             :  * assumed to have already been parsed, so cp should point to the number's
    7032                 :             :  * first digit in the base specified.
    7033                 :             :  *
    7034                 :             :  * base is expected to be 2, 8 or 16.
    7035                 :             :  *
    7036                 :             :  * Returns true on success, false on failure (if escontext points to an
    7037                 :             :  * ErrorSaveContext; otherwise errors are thrown).
    7038                 :             :  */
    7039                 :             : static bool
    7040                 :         104 : set_var_from_non_decimal_integer_str(const char *str, const char *cp, int sign,
    7041                 :             :                                      int base, NumericVar *dest,
    7042                 :             :                                      const char **endptr, Node *escontext)
    7043                 :             : {
    7044                 :         104 :     const char *firstdigit = cp;
    7045                 :             :     int64       tmp;
    7046                 :             :     int64       mul;
    7047                 :             :     NumericVar  tmp_var;
    7048                 :             : 
    7049                 :         104 :     init_var(&tmp_var);
    7050                 :             : 
    7051                 :         104 :     zero_var(dest);
    7052                 :             : 
    7053                 :             :     /*
    7054                 :             :      * Process input digits in groups that fit in int64.  Here "tmp" is the
    7055                 :             :      * value of the digits in the group, and "mul" is base^n, where n is the
    7056                 :             :      * number of digits in the group.  Thus tmp < mul, and we must start a new
    7057                 :             :      * group when mul * base threatens to overflow PG_INT64_MAX.
    7058                 :             :      */
    7059                 :         104 :     tmp = 0;
    7060                 :         104 :     mul = 1;
    7061                 :             : 
    7062         [ +  + ]:         104 :     if (base == 16)
    7063                 :             :     {
    7064         [ +  + ]:         552 :         while (*cp)
    7065                 :             :         {
    7066         [ +  + ]:         532 :             if (isxdigit((unsigned char) *cp))
    7067                 :             :             {
    7068         [ +  + ]:         472 :                 if (mul > PG_INT64_MAX / 16)
    7069                 :             :                 {
    7070                 :             :                     /* Add the contribution from this group of digits */
    7071                 :          20 :                     int64_to_numericvar(mul, &tmp_var);
    7072                 :          20 :                     mul_var(dest, &tmp_var, dest, 0);
    7073                 :          20 :                     int64_to_numericvar(tmp, &tmp_var);
    7074                 :          20 :                     add_var(dest, &tmp_var, dest);
    7075                 :             : 
    7076                 :             :                     /* Result will overflow if weight overflows int16 */
    7077         [ -  + ]:          20 :                     if (dest->weight > NUMERIC_WEIGHT_MAX)
    7078                 :           0 :                         goto out_of_range;
    7079                 :             : 
    7080                 :             :                     /* Begin a new group */
    7081                 :          20 :                     tmp = 0;
    7082                 :          20 :                     mul = 1;
    7083                 :             :                 }
    7084                 :             : 
    7085                 :         472 :                 tmp = tmp * 16 + xdigit_value(*cp++);
    7086                 :         472 :                 mul = mul * 16;
    7087                 :             :             }
    7088         [ +  + ]:          60 :             else if (*cp == '_')
    7089                 :             :             {
    7090                 :             :                 /* Underscore must be followed by more digits */
    7091                 :          44 :                 cp++;
    7092         [ +  + ]:          44 :                 if (!isxdigit((unsigned char) *cp))
    7093                 :          12 :                     goto invalid_syntax;
    7094                 :             :             }
    7095                 :             :             else
    7096                 :          16 :                 break;
    7097                 :             :         }
    7098                 :             :     }
    7099         [ +  + ]:          56 :     else if (base == 8)
    7100                 :             :     {
    7101         [ +  + ]:         424 :         while (*cp)
    7102                 :             :         {
    7103   [ +  +  +  + ]:         404 :             if (*cp >= '0' && *cp <= '7')
    7104                 :             :             {
    7105         [ +  + ]:         372 :                 if (mul > PG_INT64_MAX / 8)
    7106                 :             :                 {
    7107                 :             :                     /* Add the contribution from this group of digits */
    7108                 :          12 :                     int64_to_numericvar(mul, &tmp_var);
    7109                 :          12 :                     mul_var(dest, &tmp_var, dest, 0);
    7110                 :          12 :                     int64_to_numericvar(tmp, &tmp_var);
    7111                 :          12 :                     add_var(dest, &tmp_var, dest);
    7112                 :             : 
    7113                 :             :                     /* Result will overflow if weight overflows int16 */
    7114         [ -  + ]:          12 :                     if (dest->weight > NUMERIC_WEIGHT_MAX)
    7115                 :           0 :                         goto out_of_range;
    7116                 :             : 
    7117                 :             :                     /* Begin a new group */
    7118                 :          12 :                     tmp = 0;
    7119                 :          12 :                     mul = 1;
    7120                 :             :                 }
    7121                 :             : 
    7122                 :         372 :                 tmp = tmp * 8 + (*cp++ - '0');
    7123                 :         372 :                 mul = mul * 8;
    7124                 :             :             }
    7125         [ +  + ]:          32 :             else if (*cp == '_')
    7126                 :             :             {
    7127                 :             :                 /* Underscore must be followed by more digits */
    7128                 :          24 :                 cp++;
    7129   [ +  -  -  + ]:          24 :                 if (*cp < '0' || *cp > '7')
    7130                 :           0 :                     goto invalid_syntax;
    7131                 :             :             }
    7132                 :             :             else
    7133                 :           8 :                 break;
    7134                 :             :         }
    7135                 :             :     }
    7136         [ +  - ]:          28 :     else if (base == 2)
    7137                 :             :     {
    7138         [ +  + ]:        1040 :         while (*cp)
    7139                 :             :         {
    7140   [ +  +  +  + ]:        1020 :             if (*cp >= '0' && *cp <= '1')
    7141                 :             :             {
    7142         [ +  + ]:         944 :                 if (mul > PG_INT64_MAX / 2)
    7143                 :             :                 {
    7144                 :             :                     /* Add the contribution from this group of digits */
    7145                 :          12 :                     int64_to_numericvar(mul, &tmp_var);
    7146                 :          12 :                     mul_var(dest, &tmp_var, dest, 0);
    7147                 :          12 :                     int64_to_numericvar(tmp, &tmp_var);
    7148                 :          12 :                     add_var(dest, &tmp_var, dest);
    7149                 :             : 
    7150                 :             :                     /* Result will overflow if weight overflows int16 */
    7151         [ -  + ]:          12 :                     if (dest->weight > NUMERIC_WEIGHT_MAX)
    7152                 :           0 :                         goto out_of_range;
    7153                 :             : 
    7154                 :             :                     /* Begin a new group */
    7155                 :          12 :                     tmp = 0;
    7156                 :          12 :                     mul = 1;
    7157                 :             :                 }
    7158                 :             : 
    7159                 :         944 :                 tmp = tmp * 2 + (*cp++ - '0');
    7160                 :         944 :                 mul = mul * 2;
    7161                 :             :             }
    7162         [ +  + ]:          76 :             else if (*cp == '_')
    7163                 :             :             {
    7164                 :             :                 /* Underscore must be followed by more digits */
    7165                 :          68 :                 cp++;
    7166   [ +  -  -  + ]:          68 :                 if (*cp < '0' || *cp > '1')
    7167                 :           0 :                     goto invalid_syntax;
    7168                 :             :             }
    7169                 :             :             else
    7170                 :           8 :                 break;
    7171                 :             :         }
    7172                 :             :     }
    7173                 :             :     else
    7174                 :             :         /* Should never happen; treat as invalid input */
    7175                 :           0 :         goto invalid_syntax;
    7176                 :             : 
    7177                 :             :     /* Check that we got at least one digit */
    7178         [ -  + ]:          92 :     if (unlikely(cp == firstdigit))
    7179                 :           0 :         goto invalid_syntax;
    7180                 :             : 
    7181                 :             :     /* Add the contribution from the final group of digits */
    7182                 :          92 :     int64_to_numericvar(mul, &tmp_var);
    7183                 :          92 :     mul_var(dest, &tmp_var, dest, 0);
    7184                 :          92 :     int64_to_numericvar(tmp, &tmp_var);
    7185                 :          92 :     add_var(dest, &tmp_var, dest);
    7186                 :             : 
    7187         [ -  + ]:          92 :     if (dest->weight > NUMERIC_WEIGHT_MAX)
    7188                 :           0 :         goto out_of_range;
    7189                 :             : 
    7190                 :          92 :     dest->sign = sign;
    7191                 :             : 
    7192                 :          92 :     free_var(&tmp_var);
    7193                 :             : 
    7194                 :             :     /* Return end+1 position for caller */
    7195                 :          92 :     *endptr = cp;
    7196                 :             : 
    7197                 :          92 :     return true;
    7198                 :             : 
    7199                 :           0 : out_of_range:
    7200         [ #  # ]:           0 :     ereturn(escontext, false,
    7201                 :             :             (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    7202                 :             :              errmsg("value overflows numeric format")));
    7203                 :             : 
    7204                 :          12 : invalid_syntax:
    7205         [ +  - ]:          12 :     ereturn(escontext, false,
    7206                 :             :             (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    7207                 :             :              errmsg("invalid input syntax for type %s: \"%s\"",
    7208                 :             :                     "numeric", str)));
    7209                 :             : }
    7210                 :             : 
    7211                 :             : 
    7212                 :             : /*
    7213                 :             :  * set_var_from_num() -
    7214                 :             :  *
    7215                 :             :  *  Convert the packed db format into a variable
    7216                 :             :  */
    7217                 :             : static void
    7218                 :        8827 : set_var_from_num(Numeric num, NumericVar *dest)
    7219                 :             : {
    7220                 :             :     int         ndigits;
    7221                 :             : 
    7222         [ +  + ]:        8827 :     ndigits = NUMERIC_NDIGITS(num);
    7223                 :             : 
    7224                 :        8827 :     alloc_var(dest, ndigits);
    7225                 :             : 
    7226   [ +  +  +  + ]:        8827 :     dest->weight = NUMERIC_WEIGHT(num);
    7227   [ +  +  -  + ]:        8827 :     dest->sign = NUMERIC_SIGN(num);
    7228         [ +  + ]:        8827 :     dest->dscale = NUMERIC_DSCALE(num);
    7229                 :             : 
    7230         [ +  + ]:        8827 :     memcpy(dest->digits, NUMERIC_DIGITS(num), ndigits * sizeof(NumericDigit));
    7231                 :        8827 : }
    7232                 :             : 
    7233                 :             : 
    7234                 :             : /*
    7235                 :             :  * init_var_from_num() -
    7236                 :             :  *
    7237                 :             :  *  Initialize a variable from packed db format. The digits array is not
    7238                 :             :  *  copied, which saves some cycles when the resulting var is not modified.
    7239                 :             :  *  Also, there's no need to call free_var(), as long as you don't assign any
    7240                 :             :  *  other value to it (with set_var_* functions, or by using the var as the
    7241                 :             :  *  destination of a function like add_var())
    7242                 :             :  *
    7243                 :             :  *  CAUTION: Do not modify the digits buffer of a var initialized with this
    7244                 :             :  *  function, e.g by calling round_var() or trunc_var(), as the changes will
    7245                 :             :  *  propagate to the original Numeric! It's OK to use it as the destination
    7246                 :             :  *  argument of one of the calculational functions, though.
    7247                 :             :  */
    7248                 :             : static void
    7249                 :     3872559 : init_var_from_num(Numeric num, NumericVar *dest)
    7250                 :             : {
    7251         [ +  + ]:     3872559 :     dest->ndigits = NUMERIC_NDIGITS(num);
    7252   [ +  +  +  + ]:     3872559 :     dest->weight = NUMERIC_WEIGHT(num);
    7253   [ +  +  -  + ]:     3872559 :     dest->sign = NUMERIC_SIGN(num);
    7254         [ +  + ]:     3872559 :     dest->dscale = NUMERIC_DSCALE(num);
    7255         [ +  + ]:     3872559 :     dest->digits = NUMERIC_DIGITS(num);
    7256                 :     3872559 :     dest->buf = NULL;            /* digits array is not palloc'd */
    7257                 :     3872559 : }
    7258                 :             : 
    7259                 :             : 
    7260                 :             : /*
    7261                 :             :  * set_var_from_var() -
    7262                 :             :  *
    7263                 :             :  *  Copy one variable into another
    7264                 :             :  */
    7265                 :             : static void
    7266                 :       24587 : set_var_from_var(const NumericVar *value, NumericVar *dest)
    7267                 :             : {
    7268                 :             :     NumericDigit *newbuf;
    7269                 :             : 
    7270                 :       24587 :     newbuf = digitbuf_alloc(value->ndigits + 1);
    7271                 :       24587 :     newbuf[0] = 0;              /* spare digit for rounding */
    7272         [ +  + ]:       24587 :     if (value->ndigits > 0)       /* else value->digits might be null */
    7273                 :       23911 :         memcpy(newbuf + 1, value->digits,
    7274                 :       23911 :                value->ndigits * sizeof(NumericDigit));
    7275                 :             : 
    7276         [ +  + ]:       24587 :     digitbuf_free(dest->buf);
    7277                 :             : 
    7278                 :       24587 :     memmove(dest, value, sizeof(NumericVar));
    7279                 :       24587 :     dest->buf = newbuf;
    7280                 :       24587 :     dest->digits = newbuf + 1;
    7281                 :       24587 : }
    7282                 :             : 
    7283                 :             : 
    7284                 :             : /*
    7285                 :             :  * get_str_from_var() -
    7286                 :             :  *
    7287                 :             :  *  Convert a var to text representation (guts of numeric_out).
    7288                 :             :  *  The var is displayed to the number of digits indicated by its dscale.
    7289                 :             :  *  Returns a palloc'd string.
    7290                 :             :  */
    7291                 :             : static char *
    7292                 :      562481 : get_str_from_var(const NumericVar *var)
    7293                 :             : {
    7294                 :             :     int         dscale;
    7295                 :             :     char       *str;
    7296                 :             :     char       *cp;
    7297                 :             :     char       *endcp;
    7298                 :             :     int         i;
    7299                 :             :     int         d;
    7300                 :             :     NumericDigit dig;
    7301                 :             : 
    7302                 :             : #if DEC_DIGITS > 1
    7303                 :             :     NumericDigit d1;
    7304                 :             : #endif
    7305                 :             : 
    7306                 :      562481 :     dscale = var->dscale;
    7307                 :             : 
    7308                 :             :     /*
    7309                 :             :      * Allocate space for the result.
    7310                 :             :      *
    7311                 :             :      * i is set to the # of decimal digits before decimal point. dscale is the
    7312                 :             :      * # of decimal digits we will print after decimal point. We may generate
    7313                 :             :      * as many as DEC_DIGITS-1 excess digits at the end, and in addition we
    7314                 :             :      * need room for sign, decimal point, null terminator.
    7315                 :             :      */
    7316                 :      562481 :     i = (var->weight + 1) * DEC_DIGITS;
    7317         [ +  + ]:      562481 :     if (i <= 0)
    7318                 :       72475 :         i = 1;
    7319                 :             : 
    7320                 :      562481 :     str = palloc(i + dscale + DEC_DIGITS + 2);
    7321                 :      562481 :     cp = str;
    7322                 :             : 
    7323                 :             :     /*
    7324                 :             :      * Output a dash for negative values
    7325                 :             :      */
    7326         [ +  + ]:      562481 :     if (var->sign == NUMERIC_NEG)
    7327                 :        4401 :         *cp++ = '-';
    7328                 :             : 
    7329                 :             :     /*
    7330                 :             :      * Output all digits before the decimal point
    7331                 :             :      */
    7332         [ +  + ]:      562481 :     if (var->weight < 0)
    7333                 :             :     {
    7334                 :       72475 :         d = var->weight + 1;
    7335                 :       72475 :         *cp++ = '0';
    7336                 :             :     }
    7337                 :             :     else
    7338                 :             :     {
    7339         [ +  + ]:     1042024 :         for (d = 0; d <= var->weight; d++)
    7340                 :             :         {
    7341         [ +  + ]:      552018 :             dig = (d < var->ndigits) ? var->digits[d] : 0;
    7342                 :             :             /* In the first digit, suppress extra leading decimal zeroes */
    7343                 :             : #if DEC_DIGITS == 4
    7344                 :             :             {
    7345                 :      552018 :                 bool        putit = (d > 0);
    7346                 :             : 
    7347                 :      552018 :                 d1 = dig / 1000;
    7348                 :      552018 :                 dig -= d1 * 1000;
    7349                 :      552018 :                 putit |= (d1 > 0);
    7350         [ +  + ]:      552018 :                 if (putit)
    7351                 :      102567 :                     *cp++ = d1 + '0';
    7352                 :      552018 :                 d1 = dig / 100;
    7353                 :      552018 :                 dig -= d1 * 100;
    7354                 :      552018 :                 putit |= (d1 > 0);
    7355         [ +  + ]:      552018 :                 if (putit)
    7356                 :      375304 :                     *cp++ = d1 + '0';
    7357                 :      552018 :                 d1 = dig / 10;
    7358                 :      552018 :                 dig -= d1 * 10;
    7359                 :      552018 :                 putit |= (d1 > 0);
    7360         [ +  + ]:      552018 :                 if (putit)
    7361                 :      459344 :                     *cp++ = d1 + '0';
    7362                 :      552018 :                 *cp++ = dig + '0';
    7363                 :             :             }
    7364                 :             : #elif DEC_DIGITS == 2
    7365                 :             :             d1 = dig / 10;
    7366                 :             :             dig -= d1 * 10;
    7367                 :             :             if (d1 > 0 || d > 0)
    7368                 :             :                 *cp++ = d1 + '0';
    7369                 :             :             *cp++ = dig + '0';
    7370                 :             : #elif DEC_DIGITS == 1
    7371                 :             :             *cp++ = dig + '0';
    7372                 :             : #else
    7373                 :             : #error unsupported NBASE
    7374                 :             : #endif
    7375                 :             :         }
    7376                 :             :     }
    7377                 :             : 
    7378                 :             :     /*
    7379                 :             :      * If requested, output a decimal point and all the digits that follow it.
    7380                 :             :      * We initially put out a multiple of DEC_DIGITS digits, then truncate if
    7381                 :             :      * needed.
    7382                 :             :      */
    7383         [ +  + ]:      562481 :     if (dscale > 0)
    7384                 :             :     {
    7385                 :      409719 :         *cp++ = '.';
    7386                 :      409719 :         endcp = cp + dscale;
    7387         [ +  + ]:     1150949 :         for (i = 0; i < dscale; d++, i += DEC_DIGITS)
    7388                 :             :         {
    7389   [ +  +  +  + ]:      741230 :             dig = (d >= 0 && d < var->ndigits) ? var->digits[d] : 0;
    7390                 :             : #if DEC_DIGITS == 4
    7391                 :      741230 :             d1 = dig / 1000;
    7392                 :      741230 :             dig -= d1 * 1000;
    7393                 :      741230 :             *cp++ = d1 + '0';
    7394                 :      741230 :             d1 = dig / 100;
    7395                 :      741230 :             dig -= d1 * 100;
    7396                 :      741230 :             *cp++ = d1 + '0';
    7397                 :      741230 :             d1 = dig / 10;
    7398                 :      741230 :             dig -= d1 * 10;
    7399                 :      741230 :             *cp++ = d1 + '0';
    7400                 :      741230 :             *cp++ = dig + '0';
    7401                 :             : #elif DEC_DIGITS == 2
    7402                 :             :             d1 = dig / 10;
    7403                 :             :             dig -= d1 * 10;
    7404                 :             :             *cp++ = d1 + '0';
    7405                 :             :             *cp++ = dig + '0';
    7406                 :             : #elif DEC_DIGITS == 1
    7407                 :             :             *cp++ = dig + '0';
    7408                 :             : #else
    7409                 :             : #error unsupported NBASE
    7410                 :             : #endif
    7411                 :             :         }
    7412                 :      409719 :         cp = endcp;
    7413                 :             :     }
    7414                 :             : 
    7415                 :             :     /*
    7416                 :             :      * terminate the string and return it
    7417                 :             :      */
    7418                 :      562481 :     *cp = '\0';
    7419                 :      562481 :     return str;
    7420                 :             : }
    7421                 :             : 
    7422                 :             : /*
    7423                 :             :  * get_str_from_var_sci() -
    7424                 :             :  *
    7425                 :             :  *  Convert a var to a normalised scientific notation text representation.
    7426                 :             :  *  This function does the heavy lifting for numeric_out_sci().
    7427                 :             :  *
    7428                 :             :  *  This notation has the general form a * 10^b, where a is known as the
    7429                 :             :  *  "significand" and b is known as the "exponent".
    7430                 :             :  *
    7431                 :             :  *  Because we can't do superscript in ASCII (and because we want to copy
    7432                 :             :  *  printf's behaviour) we display the exponent using E notation, with a
    7433                 :             :  *  minimum of two exponent digits.
    7434                 :             :  *
    7435                 :             :  *  For example, the value 1234 could be output as 1.2e+03.
    7436                 :             :  *
    7437                 :             :  *  We assume that the exponent can fit into an int32.
    7438                 :             :  *
    7439                 :             :  *  rscale is the number of decimal digits desired after the decimal point in
    7440                 :             :  *  the output, negative values will be treated as meaning zero.
    7441                 :             :  *
    7442                 :             :  *  Returns a palloc'd string.
    7443                 :             :  */
    7444                 :             : static char *
    7445                 :         152 : get_str_from_var_sci(const NumericVar *var, int rscale)
    7446                 :             : {
    7447                 :             :     int32       exponent;
    7448                 :             :     NumericVar  tmp_var;
    7449                 :             :     size_t      len;
    7450                 :             :     char       *str;
    7451                 :             :     char       *sig_out;
    7452                 :             : 
    7453         [ -  + ]:         152 :     if (rscale < 0)
    7454                 :           0 :         rscale = 0;
    7455                 :             : 
    7456                 :             :     /*
    7457                 :             :      * Determine the exponent of this number in normalised form.
    7458                 :             :      *
    7459                 :             :      * This is the exponent required to represent the number with only one
    7460                 :             :      * significant digit before the decimal place.
    7461                 :             :      */
    7462         [ +  + ]:         152 :     if (var->ndigits > 0)
    7463                 :             :     {
    7464                 :         140 :         exponent = (var->weight + 1) * DEC_DIGITS;
    7465                 :             : 
    7466                 :             :         /*
    7467                 :             :          * Compensate for leading decimal zeroes in the first numeric digit by
    7468                 :             :          * decrementing the exponent.
    7469                 :             :          */
    7470                 :         140 :         exponent -= DEC_DIGITS - (int) log10(var->digits[0]);
    7471                 :             :     }
    7472                 :             :     else
    7473                 :             :     {
    7474                 :             :         /*
    7475                 :             :          * If var has no digits, then it must be zero.
    7476                 :             :          *
    7477                 :             :          * Zero doesn't technically have a meaningful exponent in normalised
    7478                 :             :          * notation, but we just display the exponent as zero for consistency
    7479                 :             :          * of output.
    7480                 :             :          */
    7481                 :          12 :         exponent = 0;
    7482                 :             :     }
    7483                 :             : 
    7484                 :             :     /*
    7485                 :             :      * Divide var by 10^exponent to get the significand, rounding to rscale
    7486                 :             :      * decimal digits in the process.
    7487                 :             :      */
    7488                 :         152 :     init_var(&tmp_var);
    7489                 :             : 
    7490                 :         152 :     power_ten_int(exponent, &tmp_var);
    7491                 :         152 :     div_var(var, &tmp_var, &tmp_var, rscale, true, true);
    7492                 :         152 :     sig_out = get_str_from_var(&tmp_var);
    7493                 :             : 
    7494                 :         152 :     free_var(&tmp_var);
    7495                 :             : 
    7496                 :             :     /*
    7497                 :             :      * Allocate space for the result.
    7498                 :             :      *
    7499                 :             :      * In addition to the significand, we need room for the exponent
    7500                 :             :      * decoration ("e"), the sign of the exponent, up to 10 digits for the
    7501                 :             :      * exponent itself, and of course the null terminator.
    7502                 :             :      */
    7503                 :         152 :     len = strlen(sig_out) + 13;
    7504                 :         152 :     str = palloc(len);
    7505                 :         152 :     snprintf(str, len, "%se%+03d", sig_out, exponent);
    7506                 :             : 
    7507                 :         152 :     pfree(sig_out);
    7508                 :             : 
    7509                 :         152 :     return str;
    7510                 :             : }
    7511                 :             : 
    7512                 :             : 
    7513                 :             : /*
    7514                 :             :  * numericvar_serialize - serialize NumericVar to binary format
    7515                 :             :  *
    7516                 :             :  * At variable level, no checks are performed on the weight or dscale, allowing
    7517                 :             :  * us to pass around intermediate values with higher precision than supported
    7518                 :             :  * by the numeric type.  Note: this is incompatible with numeric_send/recv(),
    7519                 :             :  * which use 16-bit integers for these fields.
    7520                 :             :  */
    7521                 :             : static void
    7522                 :          61 : numericvar_serialize(StringInfo buf, const NumericVar *var)
    7523                 :             : {
    7524                 :             :     int         i;
    7525                 :             : 
    7526                 :          61 :     pq_sendint32(buf, var->ndigits);
    7527                 :          61 :     pq_sendint32(buf, var->weight);
    7528                 :          61 :     pq_sendint32(buf, var->sign);
    7529                 :          61 :     pq_sendint32(buf, var->dscale);
    7530         [ +  + ]:      425168 :     for (i = 0; i < var->ndigits; i++)
    7531                 :      425107 :         pq_sendint16(buf, var->digits[i]);
    7532                 :          61 : }
    7533                 :             : 
    7534                 :             : /*
    7535                 :             :  * numericvar_deserialize - deserialize binary format to NumericVar
    7536                 :             :  */
    7537                 :             : static void
    7538                 :          61 : numericvar_deserialize(StringInfo buf, NumericVar *var)
    7539                 :             : {
    7540                 :             :     int         len,
    7541                 :             :                 i;
    7542                 :             : 
    7543                 :          61 :     len = pq_getmsgint(buf, sizeof(int32));
    7544                 :             : 
    7545                 :          61 :     alloc_var(var, len);        /* sets var->ndigits */
    7546                 :             : 
    7547                 :          61 :     var->weight = pq_getmsgint(buf, sizeof(int32));
    7548                 :          61 :     var->sign = pq_getmsgint(buf, sizeof(int32));
    7549                 :          61 :     var->dscale = pq_getmsgint(buf, sizeof(int32));
    7550         [ +  + ]:      425168 :     for (i = 0; i < len; i++)
    7551                 :      425107 :         var->digits[i] = pq_getmsgint(buf, sizeof(int16));
    7552                 :          61 : }
    7553                 :             : 
    7554                 :             : 
    7555                 :             : /*
    7556                 :             :  * duplicate_numeric() - copy a packed-format Numeric
    7557                 :             :  *
    7558                 :             :  * This will handle NaN and Infinity cases.
    7559                 :             :  */
    7560                 :             : static Numeric
    7561                 :       18826 : duplicate_numeric(Numeric num)
    7562                 :             : {
    7563                 :             :     Numeric     res;
    7564                 :             : 
    7565                 :       18826 :     res = (Numeric) palloc(VARSIZE(num));
    7566                 :       18826 :     memcpy(res, num, VARSIZE(num));
    7567                 :       18826 :     return res;
    7568                 :             : }
    7569                 :             : 
    7570                 :             : /*
    7571                 :             :  * make_result_safe() -
    7572                 :             :  *
    7573                 :             :  *  Create the packed db numeric format in palloc()'d memory from
    7574                 :             :  *  a variable.  This will handle NaN and Infinity cases.
    7575                 :             :  */
    7576                 :             : static Numeric
    7577                 :     2525815 : make_result_safe(const NumericVar *var, Node *escontext)
    7578                 :             : {
    7579                 :             :     Numeric     result;
    7580                 :     2525815 :     NumericDigit *digits = var->digits;
    7581                 :     2525815 :     int         weight = var->weight;
    7582                 :     2525815 :     int         sign = var->sign;
    7583                 :             :     int         n;
    7584                 :             :     Size        len;
    7585                 :             : 
    7586         [ +  + ]:     2525815 :     if ((sign & NUMERIC_SIGN_MASK) == NUMERIC_SPECIAL)
    7587                 :             :     {
    7588                 :             :         /*
    7589                 :             :          * Verify valid special value.  This could be just an Assert, perhaps,
    7590                 :             :          * but it seems worthwhile to expend a few cycles to ensure that we
    7591                 :             :          * never write any nonzero reserved bits to disk.
    7592                 :             :          */
    7593   [ +  +  +  +  :        2208 :         if (!(sign == NUMERIC_NAN ||
                   -  + ]
    7594                 :             :               sign == NUMERIC_PINF ||
    7595                 :             :               sign == NUMERIC_NINF))
    7596         [ #  # ]:           0 :             elog(ERROR, "invalid numeric sign value 0x%x", sign);
    7597                 :             : 
    7598                 :        2208 :         result = (Numeric) palloc(NUMERIC_HDRSZ_SHORT);
    7599                 :             : 
    7600                 :        2208 :         SET_VARSIZE(result, NUMERIC_HDRSZ_SHORT);
    7601                 :        2208 :         result->choice.n_header = sign;
    7602                 :             :         /* the header word is all we need */
    7603                 :             : 
    7604                 :             :         dump_numeric("make_result()", result);
    7605                 :        2208 :         return result;
    7606                 :             :     }
    7607                 :             : 
    7608                 :     2523607 :     n = var->ndigits;
    7609                 :             : 
    7610                 :             :     /* truncate leading zeroes */
    7611   [ +  +  +  + ]:     2523637 :     while (n > 0 && *digits == 0)
    7612                 :             :     {
    7613                 :          30 :         digits++;
    7614                 :          30 :         weight--;
    7615                 :          30 :         n--;
    7616                 :             :     }
    7617                 :             :     /* truncate trailing zeroes */
    7618   [ +  +  +  + ]:     2575734 :     while (n > 0 && digits[n - 1] == 0)
    7619                 :       52127 :         n--;
    7620                 :             : 
    7621                 :             :     /* If zero result, force to weight=0 and positive sign */
    7622         [ +  + ]:     2523607 :     if (n == 0)
    7623                 :             :     {
    7624                 :       82177 :         weight = 0;
    7625                 :       82177 :         sign = NUMERIC_POS;
    7626                 :             :     }
    7627                 :             : 
    7628                 :             :     /* Build the result */
    7629   [ +  +  +  +  :     2523607 :     if (NUMERIC_CAN_BE_SHORT(var->dscale, weight))
                   +  - ]
    7630                 :             :     {
    7631                 :     2521673 :         len = NUMERIC_HDRSZ_SHORT + n * sizeof(NumericDigit);
    7632                 :     2521673 :         result = (Numeric) palloc(len);
    7633                 :     2521673 :         SET_VARSIZE(result, len);
    7634                 :     2521673 :         result->choice.n_short.n_header =
    7635                 :             :             (sign == NUMERIC_NEG ? (NUMERIC_SHORT | NUMERIC_SHORT_SIGN_MASK)
    7636                 :             :              : NUMERIC_SHORT)
    7637         [ +  + ]:     2521673 :             | (var->dscale << NUMERIC_SHORT_DSCALE_SHIFT)
    7638                 :     2521673 :             | (weight < 0 ? NUMERIC_SHORT_WEIGHT_SIGN_MASK : 0)
    7639                 :     2521673 :             | (weight & NUMERIC_SHORT_WEIGHT_MASK);
    7640                 :             :     }
    7641                 :             :     else
    7642                 :             :     {
    7643                 :        1934 :         len = NUMERIC_HDRSZ + n * sizeof(NumericDigit);
    7644                 :        1934 :         result = (Numeric) palloc(len);
    7645                 :        1934 :         SET_VARSIZE(result, len);
    7646                 :        1934 :         result->choice.n_long.n_sign_dscale =
    7647                 :        1934 :             sign | (var->dscale & NUMERIC_DSCALE_MASK);
    7648                 :        1934 :         result->choice.n_long.n_weight = weight;
    7649                 :             :     }
    7650                 :             : 
    7651                 :             :     Assert(NUMERIC_NDIGITS(result) == n);
    7652         [ +  + ]:     2523607 :     if (n > 0)
    7653         [ +  + ]:     2441430 :         memcpy(NUMERIC_DIGITS(result), digits, n * sizeof(NumericDigit));
    7654                 :             : 
    7655                 :             :     /* Check for overflow of int16 fields */
    7656   [ +  +  +  +  :     2523607 :     if (NUMERIC_WEIGHT(result) != weight ||
                   +  + ]
    7657   [ +  +  -  + ]:     2523587 :         NUMERIC_DSCALE(result) != var->dscale)
    7658         [ +  + ]:          20 :         ereturn(escontext, NULL,
    7659                 :             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    7660                 :             :                  errmsg("value overflows numeric format")));
    7661                 :             : 
    7662                 :             :     dump_numeric("make_result()", result);
    7663                 :     2523587 :     return result;
    7664                 :             : }
    7665                 :             : 
    7666                 :             : 
    7667                 :             : /*
    7668                 :             :  * make_result() -
    7669                 :             :  *
    7670                 :             :  *  An interface to make_result_safe() without "escontext" argument.
    7671                 :             :  */
    7672                 :             : static Numeric
    7673                 :     1504987 : make_result(const NumericVar *var)
    7674                 :             : {
    7675                 :     1504987 :     return make_result_safe(var, NULL);
    7676                 :             : }
    7677                 :             : 
    7678                 :             : 
    7679                 :             : /*
    7680                 :             :  * apply_typmod() -
    7681                 :             :  *
    7682                 :             :  *  Do bounds checking and rounding according to the specified typmod.
    7683                 :             :  *  Note that this is only applied to normal finite values.
    7684                 :             :  *
    7685                 :             :  * Returns true on success, false on failure (if escontext points to an
    7686                 :             :  * ErrorSaveContext; otherwise errors are thrown).
    7687                 :             :  */
    7688                 :             : static bool
    7689                 :      105028 : apply_typmod(NumericVar *var, int32 typmod, Node *escontext)
    7690                 :             : {
    7691                 :             :     int         precision;
    7692                 :             :     int         scale;
    7693                 :             :     int         maxdigits;
    7694                 :             :     int         ddigits;
    7695                 :             :     int         i;
    7696                 :             : 
    7697                 :             :     /* Do nothing if we have an invalid typmod */
    7698         [ +  + ]:      105028 :     if (!is_valid_numeric_typmod(typmod))
    7699                 :       85512 :         return true;
    7700                 :             : 
    7701                 :       19516 :     precision = numeric_typmod_precision(typmod);
    7702                 :       19516 :     scale = numeric_typmod_scale(typmod);
    7703                 :       19516 :     maxdigits = precision - scale;
    7704                 :             : 
    7705                 :             :     /* Round to target scale (and set var->dscale) */
    7706                 :       19516 :     round_var(var, scale);
    7707                 :             : 
    7708                 :             :     /* but don't allow var->dscale to be negative */
    7709         [ +  + ]:       19516 :     if (var->dscale < 0)
    7710                 :         100 :         var->dscale = 0;
    7711                 :             : 
    7712                 :             :     /*
    7713                 :             :      * Check for overflow - note we can't do this before rounding, because
    7714                 :             :      * rounding could raise the weight.  Also note that the var's weight could
    7715                 :             :      * be inflated by leading zeroes, which will be stripped before storage
    7716                 :             :      * but perhaps might not have been yet. In any case, we must recognize a
    7717                 :             :      * true zero, whose weight doesn't mean anything.
    7718                 :             :      */
    7719                 :       19516 :     ddigits = (var->weight + 1) * DEC_DIGITS;
    7720         [ +  + ]:       19516 :     if (ddigits > maxdigits)
    7721                 :             :     {
    7722                 :             :         /* Determine true weight; and check for all-zero result */
    7723         [ +  + ]:        4297 :         for (i = 0; i < var->ndigits; i++)
    7724                 :             :         {
    7725                 :        4286 :             NumericDigit dig = var->digits[i];
    7726                 :             : 
    7727         [ +  - ]:        4286 :             if (dig)
    7728                 :             :             {
    7729                 :             :                 /* Adjust for any high-order decimal zero digits */
    7730                 :             : #if DEC_DIGITS == 4
    7731         [ +  + ]:        4286 :                 if (dig < 10)
    7732                 :         206 :                     ddigits -= 3;
    7733         [ +  + ]:        4080 :                 else if (dig < 100)
    7734                 :         428 :                     ddigits -= 2;
    7735         [ +  + ]:        3652 :                 else if (dig < 1000)
    7736                 :        3640 :                     ddigits -= 1;
    7737                 :             : #elif DEC_DIGITS == 2
    7738                 :             :                 if (dig < 10)
    7739                 :             :                     ddigits -= 1;
    7740                 :             : #elif DEC_DIGITS == 1
    7741                 :             :                 /* no adjustment */
    7742                 :             : #else
    7743                 :             : #error unsupported NBASE
    7744                 :             : #endif
    7745         [ +  + ]:        4286 :                 if (ddigits > maxdigits)
    7746   [ +  +  +  +  :          64 :                     ereturn(escontext, false,
                   +  + ]
    7747                 :             :                             (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    7748                 :             :                              errmsg("numeric field overflow"),
    7749                 :             :                              errdetail("A field with precision %d, scale %d must round to an absolute value less than %s%d.",
    7750                 :             :                                        precision, scale,
    7751                 :             :                     /* Display 10^0 as 1 */
    7752                 :             :                                        maxdigits ? "10^" : "",
    7753                 :             :                                        maxdigits ? maxdigits : 1
    7754                 :             :                                        )));
    7755                 :        4222 :                 break;
    7756                 :             :             }
    7757                 :           0 :             ddigits -= DEC_DIGITS;
    7758                 :             :         }
    7759                 :             :     }
    7760                 :             : 
    7761                 :       19452 :     return true;
    7762                 :             : }
    7763                 :             : 
    7764                 :             : /*
    7765                 :             :  * apply_typmod_special() -
    7766                 :             :  *
    7767                 :             :  *  Do bounds checking according to the specified typmod, for an Inf or NaN.
    7768                 :             :  *  For convenience of most callers, the value is presented in packed form.
    7769                 :             :  *
    7770                 :             :  * Returns true on success, false on failure (if escontext points to an
    7771                 :             :  * ErrorSaveContext; otherwise errors are thrown).
    7772                 :             :  */
    7773                 :             : static bool
    7774                 :        1300 : apply_typmod_special(Numeric num, int32 typmod, Node *escontext)
    7775                 :             : {
    7776                 :             :     int         precision;
    7777                 :             :     int         scale;
    7778                 :             : 
    7779                 :             :     Assert(NUMERIC_IS_SPECIAL(num));    /* caller error if not */
    7780                 :             : 
    7781                 :             :     /*
    7782                 :             :      * NaN is allowed regardless of the typmod; that's rather dubious perhaps,
    7783                 :             :      * but it's a longstanding behavior.  Inf is rejected if we have any
    7784                 :             :      * typmod restriction, since an infinity shouldn't be claimed to fit in
    7785                 :             :      * any finite number of digits.
    7786                 :             :      */
    7787         [ +  + ]:        1300 :     if (NUMERIC_IS_NAN(num))
    7788                 :         557 :         return true;
    7789                 :             : 
    7790                 :             :     /* Do nothing if we have a default typmod (-1) */
    7791         [ +  + ]:         743 :     if (!is_valid_numeric_typmod(typmod))
    7792                 :         731 :         return true;
    7793                 :             : 
    7794                 :          12 :     precision = numeric_typmod_precision(typmod);
    7795                 :          12 :     scale = numeric_typmod_scale(typmod);
    7796                 :             : 
    7797         [ +  - ]:          12 :     ereturn(escontext, false,
    7798                 :             :             (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    7799                 :             :              errmsg("numeric field overflow"),
    7800                 :             :              errdetail("A field with precision %d, scale %d cannot hold an infinite value.",
    7801                 :             :                        precision, scale)));
    7802                 :             : }
    7803                 :             : 
    7804                 :             : 
    7805                 :             : /*
    7806                 :             :  * Convert numeric to int8, rounding if needed.
    7807                 :             :  *
    7808                 :             :  * If overflow, return false (no error is raised).  Return true if okay.
    7809                 :             :  */
    7810                 :             : static bool
    7811                 :        6662 : numericvar_to_int64(const NumericVar *var, int64 *result)
    7812                 :             : {
    7813                 :             :     NumericDigit *digits;
    7814                 :             :     int         ndigits;
    7815                 :             :     int         weight;
    7816                 :             :     int         i;
    7817                 :             :     int64       val;
    7818                 :             :     bool        neg;
    7819                 :             :     NumericVar  rounded;
    7820                 :             : 
    7821                 :             :     /* Round to nearest integer */
    7822                 :        6662 :     init_var(&rounded);
    7823                 :        6662 :     set_var_from_var(var, &rounded);
    7824                 :        6662 :     round_var(&rounded, 0);
    7825                 :             : 
    7826                 :             :     /* Check for zero input */
    7827                 :        6662 :     strip_var(&rounded);
    7828                 :        6662 :     ndigits = rounded.ndigits;
    7829         [ +  + ]:        6662 :     if (ndigits == 0)
    7830                 :             :     {
    7831                 :         348 :         *result = 0;
    7832                 :         348 :         free_var(&rounded);
    7833                 :         348 :         return true;
    7834                 :             :     }
    7835                 :             : 
    7836                 :             :     /*
    7837                 :             :      * For input like 10000000000, we must treat stripped digits as real. So
    7838                 :             :      * the loop assumes there are weight+1 digits before the decimal point.
    7839                 :             :      */
    7840                 :        6314 :     weight = rounded.weight;
    7841                 :             :     Assert(weight >= 0 && ndigits <= weight + 1);
    7842                 :             : 
    7843                 :             :     /*
    7844                 :             :      * Construct the result. To avoid issues with converting a value
    7845                 :             :      * corresponding to INT64_MIN (which can't be represented as a positive 64
    7846                 :             :      * bit two's complement integer), accumulate value as a negative number.
    7847                 :             :      */
    7848                 :        6314 :     digits = rounded.digits;
    7849                 :        6314 :     neg = (rounded.sign == NUMERIC_NEG);
    7850                 :        6314 :     val = -digits[0];
    7851         [ +  + ]:        8788 :     for (i = 1; i <= weight; i++)
    7852                 :             :     {
    7853         [ +  + ]:        2507 :         if (unlikely(pg_mul_s64_overflow(val, NBASE, &val)))
    7854                 :             :         {
    7855                 :          21 :             free_var(&rounded);
    7856                 :          21 :             return false;
    7857                 :             :         }
    7858                 :             : 
    7859         [ +  + ]:        2486 :         if (i < ndigits)
    7860                 :             :         {
    7861         [ +  + ]:        2282 :             if (unlikely(pg_sub_s64_overflow(val, digits[i], &val)))
    7862                 :             :             {
    7863                 :          12 :                 free_var(&rounded);
    7864                 :          12 :                 return false;
    7865                 :             :             }
    7866                 :             :         }
    7867                 :             :     }
    7868                 :             : 
    7869                 :        6281 :     free_var(&rounded);
    7870                 :             : 
    7871         [ +  + ]:        6281 :     if (!neg)
    7872                 :             :     {
    7873         [ +  + ]:        5731 :         if (unlikely(val == PG_INT64_MIN))
    7874                 :          16 :             return false;
    7875                 :        5715 :         val = -val;
    7876                 :             :     }
    7877                 :        6265 :     *result = val;
    7878                 :             : 
    7879                 :        6265 :     return true;
    7880                 :             : }
    7881                 :             : 
    7882                 :             : /*
    7883                 :             :  * Convert int8 value to numeric.
    7884                 :             :  */
    7885                 :             : static void
    7886                 :     1262353 : int64_to_numericvar(int64 val, NumericVar *var)
    7887                 :             : {
    7888                 :             :     uint64      uval,
    7889                 :             :                 newuval;
    7890                 :             :     NumericDigit *ptr;
    7891                 :             :     int         ndigits;
    7892                 :             : 
    7893                 :             :     /* int64 can require at most 19 decimal digits; add one for safety */
    7894                 :     1262353 :     alloc_var(var, 20 / DEC_DIGITS);
    7895         [ +  + ]:     1262353 :     if (val < 0)
    7896                 :             :     {
    7897                 :        1263 :         var->sign = NUMERIC_NEG;
    7898                 :        1263 :         uval = pg_abs_s64(val);
    7899                 :             :     }
    7900                 :             :     else
    7901                 :             :     {
    7902                 :     1261090 :         var->sign = NUMERIC_POS;
    7903                 :     1261090 :         uval = val;
    7904                 :             :     }
    7905                 :     1262353 :     var->dscale = 0;
    7906         [ +  + ]:     1262353 :     if (val == 0)
    7907                 :             :     {
    7908                 :       19379 :         var->ndigits = 0;
    7909                 :       19379 :         var->weight = 0;
    7910                 :       19379 :         return;
    7911                 :             :     }
    7912                 :     1242974 :     ptr = var->digits + var->ndigits;
    7913                 :     1242974 :     ndigits = 0;
    7914                 :             :     do
    7915                 :             :     {
    7916                 :     1440415 :         ptr--;
    7917                 :     1440415 :         ndigits++;
    7918                 :     1440415 :         newuval = uval / NBASE;
    7919                 :     1440415 :         *ptr = uval - newuval * NBASE;
    7920                 :     1440415 :         uval = newuval;
    7921         [ +  + ]:     1440415 :     } while (uval);
    7922                 :     1242974 :     var->digits = ptr;
    7923                 :     1242974 :     var->ndigits = ndigits;
    7924                 :     1242974 :     var->weight = ndigits - 1;
    7925                 :             : }
    7926                 :             : 
    7927                 :             : /*
    7928                 :             :  * Convert numeric to uint64, rounding if needed.
    7929                 :             :  *
    7930                 :             :  * If overflow, return false (no error is raised).  Return true if okay.
    7931                 :             :  */
    7932                 :             : static bool
    7933                 :         100 : numericvar_to_uint64(const NumericVar *var, uint64 *result)
    7934                 :             : {
    7935                 :             :     NumericDigit *digits;
    7936                 :             :     int         ndigits;
    7937                 :             :     int         weight;
    7938                 :             :     int         i;
    7939                 :             :     uint64      val;
    7940                 :             :     NumericVar  rounded;
    7941                 :             : 
    7942                 :             :     /* Round to nearest integer */
    7943                 :         100 :     init_var(&rounded);
    7944                 :         100 :     set_var_from_var(var, &rounded);
    7945                 :         100 :     round_var(&rounded, 0);
    7946                 :             : 
    7947                 :             :     /* Check for zero input */
    7948                 :         100 :     strip_var(&rounded);
    7949                 :         100 :     ndigits = rounded.ndigits;
    7950         [ +  + ]:         100 :     if (ndigits == 0)
    7951                 :             :     {
    7952                 :          15 :         *result = 0;
    7953                 :          15 :         free_var(&rounded);
    7954                 :          15 :         return true;
    7955                 :             :     }
    7956                 :             : 
    7957                 :             :     /* Check for negative input */
    7958         [ +  + ]:          85 :     if (rounded.sign == NUMERIC_NEG)
    7959                 :             :     {
    7960                 :           8 :         free_var(&rounded);
    7961                 :           8 :         return false;
    7962                 :             :     }
    7963                 :             : 
    7964                 :             :     /*
    7965                 :             :      * For input like 10000000000, we must treat stripped digits as real. So
    7966                 :             :      * the loop assumes there are weight+1 digits before the decimal point.
    7967                 :             :      */
    7968                 :          77 :     weight = rounded.weight;
    7969                 :             :     Assert(weight >= 0 && ndigits <= weight + 1);
    7970                 :             : 
    7971                 :             :     /* Construct the result */
    7972                 :          77 :     digits = rounded.digits;
    7973                 :          77 :     val = digits[0];
    7974         [ +  + ]:         218 :     for (i = 1; i <= weight; i++)
    7975                 :             :     {
    7976         [ -  + ]:         149 :         if (unlikely(pg_mul_u64_overflow(val, NBASE, &val)))
    7977                 :             :         {
    7978                 :           0 :             free_var(&rounded);
    7979                 :           0 :             return false;
    7980                 :             :         }
    7981                 :             : 
    7982         [ +  - ]:         149 :         if (i < ndigits)
    7983                 :             :         {
    7984         [ +  + ]:         149 :             if (unlikely(pg_add_u64_overflow(val, digits[i], &val)))
    7985                 :             :             {
    7986                 :           8 :                 free_var(&rounded);
    7987                 :           8 :                 return false;
    7988                 :             :             }
    7989                 :             :         }
    7990                 :             :     }
    7991                 :             : 
    7992                 :          69 :     free_var(&rounded);
    7993                 :             : 
    7994                 :          69 :     *result = val;
    7995                 :             : 
    7996                 :          69 :     return true;
    7997                 :             : }
    7998                 :             : 
    7999                 :             : /*
    8000                 :             :  * Convert 128 bit integer to numeric.
    8001                 :             :  */
    8002                 :             : static void
    8003                 :        6281 : int128_to_numericvar(INT128 val, NumericVar *var)
    8004                 :             : {
    8005                 :             :     int         sign;
    8006                 :             :     NumericDigit *ptr;
    8007                 :             :     int         ndigits;
    8008                 :             :     int32       dig;
    8009                 :             : 
    8010                 :             :     /* int128 can require at most 39 decimal digits; add one for safety */
    8011                 :        6281 :     alloc_var(var, 40 / DEC_DIGITS);
    8012                 :        6281 :     sign = int128_sign(val);
    8013                 :        6281 :     var->sign = sign < 0 ? NUMERIC_NEG : NUMERIC_POS;
    8014                 :        6281 :     var->dscale = 0;
    8015         [ +  + ]:        6281 :     if (sign == 0)
    8016                 :             :     {
    8017                 :         139 :         var->ndigits = 0;
    8018                 :         139 :         var->weight = 0;
    8019                 :         139 :         return;
    8020                 :             :     }
    8021                 :        6142 :     ptr = var->digits + var->ndigits;
    8022                 :        6142 :     ndigits = 0;
    8023                 :             :     do
    8024                 :             :     {
    8025                 :       33048 :         ptr--;
    8026                 :       33048 :         ndigits++;
    8027                 :       33048 :         int128_div_mod_int32(&val, NBASE, &dig);
    8028                 :       33048 :         *ptr = (NumericDigit) abs(dig);
    8029         [ +  + ]:       33048 :     } while (!int128_is_zero(val));
    8030                 :        6142 :     var->digits = ptr;
    8031                 :        6142 :     var->ndigits = ndigits;
    8032                 :        6142 :     var->weight = ndigits - 1;
    8033                 :             : }
    8034                 :             : 
    8035                 :             : /*
    8036                 :             :  * Convert a NumericVar to float8; if out of range, return +/- HUGE_VAL
    8037                 :             :  */
    8038                 :             : static double
    8039                 :         357 : numericvar_to_double_no_overflow(const NumericVar *var)
    8040                 :             : {
    8041                 :             :     char       *tmp;
    8042                 :             :     double      val;
    8043                 :             :     char       *endptr;
    8044                 :             : 
    8045                 :         357 :     tmp = get_str_from_var(var);
    8046                 :             : 
    8047                 :             :     /* unlike float8in, we ignore ERANGE from strtod */
    8048                 :         357 :     val = strtod(tmp, &endptr);
    8049         [ -  + ]:         357 :     if (*endptr != '\0')
    8050                 :             :     {
    8051                 :             :         /* shouldn't happen ... */
    8052         [ #  # ]:           0 :         ereport(ERROR,
    8053                 :             :                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
    8054                 :             :                  errmsg("invalid input syntax for type %s: \"%s\"",
    8055                 :             :                         "double precision", tmp)));
    8056                 :             :     }
    8057                 :             : 
    8058                 :         357 :     pfree(tmp);
    8059                 :             : 
    8060                 :         357 :     return val;
    8061                 :             : }
    8062                 :             : 
    8063                 :             : 
    8064                 :             : /*
    8065                 :             :  * cmp_var() -
    8066                 :             :  *
    8067                 :             :  *  Compare two values on variable level.  We assume zeroes have been
    8068                 :             :  *  truncated to no digits.
    8069                 :             :  */
    8070                 :             : static int
    8071                 :      114439 : cmp_var(const NumericVar *var1, const NumericVar *var2)
    8072                 :             : {
    8073                 :      228878 :     return cmp_var_common(var1->digits, var1->ndigits,
    8074                 :      114439 :                           var1->weight, var1->sign,
    8075                 :      114439 :                           var2->digits, var2->ndigits,
    8076                 :      114439 :                           var2->weight, var2->sign);
    8077                 :             : }
    8078                 :             : 
    8079                 :             : /*
    8080                 :             :  * cmp_var_common() -
    8081                 :             :  *
    8082                 :             :  *  Main routine of cmp_var(). This function can be used by both
    8083                 :             :  *  NumericVar and Numeric.
    8084                 :             :  */
    8085                 :             : static int
    8086                 :    18502474 : cmp_var_common(const NumericDigit *var1digits, int var1ndigits,
    8087                 :             :                int var1weight, int var1sign,
    8088                 :             :                const NumericDigit *var2digits, int var2ndigits,
    8089                 :             :                int var2weight, int var2sign)
    8090                 :             : {
    8091         [ +  + ]:    18502474 :     if (var1ndigits == 0)
    8092                 :             :     {
    8093         [ +  + ]:      422963 :         if (var2ndigits == 0)
    8094                 :      333976 :             return 0;
    8095         [ +  + ]:       88987 :         if (var2sign == NUMERIC_NEG)
    8096                 :         362 :             return 1;
    8097                 :       88625 :         return -1;
    8098                 :             :     }
    8099         [ +  + ]:    18079511 :     if (var2ndigits == 0)
    8100                 :             :     {
    8101         [ +  + ]:       69401 :         if (var1sign == NUMERIC_POS)
    8102                 :       63869 :             return 1;
    8103                 :        5532 :         return -1;
    8104                 :             :     }
    8105                 :             : 
    8106         [ +  + ]:    18010110 :     if (var1sign == NUMERIC_POS)
    8107                 :             :     {
    8108         [ +  + ]:    17963317 :         if (var2sign == NUMERIC_NEG)
    8109                 :       15909 :             return 1;
    8110                 :    17947408 :         return cmp_abs_common(var1digits, var1ndigits, var1weight,
    8111                 :             :                               var2digits, var2ndigits, var2weight);
    8112                 :             :     }
    8113                 :             : 
    8114         [ +  + ]:       46793 :     if (var2sign == NUMERIC_POS)
    8115                 :       13454 :         return -1;
    8116                 :             : 
    8117                 :       33339 :     return cmp_abs_common(var2digits, var2ndigits, var2weight,
    8118                 :             :                           var1digits, var1ndigits, var1weight);
    8119                 :             : }
    8120                 :             : 
    8121                 :             : 
    8122                 :             : /*
    8123                 :             :  * add_var() -
    8124                 :             :  *
    8125                 :             :  *  Full version of add functionality on variable level (handling signs).
    8126                 :             :  *  result might point to one of the operands too without danger.
    8127                 :             :  */
    8128                 :             : static void
    8129                 :      414496 : add_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
    8130                 :             : {
    8131                 :             :     /*
    8132                 :             :      * Decide on the signs of the two variables what to do
    8133                 :             :      */
    8134         [ +  + ]:      414496 :     if (var1->sign == NUMERIC_POS)
    8135                 :             :     {
    8136         [ +  + ]:      413241 :         if (var2->sign == NUMERIC_POS)
    8137                 :             :         {
    8138                 :             :             /*
    8139                 :             :              * Both are positive result = +(ABS(var1) + ABS(var2))
    8140                 :             :              */
    8141                 :      279646 :             add_abs(var1, var2, result);
    8142                 :      279646 :             result->sign = NUMERIC_POS;
    8143                 :             :         }
    8144                 :             :         else
    8145                 :             :         {
    8146                 :             :             /*
    8147                 :             :              * var1 is positive, var2 is negative Must compare absolute values
    8148                 :             :              */
    8149   [ +  +  +  - ]:      133595 :             switch (cmp_abs(var1, var2))
    8150                 :             :             {
    8151                 :         140 :                 case 0:
    8152                 :             :                     /* ----------
    8153                 :             :                      * ABS(var1) == ABS(var2)
    8154                 :             :                      * result = ZERO
    8155                 :             :                      * ----------
    8156                 :             :                      */
    8157                 :         140 :                     zero_var(result);
    8158                 :         140 :                     result->dscale = Max(var1->dscale, var2->dscale);
    8159                 :         140 :                     break;
    8160                 :             : 
    8161                 :      124329 :                 case 1:
    8162                 :             :                     /* ----------
    8163                 :             :                      * ABS(var1) > ABS(var2)
    8164                 :             :                      * result = +(ABS(var1) - ABS(var2))
    8165                 :             :                      * ----------
    8166                 :             :                      */
    8167                 :      124329 :                     sub_abs(var1, var2, result);
    8168                 :      124329 :                     result->sign = NUMERIC_POS;
    8169                 :      124329 :                     break;
    8170                 :             : 
    8171                 :        9126 :                 case -1:
    8172                 :             :                     /* ----------
    8173                 :             :                      * ABS(var1) < ABS(var2)
    8174                 :             :                      * result = -(ABS(var2) - ABS(var1))
    8175                 :             :                      * ----------
    8176                 :             :                      */
    8177                 :        9126 :                     sub_abs(var2, var1, result);
    8178                 :        9126 :                     result->sign = NUMERIC_NEG;
    8179                 :        9126 :                     break;
    8180                 :             :             }
    8181                 :             :         }
    8182                 :             :     }
    8183                 :             :     else
    8184                 :             :     {
    8185         [ +  + ]:        1255 :         if (var2->sign == NUMERIC_POS)
    8186                 :             :         {
    8187                 :             :             /* ----------
    8188                 :             :              * var1 is negative, var2 is positive
    8189                 :             :              * Must compare absolute values
    8190                 :             :              * ----------
    8191                 :             :              */
    8192   [ +  +  +  - ]:         318 :             switch (cmp_abs(var1, var2))
    8193                 :             :             {
    8194                 :          20 :                 case 0:
    8195                 :             :                     /* ----------
    8196                 :             :                      * ABS(var1) == ABS(var2)
    8197                 :             :                      * result = ZERO
    8198                 :             :                      * ----------
    8199                 :             :                      */
    8200                 :          20 :                     zero_var(result);
    8201                 :          20 :                     result->dscale = Max(var1->dscale, var2->dscale);
    8202                 :          20 :                     break;
    8203                 :             : 
    8204                 :         197 :                 case 1:
    8205                 :             :                     /* ----------
    8206                 :             :                      * ABS(var1) > ABS(var2)
    8207                 :             :                      * result = -(ABS(var1) - ABS(var2))
    8208                 :             :                      * ----------
    8209                 :             :                      */
    8210                 :         197 :                     sub_abs(var1, var2, result);
    8211                 :         197 :                     result->sign = NUMERIC_NEG;
    8212                 :         197 :                     break;
    8213                 :             : 
    8214                 :         101 :                 case -1:
    8215                 :             :                     /* ----------
    8216                 :             :                      * ABS(var1) < ABS(var2)
    8217                 :             :                      * result = +(ABS(var2) - ABS(var1))
    8218                 :             :                      * ----------
    8219                 :             :                      */
    8220                 :         101 :                     sub_abs(var2, var1, result);
    8221                 :         101 :                     result->sign = NUMERIC_POS;
    8222                 :         101 :                     break;
    8223                 :             :             }
    8224                 :             :         }
    8225                 :             :         else
    8226                 :             :         {
    8227                 :             :             /* ----------
    8228                 :             :              * Both are negative
    8229                 :             :              * result = -(ABS(var1) + ABS(var2))
    8230                 :             :              * ----------
    8231                 :             :              */
    8232                 :         937 :             add_abs(var1, var2, result);
    8233                 :         937 :             result->sign = NUMERIC_NEG;
    8234                 :             :         }
    8235                 :             :     }
    8236                 :      414496 : }
    8237                 :             : 
    8238                 :             : 
    8239                 :             : /*
    8240                 :             :  * sub_var() -
    8241                 :             :  *
    8242                 :             :  *  Full version of sub functionality on variable level (handling signs).
    8243                 :             :  *  result might point to one of the operands too without danger.
    8244                 :             :  */
    8245                 :             : static void
    8246                 :      351275 : sub_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
    8247                 :             : {
    8248                 :             :     /*
    8249                 :             :      * Decide on the signs of the two variables what to do
    8250                 :             :      */
    8251         [ +  + ]:      351275 :     if (var1->sign == NUMERIC_POS)
    8252                 :             :     {
    8253         [ +  + ]:      350666 :         if (var2->sign == NUMERIC_NEG)
    8254                 :             :         {
    8255                 :             :             /* ----------
    8256                 :             :              * var1 is positive, var2 is negative
    8257                 :             :              * result = +(ABS(var1) + ABS(var2))
    8258                 :             :              * ----------
    8259                 :             :              */
    8260                 :       18811 :             add_abs(var1, var2, result);
    8261                 :       18811 :             result->sign = NUMERIC_POS;
    8262                 :             :         }
    8263                 :             :         else
    8264                 :             :         {
    8265                 :             :             /* ----------
    8266                 :             :              * Both are positive
    8267                 :             :              * Must compare absolute values
    8268                 :             :              * ----------
    8269                 :             :              */
    8270   [ +  +  +  - ]:      331855 :             switch (cmp_abs(var1, var2))
    8271                 :             :             {
    8272                 :       29367 :                 case 0:
    8273                 :             :                     /* ----------
    8274                 :             :                      * ABS(var1) == ABS(var2)
    8275                 :             :                      * result = ZERO
    8276                 :             :                      * ----------
    8277                 :             :                      */
    8278                 :       29367 :                     zero_var(result);
    8279                 :       29367 :                     result->dscale = Max(var1->dscale, var2->dscale);
    8280                 :       29367 :                     break;
    8281                 :             : 
    8282                 :      297463 :                 case 1:
    8283                 :             :                     /* ----------
    8284                 :             :                      * ABS(var1) > ABS(var2)
    8285                 :             :                      * result = +(ABS(var1) - ABS(var2))
    8286                 :             :                      * ----------
    8287                 :             :                      */
    8288                 :      297463 :                     sub_abs(var1, var2, result);
    8289                 :      297463 :                     result->sign = NUMERIC_POS;
    8290                 :      297463 :                     break;
    8291                 :             : 
    8292                 :        5025 :                 case -1:
    8293                 :             :                     /* ----------
    8294                 :             :                      * ABS(var1) < ABS(var2)
    8295                 :             :                      * result = -(ABS(var2) - ABS(var1))
    8296                 :             :                      * ----------
    8297                 :             :                      */
    8298                 :        5025 :                     sub_abs(var2, var1, result);
    8299                 :        5025 :                     result->sign = NUMERIC_NEG;
    8300                 :        5025 :                     break;
    8301                 :             :             }
    8302                 :             :         }
    8303                 :             :     }
    8304                 :             :     else
    8305                 :             :     {
    8306         [ +  + ]:         609 :         if (var2->sign == NUMERIC_NEG)
    8307                 :             :         {
    8308                 :             :             /* ----------
    8309                 :             :              * Both are negative
    8310                 :             :              * Must compare absolute values
    8311                 :             :              * ----------
    8312                 :             :              */
    8313   [ +  +  +  - ]:         304 :             switch (cmp_abs(var1, var2))
    8314                 :             :             {
    8315                 :         110 :                 case 0:
    8316                 :             :                     /* ----------
    8317                 :             :                      * ABS(var1) == ABS(var2)
    8318                 :             :                      * result = ZERO
    8319                 :             :                      * ----------
    8320                 :             :                      */
    8321                 :         110 :                     zero_var(result);
    8322                 :         110 :                     result->dscale = Max(var1->dscale, var2->dscale);
    8323                 :         110 :                     break;
    8324                 :             : 
    8325                 :         162 :                 case 1:
    8326                 :             :                     /* ----------
    8327                 :             :                      * ABS(var1) > ABS(var2)
    8328                 :             :                      * result = -(ABS(var1) - ABS(var2))
    8329                 :             :                      * ----------
    8330                 :             :                      */
    8331                 :         162 :                     sub_abs(var1, var2, result);
    8332                 :         162 :                     result->sign = NUMERIC_NEG;
    8333                 :         162 :                     break;
    8334                 :             : 
    8335                 :          32 :                 case -1:
    8336                 :             :                     /* ----------
    8337                 :             :                      * ABS(var1) < ABS(var2)
    8338                 :             :                      * result = +(ABS(var2) - ABS(var1))
    8339                 :             :                      * ----------
    8340                 :             :                      */
    8341                 :          32 :                     sub_abs(var2, var1, result);
    8342                 :          32 :                     result->sign = NUMERIC_POS;
    8343                 :          32 :                     break;
    8344                 :             :             }
    8345                 :             :         }
    8346                 :             :         else
    8347                 :             :         {
    8348                 :             :             /* ----------
    8349                 :             :              * var1 is negative, var2 is positive
    8350                 :             :              * result = -(ABS(var1) + ABS(var2))
    8351                 :             :              * ----------
    8352                 :             :              */
    8353                 :         305 :             add_abs(var1, var2, result);
    8354                 :         305 :             result->sign = NUMERIC_NEG;
    8355                 :             :         }
    8356                 :             :     }
    8357                 :      351275 : }
    8358                 :             : 
    8359                 :             : 
    8360                 :             : /*
    8361                 :             :  * mul_var() -
    8362                 :             :  *
    8363                 :             :  *  Multiplication on variable level. Product of var1 * var2 is stored
    8364                 :             :  *  in result.  Result is rounded to no more than rscale fractional digits.
    8365                 :             :  */
    8366                 :             : static void
    8367                 :      795598 : mul_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result,
    8368                 :             :         int rscale)
    8369                 :             : {
    8370                 :             :     int         res_ndigits;
    8371                 :             :     int         res_ndigitpairs;
    8372                 :             :     int         res_sign;
    8373                 :             :     int         res_weight;
    8374                 :             :     int         pair_offset;
    8375                 :             :     int         maxdigits;
    8376                 :             :     int         maxdigitpairs;
    8377                 :             :     uint64     *dig,
    8378                 :             :                *dig_i1_off;
    8379                 :             :     uint64      maxdig;
    8380                 :             :     uint64      carry;
    8381                 :             :     uint64      newdig;
    8382                 :             :     int         var1ndigits;
    8383                 :             :     int         var2ndigits;
    8384                 :             :     int         var1ndigitpairs;
    8385                 :             :     int         var2ndigitpairs;
    8386                 :             :     NumericDigit *var1digits;
    8387                 :             :     NumericDigit *var2digits;
    8388                 :             :     uint32      var1digitpair;
    8389                 :             :     uint32     *var2digitpairs;
    8390                 :             :     NumericDigit *res_digits;
    8391                 :             :     int         i,
    8392                 :             :                 i1,
    8393                 :             :                 i2,
    8394                 :             :                 i2limit;
    8395                 :             : 
    8396                 :             :     /*
    8397                 :             :      * Arrange for var1 to be the shorter of the two numbers.  This improves
    8398                 :             :      * performance because the inner multiplication loop is much simpler than
    8399                 :             :      * the outer loop, so it's better to have a smaller number of iterations
    8400                 :             :      * of the outer loop.  This also reduces the number of times that the
    8401                 :             :      * accumulator array needs to be normalized.
    8402                 :             :      */
    8403         [ +  + ]:      795598 :     if (var1->ndigits > var2->ndigits)
    8404                 :             :     {
    8405                 :       10363 :         const NumericVar *tmp = var1;
    8406                 :             : 
    8407                 :       10363 :         var1 = var2;
    8408                 :       10363 :         var2 = tmp;
    8409                 :             :     }
    8410                 :             : 
    8411                 :             :     /* copy these values into local vars for speed in inner loop */
    8412                 :      795598 :     var1ndigits = var1->ndigits;
    8413                 :      795598 :     var2ndigits = var2->ndigits;
    8414                 :      795598 :     var1digits = var1->digits;
    8415                 :      795598 :     var2digits = var2->digits;
    8416                 :             : 
    8417         [ +  + ]:      795598 :     if (var1ndigits == 0)
    8418                 :             :     {
    8419                 :             :         /* one or both inputs is zero; so is result */
    8420                 :        1959 :         zero_var(result);
    8421                 :        1959 :         result->dscale = rscale;
    8422                 :        1959 :         return;
    8423                 :             :     }
    8424                 :             : 
    8425                 :             :     /*
    8426                 :             :      * If var1 has 1-6 digits and the exact result was requested, delegate to
    8427                 :             :      * mul_var_short() which uses a faster direct multiplication algorithm.
    8428                 :             :      */
    8429   [ +  +  +  + ]:      793639 :     if (var1ndigits <= 6 && rscale == var1->dscale + var2->dscale)
    8430                 :             :     {
    8431                 :      772970 :         mul_var_short(var1, var2, result);
    8432                 :      772970 :         return;
    8433                 :             :     }
    8434                 :             : 
    8435                 :             :     /* Determine result sign */
    8436         [ +  + ]:       20669 :     if (var1->sign == var2->sign)
    8437                 :       19390 :         res_sign = NUMERIC_POS;
    8438                 :             :     else
    8439                 :        1279 :         res_sign = NUMERIC_NEG;
    8440                 :             : 
    8441                 :             :     /*
    8442                 :             :      * Determine the number of result digits to compute and the (maximum
    8443                 :             :      * possible) result weight.  If the exact result would have more than
    8444                 :             :      * rscale fractional digits, truncate the computation with
    8445                 :             :      * MUL_GUARD_DIGITS guard digits, i.e., ignore input digits that would
    8446                 :             :      * only contribute to the right of that.  (This will give the exact
    8447                 :             :      * rounded-to-rscale answer unless carries out of the ignored positions
    8448                 :             :      * would have propagated through more than MUL_GUARD_DIGITS digits.)
    8449                 :             :      *
    8450                 :             :      * Note: an exact computation could not produce more than var1ndigits +
    8451                 :             :      * var2ndigits digits, but we allocate at least one extra output digit in
    8452                 :             :      * case rscale-driven rounding produces a carry out of the highest exact
    8453                 :             :      * digit.
    8454                 :             :      *
    8455                 :             :      * The computation itself is done using base-NBASE^2 arithmetic, so we
    8456                 :             :      * actually process the input digits in pairs, producing a base-NBASE^2
    8457                 :             :      * intermediate result.  This significantly improves performance, since
    8458                 :             :      * schoolbook multiplication is O(N^2) in the number of input digits, and
    8459                 :             :      * working in base NBASE^2 effectively halves "N".
    8460                 :             :      *
    8461                 :             :      * Note: in a truncated computation, we must compute at least one extra
    8462                 :             :      * output digit to ensure that all the guard digits are fully computed.
    8463                 :             :      */
    8464                 :             :     /* digit pairs in each input */
    8465                 :       20669 :     var1ndigitpairs = (var1ndigits + 1) / 2;
    8466                 :       20669 :     var2ndigitpairs = (var2ndigits + 1) / 2;
    8467                 :             : 
    8468                 :             :     /* digits in exact result */
    8469                 :       20669 :     res_ndigits = var1ndigits + var2ndigits;
    8470                 :             : 
    8471                 :             :     /* digit pairs in exact result with at least one extra output digit */
    8472                 :       20669 :     res_ndigitpairs = res_ndigits / 2 + 1;
    8473                 :             : 
    8474                 :             :     /* pair offset to align result to end of dig[] */
    8475                 :       20669 :     pair_offset = res_ndigitpairs - var1ndigitpairs - var2ndigitpairs + 1;
    8476                 :             : 
    8477                 :             :     /* maximum possible result weight (odd-length inputs shifted up below) */
    8478                 :       20669 :     res_weight = var1->weight + var2->weight + 1 + 2 * res_ndigitpairs -
    8479                 :       20669 :         res_ndigits - (var1ndigits & 1) - (var2ndigits & 1);
    8480                 :             : 
    8481                 :             :     /* rscale-based truncation with at least one extra output digit */
    8482                 :       20669 :     maxdigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS +
    8483                 :             :         MUL_GUARD_DIGITS;
    8484                 :       20669 :     maxdigitpairs = maxdigits / 2 + 1;
    8485                 :             : 
    8486                 :       20669 :     res_ndigitpairs = Min(res_ndigitpairs, maxdigitpairs);
    8487                 :       20669 :     res_ndigits = 2 * res_ndigitpairs;
    8488                 :             : 
    8489                 :             :     /*
    8490                 :             :      * In the computation below, digit pair i1 of var1 and digit pair i2 of
    8491                 :             :      * var2 are multiplied and added to digit i1+i2+pair_offset of dig[]. Thus
    8492                 :             :      * input digit pairs with index >= res_ndigitpairs - pair_offset don't
    8493                 :             :      * contribute to the result, and can be ignored.
    8494                 :             :      */
    8495         [ +  + ]:       20669 :     if (res_ndigitpairs <= pair_offset)
    8496                 :             :     {
    8497                 :             :         /* All input digits will be ignored; so result is zero */
    8498                 :          10 :         zero_var(result);
    8499                 :          10 :         result->dscale = rscale;
    8500                 :          10 :         return;
    8501                 :             :     }
    8502                 :       20659 :     var1ndigitpairs = Min(var1ndigitpairs, res_ndigitpairs - pair_offset);
    8503                 :       20659 :     var2ndigitpairs = Min(var2ndigitpairs, res_ndigitpairs - pair_offset);
    8504                 :             : 
    8505                 :             :     /*
    8506                 :             :      * We do the arithmetic in an array "dig[]" of unsigned 64-bit integers.
    8507                 :             :      * Since PG_UINT64_MAX is much larger than NBASE^4, this gives us a lot of
    8508                 :             :      * headroom to avoid normalizing carries immediately.
    8509                 :             :      *
    8510                 :             :      * maxdig tracks the maximum possible value of any dig[] entry; when this
    8511                 :             :      * threatens to exceed PG_UINT64_MAX, we take the time to propagate
    8512                 :             :      * carries.  Furthermore, we need to ensure that overflow doesn't occur
    8513                 :             :      * during the carry propagation passes either.  The carry values could be
    8514                 :             :      * as much as PG_UINT64_MAX / NBASE^2, so really we must normalize when
    8515                 :             :      * digits threaten to exceed PG_UINT64_MAX - PG_UINT64_MAX / NBASE^2.
    8516                 :             :      *
    8517                 :             :      * To avoid overflow in maxdig itself, it actually represents the maximum
    8518                 :             :      * possible value divided by NBASE^2-1, i.e., at the top of the loop it is
    8519                 :             :      * known that no dig[] entry exceeds maxdig * (NBASE^2-1).
    8520                 :             :      *
    8521                 :             :      * The conversion of var1 to base NBASE^2 is done on the fly, as each new
    8522                 :             :      * digit is required.  The digits of var2 are converted upfront, and
    8523                 :             :      * stored at the end of dig[].  To avoid loss of precision, the input
    8524                 :             :      * digits are aligned with the start of digit pair array, effectively
    8525                 :             :      * shifting them up (multiplying by NBASE) if the inputs have an odd
    8526                 :             :      * number of NBASE digits.
    8527                 :             :      */
    8528                 :       20659 :     dig = (uint64 *) palloc(res_ndigitpairs * sizeof(uint64) +
    8529                 :             :                             var2ndigitpairs * sizeof(uint32));
    8530                 :             : 
    8531                 :             :     /* convert var2 to base NBASE^2, shifting up if its length is odd */
    8532                 :       20659 :     var2digitpairs = (uint32 *) (dig + res_ndigitpairs);
    8533                 :             : 
    8534         [ +  + ]:     1048389 :     for (i2 = 0; i2 < var2ndigitpairs - 1; i2++)
    8535                 :     1027730 :         var2digitpairs[i2] = var2digits[2 * i2] * NBASE + var2digits[2 * i2 + 1];
    8536                 :             : 
    8537         [ +  + ]:       20659 :     if (2 * i2 + 1 < var2ndigits)
    8538                 :       14659 :         var2digitpairs[i2] = var2digits[2 * i2] * NBASE + var2digits[2 * i2 + 1];
    8539                 :             :     else
    8540                 :        6000 :         var2digitpairs[i2] = var2digits[2 * i2] * NBASE;
    8541                 :             : 
    8542                 :             :     /*
    8543                 :             :      * Start by multiplying var2 by the least significant contributing digit
    8544                 :             :      * pair from var1, storing the results at the end of dig[], and filling
    8545                 :             :      * the leading digits with zeros.
    8546                 :             :      *
    8547                 :             :      * The loop here is the same as the inner loop below, except that we set
    8548                 :             :      * the results in dig[], rather than adding to them.  This is the
    8549                 :             :      * performance bottleneck for multiplication, so we want to keep it simple
    8550                 :             :      * enough so that it can be auto-vectorized.  Accordingly, process the
    8551                 :             :      * digits left-to-right even though schoolbook multiplication would
    8552                 :             :      * suggest right-to-left.  Since we aren't propagating carries in this
    8553                 :             :      * loop, the order does not matter.
    8554                 :             :      */
    8555                 :       20659 :     i1 = var1ndigitpairs - 1;
    8556         [ +  + ]:       20659 :     if (2 * i1 + 1 < var1ndigits)
    8557                 :        9183 :         var1digitpair = var1digits[2 * i1] * NBASE + var1digits[2 * i1 + 1];
    8558                 :             :     else
    8559                 :       11476 :         var1digitpair = var1digits[2 * i1] * NBASE;
    8560                 :       20659 :     maxdig = var1digitpair;
    8561                 :             : 
    8562                 :       20659 :     i2limit = Min(var2ndigitpairs, res_ndigitpairs - i1 - pair_offset);
    8563                 :       20659 :     dig_i1_off = &dig[i1 + pair_offset];
    8564                 :             : 
    8565                 :       20659 :     memset(dig, 0, (i1 + pair_offset) * sizeof(uint64));
    8566         [ +  + ]:      930539 :     for (i2 = 0; i2 < i2limit; i2++)
    8567                 :      909880 :         dig_i1_off[i2] = (uint64) var1digitpair * var2digitpairs[i2];
    8568                 :             : 
    8569                 :             :     /*
    8570                 :             :      * Next, multiply var2 by the remaining digit pairs from var1, adding the
    8571                 :             :      * results to dig[] at the appropriate offsets, and normalizing whenever
    8572                 :             :      * there is a risk of any dig[] entry overflowing.
    8573                 :             :      */
    8574         [ +  + ]:     1012436 :     for (i1 = i1 - 1; i1 >= 0; i1--)
    8575                 :             :     {
    8576                 :      991777 :         var1digitpair = var1digits[2 * i1] * NBASE + var1digits[2 * i1 + 1];
    8577         [ +  + ]:      991777 :         if (var1digitpair == 0)
    8578                 :      786344 :             continue;
    8579                 :             : 
    8580                 :             :         /* Time to normalize? */
    8581                 :      205433 :         maxdig += var1digitpair;
    8582         [ +  + ]:      205433 :         if (maxdig > (PG_UINT64_MAX - PG_UINT64_MAX / NBASE_SQR) / (NBASE_SQR - 1))
    8583                 :             :         {
    8584                 :             :             /* Yes, do it (to base NBASE^2) */
    8585                 :          21 :             carry = 0;
    8586         [ +  + ]:       84074 :             for (i = res_ndigitpairs - 1; i >= 0; i--)
    8587                 :             :             {
    8588                 :       84053 :                 newdig = dig[i] + carry;
    8589         [ +  + ]:       84053 :                 if (newdig >= NBASE_SQR)
    8590                 :             :                 {
    8591                 :       80719 :                     carry = newdig / NBASE_SQR;
    8592                 :       80719 :                     newdig -= carry * NBASE_SQR;
    8593                 :             :                 }
    8594                 :             :                 else
    8595                 :        3334 :                     carry = 0;
    8596                 :       84053 :                 dig[i] = newdig;
    8597                 :             :             }
    8598                 :             :             Assert(carry == 0);
    8599                 :             :             /* Reset maxdig to indicate new worst-case */
    8600                 :          21 :             maxdig = 1 + var1digitpair;
    8601                 :             :         }
    8602                 :             : 
    8603                 :             :         /* Multiply and add */
    8604                 :      205433 :         i2limit = Min(var2ndigitpairs, res_ndigitpairs - i1 - pair_offset);
    8605                 :      205433 :         dig_i1_off = &dig[i1 + pair_offset];
    8606                 :             : 
    8607         [ +  + ]:    87005259 :         for (i2 = 0; i2 < i2limit; i2++)
    8608                 :    86799826 :             dig_i1_off[i2] += (uint64) var1digitpair * var2digitpairs[i2];
    8609                 :             :     }
    8610                 :             : 
    8611                 :             :     /*
    8612                 :             :      * Now we do a final carry propagation pass to normalize back to base
    8613                 :             :      * NBASE^2, and construct the base-NBASE result digits.  Note that this is
    8614                 :             :      * still done at full precision w/guard digits.
    8615                 :             :      */
    8616                 :       20659 :     alloc_var(result, res_ndigits);
    8617                 :       20659 :     res_digits = result->digits;
    8618                 :       20659 :     carry = 0;
    8619         [ +  + ]:     1946324 :     for (i = res_ndigitpairs - 1; i >= 0; i--)
    8620                 :             :     {
    8621                 :     1925665 :         newdig = dig[i] + carry;
    8622         [ +  + ]:     1925665 :         if (newdig >= NBASE_SQR)
    8623                 :             :         {
    8624                 :      290140 :             carry = newdig / NBASE_SQR;
    8625                 :      290140 :             newdig -= carry * NBASE_SQR;
    8626                 :             :         }
    8627                 :             :         else
    8628                 :     1635525 :             carry = 0;
    8629                 :     1925665 :         res_digits[2 * i + 1] = (NumericDigit) ((uint32) newdig % NBASE);
    8630                 :     1925665 :         res_digits[2 * i] = (NumericDigit) ((uint32) newdig / NBASE);
    8631                 :             :     }
    8632                 :             :     Assert(carry == 0);
    8633                 :             : 
    8634                 :       20659 :     pfree(dig);
    8635                 :             : 
    8636                 :             :     /*
    8637                 :             :      * Finally, round the result to the requested precision.
    8638                 :             :      */
    8639                 :       20659 :     result->weight = res_weight;
    8640                 :       20659 :     result->sign = res_sign;
    8641                 :             : 
    8642                 :             :     /* Round to target rscale (and set result->dscale) */
    8643                 :       20659 :     round_var(result, rscale);
    8644                 :             : 
    8645                 :             :     /* Strip leading and trailing zeroes */
    8646                 :       20659 :     strip_var(result);
    8647                 :             : }
    8648                 :             : 
    8649                 :             : 
    8650                 :             : /*
    8651                 :             :  * mul_var_short() -
    8652                 :             :  *
    8653                 :             :  *  Special-case multiplication function used when var1 has 1-6 digits, var2
    8654                 :             :  *  has at least as many digits as var1, and the exact product var1 * var2 is
    8655                 :             :  *  requested.
    8656                 :             :  */
    8657                 :             : static void
    8658                 :      772970 : mul_var_short(const NumericVar *var1, const NumericVar *var2,
    8659                 :             :               NumericVar *result)
    8660                 :             : {
    8661                 :      772970 :     int         var1ndigits = var1->ndigits;
    8662                 :      772970 :     int         var2ndigits = var2->ndigits;
    8663                 :      772970 :     NumericDigit *var1digits = var1->digits;
    8664                 :      772970 :     NumericDigit *var2digits = var2->digits;
    8665                 :             :     int         res_sign;
    8666                 :             :     int         res_weight;
    8667                 :             :     int         res_ndigits;
    8668                 :             :     NumericDigit *res_buf;
    8669                 :             :     NumericDigit *res_digits;
    8670                 :      772970 :     uint32      carry = 0;
    8671                 :             :     uint32      term;
    8672                 :             : 
    8673                 :             :     /* Check preconditions */
    8674                 :             :     Assert(var1ndigits >= 1);
    8675                 :             :     Assert(var1ndigits <= 6);
    8676                 :             :     Assert(var2ndigits >= var1ndigits);
    8677                 :             : 
    8678                 :             :     /*
    8679                 :             :      * Determine the result sign, weight, and number of digits to calculate.
    8680                 :             :      * The weight figured here is correct if the product has no leading zero
    8681                 :             :      * digits; otherwise strip_var() will fix things up.  Note that, unlike
    8682                 :             :      * mul_var(), we do not need to allocate an extra output digit, because we
    8683                 :             :      * are not rounding here.
    8684                 :             :      */
    8685         [ +  + ]:      772970 :     if (var1->sign == var2->sign)
    8686                 :      772163 :         res_sign = NUMERIC_POS;
    8687                 :             :     else
    8688                 :         807 :         res_sign = NUMERIC_NEG;
    8689                 :      772970 :     res_weight = var1->weight + var2->weight + 1;
    8690                 :      772970 :     res_ndigits = var1ndigits + var2ndigits;
    8691                 :             : 
    8692                 :             :     /* Allocate result digit array */
    8693                 :      772970 :     res_buf = digitbuf_alloc(res_ndigits + 1);
    8694                 :      772970 :     res_buf[0] = 0;             /* spare digit for later rounding */
    8695                 :      772970 :     res_digits = res_buf + 1;
    8696                 :             : 
    8697                 :             :     /*
    8698                 :             :      * Compute the result digits in reverse, in one pass, propagating the
    8699                 :             :      * carry up as we go.  The i'th result digit consists of the sum of the
    8700                 :             :      * products var1digits[i1] * var2digits[i2] for which i = i1 + i2 + 1.
    8701                 :             :      */
    8702                 :             : #define PRODSUM1(v1,i1,v2,i2) ((v1)[(i1)] * (v2)[(i2)])
    8703                 :             : #define PRODSUM2(v1,i1,v2,i2) (PRODSUM1(v1,i1,v2,i2) + (v1)[(i1)+1] * (v2)[(i2)-1])
    8704                 :             : #define PRODSUM3(v1,i1,v2,i2) (PRODSUM2(v1,i1,v2,i2) + (v1)[(i1)+2] * (v2)[(i2)-2])
    8705                 :             : #define PRODSUM4(v1,i1,v2,i2) (PRODSUM3(v1,i1,v2,i2) + (v1)[(i1)+3] * (v2)[(i2)-3])
    8706                 :             : #define PRODSUM5(v1,i1,v2,i2) (PRODSUM4(v1,i1,v2,i2) + (v1)[(i1)+4] * (v2)[(i2)-4])
    8707                 :             : #define PRODSUM6(v1,i1,v2,i2) (PRODSUM5(v1,i1,v2,i2) + (v1)[(i1)+5] * (v2)[(i2)-5])
    8708                 :             : 
    8709   [ +  +  +  +  :      772970 :     switch (var1ndigits)
                +  +  - ]
    8710                 :             :     {
    8711                 :      768825 :         case 1:
    8712                 :             :             /* ---------
    8713                 :             :              * 1-digit case:
    8714                 :             :              *      var1ndigits = 1
    8715                 :             :              *      var2ndigits >= 1
    8716                 :             :              *      res_ndigits = var2ndigits + 1
    8717                 :             :              * ----------
    8718                 :             :              */
    8719         [ +  + ]:     2406189 :             for (int i = var2ndigits - 1; i >= 0; i--)
    8720                 :             :             {
    8721                 :     1637364 :                 term = PRODSUM1(var1digits, 0, var2digits, i) + carry;
    8722                 :     1637364 :                 res_digits[i + 1] = (NumericDigit) (term % NBASE);
    8723                 :     1637364 :                 carry = term / NBASE;
    8724                 :             :             }
    8725                 :      768825 :             res_digits[0] = (NumericDigit) carry;
    8726                 :      768825 :             break;
    8727                 :             : 
    8728                 :         519 :         case 2:
    8729                 :             :             /* ---------
    8730                 :             :              * 2-digit case:
    8731                 :             :              *      var1ndigits = 2
    8732                 :             :              *      var2ndigits >= 2
    8733                 :             :              *      res_ndigits = var2ndigits + 2
    8734                 :             :              * ----------
    8735                 :             :              */
    8736                 :             :             /* last result digit and carry */
    8737                 :         519 :             term = PRODSUM1(var1digits, 1, var2digits, var2ndigits - 1);
    8738                 :         519 :             res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
    8739                 :         519 :             carry = term / NBASE;
    8740                 :             : 
    8741                 :             :             /* remaining digits, except for the first two */
    8742         [ +  + ]:        1573 :             for (int i = var2ndigits - 1; i >= 1; i--)
    8743                 :             :             {
    8744                 :        1054 :                 term = PRODSUM2(var1digits, 0, var2digits, i) + carry;
    8745                 :        1054 :                 res_digits[i + 1] = (NumericDigit) (term % NBASE);
    8746                 :        1054 :                 carry = term / NBASE;
    8747                 :             :             }
    8748                 :         519 :             break;
    8749                 :             : 
    8750                 :         146 :         case 3:
    8751                 :             :             /* ---------
    8752                 :             :              * 3-digit case:
    8753                 :             :              *      var1ndigits = 3
    8754                 :             :              *      var2ndigits >= 3
    8755                 :             :              *      res_ndigits = var2ndigits + 3
    8756                 :             :              * ----------
    8757                 :             :              */
    8758                 :             :             /* last two result digits */
    8759                 :         146 :             term = PRODSUM1(var1digits, 2, var2digits, var2ndigits - 1);
    8760                 :         146 :             res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
    8761                 :         146 :             carry = term / NBASE;
    8762                 :             : 
    8763                 :         146 :             term = PRODSUM2(var1digits, 1, var2digits, var2ndigits - 1) + carry;
    8764                 :         146 :             res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
    8765                 :         146 :             carry = term / NBASE;
    8766                 :             : 
    8767                 :             :             /* remaining digits, except for the first three */
    8768         [ +  + ]:         387 :             for (int i = var2ndigits - 1; i >= 2; i--)
    8769                 :             :             {
    8770                 :         241 :                 term = PRODSUM3(var1digits, 0, var2digits, i) + carry;
    8771                 :         241 :                 res_digits[i + 1] = (NumericDigit) (term % NBASE);
    8772                 :         241 :                 carry = term / NBASE;
    8773                 :             :             }
    8774                 :         146 :             break;
    8775                 :             : 
    8776                 :        2888 :         case 4:
    8777                 :             :             /* ---------
    8778                 :             :              * 4-digit case:
    8779                 :             :              *      var1ndigits = 4
    8780                 :             :              *      var2ndigits >= 4
    8781                 :             :              *      res_ndigits = var2ndigits + 4
    8782                 :             :              * ----------
    8783                 :             :              */
    8784                 :             :             /* last three result digits */
    8785                 :        2888 :             term = PRODSUM1(var1digits, 3, var2digits, var2ndigits - 1);
    8786                 :        2888 :             res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
    8787                 :        2888 :             carry = term / NBASE;
    8788                 :             : 
    8789                 :        2888 :             term = PRODSUM2(var1digits, 2, var2digits, var2ndigits - 1) + carry;
    8790                 :        2888 :             res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
    8791                 :        2888 :             carry = term / NBASE;
    8792                 :             : 
    8793                 :        2888 :             term = PRODSUM3(var1digits, 1, var2digits, var2ndigits - 1) + carry;
    8794                 :        2888 :             res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
    8795                 :        2888 :             carry = term / NBASE;
    8796                 :             : 
    8797                 :             :             /* remaining digits, except for the first four */
    8798         [ +  + ]:        8058 :             for (int i = var2ndigits - 1; i >= 3; i--)
    8799                 :             :             {
    8800                 :        5170 :                 term = PRODSUM4(var1digits, 0, var2digits, i) + carry;
    8801                 :        5170 :                 res_digits[i + 1] = (NumericDigit) (term % NBASE);
    8802                 :        5170 :                 carry = term / NBASE;
    8803                 :             :             }
    8804                 :        2888 :             break;
    8805                 :             : 
    8806                 :          91 :         case 5:
    8807                 :             :             /* ---------
    8808                 :             :              * 5-digit case:
    8809                 :             :              *      var1ndigits = 5
    8810                 :             :              *      var2ndigits >= 5
    8811                 :             :              *      res_ndigits = var2ndigits + 5
    8812                 :             :              * ----------
    8813                 :             :              */
    8814                 :             :             /* last four result digits */
    8815                 :          91 :             term = PRODSUM1(var1digits, 4, var2digits, var2ndigits - 1);
    8816                 :          91 :             res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
    8817                 :          91 :             carry = term / NBASE;
    8818                 :             : 
    8819                 :          91 :             term = PRODSUM2(var1digits, 3, var2digits, var2ndigits - 1) + carry;
    8820                 :          91 :             res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
    8821                 :          91 :             carry = term / NBASE;
    8822                 :             : 
    8823                 :          91 :             term = PRODSUM3(var1digits, 2, var2digits, var2ndigits - 1) + carry;
    8824                 :          91 :             res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
    8825                 :          91 :             carry = term / NBASE;
    8826                 :             : 
    8827                 :          91 :             term = PRODSUM4(var1digits, 1, var2digits, var2ndigits - 1) + carry;
    8828                 :          91 :             res_digits[res_ndigits - 4] = (NumericDigit) (term % NBASE);
    8829                 :          91 :             carry = term / NBASE;
    8830                 :             : 
    8831                 :             :             /* remaining digits, except for the first five */
    8832         [ +  + ]:         242 :             for (int i = var2ndigits - 1; i >= 4; i--)
    8833                 :             :             {
    8834                 :         151 :                 term = PRODSUM5(var1digits, 0, var2digits, i) + carry;
    8835                 :         151 :                 res_digits[i + 1] = (NumericDigit) (term % NBASE);
    8836                 :         151 :                 carry = term / NBASE;
    8837                 :             :             }
    8838                 :          91 :             break;
    8839                 :             : 
    8840                 :         501 :         case 6:
    8841                 :             :             /* ---------
    8842                 :             :              * 6-digit case:
    8843                 :             :              *      var1ndigits = 6
    8844                 :             :              *      var2ndigits >= 6
    8845                 :             :              *      res_ndigits = var2ndigits + 6
    8846                 :             :              * ----------
    8847                 :             :              */
    8848                 :             :             /* last five result digits */
    8849                 :         501 :             term = PRODSUM1(var1digits, 5, var2digits, var2ndigits - 1);
    8850                 :         501 :             res_digits[res_ndigits - 1] = (NumericDigit) (term % NBASE);
    8851                 :         501 :             carry = term / NBASE;
    8852                 :             : 
    8853                 :         501 :             term = PRODSUM2(var1digits, 4, var2digits, var2ndigits - 1) + carry;
    8854                 :         501 :             res_digits[res_ndigits - 2] = (NumericDigit) (term % NBASE);
    8855                 :         501 :             carry = term / NBASE;
    8856                 :             : 
    8857                 :         501 :             term = PRODSUM3(var1digits, 3, var2digits, var2ndigits - 1) + carry;
    8858                 :         501 :             res_digits[res_ndigits - 3] = (NumericDigit) (term % NBASE);
    8859                 :         501 :             carry = term / NBASE;
    8860                 :             : 
    8861                 :         501 :             term = PRODSUM4(var1digits, 2, var2digits, var2ndigits - 1) + carry;
    8862                 :         501 :             res_digits[res_ndigits - 4] = (NumericDigit) (term % NBASE);
    8863                 :         501 :             carry = term / NBASE;
    8864                 :             : 
    8865                 :         501 :             term = PRODSUM5(var1digits, 1, var2digits, var2ndigits - 1) + carry;
    8866                 :         501 :             res_digits[res_ndigits - 5] = (NumericDigit) (term % NBASE);
    8867                 :         501 :             carry = term / NBASE;
    8868                 :             : 
    8869                 :             :             /* remaining digits, except for the first six */
    8870         [ +  + ]:        1400 :             for (int i = var2ndigits - 1; i >= 5; i--)
    8871                 :             :             {
    8872                 :         899 :                 term = PRODSUM6(var1digits, 0, var2digits, i) + carry;
    8873                 :         899 :                 res_digits[i + 1] = (NumericDigit) (term % NBASE);
    8874                 :         899 :                 carry = term / NBASE;
    8875                 :             :             }
    8876                 :         501 :             break;
    8877                 :             :     }
    8878                 :             : 
    8879                 :             :     /*
    8880                 :             :      * Finally, for var1ndigits > 1, compute the remaining var1ndigits most
    8881                 :             :      * significant result digits.
    8882                 :             :      */
    8883   [ +  +  +  +  :      772970 :     switch (var1ndigits)
                   +  + ]
    8884                 :             :     {
    8885                 :         501 :         case 6:
    8886                 :         501 :             term = PRODSUM5(var1digits, 0, var2digits, 4) + carry;
    8887                 :         501 :             res_digits[5] = (NumericDigit) (term % NBASE);
    8888                 :         501 :             carry = term / NBASE;
    8889                 :             :             pg_fallthrough;
    8890                 :         592 :         case 5:
    8891                 :         592 :             term = PRODSUM4(var1digits, 0, var2digits, 3) + carry;
    8892                 :         592 :             res_digits[4] = (NumericDigit) (term % NBASE);
    8893                 :         592 :             carry = term / NBASE;
    8894                 :             :             pg_fallthrough;
    8895                 :        3480 :         case 4:
    8896                 :        3480 :             term = PRODSUM3(var1digits, 0, var2digits, 2) + carry;
    8897                 :        3480 :             res_digits[3] = (NumericDigit) (term % NBASE);
    8898                 :        3480 :             carry = term / NBASE;
    8899                 :             :             pg_fallthrough;
    8900                 :        3626 :         case 3:
    8901                 :        3626 :             term = PRODSUM2(var1digits, 0, var2digits, 1) + carry;
    8902                 :        3626 :             res_digits[2] = (NumericDigit) (term % NBASE);
    8903                 :        3626 :             carry = term / NBASE;
    8904                 :             :             pg_fallthrough;
    8905                 :        4145 :         case 2:
    8906                 :        4145 :             term = PRODSUM1(var1digits, 0, var2digits, 0) + carry;
    8907                 :        4145 :             res_digits[1] = (NumericDigit) (term % NBASE);
    8908                 :        4145 :             res_digits[0] = (NumericDigit) (term / NBASE);
    8909                 :        4145 :             break;
    8910                 :             :     }
    8911                 :             : 
    8912                 :             :     /* Store the product in result */
    8913         [ +  + ]:      772970 :     digitbuf_free(result->buf);
    8914                 :      772970 :     result->ndigits = res_ndigits;
    8915                 :      772970 :     result->buf = res_buf;
    8916                 :      772970 :     result->digits = res_digits;
    8917                 :      772970 :     result->weight = res_weight;
    8918                 :      772970 :     result->sign = res_sign;
    8919                 :      772970 :     result->dscale = var1->dscale + var2->dscale;
    8920                 :             : 
    8921                 :             :     /* Strip leading and trailing zeroes */
    8922                 :      772970 :     strip_var(result);
    8923                 :      772970 : }
    8924                 :             : 
    8925                 :             : 
    8926                 :             : /*
    8927                 :             :  * div_var() -
    8928                 :             :  *
    8929                 :             :  *  Compute the quotient var1 / var2 to rscale fractional digits.
    8930                 :             :  *
    8931                 :             :  *  If "round" is true, the result is rounded at the rscale'th digit; if
    8932                 :             :  *  false, it is truncated (towards zero) at that digit.
    8933                 :             :  *
    8934                 :             :  *  If "exact" is true, the exact result is computed to the specified rscale;
    8935                 :             :  *  if false, successive quotient digits are approximated up to rscale plus
    8936                 :             :  *  DIV_GUARD_DIGITS extra digits, ignoring all contributions from digits to
    8937                 :             :  *  the right of that, before rounding or truncating to the specified rscale.
    8938                 :             :  *  This can be significantly faster, and usually gives the same result as the
    8939                 :             :  *  exact computation, but it may occasionally be off by one in the final
    8940                 :             :  *  digit, if contributions from the ignored digits would have propagated
    8941                 :             :  *  through the guard digits.  This is good enough for the transcendental
    8942                 :             :  *  functions, where small errors are acceptable.
    8943                 :             :  */
    8944                 :             : static void
    8945                 :      380360 : div_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result,
    8946                 :             :         int rscale, bool round, bool exact)
    8947                 :             : {
    8948                 :      380360 :     int         var1ndigits = var1->ndigits;
    8949                 :      380360 :     int         var2ndigits = var2->ndigits;
    8950                 :             :     int         res_sign;
    8951                 :             :     int         res_weight;
    8952                 :             :     int         res_ndigits;
    8953                 :             :     int         var1ndigitpairs;
    8954                 :             :     int         var2ndigitpairs;
    8955                 :             :     int         res_ndigitpairs;
    8956                 :             :     int         div_ndigitpairs;
    8957                 :             :     int64      *dividend;
    8958                 :             :     int32      *divisor;
    8959                 :             :     double      fdivisor,
    8960                 :             :                 fdivisorinverse,
    8961                 :             :                 fdividend,
    8962                 :             :                 fquotient;
    8963                 :             :     int64       maxdiv;
    8964                 :             :     int         qi;
    8965                 :             :     int32       qdigit;
    8966                 :             :     int64       carry;
    8967                 :             :     int64       newdig;
    8968                 :             :     int64      *remainder;
    8969                 :             :     NumericDigit *res_digits;
    8970                 :             :     int         i;
    8971                 :             : 
    8972                 :             :     /*
    8973                 :             :      * First of all division by zero check; we must not be handed an
    8974                 :             :      * unnormalized divisor.
    8975                 :             :      */
    8976   [ +  +  -  + ]:      380360 :     if (var2ndigits == 0 || var2->digits[0] == 0)
    8977         [ +  - ]:           8 :         ereport(ERROR,
    8978                 :             :                 (errcode(ERRCODE_DIVISION_BY_ZERO),
    8979                 :             :                  errmsg("division by zero")));
    8980                 :             : 
    8981                 :             :     /*
    8982                 :             :      * If the divisor has just one or two digits, delegate to div_var_int(),
    8983                 :             :      * which uses fast short division.
    8984                 :             :      *
    8985                 :             :      * Similarly, on platforms with 128-bit integer support, delegate to
    8986                 :             :      * div_var_int64() for divisors with three or four digits.
    8987                 :             :      */
    8988         [ +  + ]:      380352 :     if (var2ndigits <= 2)
    8989                 :             :     {
    8990                 :             :         int         idivisor;
    8991                 :             :         int         idivisor_weight;
    8992                 :             : 
    8993                 :      376000 :         idivisor = var2->digits[0];
    8994                 :      376000 :         idivisor_weight = var2->weight;
    8995         [ +  + ]:      376000 :         if (var2ndigits == 2)
    8996                 :             :         {
    8997                 :        2208 :             idivisor = idivisor * NBASE + var2->digits[1];
    8998                 :        2208 :             idivisor_weight--;
    8999                 :             :         }
    9000         [ +  + ]:      376000 :         if (var2->sign == NUMERIC_NEG)
    9001                 :         440 :             idivisor = -idivisor;
    9002                 :             : 
    9003                 :      376000 :         div_var_int(var1, idivisor, idivisor_weight, result, rscale, round);
    9004                 :      376000 :         return;
    9005                 :             :     }
    9006                 :             : #ifdef HAVE_INT128
    9007         [ +  + ]:        4352 :     if (var2ndigits <= 4)
    9008                 :             :     {
    9009                 :             :         int64       idivisor;
    9010                 :             :         int         idivisor_weight;
    9011                 :             : 
    9012                 :         360 :         idivisor = var2->digits[0];
    9013                 :         360 :         idivisor_weight = var2->weight;
    9014         [ +  + ]:        1340 :         for (i = 1; i < var2ndigits; i++)
    9015                 :             :         {
    9016                 :         980 :             idivisor = idivisor * NBASE + var2->digits[i];
    9017                 :         980 :             idivisor_weight--;
    9018                 :             :         }
    9019         [ +  + ]:         360 :         if (var2->sign == NUMERIC_NEG)
    9020                 :          80 :             idivisor = -idivisor;
    9021                 :             : 
    9022                 :         360 :         div_var_int64(var1, idivisor, idivisor_weight, result, rscale, round);
    9023                 :         360 :         return;
    9024                 :             :     }
    9025                 :             : #endif
    9026                 :             : 
    9027                 :             :     /*
    9028                 :             :      * Otherwise, perform full long division.
    9029                 :             :      */
    9030                 :             : 
    9031                 :             :     /* Result zero check */
    9032         [ +  + ]:        3992 :     if (var1ndigits == 0)
    9033                 :             :     {
    9034                 :          24 :         zero_var(result);
    9035                 :          24 :         result->dscale = rscale;
    9036                 :          24 :         return;
    9037                 :             :     }
    9038                 :             : 
    9039                 :             :     /*
    9040                 :             :      * The approximate computation can be significantly faster than the exact
    9041                 :             :      * one, since the working dividend is var2ndigitpairs base-NBASE^2 digits
    9042                 :             :      * shorter below.  However, that comes with the tradeoff of computing
    9043                 :             :      * DIV_GUARD_DIGITS extra base-NBASE result digits.  Ignoring all other
    9044                 :             :      * overheads, that suggests that, in theory, the approximate computation
    9045                 :             :      * will only be faster than the exact one when var2ndigits is greater than
    9046                 :             :      * 2 * (DIV_GUARD_DIGITS + 1), independent of the size of var1.
    9047                 :             :      *
    9048                 :             :      * Thus, we're better off doing an exact computation when var2 is shorter
    9049                 :             :      * than this.  Empirically, it has been found that the exact threshold is
    9050                 :             :      * a little higher, due to other overheads in the outer division loop.
    9051                 :             :      */
    9052         [ +  + ]:        3968 :     if (var2ndigits <= 2 * (DIV_GUARD_DIGITS + 2))
    9053                 :        2712 :         exact = true;
    9054                 :             : 
    9055                 :             :     /*
    9056                 :             :      * Determine the result sign, weight and number of digits to calculate.
    9057                 :             :      * The weight figured here is correct if the emitted quotient has no
    9058                 :             :      * leading zero digits; otherwise strip_var() will fix things up.
    9059                 :             :      */
    9060         [ +  + ]:        3968 :     if (var1->sign == var2->sign)
    9061                 :        3866 :         res_sign = NUMERIC_POS;
    9062                 :             :     else
    9063                 :         102 :         res_sign = NUMERIC_NEG;
    9064                 :        3968 :     res_weight = var1->weight - var2->weight + 1;
    9065                 :             :     /* The number of accurate result digits we need to produce: */
    9066                 :        3968 :     res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
    9067                 :             :     /* ... but always at least 1 */
    9068                 :        3968 :     res_ndigits = Max(res_ndigits, 1);
    9069                 :             :     /* If rounding needed, figure one more digit to ensure correct result */
    9070         [ +  + ]:        3968 :     if (round)
    9071                 :         658 :         res_ndigits++;
    9072                 :             :     /* Add guard digits for roundoff error when producing approx result */
    9073         [ +  + ]:        3968 :     if (!exact)
    9074                 :        1246 :         res_ndigits += DIV_GUARD_DIGITS;
    9075                 :             : 
    9076                 :             :     /*
    9077                 :             :      * The computation itself is done using base-NBASE^2 arithmetic, so we
    9078                 :             :      * actually process the input digits in pairs, producing a base-NBASE^2
    9079                 :             :      * intermediate result.  This significantly improves performance, since
    9080                 :             :      * the computation is O(N^2) in the number of input digits, and working in
    9081                 :             :      * base NBASE^2 effectively halves "N".
    9082                 :             :      */
    9083                 :        3968 :     var1ndigitpairs = (var1ndigits + 1) / 2;
    9084                 :        3968 :     var2ndigitpairs = (var2ndigits + 1) / 2;
    9085                 :        3968 :     res_ndigitpairs = (res_ndigits + 1) / 2;
    9086                 :        3968 :     res_ndigits = 2 * res_ndigitpairs;
    9087                 :             : 
    9088                 :             :     /*
    9089                 :             :      * We do the arithmetic in an array "dividend[]" of signed 64-bit
    9090                 :             :      * integers.  Since PG_INT64_MAX is much larger than NBASE^4, this gives
    9091                 :             :      * us a lot of headroom to avoid normalizing carries immediately.
    9092                 :             :      *
    9093                 :             :      * When performing an exact computation, the working dividend requires
    9094                 :             :      * res_ndigitpairs + var2ndigitpairs digits.  If var1 is larger than that,
    9095                 :             :      * the extra digits do not contribute to the result, and are ignored.
    9096                 :             :      *
    9097                 :             :      * When performing an approximate computation, the working dividend only
    9098                 :             :      * requires res_ndigitpairs digits (which includes the extra guard
    9099                 :             :      * digits).  All input digits beyond that are ignored.
    9100                 :             :      */
    9101         [ +  + ]:        3968 :     if (exact)
    9102                 :             :     {
    9103                 :        2722 :         div_ndigitpairs = res_ndigitpairs + var2ndigitpairs;
    9104                 :        2722 :         var1ndigitpairs = Min(var1ndigitpairs, div_ndigitpairs);
    9105                 :             :     }
    9106                 :             :     else
    9107                 :             :     {
    9108                 :        1246 :         div_ndigitpairs = res_ndigitpairs;
    9109                 :        1246 :         var1ndigitpairs = Min(var1ndigitpairs, div_ndigitpairs);
    9110                 :        1246 :         var2ndigitpairs = Min(var2ndigitpairs, div_ndigitpairs);
    9111                 :             :     }
    9112                 :             : 
    9113                 :             :     /*
    9114                 :             :      * Allocate room for the working dividend (div_ndigitpairs 64-bit digits)
    9115                 :             :      * plus the divisor (var2ndigitpairs 32-bit base-NBASE^2 digits).
    9116                 :             :      *
    9117                 :             :      * For convenience, we allocate one extra dividend digit, which is set to
    9118                 :             :      * zero and not counted in div_ndigitpairs, so that the main loop below
    9119                 :             :      * can safely read and write the (qi+1)'th digit in the approximate case.
    9120                 :             :      */
    9121                 :        3968 :     dividend = (int64 *) palloc((div_ndigitpairs + 1) * sizeof(int64) +
    9122                 :             :                                 var2ndigitpairs * sizeof(int32));
    9123                 :        3968 :     divisor = (int32 *) (dividend + div_ndigitpairs + 1);
    9124                 :             : 
    9125                 :             :     /* load var1 into dividend[0 .. var1ndigitpairs-1], zeroing the rest */
    9126         [ +  + ]:       37128 :     for (i = 0; i < var1ndigitpairs - 1; i++)
    9127                 :       33160 :         dividend[i] = var1->digits[2 * i] * NBASE + var1->digits[2 * i + 1];
    9128                 :             : 
    9129         [ +  + ]:        3968 :     if (2 * i + 1 < var1ndigits)
    9130                 :        2341 :         dividend[i] = var1->digits[2 * i] * NBASE + var1->digits[2 * i + 1];
    9131                 :             :     else
    9132                 :        1627 :         dividend[i] = var1->digits[2 * i] * NBASE;
    9133                 :             : 
    9134                 :        3968 :     memset(dividend + i + 1, 0, (div_ndigitpairs - i) * sizeof(int64));
    9135                 :             : 
    9136                 :             :     /* load var2 into divisor[0 .. var2ndigitpairs-1] */
    9137         [ +  + ]:       29424 :     for (i = 0; i < var2ndigitpairs - 1; i++)
    9138                 :       25456 :         divisor[i] = var2->digits[2 * i] * NBASE + var2->digits[2 * i + 1];
    9139                 :             : 
    9140         [ +  + ]:        3968 :     if (2 * i + 1 < var2ndigits)
    9141                 :        2138 :         divisor[i] = var2->digits[2 * i] * NBASE + var2->digits[2 * i + 1];
    9142                 :             :     else
    9143                 :        1830 :         divisor[i] = var2->digits[2 * i] * NBASE;
    9144                 :             : 
    9145                 :             :     /*
    9146                 :             :      * We estimate each quotient digit using floating-point arithmetic, taking
    9147                 :             :      * the first 2 base-NBASE^2 digits of the (current) dividend and divisor.
    9148                 :             :      * This must be float to avoid overflow.
    9149                 :             :      *
    9150                 :             :      * Since the floating-point dividend and divisor use 4 base-NBASE input
    9151                 :             :      * digits, they include roughly 40-53 bits of information from their
    9152                 :             :      * respective inputs (assuming NBASE is 10000), which fits well in IEEE
    9153                 :             :      * double-precision variables.  The relative error in the floating-point
    9154                 :             :      * quotient digit will then be less than around 2/NBASE^3, so the
    9155                 :             :      * estimated base-NBASE^2 quotient digit will typically be correct, and
    9156                 :             :      * should not be off by more than one from the correct value.
    9157                 :             :      */
    9158                 :        3968 :     fdivisor = (double) divisor[0] * NBASE_SQR;
    9159         [ +  - ]:        3968 :     if (var2ndigitpairs > 1)
    9160                 :        3968 :         fdivisor += (double) divisor[1];
    9161                 :        3968 :     fdivisorinverse = 1.0 / fdivisor;
    9162                 :             : 
    9163                 :             :     /*
    9164                 :             :      * maxdiv tracks the maximum possible absolute value of any dividend[]
    9165                 :             :      * entry; when this threatens to exceed PG_INT64_MAX, we take the time to
    9166                 :             :      * propagate carries.  Furthermore, we need to ensure that overflow
    9167                 :             :      * doesn't occur during the carry propagation passes either.  The carry
    9168                 :             :      * values may have an absolute value as high as PG_INT64_MAX/NBASE^2 + 1,
    9169                 :             :      * so really we must normalize when digits threaten to exceed PG_INT64_MAX
    9170                 :             :      * - PG_INT64_MAX/NBASE^2 - 1.
    9171                 :             :      *
    9172                 :             :      * To avoid overflow in maxdiv itself, it represents the max absolute
    9173                 :             :      * value divided by NBASE^2-1, i.e., at the top of the loop it is known
    9174                 :             :      * that no dividend[] entry has an absolute value exceeding maxdiv *
    9175                 :             :      * (NBASE^2-1).
    9176                 :             :      *
    9177                 :             :      * Actually, though, that holds good only for dividend[] entries after
    9178                 :             :      * dividend[qi]; the adjustment done at the bottom of the loop may cause
    9179                 :             :      * dividend[qi + 1] to exceed the maxdiv limit, so that dividend[qi] in
    9180                 :             :      * the next iteration is beyond the limit.  This does not cause problems,
    9181                 :             :      * as explained below.
    9182                 :             :      */
    9183                 :        3968 :     maxdiv = 1;
    9184                 :             : 
    9185                 :             :     /*
    9186                 :             :      * Outer loop computes next quotient digit, which goes in dividend[qi].
    9187                 :             :      */
    9188         [ +  + ]:       36464 :     for (qi = 0; qi < res_ndigitpairs; qi++)
    9189                 :             :     {
    9190                 :             :         /* Approximate the current dividend value */
    9191                 :       32496 :         fdividend = (double) dividend[qi] * NBASE_SQR;
    9192                 :       32496 :         fdividend += (double) dividend[qi + 1];
    9193                 :             : 
    9194                 :             :         /* Compute the (approximate) quotient digit */
    9195                 :       32496 :         fquotient = fdividend * fdivisorinverse;
    9196         [ +  + ]:       32496 :         qdigit = (fquotient >= 0.0) ? ((int32) fquotient) :
    9197                 :           5 :             (((int32) fquotient) - 1);  /* truncate towards -infinity */
    9198                 :             : 
    9199         [ +  + ]:       32496 :         if (qdigit != 0)
    9200                 :             :         {
    9201                 :             :             /* Do we need to normalize now? */
    9202                 :       29863 :             maxdiv += i64abs(qdigit);
    9203         [ +  + ]:       29863 :             if (maxdiv > (PG_INT64_MAX - PG_INT64_MAX / NBASE_SQR - 1) / (NBASE_SQR - 1))
    9204                 :             :             {
    9205                 :             :                 /*
    9206                 :             :                  * Yes, do it.  Note that if var2ndigitpairs is much smaller
    9207                 :             :                  * than div_ndigitpairs, we can save a significant amount of
    9208                 :             :                  * effort here by noting that we only need to normalise those
    9209                 :             :                  * dividend[] entries touched where prior iterations
    9210                 :             :                  * subtracted multiples of the divisor.
    9211                 :             :                  */
    9212                 :           5 :                 carry = 0;
    9213         [ +  + ]:        5625 :                 for (i = Min(qi + var2ndigitpairs - 2, div_ndigitpairs - 1); i > qi; i--)
    9214                 :             :                 {
    9215                 :        5620 :                     newdig = dividend[i] + carry;
    9216         [ +  - ]:        5620 :                     if (newdig < 0)
    9217                 :             :                     {
    9218                 :        5620 :                         carry = -((-newdig - 1) / NBASE_SQR) - 1;
    9219                 :        5620 :                         newdig -= carry * NBASE_SQR;
    9220                 :             :                     }
    9221         [ #  # ]:           0 :                     else if (newdig >= NBASE_SQR)
    9222                 :             :                     {
    9223                 :           0 :                         carry = newdig / NBASE_SQR;
    9224                 :           0 :                         newdig -= carry * NBASE_SQR;
    9225                 :             :                     }
    9226                 :             :                     else
    9227                 :           0 :                         carry = 0;
    9228                 :        5620 :                     dividend[i] = newdig;
    9229                 :             :                 }
    9230                 :           5 :                 dividend[qi] += carry;
    9231                 :             : 
    9232                 :             :                 /*
    9233                 :             :                  * All the dividend[] digits except possibly dividend[qi] are
    9234                 :             :                  * now in the range 0..NBASE^2-1.  We do not need to consider
    9235                 :             :                  * dividend[qi] in the maxdiv value anymore, so we can reset
    9236                 :             :                  * maxdiv to 1.
    9237                 :             :                  */
    9238                 :           5 :                 maxdiv = 1;
    9239                 :             : 
    9240                 :             :                 /*
    9241                 :             :                  * Recompute the quotient digit since new info may have
    9242                 :             :                  * propagated into the top two dividend digits.
    9243                 :             :                  */
    9244                 :           5 :                 fdividend = (double) dividend[qi] * NBASE_SQR;
    9245                 :           5 :                 fdividend += (double) dividend[qi + 1];
    9246                 :           5 :                 fquotient = fdividend * fdivisorinverse;
    9247         [ +  - ]:           5 :                 qdigit = (fquotient >= 0.0) ? ((int32) fquotient) :
    9248                 :           0 :                     (((int32) fquotient) - 1);  /* truncate towards -infinity */
    9249                 :             : 
    9250                 :           5 :                 maxdiv += i64abs(qdigit);
    9251                 :             :             }
    9252                 :             : 
    9253                 :             :             /*
    9254                 :             :              * Subtract off the appropriate multiple of the divisor.
    9255                 :             :              *
    9256                 :             :              * The digits beyond dividend[qi] cannot overflow, because we know
    9257                 :             :              * they will fall within the maxdiv limit.  As for dividend[qi]
    9258                 :             :              * itself, note that qdigit is approximately trunc(dividend[qi] /
    9259                 :             :              * divisor[0]), which would make the new value simply dividend[qi]
    9260                 :             :              * mod divisor[0].  The lower-order terms in qdigit can change
    9261                 :             :              * this result by not more than about twice PG_INT64_MAX/NBASE^2,
    9262                 :             :              * so overflow is impossible.
    9263                 :             :              *
    9264                 :             :              * This inner loop is the performance bottleneck for division, so
    9265                 :             :              * code it in the same way as the inner loop of mul_var() so that
    9266                 :             :              * it can be auto-vectorized.
    9267                 :             :              */
    9268         [ +  - ]:       29863 :             if (qdigit != 0)
    9269                 :             :             {
    9270                 :       29863 :                 int         istop = Min(var2ndigitpairs, div_ndigitpairs - qi);
    9271                 :       29863 :                 int64      *dividend_qi = &dividend[qi];
    9272                 :             : 
    9273         [ +  + ]:     6518873 :                 for (i = 0; i < istop; i++)
    9274                 :     6489010 :                     dividend_qi[i] -= (int64) qdigit * divisor[i];
    9275                 :             :             }
    9276                 :             :         }
    9277                 :             : 
    9278                 :             :         /*
    9279                 :             :          * The dividend digit we are about to replace might still be nonzero.
    9280                 :             :          * Fold it into the next digit position.
    9281                 :             :          *
    9282                 :             :          * There is no risk of overflow here, although proving that requires
    9283                 :             :          * some care.  Much as with the argument for dividend[qi] not
    9284                 :             :          * overflowing, if we consider the first two terms in the numerator
    9285                 :             :          * and denominator of qdigit, we can see that the final value of
    9286                 :             :          * dividend[qi + 1] will be approximately a remainder mod
    9287                 :             :          * (divisor[0]*NBASE^2 + divisor[1]).  Accounting for the lower-order
    9288                 :             :          * terms is a bit complicated but ends up adding not much more than
    9289                 :             :          * PG_INT64_MAX/NBASE^2 to the possible range.  Thus, dividend[qi + 1]
    9290                 :             :          * cannot overflow here, and in its role as dividend[qi] in the next
    9291                 :             :          * loop iteration, it can't be large enough to cause overflow in the
    9292                 :             :          * carry propagation step (if any), either.
    9293                 :             :          *
    9294                 :             :          * But having said that: dividend[qi] can be more than
    9295                 :             :          * PG_INT64_MAX/NBASE^2, as noted above, which means that the product
    9296                 :             :          * dividend[qi] * NBASE^2 *can* overflow.  When that happens, adding
    9297                 :             :          * it to dividend[qi + 1] will always cause a canceling overflow so
    9298                 :             :          * that the end result is correct.  We could avoid the intermediate
    9299                 :             :          * overflow by doing the multiplication and addition using unsigned
    9300                 :             :          * int64 arithmetic, which is modulo 2^64, but so far there appears no
    9301                 :             :          * need.
    9302                 :             :          */
    9303                 :       32496 :         dividend[qi + 1] += dividend[qi] * NBASE_SQR;
    9304                 :             : 
    9305                 :       32496 :         dividend[qi] = qdigit;
    9306                 :             :     }
    9307                 :             : 
    9308                 :             :     /*
    9309                 :             :      * If an exact result was requested, use the remainder to correct the
    9310                 :             :      * approximate quotient.  The remainder is in dividend[], immediately
    9311                 :             :      * after the quotient digits.  Note, however, that although the remainder
    9312                 :             :      * starts at dividend[qi = res_ndigitpairs], the first digit is the result
    9313                 :             :      * of folding two remainder digits into one above, and the remainder
    9314                 :             :      * currently only occupies var2ndigitpairs - 1 digits (the last digit of
    9315                 :             :      * the working dividend was untouched by the computation above).  Thus we
    9316                 :             :      * expand the remainder down by one base-NBASE^2 digit when we normalize
    9317                 :             :      * it, so that it completely fills the last var2ndigitpairs digits of the
    9318                 :             :      * dividend array.
    9319                 :             :      */
    9320         [ +  + ]:        3968 :     if (exact)
    9321                 :             :     {
    9322                 :             :         /* Normalize the remainder, expanding it down by one digit */
    9323                 :        2722 :         remainder = &dividend[qi];
    9324                 :        2722 :         carry = 0;
    9325         [ +  + ]:       15518 :         for (i = var2ndigitpairs - 2; i >= 0; i--)
    9326                 :             :         {
    9327                 :       12796 :             newdig = remainder[i] + carry;
    9328         [ +  + ]:       12796 :             if (newdig < 0)
    9329                 :             :             {
    9330                 :       10044 :                 carry = -((-newdig - 1) / NBASE_SQR) - 1;
    9331                 :       10044 :                 newdig -= carry * NBASE_SQR;
    9332                 :             :             }
    9333         [ +  + ]:        2752 :             else if (newdig >= NBASE_SQR)
    9334                 :             :             {
    9335                 :        2696 :                 carry = newdig / NBASE_SQR;
    9336                 :        2696 :                 newdig -= carry * NBASE_SQR;
    9337                 :             :             }
    9338                 :             :             else
    9339                 :          56 :                 carry = 0;
    9340                 :       12796 :             remainder[i + 1] = newdig;
    9341                 :             :         }
    9342                 :        2722 :         remainder[0] = carry;
    9343                 :             : 
    9344         [ +  + ]:        2722 :         if (remainder[0] < 0)
    9345                 :             :         {
    9346                 :             :             /*
    9347                 :             :              * The remainder is negative, so the approximate quotient is too
    9348                 :             :              * large.  Correct by reducing the quotient by one and adding the
    9349                 :             :              * divisor to the remainder until the remainder is positive.  We
    9350                 :             :              * expect the quotient to be off by at most one, which has been
    9351                 :             :              * borne out in all testing, but not conclusively proven, so we
    9352                 :             :              * allow for larger corrections, just in case.
    9353                 :             :              */
    9354                 :             :             do
    9355                 :             :             {
    9356                 :             :                 /* Add the divisor to the remainder */
    9357                 :           5 :                 carry = 0;
    9358         [ +  + ]:          65 :                 for (i = var2ndigitpairs - 1; i > 0; i--)
    9359                 :             :                 {
    9360                 :          60 :                     newdig = remainder[i] + divisor[i] + carry;
    9361         [ -  + ]:          60 :                     if (newdig >= NBASE_SQR)
    9362                 :             :                     {
    9363                 :           0 :                         remainder[i] = newdig - NBASE_SQR;
    9364                 :           0 :                         carry = 1;
    9365                 :             :                     }
    9366                 :             :                     else
    9367                 :             :                     {
    9368                 :          60 :                         remainder[i] = newdig;
    9369                 :          60 :                         carry = 0;
    9370                 :             :                     }
    9371                 :             :                 }
    9372                 :           5 :                 remainder[0] += divisor[0] + carry;
    9373                 :             : 
    9374                 :             :                 /* Subtract 1 from the quotient (propagating carries later) */
    9375                 :           5 :                 dividend[qi - 1]--;
    9376                 :             : 
    9377         [ -  + ]:           5 :             } while (remainder[0] < 0);
    9378                 :             :         }
    9379                 :             :         else
    9380                 :             :         {
    9381                 :             :             /*
    9382                 :             :              * The remainder is nonnegative.  If it's greater than or equal to
    9383                 :             :              * the divisor, then the approximate quotient is too small and
    9384                 :             :              * must be corrected.  As above, we don't expect to have to apply
    9385                 :             :              * more than one correction, but allow for it just in case.
    9386                 :             :              */
    9387                 :             :             while (true)
    9388                 :           5 :             {
    9389                 :        2722 :                 bool        less = false;
    9390                 :             : 
    9391                 :             :                 /* Is remainder < divisor? */
    9392         [ +  + ]:        2737 :                 for (i = 0; i < var2ndigitpairs; i++)
    9393                 :             :                 {
    9394         [ +  + ]:        2732 :                     if (remainder[i] < divisor[i])
    9395                 :             :                     {
    9396                 :        2717 :                         less = true;
    9397                 :        2717 :                         break;
    9398                 :             :                     }
    9399         [ -  + ]:          15 :                     if (remainder[i] > divisor[i])
    9400                 :           0 :                         break;  /* remainder > divisor */
    9401                 :             :                 }
    9402         [ +  + ]:        2722 :                 if (less)
    9403                 :        2717 :                     break;      /* quotient is correct */
    9404                 :             : 
    9405                 :             :                 /* Subtract the divisor from the remainder */
    9406                 :           5 :                 carry = 0;
    9407         [ +  + ]:          15 :                 for (i = var2ndigitpairs - 1; i > 0; i--)
    9408                 :             :                 {
    9409                 :          10 :                     newdig = remainder[i] - divisor[i] + carry;
    9410         [ -  + ]:          10 :                     if (newdig < 0)
    9411                 :             :                     {
    9412                 :           0 :                         remainder[i] = newdig + NBASE_SQR;
    9413                 :           0 :                         carry = -1;
    9414                 :             :                     }
    9415                 :             :                     else
    9416                 :             :                     {
    9417                 :          10 :                         remainder[i] = newdig;
    9418                 :          10 :                         carry = 0;
    9419                 :             :                     }
    9420                 :             :                 }
    9421                 :           5 :                 remainder[0] = remainder[0] - divisor[0] + carry;
    9422                 :             : 
    9423                 :             :                 /* Add 1 to the quotient (propagating carries later) */
    9424                 :           5 :                 dividend[qi - 1]++;
    9425                 :             :             }
    9426                 :             :         }
    9427                 :             :     }
    9428                 :             : 
    9429                 :             :     /*
    9430                 :             :      * Because the quotient digits were estimates that might have been off by
    9431                 :             :      * one (and we didn't bother propagating carries when adjusting the
    9432                 :             :      * quotient above), some quotient digits might be out of range, so do a
    9433                 :             :      * final carry propagation pass to normalize back to base NBASE^2, and
    9434                 :             :      * construct the base-NBASE result digits.  Note that this is still done
    9435                 :             :      * at full precision w/guard digits.
    9436                 :             :      */
    9437                 :        3968 :     alloc_var(result, res_ndigits);
    9438                 :        3968 :     res_digits = result->digits;
    9439                 :        3968 :     carry = 0;
    9440         [ +  + ]:       36464 :     for (i = res_ndigitpairs - 1; i >= 0; i--)
    9441                 :             :     {
    9442                 :       32496 :         newdig = dividend[i] + carry;
    9443         [ +  + ]:       32496 :         if (newdig < 0)
    9444                 :             :         {
    9445                 :           5 :             carry = -((-newdig - 1) / NBASE_SQR) - 1;
    9446                 :           5 :             newdig -= carry * NBASE_SQR;
    9447                 :             :         }
    9448         [ -  + ]:       32491 :         else if (newdig >= NBASE_SQR)
    9449                 :             :         {
    9450                 :           0 :             carry = newdig / NBASE_SQR;
    9451                 :           0 :             newdig -= carry * NBASE_SQR;
    9452                 :             :         }
    9453                 :             :         else
    9454                 :       32491 :             carry = 0;
    9455                 :       32496 :         res_digits[2 * i + 1] = (NumericDigit) ((uint32) newdig % NBASE);
    9456                 :       32496 :         res_digits[2 * i] = (NumericDigit) ((uint32) newdig / NBASE);
    9457                 :             :     }
    9458                 :             :     Assert(carry == 0);
    9459                 :             : 
    9460                 :        3968 :     pfree(dividend);
    9461                 :             : 
    9462                 :             :     /*
    9463                 :             :      * Finally, round or truncate the result to the requested precision.
    9464                 :             :      */
    9465                 :        3968 :     result->weight = res_weight;
    9466                 :        3968 :     result->sign = res_sign;
    9467                 :             : 
    9468                 :             :     /* Round or truncate to target rscale (and set result->dscale) */
    9469         [ +  + ]:        3968 :     if (round)
    9470                 :         658 :         round_var(result, rscale);
    9471                 :             :     else
    9472                 :        3310 :         trunc_var(result, rscale);
    9473                 :             : 
    9474                 :             :     /* Strip leading and trailing zeroes */
    9475                 :        3968 :     strip_var(result);
    9476                 :             : }
    9477                 :             : 
    9478                 :             : 
    9479                 :             : /*
    9480                 :             :  * div_var_int() -
    9481                 :             :  *
    9482                 :             :  *  Divide a numeric variable by a 32-bit integer with the specified weight.
    9483                 :             :  *  The quotient var / (ival * NBASE^ival_weight) is stored in result.
    9484                 :             :  */
    9485                 :             : static void
    9486                 :      389758 : div_var_int(const NumericVar *var, int ival, int ival_weight,
    9487                 :             :             NumericVar *result, int rscale, bool round)
    9488                 :             : {
    9489                 :      389758 :     NumericDigit *var_digits = var->digits;
    9490                 :      389758 :     int         var_ndigits = var->ndigits;
    9491                 :             :     int         res_sign;
    9492                 :             :     int         res_weight;
    9493                 :             :     int         res_ndigits;
    9494                 :             :     NumericDigit *res_buf;
    9495                 :             :     NumericDigit *res_digits;
    9496                 :             :     uint32      divisor;
    9497                 :             :     int         i;
    9498                 :             : 
    9499                 :             :     /* Guard against division by zero */
    9500         [ -  + ]:      389758 :     if (ival == 0)
    9501         [ #  # ]:           0 :         ereport(ERROR,
    9502                 :             :                 errcode(ERRCODE_DIVISION_BY_ZERO),
    9503                 :             :                 errmsg("division by zero"));
    9504                 :             : 
    9505                 :             :     /* Result zero check */
    9506         [ +  + ]:      389758 :     if (var_ndigits == 0)
    9507                 :             :     {
    9508                 :        1583 :         zero_var(result);
    9509                 :        1583 :         result->dscale = rscale;
    9510                 :        1583 :         return;
    9511                 :             :     }
    9512                 :             : 
    9513                 :             :     /*
    9514                 :             :      * Determine the result sign, weight and number of digits to calculate.
    9515                 :             :      * The weight figured here is correct if the emitted quotient has no
    9516                 :             :      * leading zero digits; otherwise strip_var() will fix things up.
    9517                 :             :      */
    9518         [ +  + ]:      388175 :     if (var->sign == NUMERIC_POS)
    9519         [ +  + ]:      385931 :         res_sign = ival > 0 ? NUMERIC_POS : NUMERIC_NEG;
    9520                 :             :     else
    9521         [ +  + ]:        2244 :         res_sign = ival > 0 ? NUMERIC_NEG : NUMERIC_POS;
    9522                 :      388175 :     res_weight = var->weight - ival_weight;
    9523                 :             :     /* The number of accurate result digits we need to produce: */
    9524                 :      388175 :     res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
    9525                 :             :     /* ... but always at least 1 */
    9526                 :      388175 :     res_ndigits = Max(res_ndigits, 1);
    9527                 :             :     /* If rounding needed, figure one more digit to ensure correct result */
    9528         [ +  + ]:      388175 :     if (round)
    9529                 :      111701 :         res_ndigits++;
    9530                 :             : 
    9531                 :      388175 :     res_buf = digitbuf_alloc(res_ndigits + 1);
    9532                 :      388175 :     res_buf[0] = 0;             /* spare digit for later rounding */
    9533                 :      388175 :     res_digits = res_buf + 1;
    9534                 :             : 
    9535                 :             :     /*
    9536                 :             :      * Now compute the quotient digits.  This is the short division algorithm
    9537                 :             :      * described in Knuth volume 2, section 4.3.1 exercise 16, except that we
    9538                 :             :      * allow the divisor to exceed the internal base.
    9539                 :             :      *
    9540                 :             :      * In this algorithm, the carry from one digit to the next is at most
    9541                 :             :      * divisor - 1.  Therefore, while processing the next digit, carry may
    9542                 :             :      * become as large as divisor * NBASE - 1, and so it requires a 64-bit
    9543                 :             :      * integer if this exceeds UINT_MAX.
    9544                 :             :      */
    9545                 :      388175 :     divisor = abs(ival);
    9546                 :             : 
    9547         [ +  + ]:      388175 :     if (divisor <= UINT_MAX / NBASE)
    9548                 :             :     {
    9549                 :             :         /* carry cannot overflow 32 bits */
    9550                 :      386378 :         uint32      carry = 0;
    9551                 :             : 
    9552         [ +  + ]:     1914290 :         for (i = 0; i < res_ndigits; i++)
    9553                 :             :         {
    9554         [ +  + ]:     1527912 :             carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
    9555                 :     1527912 :             res_digits[i] = (NumericDigit) (carry / divisor);
    9556                 :     1527912 :             carry = carry % divisor;
    9557                 :             :         }
    9558                 :             :     }
    9559                 :             :     else
    9560                 :             :     {
    9561                 :             :         /* carry may exceed 32 bits */
    9562                 :        1797 :         uint64      carry = 0;
    9563                 :             : 
    9564         [ +  + ]:        5840 :         for (i = 0; i < res_ndigits; i++)
    9565                 :             :         {
    9566         [ +  + ]:        4043 :             carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
    9567                 :        4043 :             res_digits[i] = (NumericDigit) (carry / divisor);
    9568                 :        4043 :             carry = carry % divisor;
    9569                 :             :         }
    9570                 :             :     }
    9571                 :             : 
    9572                 :             :     /* Store the quotient in result */
    9573         [ +  + ]:      388175 :     digitbuf_free(result->buf);
    9574                 :      388175 :     result->ndigits = res_ndigits;
    9575                 :      388175 :     result->buf = res_buf;
    9576                 :      388175 :     result->digits = res_digits;
    9577                 :      388175 :     result->weight = res_weight;
    9578                 :      388175 :     result->sign = res_sign;
    9579                 :             : 
    9580                 :             :     /* Round or truncate to target rscale (and set result->dscale) */
    9581         [ +  + ]:      388175 :     if (round)
    9582                 :      111701 :         round_var(result, rscale);
    9583                 :             :     else
    9584                 :      276474 :         trunc_var(result, rscale);
    9585                 :             : 
    9586                 :             :     /* Strip leading/trailing zeroes */
    9587                 :      388175 :     strip_var(result);
    9588                 :             : }
    9589                 :             : 
    9590                 :             : 
    9591                 :             : #ifdef HAVE_INT128
    9592                 :             : /*
    9593                 :             :  * div_var_int64() -
    9594                 :             :  *
    9595                 :             :  *  Divide a numeric variable by a 64-bit integer with the specified weight.
    9596                 :             :  *  The quotient var / (ival * NBASE^ival_weight) is stored in result.
    9597                 :             :  *
    9598                 :             :  *  This duplicates the logic in div_var_int(), so any changes made there
    9599                 :             :  *  should be made here too.
    9600                 :             :  */
    9601                 :             : static void
    9602                 :         360 : div_var_int64(const NumericVar *var, int64 ival, int ival_weight,
    9603                 :             :               NumericVar *result, int rscale, bool round)
    9604                 :             : {
    9605                 :         360 :     NumericDigit *var_digits = var->digits;
    9606                 :         360 :     int         var_ndigits = var->ndigits;
    9607                 :             :     int         res_sign;
    9608                 :             :     int         res_weight;
    9609                 :             :     int         res_ndigits;
    9610                 :             :     NumericDigit *res_buf;
    9611                 :             :     NumericDigit *res_digits;
    9612                 :             :     uint64      divisor;
    9613                 :             :     int         i;
    9614                 :             : 
    9615                 :             :     /* Guard against division by zero */
    9616         [ -  + ]:         360 :     if (ival == 0)
    9617         [ #  # ]:           0 :         ereport(ERROR,
    9618                 :             :                 errcode(ERRCODE_DIVISION_BY_ZERO),
    9619                 :             :                 errmsg("division by zero"));
    9620                 :             : 
    9621                 :             :     /* Result zero check */
    9622         [ +  + ]:         360 :     if (var_ndigits == 0)
    9623                 :             :     {
    9624                 :          64 :         zero_var(result);
    9625                 :          64 :         result->dscale = rscale;
    9626                 :          64 :         return;
    9627                 :             :     }
    9628                 :             : 
    9629                 :             :     /*
    9630                 :             :      * Determine the result sign, weight and number of digits to calculate.
    9631                 :             :      * The weight figured here is correct if the emitted quotient has no
    9632                 :             :      * leading zero digits; otherwise strip_var() will fix things up.
    9633                 :             :      */
    9634         [ +  + ]:         296 :     if (var->sign == NUMERIC_POS)
    9635         [ +  + ]:         175 :         res_sign = ival > 0 ? NUMERIC_POS : NUMERIC_NEG;
    9636                 :             :     else
    9637         [ +  + ]:         121 :         res_sign = ival > 0 ? NUMERIC_NEG : NUMERIC_POS;
    9638                 :         296 :     res_weight = var->weight - ival_weight;
    9639                 :             :     /* The number of accurate result digits we need to produce: */
    9640                 :         296 :     res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
    9641                 :             :     /* ... but always at least 1 */
    9642                 :         296 :     res_ndigits = Max(res_ndigits, 1);
    9643                 :             :     /* If rounding needed, figure one more digit to ensure correct result */
    9644         [ +  + ]:         296 :     if (round)
    9645                 :         291 :         res_ndigits++;
    9646                 :             : 
    9647                 :         296 :     res_buf = digitbuf_alloc(res_ndigits + 1);
    9648                 :         296 :     res_buf[0] = 0;             /* spare digit for later rounding */
    9649                 :         296 :     res_digits = res_buf + 1;
    9650                 :             : 
    9651                 :             :     /*
    9652                 :             :      * Now compute the quotient digits.  This is the short division algorithm
    9653                 :             :      * described in Knuth volume 2, section 4.3.1 exercise 16, except that we
    9654                 :             :      * allow the divisor to exceed the internal base.
    9655                 :             :      *
    9656                 :             :      * In this algorithm, the carry from one digit to the next is at most
    9657                 :             :      * divisor - 1.  Therefore, while processing the next digit, carry may
    9658                 :             :      * become as large as divisor * NBASE - 1, and so it requires a 128-bit
    9659                 :             :      * integer if this exceeds PG_UINT64_MAX.
    9660                 :             :      */
    9661                 :         296 :     divisor = i64abs(ival);
    9662                 :             : 
    9663         [ +  + ]:         296 :     if (divisor <= PG_UINT64_MAX / NBASE)
    9664                 :             :     {
    9665                 :             :         /* carry cannot overflow 64 bits */
    9666                 :         232 :         uint64      carry = 0;
    9667                 :             : 
    9668         [ +  + ]:        2361 :         for (i = 0; i < res_ndigits; i++)
    9669                 :             :         {
    9670         [ +  + ]:        2129 :             carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
    9671                 :        2129 :             res_digits[i] = (NumericDigit) (carry / divisor);
    9672                 :        2129 :             carry = carry % divisor;
    9673                 :             :         }
    9674                 :             :     }
    9675                 :             :     else
    9676                 :             :     {
    9677                 :             :         /* carry may exceed 64 bits */
    9678                 :          64 :         uint128     carry = 0;
    9679                 :             : 
    9680         [ +  + ]:         688 :         for (i = 0; i < res_ndigits; i++)
    9681                 :             :         {
    9682         [ +  + ]:         624 :             carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
    9683                 :         624 :             res_digits[i] = (NumericDigit) (carry / divisor);
    9684                 :         624 :             carry = carry % divisor;
    9685                 :             :         }
    9686                 :             :     }
    9687                 :             : 
    9688                 :             :     /* Store the quotient in result */
    9689         [ +  + ]:         296 :     digitbuf_free(result->buf);
    9690                 :         296 :     result->ndigits = res_ndigits;
    9691                 :         296 :     result->buf = res_buf;
    9692                 :         296 :     result->digits = res_digits;
    9693                 :         296 :     result->weight = res_weight;
    9694                 :         296 :     result->sign = res_sign;
    9695                 :             : 
    9696                 :             :     /* Round or truncate to target rscale (and set result->dscale) */
    9697         [ +  + ]:         296 :     if (round)
    9698                 :         291 :         round_var(result, rscale);
    9699                 :             :     else
    9700                 :           5 :         trunc_var(result, rscale);
    9701                 :             : 
    9702                 :             :     /* Strip leading/trailing zeroes */
    9703                 :         296 :     strip_var(result);
    9704                 :             : }
    9705                 :             : #endif
    9706                 :             : 
    9707                 :             : 
    9708                 :             : /*
    9709                 :             :  * Default scale selection for division
    9710                 :             :  *
    9711                 :             :  * Returns the appropriate result scale for the division result.
    9712                 :             :  */
    9713                 :             : static int
    9714                 :       99380 : select_div_scale(const NumericVar *var1, const NumericVar *var2)
    9715                 :             : {
    9716                 :             :     int         weight1,
    9717                 :             :                 weight2,
    9718                 :             :                 qweight,
    9719                 :             :                 i;
    9720                 :             :     NumericDigit firstdigit1,
    9721                 :             :                 firstdigit2;
    9722                 :             :     int         rscale;
    9723                 :             : 
    9724                 :             :     /*
    9725                 :             :      * The result scale of a division isn't specified in any SQL standard. For
    9726                 :             :      * PostgreSQL we select a result scale that will give at least
    9727                 :             :      * NUMERIC_MIN_SIG_DIGITS significant digits, so that numeric gives a
    9728                 :             :      * result no less accurate than float8; but use a scale not less than
    9729                 :             :      * either input's display scale.
    9730                 :             :      */
    9731                 :             : 
    9732                 :             :     /* Get the actual (normalized) weight and first digit of each input */
    9733                 :             : 
    9734                 :       99380 :     weight1 = 0;                /* values to use if var1 is zero */
    9735                 :       99380 :     firstdigit1 = 0;
    9736         [ +  + ]:       99380 :     for (i = 0; i < var1->ndigits; i++)
    9737                 :             :     {
    9738                 :       98247 :         firstdigit1 = var1->digits[i];
    9739         [ +  - ]:       98247 :         if (firstdigit1 != 0)
    9740                 :             :         {
    9741                 :       98247 :             weight1 = var1->weight - i;
    9742                 :       98247 :             break;
    9743                 :             :         }
    9744                 :             :     }
    9745                 :             : 
    9746                 :       99380 :     weight2 = 0;                /* values to use if var2 is zero */
    9747                 :       99380 :     firstdigit2 = 0;
    9748         [ +  + ]:       99380 :     for (i = 0; i < var2->ndigits; i++)
    9749                 :             :     {
    9750                 :       99347 :         firstdigit2 = var2->digits[i];
    9751         [ +  - ]:       99347 :         if (firstdigit2 != 0)
    9752                 :             :         {
    9753                 :       99347 :             weight2 = var2->weight - i;
    9754                 :       99347 :             break;
    9755                 :             :         }
    9756                 :             :     }
    9757                 :             : 
    9758                 :             :     /*
    9759                 :             :      * Estimate weight of quotient.  If the two first digits are equal, we
    9760                 :             :      * can't be sure, but assume that var1 is less than var2.
    9761                 :             :      */
    9762                 :       99380 :     qweight = weight1 - weight2;
    9763         [ +  + ]:       99380 :     if (firstdigit1 <= firstdigit2)
    9764                 :       88549 :         qweight--;
    9765                 :             : 
    9766                 :             :     /* Select result scale */
    9767                 :       99380 :     rscale = NUMERIC_MIN_SIG_DIGITS - qweight * DEC_DIGITS;
    9768                 :       99380 :     rscale = Max(rscale, var1->dscale);
    9769                 :       99380 :     rscale = Max(rscale, var2->dscale);
    9770                 :       99380 :     rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
    9771                 :       99380 :     rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
    9772                 :             : 
    9773                 :       99380 :     return rscale;
    9774                 :             : }
    9775                 :             : 
    9776                 :             : 
    9777                 :             : /*
    9778                 :             :  * mod_var() -
    9779                 :             :  *
    9780                 :             :  *  Calculate the modulo of two numerics at variable level
    9781                 :             :  */
    9782                 :             : static void
    9783                 :      275438 : mod_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
    9784                 :             : {
    9785                 :             :     NumericVar  tmp;
    9786                 :             : 
    9787                 :      275438 :     init_var(&tmp);
    9788                 :             : 
    9789                 :             :     /* ---------
    9790                 :             :      * We do this using the equation
    9791                 :             :      *      mod(x,y) = x - trunc(x/y)*y
    9792                 :             :      * div_var can be persuaded to give us trunc(x/y) directly.
    9793                 :             :      * ----------
    9794                 :             :      */
    9795                 :      275438 :     div_var(var1, var2, &tmp, 0, false, true);
    9796                 :             : 
    9797                 :      275438 :     mul_var(var2, &tmp, &tmp, var2->dscale);
    9798                 :             : 
    9799                 :      275438 :     sub_var(var1, &tmp, result);
    9800                 :             : 
    9801                 :      275438 :     free_var(&tmp);
    9802                 :      275438 : }
    9803                 :             : 
    9804                 :             : 
    9805                 :             : /*
    9806                 :             :  * div_mod_var() -
    9807                 :             :  *
    9808                 :             :  *  Calculate the truncated integer quotient and numeric remainder of two
    9809                 :             :  *  numeric variables.  The remainder is precise to var2's dscale.
    9810                 :             :  */
    9811                 :             : static void
    9812                 :        3295 : div_mod_var(const NumericVar *var1, const NumericVar *var2,
    9813                 :             :             NumericVar *quot, NumericVar *rem)
    9814                 :             : {
    9815                 :             :     NumericVar  q;
    9816                 :             :     NumericVar  r;
    9817                 :             : 
    9818                 :        3295 :     init_var(&q);
    9819                 :        3295 :     init_var(&r);
    9820                 :             : 
    9821                 :             :     /*
    9822                 :             :      * Use div_var() with exact = false to get an initial estimate for the
    9823                 :             :      * integer quotient (truncated towards zero).  This might be slightly
    9824                 :             :      * inaccurate, but we correct it below.
    9825                 :             :      */
    9826                 :        3295 :     div_var(var1, var2, &q, 0, false, false);
    9827                 :             : 
    9828                 :             :     /* Compute initial estimate of remainder using the quotient estimate. */
    9829                 :        3295 :     mul_var(var2, &q, &r, var2->dscale);
    9830                 :        3295 :     sub_var(var1, &r, &r);
    9831                 :             : 
    9832                 :             :     /*
    9833                 :             :      * Adjust the results if necessary --- the remainder should have the same
    9834                 :             :      * sign as var1, and its absolute value should be less than the absolute
    9835                 :             :      * value of var2.
    9836                 :             :      */
    9837   [ +  -  -  + ]:        3295 :     while (r.ndigits != 0 && r.sign != var1->sign)
    9838                 :             :     {
    9839                 :             :         /* The absolute value of the quotient is too large */
    9840         [ #  # ]:           0 :         if (var1->sign == var2->sign)
    9841                 :             :         {
    9842                 :           0 :             sub_var(&q, &const_one, &q);
    9843                 :           0 :             add_var(&r, var2, &r);
    9844                 :             :         }
    9845                 :             :         else
    9846                 :             :         {
    9847                 :           0 :             add_var(&q, &const_one, &q);
    9848                 :           0 :             sub_var(&r, var2, &r);
    9849                 :             :         }
    9850                 :             :     }
    9851                 :             : 
    9852         [ -  + ]:        3295 :     while (cmp_abs(&r, var2) >= 0)
    9853                 :             :     {
    9854                 :             :         /* The absolute value of the quotient is too small */
    9855         [ #  # ]:           0 :         if (var1->sign == var2->sign)
    9856                 :             :         {
    9857                 :           0 :             add_var(&q, &const_one, &q);
    9858                 :           0 :             sub_var(&r, var2, &r);
    9859                 :             :         }
    9860                 :             :         else
    9861                 :             :         {
    9862                 :           0 :             sub_var(&q, &const_one, &q);
    9863                 :           0 :             add_var(&r, var2, &r);
    9864                 :             :         }
    9865                 :             :     }
    9866                 :             : 
    9867                 :        3295 :     set_var_from_var(&q, quot);
    9868                 :        3295 :     set_var_from_var(&r, rem);
    9869                 :             : 
    9870                 :        3295 :     free_var(&q);
    9871                 :        3295 :     free_var(&r);
    9872                 :        3295 : }
    9873                 :             : 
    9874                 :             : 
    9875                 :             : /*
    9876                 :             :  * ceil_var() -
    9877                 :             :  *
    9878                 :             :  *  Return the smallest integer greater than or equal to the argument
    9879                 :             :  *  on variable level
    9880                 :             :  */
    9881                 :             : static void
    9882                 :         136 : ceil_var(const NumericVar *var, NumericVar *result)
    9883                 :             : {
    9884                 :             :     NumericVar  tmp;
    9885                 :             : 
    9886                 :         136 :     init_var(&tmp);
    9887                 :         136 :     set_var_from_var(var, &tmp);
    9888                 :             : 
    9889                 :         136 :     trunc_var(&tmp, 0);
    9890                 :             : 
    9891   [ +  +  +  + ]:         136 :     if (var->sign == NUMERIC_POS && cmp_var(var, &tmp) != 0)
    9892                 :          40 :         add_var(&tmp, &const_one, &tmp);
    9893                 :             : 
    9894                 :         136 :     set_var_from_var(&tmp, result);
    9895                 :         136 :     free_var(&tmp);
    9896                 :         136 : }
    9897                 :             : 
    9898                 :             : 
    9899                 :             : /*
    9900                 :             :  * floor_var() -
    9901                 :             :  *
    9902                 :             :  *  Return the largest integer equal to or less than the argument
    9903                 :             :  *  on variable level
    9904                 :             :  */
    9905                 :             : static void
    9906                 :          72 : floor_var(const NumericVar *var, NumericVar *result)
    9907                 :             : {
    9908                 :             :     NumericVar  tmp;
    9909                 :             : 
    9910                 :          72 :     init_var(&tmp);
    9911                 :          72 :     set_var_from_var(var, &tmp);
    9912                 :             : 
    9913                 :          72 :     trunc_var(&tmp, 0);
    9914                 :             : 
    9915   [ +  +  +  + ]:          72 :     if (var->sign == NUMERIC_NEG && cmp_var(var, &tmp) != 0)
    9916                 :          20 :         sub_var(&tmp, &const_one, &tmp);
    9917                 :             : 
    9918                 :          72 :     set_var_from_var(&tmp, result);
    9919                 :          72 :     free_var(&tmp);
    9920                 :          72 : }
    9921                 :             : 
    9922                 :             : 
    9923                 :             : /*
    9924                 :             :  * gcd_var() -
    9925                 :             :  *
    9926                 :             :  *  Calculate the greatest common divisor of two numerics at variable level
    9927                 :             :  */
    9928                 :             : static void
    9929                 :         148 : gcd_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
    9930                 :             : {
    9931                 :             :     int         res_dscale;
    9932                 :             :     int         cmp;
    9933                 :             :     NumericVar  tmp_arg;
    9934                 :             :     NumericVar  mod;
    9935                 :             : 
    9936                 :         148 :     res_dscale = Max(var1->dscale, var2->dscale);
    9937                 :             : 
    9938                 :             :     /*
    9939                 :             :      * Arrange for var1 to be the number with the greater absolute value.
    9940                 :             :      *
    9941                 :             :      * This would happen automatically in the loop below, but avoids an
    9942                 :             :      * expensive modulo operation.
    9943                 :             :      */
    9944                 :         148 :     cmp = cmp_abs(var1, var2);
    9945         [ +  + ]:         148 :     if (cmp < 0)
    9946                 :             :     {
    9947                 :          56 :         const NumericVar *tmp = var1;
    9948                 :             : 
    9949                 :          56 :         var1 = var2;
    9950                 :          56 :         var2 = tmp;
    9951                 :             :     }
    9952                 :             : 
    9953                 :             :     /*
    9954                 :             :      * Also avoid the taking the modulo if the inputs have the same absolute
    9955                 :             :      * value, or if the smaller input is zero.
    9956                 :             :      */
    9957   [ +  +  +  + ]:         148 :     if (cmp == 0 || var2->ndigits == 0)
    9958                 :             :     {
    9959                 :          48 :         set_var_from_var(var1, result);
    9960                 :          48 :         result->sign = NUMERIC_POS;
    9961                 :          48 :         result->dscale = res_dscale;
    9962                 :          48 :         return;
    9963                 :             :     }
    9964                 :             : 
    9965                 :         100 :     init_var(&tmp_arg);
    9966                 :         100 :     init_var(&mod);
    9967                 :             : 
    9968                 :             :     /* Use the Euclidean algorithm to find the GCD */
    9969                 :         100 :     set_var_from_var(var1, &tmp_arg);
    9970                 :         100 :     set_var_from_var(var2, result);
    9971                 :             : 
    9972                 :             :     for (;;)
    9973                 :             :     {
    9974                 :             :         /* this loop can take a while, so allow it to be interrupted */
    9975         [ -  + ]:         392 :         CHECK_FOR_INTERRUPTS();
    9976                 :             : 
    9977                 :         392 :         mod_var(&tmp_arg, result, &mod);
    9978         [ +  + ]:         392 :         if (mod.ndigits == 0)
    9979                 :         100 :             break;
    9980                 :         292 :         set_var_from_var(result, &tmp_arg);
    9981                 :         292 :         set_var_from_var(&mod, result);
    9982                 :             :     }
    9983                 :         100 :     result->sign = NUMERIC_POS;
    9984                 :         100 :     result->dscale = res_dscale;
    9985                 :             : 
    9986                 :         100 :     free_var(&tmp_arg);
    9987                 :         100 :     free_var(&mod);
    9988                 :             : }
    9989                 :             : 
    9990                 :             : 
    9991                 :             : /*
    9992                 :             :  * sqrt_var() -
    9993                 :             :  *
    9994                 :             :  *  Compute the square root of x using the Karatsuba Square Root algorithm.
    9995                 :             :  *  NOTE: we allow rscale < 0 here, implying rounding before the decimal
    9996                 :             :  *  point.
    9997                 :             :  */
    9998                 :             : static void
    9999                 :        3048 : sqrt_var(const NumericVar *arg, NumericVar *result, int rscale)
   10000                 :             : {
   10001                 :             :     int         stat;
   10002                 :             :     int         res_weight;
   10003                 :             :     int         res_ndigits;
   10004                 :             :     int         src_ndigits;
   10005                 :             :     int         step;
   10006                 :             :     int         ndigits[32];
   10007                 :             :     int         blen;
   10008                 :             :     int64       arg_int64;
   10009                 :             :     int         src_idx;
   10010                 :             :     int64       s_int64;
   10011                 :             :     int64       r_int64;
   10012                 :             :     NumericVar  s_var;
   10013                 :             :     NumericVar  r_var;
   10014                 :             :     NumericVar  a0_var;
   10015                 :             :     NumericVar  a1_var;
   10016                 :             :     NumericVar  q_var;
   10017                 :             :     NumericVar  u_var;
   10018                 :             : 
   10019                 :        3048 :     stat = cmp_var(arg, &const_zero);
   10020         [ +  + ]:        3048 :     if (stat == 0)
   10021                 :             :     {
   10022                 :          12 :         zero_var(result);
   10023                 :          12 :         result->dscale = rscale;
   10024                 :          12 :         return;
   10025                 :             :     }
   10026                 :             : 
   10027                 :             :     /*
   10028                 :             :      * SQL2003 defines sqrt() in terms of power, so we need to emit the right
   10029                 :             :      * SQLSTATE error code if the operand is negative.
   10030                 :             :      */
   10031         [ +  + ]:        3036 :     if (stat < 0)
   10032         [ +  - ]:           4 :         ereport(ERROR,
   10033                 :             :                 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
   10034                 :             :                  errmsg("cannot take square root of a negative number")));
   10035                 :             : 
   10036                 :        3032 :     init_var(&s_var);
   10037                 :        3032 :     init_var(&r_var);
   10038                 :        3032 :     init_var(&a0_var);
   10039                 :        3032 :     init_var(&a1_var);
   10040                 :        3032 :     init_var(&q_var);
   10041                 :        3032 :     init_var(&u_var);
   10042                 :             : 
   10043                 :             :     /*
   10044                 :             :      * The result weight is half the input weight, rounded towards minus
   10045                 :             :      * infinity --- res_weight = floor(arg->weight / 2).
   10046                 :             :      */
   10047         [ +  + ]:        3032 :     if (arg->weight >= 0)
   10048                 :        2761 :         res_weight = arg->weight / 2;
   10049                 :             :     else
   10050                 :         271 :         res_weight = -((-arg->weight - 1) / 2 + 1);
   10051                 :             : 
   10052                 :             :     /*
   10053                 :             :      * Number of NBASE digits to compute.  To ensure correct rounding, compute
   10054                 :             :      * at least 1 extra decimal digit.  We explicitly allow rscale to be
   10055                 :             :      * negative here, but must always compute at least 1 NBASE digit.  Thus
   10056                 :             :      * res_ndigits = res_weight + 1 + ceil((rscale + 1) / DEC_DIGITS) or 1.
   10057                 :             :      */
   10058         [ +  - ]:        3032 :     if (rscale + 1 >= 0)
   10059                 :        3032 :         res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS) / DEC_DIGITS;
   10060                 :             :     else
   10061                 :           0 :         res_ndigits = res_weight + 1 - (-rscale - 1) / DEC_DIGITS;
   10062                 :        3032 :     res_ndigits = Max(res_ndigits, 1);
   10063                 :             : 
   10064                 :             :     /*
   10065                 :             :      * Number of source NBASE digits logically required to produce a result
   10066                 :             :      * with this precision --- every digit before the decimal point, plus 2
   10067                 :             :      * for each result digit after the decimal point (or minus 2 for each
   10068                 :             :      * result digit we round before the decimal point).
   10069                 :             :      */
   10070                 :        3032 :     src_ndigits = arg->weight + 1 + (res_ndigits - res_weight - 1) * 2;
   10071                 :        3032 :     src_ndigits = Max(src_ndigits, 1);
   10072                 :             : 
   10073                 :             :     /* ----------
   10074                 :             :      * From this point on, we treat the input and the result as integers and
   10075                 :             :      * compute the integer square root and remainder using the Karatsuba
   10076                 :             :      * Square Root algorithm, which may be written recursively as follows:
   10077                 :             :      *
   10078                 :             :      *  SqrtRem(n = a3*b^3 + a2*b^2 + a1*b + a0):
   10079                 :             :      *      [ for some base b, and coefficients a0,a1,a2,a3 chosen so that
   10080                 :             :      *        0 <= a0,a1,a2 < b and a3 >= b/4 ]
   10081                 :             :      *      Let (s,r) = SqrtRem(a3*b + a2)
   10082                 :             :      *      Let (q,u) = DivRem(r*b + a1, 2*s)
   10083                 :             :      *      Let s = s*b + q
   10084                 :             :      *      Let r = u*b + a0 - q^2
   10085                 :             :      *      If r < 0 Then
   10086                 :             :      *          Let r = r + s
   10087                 :             :      *          Let s = s - 1
   10088                 :             :      *          Let r = r + s
   10089                 :             :      *      Return (s,r)
   10090                 :             :      *
   10091                 :             :      * See "Karatsuba Square Root", Paul Zimmermann, INRIA Research Report
   10092                 :             :      * RR-3805, November 1999.  At the time of writing this was available
   10093                 :             :      * on the net at <https://hal.inria.fr/inria-00072854>.
   10094                 :             :      *
   10095                 :             :      * The way to read the assumption "n = a3*b^3 + a2*b^2 + a1*b + a0" is
   10096                 :             :      * "choose a base b such that n requires at least four base-b digits to
   10097                 :             :      * express; then those digits are a3,a2,a1,a0, with a3 possibly larger
   10098                 :             :      * than b".  For optimal performance, b should have approximately a
   10099                 :             :      * quarter the number of digits in the input, so that the outer square
   10100                 :             :      * root computes roughly twice as many digits as the inner one.  For
   10101                 :             :      * simplicity, we choose b = NBASE^blen, an integer power of NBASE.
   10102                 :             :      *
   10103                 :             :      * We implement the algorithm iteratively rather than recursively, to
   10104                 :             :      * allow the working variables to be reused.  With this approach, each
   10105                 :             :      * digit of the input is read precisely once --- src_idx tracks the number
   10106                 :             :      * of input digits used so far.
   10107                 :             :      *
   10108                 :             :      * The array ndigits[] holds the number of NBASE digits of the input that
   10109                 :             :      * will have been used at the end of each iteration, which roughly doubles
   10110                 :             :      * each time.  Note that the array elements are stored in reverse order,
   10111                 :             :      * so if the final iteration requires src_ndigits = 37 input digits, the
   10112                 :             :      * array will contain [37,19,11,7,5,3], and we would start by computing
   10113                 :             :      * the square root of the 3 most significant NBASE digits.
   10114                 :             :      *
   10115                 :             :      * In each iteration, we choose blen to be the largest integer for which
   10116                 :             :      * the input number has a3 >= b/4, when written in the form above.  In
   10117                 :             :      * general, this means blen = src_ndigits / 4 (truncated), but if
   10118                 :             :      * src_ndigits is a multiple of 4, that might lead to the coefficient a3
   10119                 :             :      * being less than b/4 (if the first input digit is less than NBASE/4), in
   10120                 :             :      * which case we choose blen = src_ndigits / 4 - 1.  The number of digits
   10121                 :             :      * in the inner square root is then src_ndigits - 2*blen.  So, for
   10122                 :             :      * example, if we have src_ndigits = 26 initially, the array ndigits[]
   10123                 :             :      * will be either [26,14,8,4] or [26,14,8,6,4], depending on the size of
   10124                 :             :      * the first input digit.
   10125                 :             :      *
   10126                 :             :      * Additionally, we can put an upper bound on the number of steps required
   10127                 :             :      * as follows --- suppose that the number of source digits is an n-bit
   10128                 :             :      * number in the range [2^(n-1), 2^n-1], then blen will be in the range
   10129                 :             :      * [2^(n-3)-1, 2^(n-2)-1] and the number of digits in the inner square
   10130                 :             :      * root will be in the range [2^(n-2), 2^(n-1)+1].  In the next step, blen
   10131                 :             :      * will be in the range [2^(n-4)-1, 2^(n-3)] and the number of digits in
   10132                 :             :      * the next inner square root will be in the range [2^(n-3), 2^(n-2)+1].
   10133                 :             :      * This pattern repeats, and in the worst case the array ndigits[] will
   10134                 :             :      * contain [2^n-1, 2^(n-1)+1, 2^(n-2)+1, ... 9, 5, 3], and the computation
   10135                 :             :      * will require n steps.  Therefore, since all digit array sizes are
   10136                 :             :      * signed 32-bit integers, the number of steps required is guaranteed to
   10137                 :             :      * be less than 32.
   10138                 :             :      * ----------
   10139                 :             :      */
   10140                 :        3032 :     step = 0;
   10141         [ +  + ]:       14531 :     while ((ndigits[step] = src_ndigits) > 4)
   10142                 :             :     {
   10143                 :             :         /* Choose b so that a3 >= b/4, as described above */
   10144                 :       11499 :         blen = src_ndigits / 4;
   10145   [ +  +  +  + ]:       11499 :         if (blen * 4 == src_ndigits && arg->digits[0] < NBASE / 4)
   10146                 :         259 :             blen--;
   10147                 :             : 
   10148                 :             :         /* Number of digits in the next step (inner square root) */
   10149                 :       11499 :         src_ndigits -= 2 * blen;
   10150                 :       11499 :         step++;
   10151                 :             :     }
   10152                 :             : 
   10153                 :             :     /*
   10154                 :             :      * First iteration (innermost square root and remainder):
   10155                 :             :      *
   10156                 :             :      * Here src_ndigits <= 4, and the input fits in an int64.  Its square root
   10157                 :             :      * has at most 9 decimal digits, so estimate it using double precision
   10158                 :             :      * arithmetic, which will in fact almost certainly return the correct
   10159                 :             :      * result with no further correction required.
   10160                 :             :      */
   10161                 :        3032 :     arg_int64 = arg->digits[0];
   10162         [ +  + ]:        9695 :     for (src_idx = 1; src_idx < src_ndigits; src_idx++)
   10163                 :             :     {
   10164                 :        6663 :         arg_int64 *= NBASE;
   10165         [ +  + ]:        6663 :         if (src_idx < arg->ndigits)
   10166                 :        5647 :             arg_int64 += arg->digits[src_idx];
   10167                 :             :     }
   10168                 :             : 
   10169                 :        3032 :     s_int64 = (int64) sqrt((double) arg_int64);
   10170                 :        3032 :     r_int64 = arg_int64 - s_int64 * s_int64;
   10171                 :             : 
   10172                 :             :     /*
   10173                 :             :      * Use Newton's method to correct the result, if necessary.
   10174                 :             :      *
   10175                 :             :      * This uses integer division with truncation to compute the truncated
   10176                 :             :      * integer square root by iterating using the formula x -> (x + n/x) / 2.
   10177                 :             :      * This is known to converge to isqrt(n), unless n+1 is a perfect square.
   10178                 :             :      * If n+1 is a perfect square, the sequence will oscillate between the two
   10179                 :             :      * values isqrt(n) and isqrt(n)+1, so we can be assured of convergence by
   10180                 :             :      * checking the remainder.
   10181                 :             :      */
   10182   [ -  +  -  + ]:        3032 :     while (r_int64 < 0 || r_int64 > 2 * s_int64)
   10183                 :             :     {
   10184                 :           0 :         s_int64 = (s_int64 + arg_int64 / s_int64) / 2;
   10185                 :           0 :         r_int64 = arg_int64 - s_int64 * s_int64;
   10186                 :             :     }
   10187                 :             : 
   10188                 :             :     /*
   10189                 :             :      * Iterations with src_ndigits <= 8:
   10190                 :             :      *
   10191                 :             :      * The next 1 or 2 iterations compute larger (outer) square roots with
   10192                 :             :      * src_ndigits <= 8, so the result still fits in an int64 (even though the
   10193                 :             :      * input no longer does) and we can continue to compute using int64
   10194                 :             :      * variables to avoid more expensive numeric computations.
   10195                 :             :      *
   10196                 :             :      * It is fairly easy to see that there is no risk of the intermediate
   10197                 :             :      * values below overflowing 64-bit integers.  In the worst case, the
   10198                 :             :      * previous iteration will have computed a 3-digit square root (of a
   10199                 :             :      * 6-digit input less than NBASE^6 / 4), so at the start of this
   10200                 :             :      * iteration, s will be less than NBASE^3 / 2 = 10^12 / 2, and r will be
   10201                 :             :      * less than 10^12.  In this case, blen will be 1, so numer will be less
   10202                 :             :      * than 10^17, and denom will be less than 10^12 (and hence u will also be
   10203                 :             :      * less than 10^12).  Finally, since q^2 = u*b + a0 - r, we can also be
   10204                 :             :      * sure that q^2 < 10^17.  Therefore all these quantities fit comfortably
   10205                 :             :      * in 64-bit integers.
   10206                 :             :      */
   10207                 :        3032 :     step--;
   10208   [ +  -  +  + ]:        7672 :     while (step >= 0 && (src_ndigits = ndigits[step]) <= 8)
   10209                 :             :     {
   10210                 :             :         int         b;
   10211                 :             :         int         a0;
   10212                 :             :         int         a1;
   10213                 :             :         int         i;
   10214                 :             :         int64       numer;
   10215                 :             :         int64       denom;
   10216                 :             :         int64       q;
   10217                 :             :         int64       u;
   10218                 :             : 
   10219                 :        4640 :         blen = (src_ndigits - src_idx) / 2;
   10220                 :             : 
   10221                 :             :         /* Extract a1 and a0, and compute b */
   10222                 :        4640 :         a0 = 0;
   10223                 :        4640 :         a1 = 0;
   10224                 :        4640 :         b = 1;
   10225                 :             : 
   10226         [ +  + ]:        9399 :         for (i = 0; i < blen; i++, src_idx++)
   10227                 :             :         {
   10228                 :        4759 :             b *= NBASE;
   10229                 :        4759 :             a1 *= NBASE;
   10230         [ +  + ]:        4759 :             if (src_idx < arg->ndigits)
   10231                 :        3532 :                 a1 += arg->digits[src_idx];
   10232                 :             :         }
   10233                 :             : 
   10234         [ +  + ]:        9399 :         for (i = 0; i < blen; i++, src_idx++)
   10235                 :             :         {
   10236                 :        4759 :             a0 *= NBASE;
   10237         [ +  + ]:        4759 :             if (src_idx < arg->ndigits)
   10238                 :        3420 :                 a0 += arg->digits[src_idx];
   10239                 :             :         }
   10240                 :             : 
   10241                 :             :         /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
   10242                 :        4640 :         numer = r_int64 * b + a1;
   10243                 :        4640 :         denom = 2 * s_int64;
   10244                 :        4640 :         q = numer / denom;
   10245                 :        4640 :         u = numer - q * denom;
   10246                 :             : 
   10247                 :             :         /* Compute s = s*b + q and r = u*b + a0 - q^2 */
   10248                 :        4640 :         s_int64 = s_int64 * b + q;
   10249                 :        4640 :         r_int64 = u * b + a0 - q * q;
   10250                 :             : 
   10251         [ +  + ]:        4640 :         if (r_int64 < 0)
   10252                 :             :         {
   10253                 :             :             /* s is too large by 1; set r += s, s--, r += s */
   10254                 :         161 :             r_int64 += s_int64;
   10255                 :         161 :             s_int64--;
   10256                 :         161 :             r_int64 += s_int64;
   10257                 :             :         }
   10258                 :             : 
   10259                 :             :         Assert(src_idx == src_ndigits); /* All input digits consumed */
   10260                 :        4640 :         step--;
   10261                 :             :     }
   10262                 :             : 
   10263                 :             :     /*
   10264                 :             :      * On platforms with 128-bit integer support, we can further delay the
   10265                 :             :      * need to use numeric variables.
   10266                 :             :      */
   10267                 :             : #ifdef HAVE_INT128
   10268         [ +  - ]:        3032 :     if (step >= 0)
   10269                 :             :     {
   10270                 :             :         int128      s_int128;
   10271                 :             :         int128      r_int128;
   10272                 :             : 
   10273                 :        3032 :         s_int128 = s_int64;
   10274                 :        3032 :         r_int128 = r_int64;
   10275                 :             : 
   10276                 :             :         /*
   10277                 :             :          * Iterations with src_ndigits <= 16:
   10278                 :             :          *
   10279                 :             :          * The result fits in an int128 (even though the input doesn't) so we
   10280                 :             :          * use int128 variables to avoid more expensive numeric computations.
   10281                 :             :          */
   10282   [ +  +  +  + ]:        6596 :         while (step >= 0 && (src_ndigits = ndigits[step]) <= 16)
   10283                 :             :         {
   10284                 :             :             int64       b;
   10285                 :             :             int64       a0;
   10286                 :             :             int64       a1;
   10287                 :             :             int64       i;
   10288                 :             :             int128      numer;
   10289                 :             :             int128      denom;
   10290                 :             :             int128      q;
   10291                 :             :             int128      u;
   10292                 :             : 
   10293                 :        3564 :             blen = (src_ndigits - src_idx) / 2;
   10294                 :             : 
   10295                 :             :             /* Extract a1 and a0, and compute b */
   10296                 :        3564 :             a0 = 0;
   10297                 :        3564 :             a1 = 0;
   10298                 :        3564 :             b = 1;
   10299                 :             : 
   10300         [ +  + ]:       11796 :             for (i = 0; i < blen; i++, src_idx++)
   10301                 :             :             {
   10302                 :        8232 :                 b *= NBASE;
   10303                 :        8232 :                 a1 *= NBASE;
   10304         [ +  + ]:        8232 :                 if (src_idx < arg->ndigits)
   10305                 :        4947 :                     a1 += arg->digits[src_idx];
   10306                 :             :             }
   10307                 :             : 
   10308         [ +  + ]:       11796 :             for (i = 0; i < blen; i++, src_idx++)
   10309                 :             :             {
   10310                 :        8232 :                 a0 *= NBASE;
   10311         [ +  + ]:        8232 :                 if (src_idx < arg->ndigits)
   10312                 :        3407 :                     a0 += arg->digits[src_idx];
   10313                 :             :             }
   10314                 :             : 
   10315                 :             :             /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
   10316                 :        3564 :             numer = r_int128 * b + a1;
   10317                 :        3564 :             denom = 2 * s_int128;
   10318                 :        3564 :             q = numer / denom;
   10319                 :        3564 :             u = numer - q * denom;
   10320                 :             : 
   10321                 :             :             /* Compute s = s*b + q and r = u*b + a0 - q^2 */
   10322                 :        3564 :             s_int128 = s_int128 * b + q;
   10323                 :        3564 :             r_int128 = u * b + a0 - q * q;
   10324                 :             : 
   10325         [ +  + ]:        3564 :             if (r_int128 < 0)
   10326                 :             :             {
   10327                 :             :                 /* s is too large by 1; set r += s, s--, r += s */
   10328                 :         146 :                 r_int128 += s_int128;
   10329                 :         146 :                 s_int128--;
   10330                 :         146 :                 r_int128 += s_int128;
   10331                 :             :             }
   10332                 :             : 
   10333                 :             :             Assert(src_idx == src_ndigits); /* All input digits consumed */
   10334                 :        3564 :             step--;
   10335                 :             :         }
   10336                 :             : 
   10337                 :             :         /*
   10338                 :             :          * All remaining iterations require numeric variables.  Convert the
   10339                 :             :          * integer values to NumericVar and continue.  Note that in the final
   10340                 :             :          * iteration we don't need the remainder, so we can save a few cycles
   10341                 :             :          * there by not fully computing it.
   10342                 :             :          */
   10343                 :        3032 :         int128_to_numericvar(s_int128, &s_var);
   10344         [ +  + ]:        3032 :         if (step >= 0)
   10345                 :        2008 :             int128_to_numericvar(r_int128, &r_var);
   10346                 :             :     }
   10347                 :             :     else
   10348                 :             :     {
   10349                 :           0 :         int64_to_numericvar(s_int64, &s_var);
   10350                 :             :         /* step < 0, so we certainly don't need r */
   10351                 :             :     }
   10352                 :             : #else                           /* !HAVE_INT128 */
   10353                 :             :     int64_to_numericvar(s_int64, &s_var);
   10354                 :             :     if (step >= 0)
   10355                 :             :         int64_to_numericvar(r_int64, &r_var);
   10356                 :             : #endif                          /* HAVE_INT128 */
   10357                 :             : 
   10358                 :             :     /*
   10359                 :             :      * The remaining iterations with src_ndigits > 8 (or 16, if have int128)
   10360                 :             :      * use numeric variables.
   10361                 :             :      */
   10362         [ +  + ]:        6327 :     while (step >= 0)
   10363                 :             :     {
   10364                 :             :         int         tmp_len;
   10365                 :             : 
   10366                 :        3295 :         src_ndigits = ndigits[step];
   10367                 :        3295 :         blen = (src_ndigits - src_idx) / 2;
   10368                 :             : 
   10369                 :             :         /* Extract a1 and a0 */
   10370         [ +  + ]:        3295 :         if (src_idx < arg->ndigits)
   10371                 :             :         {
   10372                 :        1088 :             tmp_len = Min(blen, arg->ndigits - src_idx);
   10373                 :        1088 :             alloc_var(&a1_var, tmp_len);
   10374                 :        1088 :             memcpy(a1_var.digits, arg->digits + src_idx,
   10375                 :             :                    tmp_len * sizeof(NumericDigit));
   10376                 :        1088 :             a1_var.weight = blen - 1;
   10377                 :        1088 :             a1_var.sign = NUMERIC_POS;
   10378                 :        1088 :             a1_var.dscale = 0;
   10379                 :        1088 :             strip_var(&a1_var);
   10380                 :             :         }
   10381                 :             :         else
   10382                 :             :         {
   10383                 :        2207 :             zero_var(&a1_var);
   10384                 :        2207 :             a1_var.dscale = 0;
   10385                 :             :         }
   10386                 :        3295 :         src_idx += blen;
   10387                 :             : 
   10388         [ +  + ]:        3295 :         if (src_idx < arg->ndigits)
   10389                 :             :         {
   10390                 :        1088 :             tmp_len = Min(blen, arg->ndigits - src_idx);
   10391                 :        1088 :             alloc_var(&a0_var, tmp_len);
   10392                 :        1088 :             memcpy(a0_var.digits, arg->digits + src_idx,
   10393                 :             :                    tmp_len * sizeof(NumericDigit));
   10394                 :        1088 :             a0_var.weight = blen - 1;
   10395                 :        1088 :             a0_var.sign = NUMERIC_POS;
   10396                 :        1088 :             a0_var.dscale = 0;
   10397                 :        1088 :             strip_var(&a0_var);
   10398                 :             :         }
   10399                 :             :         else
   10400                 :             :         {
   10401                 :        2207 :             zero_var(&a0_var);
   10402                 :        2207 :             a0_var.dscale = 0;
   10403                 :             :         }
   10404                 :        3295 :         src_idx += blen;
   10405                 :             : 
   10406                 :             :         /* Compute (q,u) = DivRem(r*b + a1, 2*s) */
   10407                 :        3295 :         set_var_from_var(&r_var, &q_var);
   10408                 :        3295 :         q_var.weight += blen;
   10409                 :        3295 :         add_var(&q_var, &a1_var, &q_var);
   10410                 :        3295 :         add_var(&s_var, &s_var, &u_var);
   10411                 :        3295 :         div_mod_var(&q_var, &u_var, &q_var, &u_var);
   10412                 :             : 
   10413                 :             :         /* Compute s = s*b + q */
   10414                 :        3295 :         s_var.weight += blen;
   10415                 :        3295 :         add_var(&s_var, &q_var, &s_var);
   10416                 :             : 
   10417                 :             :         /*
   10418                 :             :          * Compute r = u*b + a0 - q^2.
   10419                 :             :          *
   10420                 :             :          * In the final iteration, we don't actually need r; we just need to
   10421                 :             :          * know whether it is negative, so that we know whether to adjust s.
   10422                 :             :          * So instead of the final subtraction we can just compare.
   10423                 :             :          */
   10424                 :        3295 :         u_var.weight += blen;
   10425                 :        3295 :         add_var(&u_var, &a0_var, &u_var);
   10426                 :        3295 :         mul_var(&q_var, &q_var, &q_var, 0);
   10427                 :             : 
   10428         [ +  + ]:        3295 :         if (step > 0)
   10429                 :             :         {
   10430                 :             :             /* Need r for later iterations */
   10431                 :        1287 :             sub_var(&u_var, &q_var, &r_var);
   10432         [ +  + ]:        1287 :             if (r_var.sign == NUMERIC_NEG)
   10433                 :             :             {
   10434                 :             :                 /* s is too large by 1; set r += s, s--, r += s */
   10435                 :          85 :                 add_var(&r_var, &s_var, &r_var);
   10436                 :          85 :                 sub_var(&s_var, &const_one, &s_var);
   10437                 :          85 :                 add_var(&r_var, &s_var, &r_var);
   10438                 :             :             }
   10439                 :             :         }
   10440                 :             :         else
   10441                 :             :         {
   10442                 :             :             /* Don't need r anymore, except to test if s is too large by 1 */
   10443         [ +  + ]:        2008 :             if (cmp_var(&u_var, &q_var) < 0)
   10444                 :          27 :                 sub_var(&s_var, &const_one, &s_var);
   10445                 :             :         }
   10446                 :             : 
   10447                 :             :         Assert(src_idx == src_ndigits); /* All input digits consumed */
   10448                 :        3295 :         step--;
   10449                 :             :     }
   10450                 :             : 
   10451                 :             :     /*
   10452                 :             :      * Construct the final result, rounding it to the requested precision.
   10453                 :             :      */
   10454                 :        3032 :     set_var_from_var(&s_var, result);
   10455                 :        3032 :     result->weight = res_weight;
   10456                 :        3032 :     result->sign = NUMERIC_POS;
   10457                 :             : 
   10458                 :             :     /* Round to target rscale (and set result->dscale) */
   10459                 :        3032 :     round_var(result, rscale);
   10460                 :             : 
   10461                 :             :     /* Strip leading and trailing zeroes */
   10462                 :        3032 :     strip_var(result);
   10463                 :             : 
   10464                 :        3032 :     free_var(&s_var);
   10465                 :        3032 :     free_var(&r_var);
   10466                 :        3032 :     free_var(&a0_var);
   10467                 :        3032 :     free_var(&a1_var);
   10468                 :        3032 :     free_var(&q_var);
   10469                 :        3032 :     free_var(&u_var);
   10470                 :             : }
   10471                 :             : 
   10472                 :             : 
   10473                 :             : /*
   10474                 :             :  * exp_var() -
   10475                 :             :  *
   10476                 :             :  *  Raise e to the power of x, computed to rscale fractional digits
   10477                 :             :  */
   10478                 :             : static void
   10479                 :         139 : exp_var(const NumericVar *arg, NumericVar *result, int rscale)
   10480                 :             : {
   10481                 :             :     NumericVar  x;
   10482                 :             :     NumericVar  elem;
   10483                 :             :     int         ni;
   10484                 :             :     double      val;
   10485                 :             :     int         dweight;
   10486                 :             :     int         ndiv2;
   10487                 :             :     int         sig_digits;
   10488                 :             :     int         local_rscale;
   10489                 :             : 
   10490                 :         139 :     init_var(&x);
   10491                 :         139 :     init_var(&elem);
   10492                 :             : 
   10493                 :         139 :     set_var_from_var(arg, &x);
   10494                 :             : 
   10495                 :             :     /*
   10496                 :             :      * Estimate the dweight of the result using floating point arithmetic, so
   10497                 :             :      * that we can choose an appropriate local rscale for the calculation.
   10498                 :             :      */
   10499                 :         139 :     val = numericvar_to_double_no_overflow(&x);
   10500                 :             : 
   10501                 :             :     /* Guard against overflow/underflow */
   10502                 :             :     /* If you change this limit, see also power_var()'s limit */
   10503         [ +  + ]:         139 :     if (fabs(val) >= NUMERIC_MAX_RESULT_SCALE * 3)
   10504                 :             :     {
   10505         [ -  + ]:           5 :         if (val > 0)
   10506         [ #  # ]:           0 :             ereport(ERROR,
   10507                 :             :                     (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
   10508                 :             :                      errmsg("value overflows numeric format")));
   10509                 :           5 :         zero_var(result);
   10510                 :           5 :         result->dscale = rscale;
   10511                 :           5 :         return;
   10512                 :             :     }
   10513                 :             : 
   10514                 :             :     /* decimal weight = log10(e^x) = x * log10(e) */
   10515                 :         134 :     dweight = (int) (val * 0.434294481903252);
   10516                 :             : 
   10517                 :             :     /*
   10518                 :             :      * Reduce x to the range -0.01 <= x <= 0.01 (approximately) by dividing by
   10519                 :             :      * 2^ndiv2, to improve the convergence rate of the Taylor series.
   10520                 :             :      *
   10521                 :             :      * Note that the overflow check above ensures that fabs(x) < 6000, which
   10522                 :             :      * means that ndiv2 <= 20 here.
   10523                 :             :      */
   10524         [ +  + ]:         134 :     if (fabs(val) > 0.01)
   10525                 :             :     {
   10526                 :         110 :         ndiv2 = 1;
   10527                 :         110 :         val /= 2;
   10528                 :             : 
   10529         [ +  + ]:        1402 :         while (fabs(val) > 0.01)
   10530                 :             :         {
   10531                 :        1292 :             ndiv2++;
   10532                 :        1292 :             val /= 2;
   10533                 :             :         }
   10534                 :             : 
   10535                 :         110 :         local_rscale = x.dscale + ndiv2;
   10536                 :         110 :         div_var_int(&x, 1 << ndiv2, 0, &x, local_rscale, true);
   10537                 :             :     }
   10538                 :             :     else
   10539                 :          24 :         ndiv2 = 0;
   10540                 :             : 
   10541                 :             :     /*
   10542                 :             :      * Set the scale for the Taylor series expansion.  The final result has
   10543                 :             :      * (dweight + rscale + 1) significant digits.  In addition, we have to
   10544                 :             :      * raise the Taylor series result to the power 2^ndiv2, which introduces
   10545                 :             :      * an error of up to around log10(2^ndiv2) digits, so work with this many
   10546                 :             :      * extra digits of precision (plus a few more for good measure).
   10547                 :             :      */
   10548                 :         134 :     sig_digits = 1 + dweight + rscale + (int) (ndiv2 * 0.301029995663981);
   10549                 :         134 :     sig_digits = Max(sig_digits, 0) + 8;
   10550                 :             : 
   10551                 :         134 :     local_rscale = sig_digits - 1;
   10552                 :             : 
   10553                 :             :     /*
   10554                 :             :      * Use the Taylor series
   10555                 :             :      *
   10556                 :             :      * exp(x) = 1 + x + x^2/2! + x^3/3! + ...
   10557                 :             :      *
   10558                 :             :      * Given the limited range of x, this should converge reasonably quickly.
   10559                 :             :      * We run the series until the terms fall below the local_rscale limit.
   10560                 :             :      */
   10561                 :         134 :     add_var(&const_one, &x, result);
   10562                 :             : 
   10563                 :         134 :     mul_var(&x, &x, &elem, local_rscale);
   10564                 :         134 :     ni = 2;
   10565                 :         134 :     div_var_int(&elem, ni, 0, &elem, local_rscale, true);
   10566                 :             : 
   10567         [ +  + ]:        3639 :     while (elem.ndigits != 0)
   10568                 :             :     {
   10569                 :        3505 :         add_var(result, &elem, result);
   10570                 :             : 
   10571                 :        3505 :         mul_var(&elem, &x, &elem, local_rscale);
   10572                 :        3505 :         ni++;
   10573                 :        3505 :         div_var_int(&elem, ni, 0, &elem, local_rscale, true);
   10574                 :             :     }
   10575                 :             : 
   10576                 :             :     /*
   10577                 :             :      * Compensate for the argument range reduction.  Since the weight of the
   10578                 :             :      * result doubles with each multiplication, we can reduce the local rscale
   10579                 :             :      * as we proceed.
   10580                 :             :      */
   10581         [ +  + ]:        1536 :     while (ndiv2-- > 0)
   10582                 :             :     {
   10583                 :        1402 :         local_rscale = sig_digits - result->weight * 2 * DEC_DIGITS;
   10584                 :        1402 :         local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
   10585                 :        1402 :         mul_var(result, result, result, local_rscale);
   10586                 :             :     }
   10587                 :             : 
   10588                 :             :     /* Round to requested rscale */
   10589                 :         134 :     round_var(result, rscale);
   10590                 :             : 
   10591                 :         134 :     free_var(&x);
   10592                 :         134 :     free_var(&elem);
   10593                 :             : }
   10594                 :             : 
   10595                 :             : 
   10596                 :             : /*
   10597                 :             :  * Estimate the dweight of the most significant decimal digit of the natural
   10598                 :             :  * logarithm of a number.
   10599                 :             :  *
   10600                 :             :  * Essentially, we're approximating log10(abs(ln(var))).  This is used to
   10601                 :             :  * determine the appropriate rscale when computing natural logarithms.
   10602                 :             :  *
   10603                 :             :  * Note: many callers call this before range-checking the input.  Therefore,
   10604                 :             :  * we must be robust against values that are invalid to apply ln() to.
   10605                 :             :  * We don't wish to throw an error here, so just return zero in such cases.
   10606                 :             :  */
   10607                 :             : static int
   10608                 :         534 : estimate_ln_dweight(const NumericVar *var)
   10609                 :             : {
   10610                 :             :     int         ln_dweight;
   10611                 :             : 
   10612                 :             :     /* Caller should fail on ln(negative), but for the moment return zero */
   10613         [ +  + ]:         534 :     if (var->sign != NUMERIC_POS)
   10614                 :          28 :         return 0;
   10615                 :             : 
   10616   [ +  +  +  + ]:         953 :     if (cmp_var(var, &const_zero_point_nine) >= 0 &&
   10617                 :         447 :         cmp_var(var, &const_one_point_one) <= 0)
   10618                 :          70 :     {
   10619                 :             :         /*
   10620                 :             :          * 0.9 <= var <= 1.1
   10621                 :             :          *
   10622                 :             :          * ln(var) has a negative weight (possibly very large).  To get a
   10623                 :             :          * reasonably accurate result, estimate it using ln(1+x) ~= x.
   10624                 :             :          */
   10625                 :             :         NumericVar  x;
   10626                 :             : 
   10627                 :          70 :         init_var(&x);
   10628                 :          70 :         sub_var(var, &const_one, &x);
   10629                 :             : 
   10630         [ +  + ]:          70 :         if (x.ndigits > 0)
   10631                 :             :         {
   10632                 :             :             /* Use weight of most significant decimal digit of x */
   10633                 :          35 :             ln_dweight = x.weight * DEC_DIGITS + (int) log10(x.digits[0]);
   10634                 :             :         }
   10635                 :             :         else
   10636                 :             :         {
   10637                 :             :             /* x = 0.  Since ln(1) = 0 exactly, we don't need extra digits */
   10638                 :          35 :             ln_dweight = 0;
   10639                 :             :         }
   10640                 :             : 
   10641                 :          70 :         free_var(&x);
   10642                 :             :     }
   10643                 :             :     else
   10644                 :             :     {
   10645                 :             :         /*
   10646                 :             :          * Estimate the logarithm using the first couple of digits from the
   10647                 :             :          * input number.  This will give an accurate result whenever the input
   10648                 :             :          * is not too close to 1.
   10649                 :             :          */
   10650         [ +  + ]:         436 :         if (var->ndigits > 0)
   10651                 :             :         {
   10652                 :             :             int         digits;
   10653                 :             :             int         dweight;
   10654                 :             :             double      ln_var;
   10655                 :             : 
   10656                 :         408 :             digits = var->digits[0];
   10657                 :         408 :             dweight = var->weight * DEC_DIGITS;
   10658                 :             : 
   10659         [ +  + ]:         408 :             if (var->ndigits > 1)
   10660                 :             :             {
   10661                 :         250 :                 digits = digits * NBASE + var->digits[1];
   10662                 :         250 :                 dweight -= DEC_DIGITS;
   10663                 :             :             }
   10664                 :             : 
   10665                 :             :             /*----------
   10666                 :             :              * We have var ~= digits * 10^dweight
   10667                 :             :              * so ln(var) ~= ln(digits) + dweight * ln(10)
   10668                 :             :              *----------
   10669                 :             :              */
   10670                 :         408 :             ln_var = log((double) digits) + dweight * 2.302585092994046;
   10671                 :         408 :             ln_dweight = (int) log10(fabs(ln_var));
   10672                 :             :         }
   10673                 :             :         else
   10674                 :             :         {
   10675                 :             :             /* Caller should fail on ln(0), but for the moment return zero */
   10676                 :          28 :             ln_dweight = 0;
   10677                 :             :         }
   10678                 :             :     }
   10679                 :             : 
   10680                 :         506 :     return ln_dweight;
   10681                 :             : }
   10682                 :             : 
   10683                 :             : 
   10684                 :             : /*
   10685                 :             :  * ln_var() -
   10686                 :             :  *
   10687                 :             :  *  Compute the natural log of x
   10688                 :             :  */
   10689                 :             : static void
   10690                 :         607 : ln_var(const NumericVar *arg, NumericVar *result, int rscale)
   10691                 :             : {
   10692                 :             :     NumericVar  x;
   10693                 :             :     NumericVar  xx;
   10694                 :             :     int         ni;
   10695                 :             :     NumericVar  elem;
   10696                 :             :     NumericVar  fact;
   10697                 :             :     int         nsqrt;
   10698                 :             :     int         local_rscale;
   10699                 :             :     int         cmp;
   10700                 :             : 
   10701                 :         607 :     cmp = cmp_var(arg, &const_zero);
   10702         [ +  + ]:         607 :     if (cmp == 0)
   10703         [ +  - ]:          28 :         ereport(ERROR,
   10704                 :             :                 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
   10705                 :             :                  errmsg("cannot take logarithm of zero")));
   10706         [ +  + ]:         579 :     else if (cmp < 0)
   10707         [ +  - ]:          24 :         ereport(ERROR,
   10708                 :             :                 (errcode(ERRCODE_INVALID_ARGUMENT_FOR_LOG),
   10709                 :             :                  errmsg("cannot take logarithm of a negative number")));
   10710                 :             : 
   10711                 :         555 :     init_var(&x);
   10712                 :         555 :     init_var(&xx);
   10713                 :         555 :     init_var(&elem);
   10714                 :         555 :     init_var(&fact);
   10715                 :             : 
   10716                 :         555 :     set_var_from_var(arg, &x);
   10717                 :         555 :     set_var_from_var(&const_two, &fact);
   10718                 :             : 
   10719                 :             :     /*
   10720                 :             :      * Reduce input into range 0.9 < x < 1.1 with repeated sqrt() operations.
   10721                 :             :      *
   10722                 :             :      * The final logarithm will have up to around rscale+6 significant digits.
   10723                 :             :      * Each sqrt() will roughly halve the weight of x, so adjust the local
   10724                 :             :      * rscale as we work so that we keep this many significant digits at each
   10725                 :             :      * step (plus a few more for good measure).
   10726                 :             :      *
   10727                 :             :      * Note that we allow local_rscale < 0 during this input reduction
   10728                 :             :      * process, which implies rounding before the decimal point.  sqrt_var()
   10729                 :             :      * explicitly supports this, and it significantly reduces the work
   10730                 :             :      * required to reduce very large inputs to the required range.  Once the
   10731                 :             :      * input reduction is complete, x.weight will be 0 and its display scale
   10732                 :             :      * will be non-negative again.
   10733                 :             :      */
   10734                 :         555 :     nsqrt = 0;
   10735         [ +  + ]:         826 :     while (cmp_var(&x, &const_zero_point_nine) <= 0)
   10736                 :             :     {
   10737                 :         271 :         local_rscale = rscale - x.weight * DEC_DIGITS / 2 + 8;
   10738                 :         271 :         sqrt_var(&x, &x, local_rscale);
   10739                 :         271 :         mul_var(&fact, &const_two, &fact, 0);
   10740                 :         271 :         nsqrt++;
   10741                 :             :     }
   10742         [ +  + ]:        2984 :     while (cmp_var(&x, &const_one_point_one) >= 0)
   10743                 :             :     {
   10744                 :        2429 :         local_rscale = rscale - x.weight * DEC_DIGITS / 2 + 8;
   10745                 :        2429 :         sqrt_var(&x, &x, local_rscale);
   10746                 :        2429 :         mul_var(&fact, &const_two, &fact, 0);
   10747                 :        2429 :         nsqrt++;
   10748                 :             :     }
   10749                 :             : 
   10750                 :             :     /*
   10751                 :             :      * We use the Taylor series for 0.5 * ln((1+z)/(1-z)),
   10752                 :             :      *
   10753                 :             :      * z + z^3/3 + z^5/5 + ...
   10754                 :             :      *
   10755                 :             :      * where z = (x-1)/(x+1) is in the range (approximately) -0.053 .. 0.048
   10756                 :             :      * due to the above range-reduction of x.
   10757                 :             :      *
   10758                 :             :      * The convergence of this is not as fast as one would like, but is
   10759                 :             :      * tolerable given that z is small.
   10760                 :             :      *
   10761                 :             :      * The Taylor series result will be multiplied by 2^(nsqrt+1), which has a
   10762                 :             :      * decimal weight of (nsqrt+1) * log10(2), so work with this many extra
   10763                 :             :      * digits of precision (plus a few more for good measure).
   10764                 :             :      */
   10765                 :         555 :     local_rscale = rscale + (int) ((nsqrt + 1) * 0.301029995663981) + 8;
   10766                 :             : 
   10767                 :         555 :     sub_var(&x, &const_one, result);
   10768                 :         555 :     add_var(&x, &const_one, &elem);
   10769                 :         555 :     div_var(result, &elem, result, local_rscale, true, false);
   10770                 :         555 :     set_var_from_var(result, &xx);
   10771                 :         555 :     mul_var(result, result, &x, local_rscale);
   10772                 :             : 
   10773                 :         555 :     ni = 1;
   10774                 :             : 
   10775                 :             :     for (;;)
   10776                 :             :     {
   10777                 :       10009 :         ni += 2;
   10778                 :       10009 :         mul_var(&xx, &x, &xx, local_rscale);
   10779                 :       10009 :         div_var_int(&xx, ni, 0, &elem, local_rscale, true);
   10780                 :             : 
   10781         [ +  + ]:       10009 :         if (elem.ndigits == 0)
   10782                 :         555 :             break;
   10783                 :             : 
   10784                 :        9454 :         add_var(result, &elem, result);
   10785                 :             : 
   10786         [ -  + ]:        9454 :         if (elem.weight < (result->weight - local_rscale * 2 / DEC_DIGITS))
   10787                 :           0 :             break;
   10788                 :             :     }
   10789                 :             : 
   10790                 :             :     /* Compensate for argument range reduction, round to requested rscale */
   10791                 :         555 :     mul_var(result, &fact, result, rscale);
   10792                 :             : 
   10793                 :         555 :     free_var(&x);
   10794                 :         555 :     free_var(&xx);
   10795                 :         555 :     free_var(&elem);
   10796                 :         555 :     free_var(&fact);
   10797                 :         555 : }
   10798                 :             : 
   10799                 :             : 
   10800                 :             : /*
   10801                 :             :  * log_var() -
   10802                 :             :  *
   10803                 :             :  *  Compute the logarithm of num in a given base.
   10804                 :             :  *
   10805                 :             :  *  Note: this routine chooses dscale of the result.
   10806                 :             :  */
   10807                 :             : static void
   10808                 :         156 : log_var(const NumericVar *base, const NumericVar *num, NumericVar *result)
   10809                 :             : {
   10810                 :             :     NumericVar  ln_base;
   10811                 :             :     NumericVar  ln_num;
   10812                 :             :     int         ln_base_dweight;
   10813                 :             :     int         ln_num_dweight;
   10814                 :             :     int         result_dweight;
   10815                 :             :     int         rscale;
   10816                 :             :     int         ln_base_rscale;
   10817                 :             :     int         ln_num_rscale;
   10818                 :             : 
   10819                 :         156 :     init_var(&ln_base);
   10820                 :         156 :     init_var(&ln_num);
   10821                 :             : 
   10822                 :             :     /* Estimated dweights of ln(base), ln(num) and the final result */
   10823                 :         156 :     ln_base_dweight = estimate_ln_dweight(base);
   10824                 :         156 :     ln_num_dweight = estimate_ln_dweight(num);
   10825                 :         156 :     result_dweight = ln_num_dweight - ln_base_dweight;
   10826                 :             : 
   10827                 :             :     /*
   10828                 :             :      * Select the scale of the result so that it will have at least
   10829                 :             :      * NUMERIC_MIN_SIG_DIGITS significant digits and is not less than either
   10830                 :             :      * input's display scale.
   10831                 :             :      */
   10832                 :         156 :     rscale = NUMERIC_MIN_SIG_DIGITS - result_dweight;
   10833                 :         156 :     rscale = Max(rscale, base->dscale);
   10834                 :         156 :     rscale = Max(rscale, num->dscale);
   10835                 :         156 :     rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
   10836                 :         156 :     rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
   10837                 :             : 
   10838                 :             :     /*
   10839                 :             :      * Set the scales for ln(base) and ln(num) so that they each have more
   10840                 :             :      * significant digits than the final result.
   10841                 :             :      */
   10842                 :         156 :     ln_base_rscale = rscale + result_dweight - ln_base_dweight + 8;
   10843                 :         156 :     ln_base_rscale = Max(ln_base_rscale, NUMERIC_MIN_DISPLAY_SCALE);
   10844                 :             : 
   10845                 :         156 :     ln_num_rscale = rscale + result_dweight - ln_num_dweight + 8;
   10846                 :         156 :     ln_num_rscale = Max(ln_num_rscale, NUMERIC_MIN_DISPLAY_SCALE);
   10847                 :             : 
   10848                 :             :     /* Form natural logarithms */
   10849                 :         156 :     ln_var(base, &ln_base, ln_base_rscale);
   10850                 :         140 :     ln_var(num, &ln_num, ln_num_rscale);
   10851                 :             : 
   10852                 :             :     /* Divide and round to the required scale */
   10853                 :         120 :     div_var(&ln_num, &ln_base, result, rscale, true, false);
   10854                 :             : 
   10855                 :         116 :     free_var(&ln_num);
   10856                 :         116 :     free_var(&ln_base);
   10857                 :         116 : }
   10858                 :             : 
   10859                 :             : 
   10860                 :             : /*
   10861                 :             :  * power_var() -
   10862                 :             :  *
   10863                 :             :  *  Raise base to the power of exp
   10864                 :             :  *
   10865                 :             :  *  Note: this routine chooses dscale of the result.
   10866                 :             :  */
   10867                 :             : static void
   10868                 :         968 : power_var(const NumericVar *base, const NumericVar *exp, NumericVar *result)
   10869                 :             : {
   10870                 :             :     int         res_sign;
   10871                 :             :     NumericVar  abs_base;
   10872                 :             :     NumericVar  ln_base;
   10873                 :             :     NumericVar  ln_num;
   10874                 :             :     int         ln_dweight;
   10875                 :             :     int         rscale;
   10876                 :             :     int         sig_digits;
   10877                 :             :     int         local_rscale;
   10878                 :             :     double      val;
   10879                 :             : 
   10880                 :             :     /* If exp can be represented as an integer, use power_var_int */
   10881   [ +  +  +  + ]:         968 :     if (exp->ndigits == 0 || exp->ndigits <= exp->weight + 1)
   10882                 :             :     {
   10883                 :             :         /* exact integer, but does it fit in int? */
   10884                 :             :         int64       expval64;
   10885                 :             : 
   10886         [ +  + ]:         878 :         if (numericvar_to_int64(exp, &expval64))
   10887                 :             :         {
   10888   [ +  -  +  + ]:         873 :             if (expval64 >= PG_INT32_MIN && expval64 <= PG_INT32_MAX)
   10889                 :             :             {
   10890                 :             :                 /* Okay, use power_var_int */
   10891                 :         848 :                 power_var_int(base, (int) expval64, exp->dscale, result);
   10892                 :         840 :                 return;
   10893                 :             :             }
   10894                 :             :         }
   10895                 :             :     }
   10896                 :             : 
   10897                 :             :     /*
   10898                 :             :      * This avoids log(0) for cases of 0 raised to a non-integer.  0 ^ 0 is
   10899                 :             :      * handled by power_var_int().
   10900                 :             :      */
   10901         [ +  + ]:         120 :     if (cmp_var(base, &const_zero) == 0)
   10902                 :             :     {
   10903                 :          14 :         set_var_from_var(&const_zero, result);
   10904                 :          14 :         result->dscale = NUMERIC_MIN_SIG_DIGITS; /* no need to round */
   10905                 :          14 :         return;
   10906                 :             :     }
   10907                 :             : 
   10908                 :         106 :     init_var(&abs_base);
   10909                 :         106 :     init_var(&ln_base);
   10910                 :         106 :     init_var(&ln_num);
   10911                 :             : 
   10912                 :             :     /*
   10913                 :             :      * If base is negative, insist that exp be an integer.  The result is then
   10914                 :             :      * positive if exp is even and negative if exp is odd.
   10915                 :             :      */
   10916         [ +  + ]:         106 :     if (base->sign == NUMERIC_NEG)
   10917                 :             :     {
   10918                 :             :         /*
   10919                 :             :          * Check that exp is an integer.  This error code is defined by the
   10920                 :             :          * SQL standard, and matches other errors in numeric_power().
   10921                 :             :          */
   10922   [ +  -  +  + ]:          27 :         if (exp->ndigits > 0 && exp->ndigits > exp->weight + 1)
   10923         [ +  - ]:          12 :             ereport(ERROR,
   10924                 :             :                     (errcode(ERRCODE_INVALID_ARGUMENT_FOR_POWER_FUNCTION),
   10925                 :             :                      errmsg("a negative number raised to a non-integer power yields a complex result")));
   10926                 :             : 
   10927                 :             :         /* Test if exp is odd or even */
   10928   [ +  -  +  + ]:          15 :         if (exp->ndigits > 0 && exp->ndigits == exp->weight + 1 &&
   10929         [ +  + ]:          10 :             (exp->digits[exp->ndigits - 1] & 1))
   10930                 :           5 :             res_sign = NUMERIC_NEG;
   10931                 :             :         else
   10932                 :          10 :             res_sign = NUMERIC_POS;
   10933                 :             : 
   10934                 :             :         /* Then work with abs(base) below */
   10935                 :          15 :         set_var_from_var(base, &abs_base);
   10936                 :          15 :         abs_base.sign = NUMERIC_POS;
   10937                 :          15 :         base = &abs_base;
   10938                 :             :     }
   10939                 :             :     else
   10940                 :          79 :         res_sign = NUMERIC_POS;
   10941                 :             : 
   10942                 :             :     /*----------
   10943                 :             :      * Decide on the scale for the ln() calculation.  For this we need an
   10944                 :             :      * estimate of the weight of the result, which we obtain by doing an
   10945                 :             :      * initial low-precision calculation of exp * ln(base).
   10946                 :             :      *
   10947                 :             :      * We want result = e ^ (exp * ln(base))
   10948                 :             :      * so result dweight = log10(result) = exp * ln(base) * log10(e)
   10949                 :             :      *
   10950                 :             :      * We also perform a crude overflow test here so that we can exit early if
   10951                 :             :      * the full-precision result is sure to overflow, and to guard against
   10952                 :             :      * integer overflow when determining the scale for the real calculation.
   10953                 :             :      * exp_var() supports inputs up to NUMERIC_MAX_RESULT_SCALE * 3, so the
   10954                 :             :      * result will overflow if exp * ln(base) >= NUMERIC_MAX_RESULT_SCALE * 3.
   10955                 :             :      * Since the values here are only approximations, we apply a small fuzz
   10956                 :             :      * factor to this overflow test and let exp_var() determine the exact
   10957                 :             :      * overflow threshold so that it is consistent for all inputs.
   10958                 :             :      *----------
   10959                 :             :      */
   10960                 :          94 :     ln_dweight = estimate_ln_dweight(base);
   10961                 :             : 
   10962                 :             :     /*
   10963                 :             :      * Set the scale for the low-precision calculation, computing ln(base) to
   10964                 :             :      * around 8 significant digits.  Note that ln_dweight may be as small as
   10965                 :             :      * -NUMERIC_DSCALE_MAX, so the scale may exceed NUMERIC_MAX_DISPLAY_SCALE
   10966                 :             :      * here.
   10967                 :             :      */
   10968                 :          94 :     local_rscale = 8 - ln_dweight;
   10969                 :          94 :     local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
   10970                 :             : 
   10971                 :          94 :     ln_var(base, &ln_base, local_rscale);
   10972                 :             : 
   10973                 :          94 :     mul_var(&ln_base, exp, &ln_num, local_rscale);
   10974                 :             : 
   10975                 :          94 :     val = numericvar_to_double_no_overflow(&ln_num);
   10976                 :             : 
   10977                 :             :     /* initial overflow/underflow test with fuzz factor */
   10978         [ +  + ]:          94 :     if (fabs(val) > NUMERIC_MAX_RESULT_SCALE * 3.01)
   10979                 :             :     {
   10980         [ -  + ]:           5 :         if (val > 0)
   10981         [ #  # ]:           0 :             ereport(ERROR,
   10982                 :             :                     (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
   10983                 :             :                      errmsg("value overflows numeric format")));
   10984                 :           5 :         zero_var(result);
   10985                 :           5 :         result->dscale = NUMERIC_MAX_DISPLAY_SCALE;
   10986                 :           5 :         return;
   10987                 :             :     }
   10988                 :             : 
   10989                 :          89 :     val *= 0.434294481903252;   /* approximate decimal result weight */
   10990                 :             : 
   10991                 :             :     /* choose the result scale */
   10992                 :          89 :     rscale = NUMERIC_MIN_SIG_DIGITS - (int) val;
   10993                 :          89 :     rscale = Max(rscale, base->dscale);
   10994                 :          89 :     rscale = Max(rscale, exp->dscale);
   10995                 :          89 :     rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
   10996                 :          89 :     rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
   10997                 :             : 
   10998                 :             :     /* significant digits required in the result */
   10999                 :          89 :     sig_digits = rscale + (int) val;
   11000                 :          89 :     sig_digits = Max(sig_digits, 0);
   11001                 :             : 
   11002                 :             :     /* set the scale for the real exp * ln(base) calculation */
   11003                 :          89 :     local_rscale = sig_digits - ln_dweight + 8;
   11004                 :          89 :     local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
   11005                 :             : 
   11006                 :             :     /* and do the real calculation */
   11007                 :             : 
   11008                 :          89 :     ln_var(base, &ln_base, local_rscale);
   11009                 :             : 
   11010                 :          89 :     mul_var(&ln_base, exp, &ln_num, local_rscale);
   11011                 :             : 
   11012                 :          89 :     exp_var(&ln_num, result, rscale);
   11013                 :             : 
   11014   [ +  +  +  - ]:          89 :     if (res_sign == NUMERIC_NEG && result->ndigits > 0)
   11015                 :           5 :         result->sign = NUMERIC_NEG;
   11016                 :             : 
   11017                 :          89 :     free_var(&ln_num);
   11018                 :          89 :     free_var(&ln_base);
   11019                 :          89 :     free_var(&abs_base);
   11020                 :             : }
   11021                 :             : 
   11022                 :             : /*
   11023                 :             :  * power_var_int() -
   11024                 :             :  *
   11025                 :             :  *  Raise base to the power of exp, where exp is an integer.
   11026                 :             :  *
   11027                 :             :  *  Note: this routine chooses dscale of the result.
   11028                 :             :  */
   11029                 :             : static void
   11030                 :         848 : power_var_int(const NumericVar *base, int exp, int exp_dscale,
   11031                 :             :               NumericVar *result)
   11032                 :             : {
   11033                 :             :     double      f;
   11034                 :             :     int         p;
   11035                 :             :     int         i;
   11036                 :             :     int         rscale;
   11037                 :             :     int         sig_digits;
   11038                 :             :     unsigned int mask;
   11039                 :             :     bool        neg;
   11040                 :             :     NumericVar  base_prod;
   11041                 :             :     int         local_rscale;
   11042                 :             : 
   11043                 :             :     /*
   11044                 :             :      * Choose the result scale.  For this we need an estimate of the decimal
   11045                 :             :      * weight of the result, which we obtain by approximating using double
   11046                 :             :      * precision arithmetic.
   11047                 :             :      *
   11048                 :             :      * We also perform crude overflow/underflow tests here so that we can exit
   11049                 :             :      * early if the result is sure to overflow/underflow, and to guard against
   11050                 :             :      * integer overflow when choosing the result scale.
   11051                 :             :      */
   11052         [ +  + ]:         848 :     if (base->ndigits != 0)
   11053                 :             :     {
   11054                 :             :         /*----------
   11055                 :             :          * Choose f (double) and p (int) such that base ~= f * 10^p.
   11056                 :             :          * Then log10(result) = log10(base^exp) ~= exp * (log10(f) + p).
   11057                 :             :          *----------
   11058                 :             :          */
   11059                 :         826 :         f = base->digits[0];
   11060                 :         826 :         p = base->weight * DEC_DIGITS;
   11061                 :             : 
   11062   [ +  +  +  - ]:         891 :         for (i = 1; i < base->ndigits && i * DEC_DIGITS < 16; i++)
   11063                 :             :         {
   11064                 :          65 :             f = f * NBASE + base->digits[i];
   11065                 :          65 :             p -= DEC_DIGITS;
   11066                 :             :         }
   11067                 :             : 
   11068                 :         826 :         f = exp * (log10(f) + p);   /* approximate decimal result weight */
   11069                 :             :     }
   11070                 :             :     else
   11071                 :          22 :         f = 0;                  /* result is 0 or 1 (weight 0), or error */
   11072                 :             : 
   11073                 :             :     /* overflow/underflow tests with fuzz factors */
   11074         [ +  + ]:         848 :     if (f > (NUMERIC_WEIGHT_MAX + 1) * DEC_DIGITS)
   11075         [ +  - ]:           8 :         ereport(ERROR,
   11076                 :             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
   11077                 :             :                  errmsg("value overflows numeric format")));
   11078         [ +  + ]:         840 :     if (f + 1 < -NUMERIC_MAX_DISPLAY_SCALE)
   11079                 :             :     {
   11080                 :          10 :         zero_var(result);
   11081                 :          10 :         result->dscale = NUMERIC_MAX_DISPLAY_SCALE;
   11082                 :         151 :         return;
   11083                 :             :     }
   11084                 :             : 
   11085                 :             :     /*
   11086                 :             :      * Choose the result scale in the same way as power_var(), so it has at
   11087                 :             :      * least NUMERIC_MIN_SIG_DIGITS significant digits and is not less than
   11088                 :             :      * either input's display scale.
   11089                 :             :      */
   11090                 :         830 :     rscale = NUMERIC_MIN_SIG_DIGITS - (int) f;
   11091                 :         830 :     rscale = Max(rscale, base->dscale);
   11092                 :         830 :     rscale = Max(rscale, exp_dscale);
   11093                 :         830 :     rscale = Max(rscale, NUMERIC_MIN_DISPLAY_SCALE);
   11094                 :         830 :     rscale = Min(rscale, NUMERIC_MAX_DISPLAY_SCALE);
   11095                 :             : 
   11096                 :             :     /* Handle some common special cases, as well as corner cases */
   11097   [ +  +  +  +  :         830 :     switch (exp)
                      + ]
   11098                 :             :     {
   11099                 :          52 :         case 0:
   11100                 :             : 
   11101                 :             :             /*
   11102                 :             :              * While 0 ^ 0 can be either 1 or indeterminate (error), we treat
   11103                 :             :              * it as 1 because most programming languages do this. SQL:2003
   11104                 :             :              * also requires a return value of 1.
   11105                 :             :              * https://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_zero_power
   11106                 :             :              */
   11107                 :          52 :             set_var_from_var(&const_one, result);
   11108                 :          52 :             result->dscale = rscale; /* no need to round */
   11109                 :          52 :             return;
   11110                 :          32 :         case 1:
   11111                 :          32 :             set_var_from_var(base, result);
   11112                 :          32 :             round_var(result, rscale);
   11113                 :          32 :             return;
   11114                 :          21 :         case -1:
   11115                 :          21 :             div_var(&const_one, base, result, rscale, true, true);
   11116                 :          21 :             return;
   11117                 :          36 :         case 2:
   11118                 :          36 :             mul_var(base, base, result, rscale);
   11119                 :          36 :             return;
   11120                 :         689 :         default:
   11121                 :         689 :             break;
   11122                 :             :     }
   11123                 :             : 
   11124                 :             :     /* Handle the special case where the base is zero */
   11125         [ -  + ]:         689 :     if (base->ndigits == 0)
   11126                 :             :     {
   11127         [ #  # ]:           0 :         if (exp < 0)
   11128         [ #  # ]:           0 :             ereport(ERROR,
   11129                 :             :                     (errcode(ERRCODE_DIVISION_BY_ZERO),
   11130                 :             :                      errmsg("division by zero")));
   11131                 :           0 :         zero_var(result);
   11132                 :           0 :         result->dscale = rscale;
   11133                 :           0 :         return;
   11134                 :             :     }
   11135                 :             : 
   11136                 :             :     /*
   11137                 :             :      * The general case repeatedly multiplies base according to the bit
   11138                 :             :      * pattern of exp.
   11139                 :             :      *
   11140                 :             :      * The local rscale used for each multiplication is varied to keep a fixed
   11141                 :             :      * number of significant digits, sufficient to give the required result
   11142                 :             :      * scale.
   11143                 :             :      */
   11144                 :             : 
   11145                 :             :     /*
   11146                 :             :      * Approximate number of significant digits in the result.  Note that the
   11147                 :             :      * underflow test above, together with the choice of rscale, ensures that
   11148                 :             :      * this approximation is necessarily > 0.
   11149                 :             :      */
   11150                 :         689 :     sig_digits = 1 + rscale + (int) f;
   11151                 :             : 
   11152                 :             :     /*
   11153                 :             :      * The multiplications to produce the result may introduce an error of up
   11154                 :             :      * to around log10(abs(exp)) digits, so work with this many extra digits
   11155                 :             :      * of precision (plus a few more for good measure).
   11156                 :             :      */
   11157                 :         689 :     sig_digits += (int) log(fabs((double) exp)) + 8;
   11158                 :             : 
   11159                 :             :     /*
   11160                 :             :      * Now we can proceed with the multiplications.
   11161                 :             :      */
   11162                 :         689 :     neg = (exp < 0);
   11163                 :         689 :     mask = pg_abs_s32(exp);
   11164                 :             : 
   11165                 :         689 :     init_var(&base_prod);
   11166                 :         689 :     set_var_from_var(base, &base_prod);
   11167                 :             : 
   11168         [ +  + ]:         689 :     if (mask & 1)
   11169                 :         343 :         set_var_from_var(base, result);
   11170                 :             :     else
   11171                 :         346 :         set_var_from_var(&const_one, result);
   11172                 :             : 
   11173         [ +  + ]:        3618 :     while ((mask >>= 1) > 0)
   11174                 :             :     {
   11175                 :             :         /*
   11176                 :             :          * Do the multiplications using rscales large enough to hold the
   11177                 :             :          * results to the required number of significant digits, but don't
   11178                 :             :          * waste time by exceeding the scales of the numbers themselves.
   11179                 :             :          */
   11180                 :        2929 :         local_rscale = sig_digits - 2 * base_prod.weight * DEC_DIGITS;
   11181                 :        2929 :         local_rscale = Min(local_rscale, 2 * base_prod.dscale);
   11182                 :        2929 :         local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
   11183                 :             : 
   11184                 :        2929 :         mul_var(&base_prod, &base_prod, &base_prod, local_rscale);
   11185                 :             : 
   11186         [ +  + ]:        2929 :         if (mask & 1)
   11187                 :             :         {
   11188                 :        1932 :             local_rscale = sig_digits -
   11189                 :        1932 :                 (base_prod.weight + result->weight) * DEC_DIGITS;
   11190                 :        1932 :             local_rscale = Min(local_rscale,
   11191                 :             :                                base_prod.dscale + result->dscale);
   11192                 :        1932 :             local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
   11193                 :             : 
   11194                 :        1932 :             mul_var(&base_prod, result, result, local_rscale);
   11195                 :             :         }
   11196                 :             : 
   11197                 :             :         /*
   11198                 :             :          * When abs(base) > 1, the number of digits to the left of the decimal
   11199                 :             :          * point in base_prod doubles at each iteration, so if exp is large we
   11200                 :             :          * could easily spend large amounts of time and memory space doing the
   11201                 :             :          * multiplications.  But once the weight exceeds what will fit in
   11202                 :             :          * int16, the final result is guaranteed to overflow (or underflow, if
   11203                 :             :          * exp < 0), so we can give up before wasting too many cycles.
   11204                 :             :          */
   11205         [ +  - ]:        2929 :         if (base_prod.weight > NUMERIC_WEIGHT_MAX ||
   11206         [ -  + ]:        2929 :             result->weight > NUMERIC_WEIGHT_MAX)
   11207                 :             :         {
   11208                 :             :             /* overflow, unless neg, in which case result should be 0 */
   11209         [ #  # ]:           0 :             if (!neg)
   11210         [ #  # ]:           0 :                 ereport(ERROR,
   11211                 :             :                         (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
   11212                 :             :                          errmsg("value overflows numeric format")));
   11213                 :           0 :             zero_var(result);
   11214                 :           0 :             neg = false;
   11215                 :           0 :             break;
   11216                 :             :         }
   11217                 :             :     }
   11218                 :             : 
   11219                 :         689 :     free_var(&base_prod);
   11220                 :             : 
   11221                 :             :     /* Compensate for input sign, and round to requested rscale */
   11222         [ +  + ]:         689 :     if (neg)
   11223                 :         328 :         div_var(&const_one, result, result, rscale, true, false);
   11224                 :             :     else
   11225                 :         361 :         round_var(result, rscale);
   11226                 :             : }
   11227                 :             : 
   11228                 :             : /*
   11229                 :             :  * power_ten_int() -
   11230                 :             :  *
   11231                 :             :  *  Raise ten to the power of exp, where exp is an integer.  Note that unlike
   11232                 :             :  *  power_var_int(), this does no overflow/underflow checking or rounding.
   11233                 :             :  */
   11234                 :             : static void
   11235                 :         152 : power_ten_int(int exp, NumericVar *result)
   11236                 :             : {
   11237                 :             :     /* Construct the result directly, starting from 10^0 = 1 */
   11238                 :         152 :     set_var_from_var(&const_one, result);
   11239                 :             : 
   11240                 :             :     /* Scale needed to represent the result exactly */
   11241         [ +  + ]:         152 :     result->dscale = exp < 0 ? -exp : 0;
   11242                 :             : 
   11243                 :             :     /* Base-NBASE weight of result and remaining exponent */
   11244         [ +  + ]:         152 :     if (exp >= 0)
   11245                 :         108 :         result->weight = exp / DEC_DIGITS;
   11246                 :             :     else
   11247                 :          44 :         result->weight = (exp + 1) / DEC_DIGITS - 1;
   11248                 :             : 
   11249                 :         152 :     exp -= result->weight * DEC_DIGITS;
   11250                 :             : 
   11251                 :             :     /* Final adjustment of the result's single NBASE digit */
   11252         [ +  + ]:         396 :     while (exp-- > 0)
   11253                 :         244 :         result->digits[0] *= 10;
   11254                 :         152 : }
   11255                 :             : 
   11256                 :             : /*
   11257                 :             :  * random_var() - return a random value in the range [rmin, rmax].
   11258                 :             :  */
   11259                 :             : static void
   11260                 :       22292 : random_var(pg_prng_state *state, const NumericVar *rmin,
   11261                 :             :            const NumericVar *rmax, NumericVar *result)
   11262                 :             : {
   11263                 :             :     int         rscale;
   11264                 :             :     NumericVar  rlen;
   11265                 :             :     int         res_ndigits;
   11266                 :             :     int         n;
   11267                 :             :     int         pow10;
   11268                 :             :     int         i;
   11269                 :             :     uint64      rlen64;
   11270                 :             :     int         rlen64_ndigits;
   11271                 :             : 
   11272                 :       22292 :     rscale = Max(rmin->dscale, rmax->dscale);
   11273                 :             : 
   11274                 :             :     /* Compute rlen = rmax - rmin and check the range bounds */
   11275                 :       22292 :     init_var(&rlen);
   11276                 :       22292 :     sub_var(rmax, rmin, &rlen);
   11277                 :             : 
   11278         [ +  + ]:       22292 :     if (rlen.sign == NUMERIC_NEG)
   11279         [ +  - ]:           4 :         ereport(ERROR,
   11280                 :             :                 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
   11281                 :             :                 errmsg("lower bound must be less than or equal to upper bound"));
   11282                 :             : 
   11283                 :             :     /* Special case for an empty range */
   11284         [ +  + ]:       22288 :     if (rlen.ndigits == 0)
   11285                 :             :     {
   11286                 :           8 :         set_var_from_var(rmin, result);
   11287                 :           8 :         result->dscale = rscale;
   11288                 :           8 :         free_var(&rlen);
   11289                 :           8 :         return;
   11290                 :             :     }
   11291                 :             : 
   11292                 :             :     /*
   11293                 :             :      * Otherwise, select a random value in the range [0, rlen = rmax - rmin],
   11294                 :             :      * and shift it to the required range by adding rmin.
   11295                 :             :      */
   11296                 :             : 
   11297                 :             :     /* Required result digits */
   11298                 :       22280 :     res_ndigits = rlen.weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
   11299                 :             : 
   11300                 :             :     /*
   11301                 :             :      * To get the required rscale, the final result digit must be a multiple
   11302                 :             :      * of pow10 = 10^n, where n = (-rscale) mod DEC_DIGITS.
   11303                 :             :      */
   11304                 :       22280 :     n = ((rscale + DEC_DIGITS - 1) / DEC_DIGITS) * DEC_DIGITS - rscale;
   11305                 :       22280 :     pow10 = 1;
   11306         [ +  + ]:       58600 :     for (i = 0; i < n; i++)
   11307                 :       36320 :         pow10 *= 10;
   11308                 :             : 
   11309                 :             :     /*
   11310                 :             :      * To choose a random value uniformly from the range [0, rlen], we choose
   11311                 :             :      * from the slightly larger range [0, rlen2], where rlen2 is formed from
   11312                 :             :      * rlen by copying the first 4 NBASE digits, and setting all remaining
   11313                 :             :      * decimal digits to "9".
   11314                 :             :      *
   11315                 :             :      * Without loss of generality, we can ignore the weight of rlen2 and treat
   11316                 :             :      * it as a pure integer for the purposes of this discussion.  The process
   11317                 :             :      * above gives rlen2 + 1 = rlen64 * 10^N, for some integer N, where rlen64
   11318                 :             :      * is a 64-bit integer formed from the first 4 NBASE digits copied from
   11319                 :             :      * rlen.  Since this trivially factors into smaller pieces that fit in
   11320                 :             :      * 64-bit integers, the task of choosing a random value uniformly from the
   11321                 :             :      * rlen2 + 1 possible values in [0, rlen2] is much simpler.
   11322                 :             :      *
   11323                 :             :      * If the random value selected is too large, it is rejected, and we try
   11324                 :             :      * again until we get a result <= rlen, ensuring that the overall result
   11325                 :             :      * is uniform (no particular value is any more likely than any other).
   11326                 :             :      *
   11327                 :             :      * Since rlen64 holds 4 NBASE digits from rlen, it contains at least
   11328                 :             :      * DEC_DIGITS * 3 + 1 decimal digits (i.e., at least 13 decimal digits,
   11329                 :             :      * when DEC_DIGITS is 4). Therefore the probability of needing to reject
   11330                 :             :      * the value chosen and retry is less than 1e-13.
   11331                 :             :      */
   11332                 :       22280 :     rlen64 = (uint64) rlen.digits[0];
   11333                 :       22280 :     rlen64_ndigits = 1;
   11334   [ +  +  +  + ]:       50808 :     while (rlen64_ndigits < res_ndigits && rlen64_ndigits < 4)
   11335                 :             :     {
   11336                 :       28528 :         rlen64 *= NBASE;
   11337         [ +  + ]:       28528 :         if (rlen64_ndigits < rlen.ndigits)
   11338                 :        4408 :             rlen64 += rlen.digits[rlen64_ndigits];
   11339                 :       28528 :         rlen64_ndigits++;
   11340                 :             :     }
   11341                 :             : 
   11342                 :             :     /* Loop until we get a result <= rlen */
   11343                 :             :     do
   11344                 :             :     {
   11345                 :             :         NumericDigit *res_digits;
   11346                 :             :         uint64      rand;
   11347                 :             :         int         whole_ndigits;
   11348                 :             : 
   11349                 :       22280 :         alloc_var(result, res_ndigits);
   11350                 :       22280 :         result->sign = NUMERIC_POS;
   11351                 :       22280 :         result->weight = rlen.weight;
   11352                 :       22280 :         result->dscale = rscale;
   11353                 :       22280 :         res_digits = result->digits;
   11354                 :             : 
   11355                 :             :         /*
   11356                 :             :          * Set the first rlen64_ndigits using a random value in [0, rlen64].
   11357                 :             :          *
   11358                 :             :          * If this is the whole result, and rscale is not a multiple of
   11359                 :             :          * DEC_DIGITS (pow10 from above is not 1), then we need this to be a
   11360                 :             :          * multiple of pow10.
   11361                 :             :          */
   11362   [ +  +  +  + ]:       22280 :         if (rlen64_ndigits == res_ndigits && pow10 != 1)
   11363                 :       14088 :             rand = pg_prng_uint64_range(state, 0, rlen64 / pow10) * pow10;
   11364                 :             :         else
   11365                 :        8192 :             rand = pg_prng_uint64_range(state, 0, rlen64);
   11366                 :             : 
   11367         [ +  + ]:       73088 :         for (i = rlen64_ndigits - 1; i >= 0; i--)
   11368                 :             :         {
   11369                 :       50808 :             res_digits[i] = (NumericDigit) (rand % NBASE);
   11370                 :       50808 :             rand = rand / NBASE;
   11371                 :             :         }
   11372                 :             : 
   11373                 :             :         /*
   11374                 :             :          * Set the remaining digits to random values in range [0, NBASE),
   11375                 :             :          * noting that the last digit needs to be a multiple of pow10.
   11376                 :             :          */
   11377                 :       22280 :         whole_ndigits = res_ndigits;
   11378         [ +  + ]:       22280 :         if (pow10 != 1)
   11379                 :       22140 :             whole_ndigits--;
   11380                 :             : 
   11381                 :             :         /* Set whole digits in groups of 4 for best performance */
   11382                 :       22280 :         i = rlen64_ndigits;
   11383         [ +  + ]:       22320 :         while (i < whole_ndigits - 3)
   11384                 :             :         {
   11385                 :          40 :             rand = pg_prng_uint64_range(state, 0,
   11386                 :             :                                         (uint64) NBASE * NBASE * NBASE * NBASE - 1);
   11387                 :          40 :             res_digits[i++] = (NumericDigit) (rand % NBASE);
   11388                 :          40 :             rand = rand / NBASE;
   11389                 :          40 :             res_digits[i++] = (NumericDigit) (rand % NBASE);
   11390                 :          40 :             rand = rand / NBASE;
   11391                 :          40 :             res_digits[i++] = (NumericDigit) (rand % NBASE);
   11392                 :          40 :             rand = rand / NBASE;
   11393                 :          40 :             res_digits[i++] = (NumericDigit) rand;
   11394                 :             :         }
   11395                 :             : 
   11396                 :             :         /* Remaining whole digits */
   11397         [ +  + ]:       22420 :         while (i < whole_ndigits)
   11398                 :             :         {
   11399                 :         140 :             rand = pg_prng_uint64_range(state, 0, NBASE - 1);
   11400                 :         140 :             res_digits[i++] = (NumericDigit) rand;
   11401                 :             :         }
   11402                 :             : 
   11403                 :             :         /* Final partial digit (multiple of pow10) */
   11404         [ +  + ]:       22280 :         if (i < res_ndigits)
   11405                 :             :         {
   11406                 :        8052 :             rand = pg_prng_uint64_range(state, 0, NBASE / pow10 - 1) * pow10;
   11407                 :        8052 :             res_digits[i] = (NumericDigit) rand;
   11408                 :             :         }
   11409                 :             : 
   11410                 :             :         /* Remove leading/trailing zeroes */
   11411                 :       22280 :         strip_var(result);
   11412                 :             : 
   11413                 :             :         /* If result > rlen, try again */
   11414                 :             : 
   11415         [ -  + ]:       22280 :     } while (cmp_var(result, &rlen) > 0);
   11416                 :             : 
   11417                 :             :     /* Offset the result to the required range */
   11418                 :       22280 :     add_var(result, rmin, result);
   11419                 :             : 
   11420                 :       22280 :     free_var(&rlen);
   11421                 :             : }
   11422                 :             : 
   11423                 :             : 
   11424                 :             : /* ----------------------------------------------------------------------
   11425                 :             :  *
   11426                 :             :  * Following are the lowest level functions that operate unsigned
   11427                 :             :  * on the variable level
   11428                 :             :  *
   11429                 :             :  * ----------------------------------------------------------------------
   11430                 :             :  */
   11431                 :             : 
   11432                 :             : 
   11433                 :             : /* ----------
   11434                 :             :  * cmp_abs() -
   11435                 :             :  *
   11436                 :             :  *  Compare the absolute values of var1 and var2
   11437                 :             :  *  Returns:    -1 for ABS(var1) < ABS(var2)
   11438                 :             :  *              0  for ABS(var1) == ABS(var2)
   11439                 :             :  *              1  for ABS(var1) > ABS(var2)
   11440                 :             :  * ----------
   11441                 :             :  */
   11442                 :             : static int
   11443                 :      469515 : cmp_abs(const NumericVar *var1, const NumericVar *var2)
   11444                 :             : {
   11445                 :      939030 :     return cmp_abs_common(var1->digits, var1->ndigits, var1->weight,
   11446                 :      469515 :                           var2->digits, var2->ndigits, var2->weight);
   11447                 :             : }
   11448                 :             : 
   11449                 :             : /* ----------
   11450                 :             :  * cmp_abs_common() -
   11451                 :             :  *
   11452                 :             :  *  Main routine of cmp_abs(). This function can be used by both
   11453                 :             :  *  NumericVar and Numeric.
   11454                 :             :  * ----------
   11455                 :             :  */
   11456                 :             : static int
   11457                 :    18450262 : cmp_abs_common(const NumericDigit *var1digits, int var1ndigits, int var1weight,
   11458                 :             :                const NumericDigit *var2digits, int var2ndigits, int var2weight)
   11459                 :             : {
   11460                 :    18450262 :     int         i1 = 0;
   11461                 :    18450262 :     int         i2 = 0;
   11462                 :             : 
   11463                 :             :     /* Check any digits before the first common digit */
   11464                 :             : 
   11465   [ +  +  +  + ]:    18450262 :     while (var1weight > var2weight && i1 < var1ndigits)
   11466                 :             :     {
   11467         [ +  - ]:       14786 :         if (var1digits[i1++] != 0)
   11468                 :       14786 :             return 1;
   11469                 :           0 :         var1weight--;
   11470                 :             :     }
   11471   [ +  +  +  + ]:    18435476 :     while (var2weight > var1weight && i2 < var2ndigits)
   11472                 :             :     {
   11473         [ +  - ]:      100531 :         if (var2digits[i2++] != 0)
   11474                 :      100531 :             return -1;
   11475                 :           0 :         var2weight--;
   11476                 :             :     }
   11477                 :             : 
   11478                 :             :     /* At this point, either w1 == w2 or we've run out of digits */
   11479                 :             : 
   11480         [ +  + ]:    18334945 :     if (var1weight == var2weight)
   11481                 :             :     {
   11482   [ +  +  +  + ]:    28819567 :         while (i1 < var1ndigits && i2 < var2ndigits)
   11483                 :             :         {
   11484                 :    19356777 :             int         stat = var1digits[i1++] - var2digits[i2++];
   11485                 :             : 
   11486         [ +  + ]:    19356777 :             if (stat)
   11487                 :             :             {
   11488         [ +  + ]:     8867933 :                 if (stat > 0)
   11489                 :     5255853 :                     return 1;
   11490                 :     3612080 :                 return -1;
   11491                 :             :             }
   11492                 :             :         }
   11493                 :             :     }
   11494                 :             : 
   11495                 :             :     /*
   11496                 :             :      * At this point, we've run out of digits on one side or the other; so any
   11497                 :             :      * remaining nonzero digits imply that side is larger
   11498                 :             :      */
   11499         [ +  + ]:     9467112 :     while (i1 < var1ndigits)
   11500                 :             :     {
   11501         [ +  + ]:        6268 :         if (var1digits[i1++] != 0)
   11502                 :        6168 :             return 1;
   11503                 :             :     }
   11504         [ +  + ]:     9461096 :     while (i2 < var2ndigits)
   11505                 :             :     {
   11506         [ +  + ]:         846 :         if (var2digits[i2++] != 0)
   11507                 :         594 :             return -1;
   11508                 :             :     }
   11509                 :             : 
   11510                 :     9460250 :     return 0;
   11511                 :             : }
   11512                 :             : 
   11513                 :             : 
   11514                 :             : /*
   11515                 :             :  * add_abs() -
   11516                 :             :  *
   11517                 :             :  *  Add the absolute values of two variables into result.
   11518                 :             :  *  result might point to one of the operands without danger.
   11519                 :             :  */
   11520                 :             : static void
   11521                 :      299699 : add_abs(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
   11522                 :             : {
   11523                 :             :     NumericDigit *res_buf;
   11524                 :             :     NumericDigit *res_digits;
   11525                 :             :     int         res_ndigits;
   11526                 :             :     int         res_weight;
   11527                 :             :     int         res_rscale,
   11528                 :             :                 rscale1,
   11529                 :             :                 rscale2;
   11530                 :             :     int         res_dscale;
   11531                 :             :     int         i,
   11532                 :             :                 i1,
   11533                 :             :                 i2;
   11534                 :      299699 :     int         carry = 0;
   11535                 :             : 
   11536                 :             :     /* copy these values into local vars for speed in inner loop */
   11537                 :      299699 :     int         var1ndigits = var1->ndigits;
   11538                 :      299699 :     int         var2ndigits = var2->ndigits;
   11539                 :      299699 :     NumericDigit *var1digits = var1->digits;
   11540                 :      299699 :     NumericDigit *var2digits = var2->digits;
   11541                 :             : 
   11542                 :      299699 :     res_weight = Max(var1->weight, var2->weight) + 1;
   11543                 :             : 
   11544                 :      299699 :     res_dscale = Max(var1->dscale, var2->dscale);
   11545                 :             : 
   11546                 :             :     /* Note: here we are figuring rscale in base-NBASE digits */
   11547                 :      299699 :     rscale1 = var1->ndigits - var1->weight - 1;
   11548                 :      299699 :     rscale2 = var2->ndigits - var2->weight - 1;
   11549                 :      299699 :     res_rscale = Max(rscale1, rscale2);
   11550                 :             : 
   11551                 :      299699 :     res_ndigits = res_rscale + res_weight + 1;
   11552         [ -  + ]:      299699 :     if (res_ndigits <= 0)
   11553                 :           0 :         res_ndigits = 1;
   11554                 :             : 
   11555                 :      299699 :     res_buf = digitbuf_alloc(res_ndigits + 1);
   11556                 :      299699 :     res_buf[0] = 0;             /* spare digit for later rounding */
   11557                 :      299699 :     res_digits = res_buf + 1;
   11558                 :             : 
   11559                 :      299699 :     i1 = res_rscale + var1->weight + 1;
   11560                 :      299699 :     i2 = res_rscale + var2->weight + 1;
   11561         [ +  + ]:     2480804 :     for (i = res_ndigits - 1; i >= 0; i--)
   11562                 :             :     {
   11563                 :     2181105 :         i1--;
   11564                 :     2181105 :         i2--;
   11565   [ +  +  +  + ]:     2181105 :         if (i1 >= 0 && i1 < var1ndigits)
   11566                 :      988204 :             carry += var1digits[i1];
   11567   [ +  +  +  + ]:     2181105 :         if (i2 >= 0 && i2 < var2ndigits)
   11568                 :      780031 :             carry += var2digits[i2];
   11569                 :             : 
   11570         [ +  + ]:     2181105 :         if (carry >= NBASE)
   11571                 :             :         {
   11572                 :      159515 :             res_digits[i] = carry - NBASE;
   11573                 :      159515 :             carry = 1;
   11574                 :             :         }
   11575                 :             :         else
   11576                 :             :         {
   11577                 :     2021590 :             res_digits[i] = carry;
   11578                 :     2021590 :             carry = 0;
   11579                 :             :         }
   11580                 :             :     }
   11581                 :             : 
   11582                 :             :     Assert(carry == 0);         /* else we failed to allow for carry out */
   11583                 :             : 
   11584         [ +  + ]:      299699 :     digitbuf_free(result->buf);
   11585                 :      299699 :     result->ndigits = res_ndigits;
   11586                 :      299699 :     result->buf = res_buf;
   11587                 :      299699 :     result->digits = res_digits;
   11588                 :      299699 :     result->weight = res_weight;
   11589                 :      299699 :     result->dscale = res_dscale;
   11590                 :             : 
   11591                 :             :     /* Remove leading/trailing zeroes */
   11592                 :      299699 :     strip_var(result);
   11593                 :      299699 : }
   11594                 :             : 
   11595                 :             : 
   11596                 :             : /*
   11597                 :             :  * sub_abs()
   11598                 :             :  *
   11599                 :             :  *  Subtract the absolute value of var2 from the absolute value of var1
   11600                 :             :  *  and store in result. result might point to one of the operands
   11601                 :             :  *  without danger.
   11602                 :             :  *
   11603                 :             :  *  ABS(var1) MUST BE GREATER OR EQUAL ABS(var2) !!!
   11604                 :             :  */
   11605                 :             : static void
   11606                 :      436435 : sub_abs(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
   11607                 :             : {
   11608                 :             :     NumericDigit *res_buf;
   11609                 :             :     NumericDigit *res_digits;
   11610                 :             :     int         res_ndigits;
   11611                 :             :     int         res_weight;
   11612                 :             :     int         res_rscale,
   11613                 :             :                 rscale1,
   11614                 :             :                 rscale2;
   11615                 :             :     int         res_dscale;
   11616                 :             :     int         i,
   11617                 :             :                 i1,
   11618                 :             :                 i2;
   11619                 :      436435 :     int         borrow = 0;
   11620                 :             : 
   11621                 :             :     /* copy these values into local vars for speed in inner loop */
   11622                 :      436435 :     int         var1ndigits = var1->ndigits;
   11623                 :      436435 :     int         var2ndigits = var2->ndigits;
   11624                 :      436435 :     NumericDigit *var1digits = var1->digits;
   11625                 :      436435 :     NumericDigit *var2digits = var2->digits;
   11626                 :             : 
   11627                 :      436435 :     res_weight = var1->weight;
   11628                 :             : 
   11629                 :      436435 :     res_dscale = Max(var1->dscale, var2->dscale);
   11630                 :             : 
   11631                 :             :     /* Note: here we are figuring rscale in base-NBASE digits */
   11632                 :      436435 :     rscale1 = var1->ndigits - var1->weight - 1;
   11633                 :      436435 :     rscale2 = var2->ndigits - var2->weight - 1;
   11634                 :      436435 :     res_rscale = Max(rscale1, rscale2);
   11635                 :             : 
   11636                 :      436435 :     res_ndigits = res_rscale + res_weight + 1;
   11637         [ -  + ]:      436435 :     if (res_ndigits <= 0)
   11638                 :           0 :         res_ndigits = 1;
   11639                 :             : 
   11640                 :      436435 :     res_buf = digitbuf_alloc(res_ndigits + 1);
   11641                 :      436435 :     res_buf[0] = 0;             /* spare digit for later rounding */
   11642                 :      436435 :     res_digits = res_buf + 1;
   11643                 :             : 
   11644                 :      436435 :     i1 = res_rscale + var1->weight + 1;
   11645                 :      436435 :     i2 = res_rscale + var2->weight + 1;
   11646         [ +  + ]:     3490144 :     for (i = res_ndigits - 1; i >= 0; i--)
   11647                 :             :     {
   11648                 :     3053709 :         i1--;
   11649                 :     3053709 :         i2--;
   11650   [ +  -  +  + ]:     3053709 :         if (i1 >= 0 && i1 < var1ndigits)
   11651                 :     2742118 :             borrow += var1digits[i1];
   11652   [ +  +  +  + ]:     3053709 :         if (i2 >= 0 && i2 < var2ndigits)
   11653                 :     2698291 :             borrow -= var2digits[i2];
   11654                 :             : 
   11655         [ +  + ]:     3053709 :         if (borrow < 0)
   11656                 :             :         {
   11657                 :      334150 :             res_digits[i] = borrow + NBASE;
   11658                 :      334150 :             borrow = -1;
   11659                 :             :         }
   11660                 :             :         else
   11661                 :             :         {
   11662                 :     2719559 :             res_digits[i] = borrow;
   11663                 :     2719559 :             borrow = 0;
   11664                 :             :         }
   11665                 :             :     }
   11666                 :             : 
   11667                 :             :     Assert(borrow == 0);        /* else caller gave us var1 < var2 */
   11668                 :             : 
   11669         [ +  + ]:      436435 :     digitbuf_free(result->buf);
   11670                 :      436435 :     result->ndigits = res_ndigits;
   11671                 :      436435 :     result->buf = res_buf;
   11672                 :      436435 :     result->digits = res_digits;
   11673                 :      436435 :     result->weight = res_weight;
   11674                 :      436435 :     result->dscale = res_dscale;
   11675                 :             : 
   11676                 :             :     /* Remove leading/trailing zeroes */
   11677                 :      436435 :     strip_var(result);
   11678                 :      436435 : }
   11679                 :             : 
   11680                 :             : /*
   11681                 :             :  * round_var
   11682                 :             :  *
   11683                 :             :  * Round the value of a variable to no more than rscale decimal digits
   11684                 :             :  * after the decimal point.  NOTE: we allow rscale < 0 here, implying
   11685                 :             :  * rounding before the decimal point.
   11686                 :             :  */
   11687                 :             : static void
   11688                 :      168304 : round_var(NumericVar *var, int rscale)
   11689                 :             : {
   11690                 :      168304 :     NumericDigit *digits = var->digits;
   11691                 :             :     int         di;
   11692                 :             :     int         ndigits;
   11693                 :             :     int         carry;
   11694                 :             : 
   11695                 :      168304 :     var->dscale = rscale;
   11696                 :             : 
   11697                 :             :     /* decimal digits wanted */
   11698                 :      168304 :     di = (var->weight + 1) * DEC_DIGITS + rscale;
   11699                 :             : 
   11700                 :             :     /*
   11701                 :             :      * If di = 0, the value loses all digits, but could round up to 1 if its
   11702                 :             :      * first extra digit is >= 5.  If di < 0 the result must be 0.
   11703                 :             :      */
   11704         [ +  + ]:      168304 :     if (di < 0)
   11705                 :             :     {
   11706                 :          71 :         var->ndigits = 0;
   11707                 :          71 :         var->weight = 0;
   11708                 :          71 :         var->sign = NUMERIC_POS;
   11709                 :             :     }
   11710                 :             :     else
   11711                 :             :     {
   11712                 :             :         /* NBASE digits wanted */
   11713                 :      168233 :         ndigits = (di + DEC_DIGITS - 1) / DEC_DIGITS;
   11714                 :             : 
   11715                 :             :         /* 0, or number of decimal digits to keep in last NBASE digit */
   11716                 :      168233 :         di %= DEC_DIGITS;
   11717                 :             : 
   11718         [ +  + ]:      168233 :         if (ndigits < var->ndigits ||
   11719   [ +  +  +  + ]:       30699 :             (ndigits == var->ndigits && di > 0))
   11720                 :             :         {
   11721                 :      140011 :             var->ndigits = ndigits;
   11722                 :             : 
   11723                 :             : #if DEC_DIGITS == 1
   11724                 :             :             /* di must be zero */
   11725                 :             :             carry = (digits[ndigits] >= HALF_NBASE) ? 1 : 0;
   11726                 :             : #else
   11727         [ +  + ]:      140011 :             if (di == 0)
   11728                 :      109931 :                 carry = (digits[ndigits] >= HALF_NBASE) ? 1 : 0;
   11729                 :             :             else
   11730                 :             :             {
   11731                 :             :                 /* Must round within last NBASE digit */
   11732                 :             :                 int         extra,
   11733                 :             :                             pow10;
   11734                 :             : 
   11735                 :             : #if DEC_DIGITS == 4
   11736                 :       30080 :                 pow10 = round_powers[di];
   11737                 :             : #elif DEC_DIGITS == 2
   11738                 :             :                 pow10 = 10;
   11739                 :             : #else
   11740                 :             : #error unsupported NBASE
   11741                 :             : #endif
   11742                 :       30080 :                 extra = digits[--ndigits] % pow10;
   11743                 :       30080 :                 digits[ndigits] -= extra;
   11744                 :       30080 :                 carry = 0;
   11745         [ +  + ]:       30080 :                 if (extra >= pow10 / 2)
   11746                 :             :                 {
   11747                 :       14019 :                     pow10 += digits[ndigits];
   11748         [ +  + ]:       14019 :                     if (pow10 >= NBASE)
   11749                 :             :                     {
   11750                 :         595 :                         pow10 -= NBASE;
   11751                 :         595 :                         carry = 1;
   11752                 :             :                     }
   11753                 :       14019 :                     digits[ndigits] = pow10;
   11754                 :             :                 }
   11755                 :             :             }
   11756                 :             : #endif
   11757                 :             : 
   11758                 :             :             /* Propagate carry if needed */
   11759         [ +  + ]:      166945 :             while (carry)
   11760                 :             :             {
   11761                 :       26934 :                 carry += digits[--ndigits];
   11762         [ +  + ]:       26934 :                 if (carry >= NBASE)
   11763                 :             :                 {
   11764                 :       20528 :                     digits[ndigits] = carry - NBASE;
   11765                 :       20528 :                     carry = 1;
   11766                 :             :                 }
   11767                 :             :                 else
   11768                 :             :                 {
   11769                 :        6406 :                     digits[ndigits] = carry;
   11770                 :        6406 :                     carry = 0;
   11771                 :             :                 }
   11772                 :             :             }
   11773                 :             : 
   11774         [ +  + ]:      140011 :             if (ndigits < 0)
   11775                 :             :             {
   11776                 :             :                 Assert(ndigits == -1);  /* better not have added > 1 digit */
   11777                 :             :                 Assert(var->digits > var->buf);
   11778                 :          65 :                 var->digits--;
   11779                 :          65 :                 var->ndigits++;
   11780                 :          65 :                 var->weight++;
   11781                 :             :             }
   11782                 :             :         }
   11783                 :             :     }
   11784                 :      168304 : }
   11785                 :             : 
   11786                 :             : /*
   11787                 :             :  * trunc_var
   11788                 :             :  *
   11789                 :             :  * Truncate (towards zero) the value of a variable at rscale decimal digits
   11790                 :             :  * after the decimal point.  NOTE: we allow rscale < 0 here, implying
   11791                 :             :  * truncation before the decimal point.
   11792                 :             :  */
   11793                 :             : static void
   11794                 :      280501 : trunc_var(NumericVar *var, int rscale)
   11795                 :             : {
   11796                 :             :     int         di;
   11797                 :             :     int         ndigits;
   11798                 :             : 
   11799                 :      280501 :     var->dscale = rscale;
   11800                 :             : 
   11801                 :             :     /* decimal digits wanted */
   11802                 :      280501 :     di = (var->weight + 1) * DEC_DIGITS + rscale;
   11803                 :             : 
   11804                 :             :     /*
   11805                 :             :      * If di <= 0, the value loses all digits.
   11806                 :             :      */
   11807         [ +  + ]:      280501 :     if (di <= 0)
   11808                 :             :     {
   11809                 :          66 :         var->ndigits = 0;
   11810                 :          66 :         var->weight = 0;
   11811                 :          66 :         var->sign = NUMERIC_POS;
   11812                 :             :     }
   11813                 :             :     else
   11814                 :             :     {
   11815                 :             :         /* NBASE digits wanted */
   11816                 :      280435 :         ndigits = (di + DEC_DIGITS - 1) / DEC_DIGITS;
   11817                 :             : 
   11818         [ +  + ]:      280435 :         if (ndigits <= var->ndigits)
   11819                 :             :         {
   11820                 :      280247 :             var->ndigits = ndigits;
   11821                 :             : 
   11822                 :             : #if DEC_DIGITS == 1
   11823                 :             :             /* no within-digit stuff to worry about */
   11824                 :             : #else
   11825                 :             :             /* 0, or number of decimal digits to keep in last NBASE digit */
   11826                 :      280247 :             di %= DEC_DIGITS;
   11827                 :             : 
   11828         [ +  + ]:      280247 :             if (di > 0)
   11829                 :             :             {
   11830                 :             :                 /* Must truncate within last NBASE digit */
   11831                 :          63 :                 NumericDigit *digits = var->digits;
   11832                 :             :                 int         extra,
   11833                 :             :                             pow10;
   11834                 :             : 
   11835                 :             : #if DEC_DIGITS == 4
   11836                 :          63 :                 pow10 = round_powers[di];
   11837                 :             : #elif DEC_DIGITS == 2
   11838                 :             :                 pow10 = 10;
   11839                 :             : #else
   11840                 :             : #error unsupported NBASE
   11841                 :             : #endif
   11842                 :          63 :                 extra = digits[--ndigits] % pow10;
   11843                 :          63 :                 digits[ndigits] -= extra;
   11844                 :             :             }
   11845                 :             : #endif
   11846                 :             :         }
   11847                 :             :     }
   11848                 :      280501 : }
   11849                 :             : 
   11850                 :             : /*
   11851                 :             :  * strip_var
   11852                 :             :  *
   11853                 :             :  * Strip any leading and trailing zeroes from a numeric variable
   11854                 :             :  */
   11855                 :             : static void
   11856                 :     2189044 : strip_var(NumericVar *var)
   11857                 :             : {
   11858                 :     2189044 :     NumericDigit *digits = var->digits;
   11859                 :     2189044 :     int         ndigits = var->ndigits;
   11860                 :             : 
   11861                 :             :     /* Strip leading zeroes */
   11862   [ +  +  +  + ]:     3761353 :     while (ndigits > 0 && *digits == 0)
   11863                 :             :     {
   11864                 :     1572309 :         digits++;
   11865                 :     1572309 :         var->weight--;
   11866                 :     1572309 :         ndigits--;
   11867                 :             :     }
   11868                 :             : 
   11869                 :             :     /* Strip trailing zeroes */
   11870   [ +  +  +  + ]:     2641467 :     while (ndigits > 0 && digits[ndigits - 1] == 0)
   11871                 :      452423 :         ndigits--;
   11872                 :             : 
   11873                 :             :     /* If it's zero, normalize the sign and weight */
   11874         [ +  + ]:     2189044 :     if (ndigits == 0)
   11875                 :             :     {
   11876                 :       32322 :         var->sign = NUMERIC_POS;
   11877                 :       32322 :         var->weight = 0;
   11878                 :             :     }
   11879                 :             : 
   11880                 :     2189044 :     var->digits = digits;
   11881                 :     2189044 :     var->ndigits = ndigits;
   11882                 :     2189044 : }
   11883                 :             : 
   11884                 :             : 
   11885                 :             : /* ----------------------------------------------------------------------
   11886                 :             :  *
   11887                 :             :  * Fast sum accumulator functions
   11888                 :             :  *
   11889                 :             :  * ----------------------------------------------------------------------
   11890                 :             :  */
   11891                 :             : 
   11892                 :             : /*
   11893                 :             :  * Reset the accumulator's value to zero.  The buffers to hold the digits
   11894                 :             :  * are not free'd.
   11895                 :             :  */
   11896                 :             : static void
   11897                 :          12 : accum_sum_reset(NumericSumAccum *accum)
   11898                 :             : {
   11899                 :             :     int         i;
   11900                 :             : 
   11901                 :          12 :     accum->dscale = 0;
   11902         [ +  + ]:          44 :     for (i = 0; i < accum->ndigits; i++)
   11903                 :             :     {
   11904                 :          32 :         accum->pos_digits[i] = 0;
   11905                 :          32 :         accum->neg_digits[i] = 0;
   11906                 :             :     }
   11907                 :          12 : }
   11908                 :             : 
   11909                 :             : /*
   11910                 :             :  * Accumulate a new value.
   11911                 :             :  */
   11912                 :             : static void
   11913                 :     1570442 : accum_sum_add(NumericSumAccum *accum, const NumericVar *val)
   11914                 :             : {
   11915                 :             :     int32      *accum_digits;
   11916                 :             :     int         i,
   11917                 :             :                 val_i;
   11918                 :             :     int         val_ndigits;
   11919                 :             :     NumericDigit *val_digits;
   11920                 :             : 
   11921                 :             :     /*
   11922                 :             :      * If we have accumulated too many values since the last carry
   11923                 :             :      * propagation, do it now, to avoid overflowing.  (We could allow more
   11924                 :             :      * than NBASE - 1, if we reserved two extra digits, rather than one, for
   11925                 :             :      * carry propagation.  But even with NBASE - 1, this needs to be done so
   11926                 :             :      * seldom, that the performance difference is negligible.)
   11927                 :             :      */
   11928         [ +  + ]:     1570442 :     if (accum->num_uncarried == NBASE - 1)
   11929                 :         110 :         accum_sum_carry(accum);
   11930                 :             : 
   11931                 :             :     /*
   11932                 :             :      * Adjust the weight or scale of the old value, so that it can accommodate
   11933                 :             :      * the new value.
   11934                 :             :      */
   11935                 :     1570442 :     accum_sum_rescale(accum, val);
   11936                 :             : 
   11937                 :             :     /* */
   11938         [ +  + ]:     1570442 :     if (val->sign == NUMERIC_POS)
   11939                 :     1169990 :         accum_digits = accum->pos_digits;
   11940                 :             :     else
   11941                 :      400452 :         accum_digits = accum->neg_digits;
   11942                 :             : 
   11943                 :             :     /* copy these values into local vars for speed in loop */
   11944                 :     1570442 :     val_ndigits = val->ndigits;
   11945                 :     1570442 :     val_digits = val->digits;
   11946                 :             : 
   11947                 :     1570442 :     i = accum->weight - val->weight;
   11948         [ +  + ]:     7926581 :     for (val_i = 0; val_i < val_ndigits; val_i++)
   11949                 :             :     {
   11950                 :     6356139 :         accum_digits[i] += (int32) val_digits[val_i];
   11951                 :     6356139 :         i++;
   11952                 :             :     }
   11953                 :             : 
   11954                 :     1570442 :     accum->num_uncarried++;
   11955                 :     1570442 : }
   11956                 :             : 
   11957                 :             : /*
   11958                 :             :  * Propagate carries.
   11959                 :             :  */
   11960                 :             : static void
   11961                 :      115162 : accum_sum_carry(NumericSumAccum *accum)
   11962                 :             : {
   11963                 :             :     int         i;
   11964                 :             :     int         ndigits;
   11965                 :             :     int32      *dig;
   11966                 :             :     int32       carry;
   11967                 :      115162 :     int32       newdig = 0;
   11968                 :             : 
   11969                 :             :     /*
   11970                 :             :      * If no new values have been added since last carry propagation, nothing
   11971                 :             :      * to do.
   11972                 :             :      */
   11973         [ +  + ]:      115162 :     if (accum->num_uncarried == 0)
   11974                 :          48 :         return;
   11975                 :             : 
   11976                 :             :     /*
   11977                 :             :      * We maintain that the weight of the accumulator is always one larger
   11978                 :             :      * than needed to hold the current value, before carrying, to make sure
   11979                 :             :      * there is enough space for the possible extra digit when carry is
   11980                 :             :      * propagated.  We cannot expand the buffer here, unless we require
   11981                 :             :      * callers of accum_sum_final() to switch to the right memory context.
   11982                 :             :      */
   11983                 :             :     Assert(accum->pos_digits[0] == 0 && accum->neg_digits[0] == 0);
   11984                 :             : 
   11985                 :      115114 :     ndigits = accum->ndigits;
   11986                 :             : 
   11987                 :             :     /* Propagate carry in the positive sum */
   11988                 :      115114 :     dig = accum->pos_digits;
   11989                 :      115114 :     carry = 0;
   11990         [ +  + ]:     1737007 :     for (i = ndigits - 1; i >= 0; i--)
   11991                 :             :     {
   11992                 :     1621893 :         newdig = dig[i] + carry;
   11993         [ +  + ]:     1621893 :         if (newdig >= NBASE)
   11994                 :             :         {
   11995                 :       73880 :             carry = newdig / NBASE;
   11996                 :       73880 :             newdig -= carry * NBASE;
   11997                 :             :         }
   11998                 :             :         else
   11999                 :     1548013 :             carry = 0;
   12000                 :     1621893 :         dig[i] = newdig;
   12001                 :             :     }
   12002                 :             :     /* Did we use up the digit reserved for carry propagation? */
   12003         [ +  + ]:      115114 :     if (newdig > 0)
   12004                 :        1763 :         accum->have_carry_space = false;
   12005                 :             : 
   12006                 :             :     /* And the same for the negative sum */
   12007                 :      115114 :     dig = accum->neg_digits;
   12008                 :      115114 :     carry = 0;
   12009         [ +  + ]:     1737007 :     for (i = ndigits - 1; i >= 0; i--)
   12010                 :             :     {
   12011                 :     1621893 :         newdig = dig[i] + carry;
   12012         [ +  + ]:     1621893 :         if (newdig >= NBASE)
   12013                 :             :         {
   12014                 :         132 :             carry = newdig / NBASE;
   12015                 :         132 :             newdig -= carry * NBASE;
   12016                 :             :         }
   12017                 :             :         else
   12018                 :     1621761 :             carry = 0;
   12019                 :     1621893 :         dig[i] = newdig;
   12020                 :             :     }
   12021         [ +  + ]:      115114 :     if (newdig > 0)
   12022                 :          20 :         accum->have_carry_space = false;
   12023                 :             : 
   12024                 :      115114 :     accum->num_uncarried = 0;
   12025                 :             : }
   12026                 :             : 
   12027                 :             : /*
   12028                 :             :  * Re-scale accumulator to accommodate new value.
   12029                 :             :  *
   12030                 :             :  * If the new value has more digits than the current digit buffers in the
   12031                 :             :  * accumulator, enlarge the buffers.
   12032                 :             :  */
   12033                 :             : static void
   12034                 :     1570442 : accum_sum_rescale(NumericSumAccum *accum, const NumericVar *val)
   12035                 :             : {
   12036                 :     1570442 :     int         old_weight = accum->weight;
   12037                 :     1570442 :     int         old_ndigits = accum->ndigits;
   12038                 :             :     int         accum_ndigits;
   12039                 :             :     int         accum_weight;
   12040                 :             :     int         accum_rscale;
   12041                 :             :     int         val_rscale;
   12042                 :             : 
   12043                 :     1570442 :     accum_weight = old_weight;
   12044                 :     1570442 :     accum_ndigits = old_ndigits;
   12045                 :             : 
   12046                 :             :     /*
   12047                 :             :      * Does the new value have a larger weight? If so, enlarge the buffers,
   12048                 :             :      * and shift the existing value to the new weight, by adding leading
   12049                 :             :      * zeros.
   12050                 :             :      *
   12051                 :             :      * We enforce that the accumulator always has a weight one larger than
   12052                 :             :      * needed for the inputs, so that we have space for an extra digit at the
   12053                 :             :      * final carry-propagation phase, if necessary.
   12054                 :             :      */
   12055         [ +  + ]:     1570442 :     if (val->weight >= accum_weight)
   12056                 :             :     {
   12057                 :      174800 :         accum_weight = val->weight + 1;
   12058                 :      174800 :         accum_ndigits = accum_ndigits + (accum_weight - old_weight);
   12059                 :             :     }
   12060                 :             : 
   12061                 :             :     /*
   12062                 :             :      * Even though the new value is small, we might've used up the space
   12063                 :             :      * reserved for the carry digit in the last call to accum_sum_carry().  If
   12064                 :             :      * so, enlarge to make room for another one.
   12065                 :             :      */
   12066         [ +  + ]:     1395642 :     else if (!accum->have_carry_space)
   12067                 :             :     {
   12068                 :          54 :         accum_weight++;
   12069                 :          54 :         accum_ndigits++;
   12070                 :             :     }
   12071                 :             : 
   12072                 :             :     /* Is the new value wider on the right side? */
   12073                 :     1570442 :     accum_rscale = accum_ndigits - accum_weight - 1;
   12074                 :     1570442 :     val_rscale = val->ndigits - val->weight - 1;
   12075         [ +  + ]:     1570442 :     if (val_rscale > accum_rscale)
   12076                 :      114816 :         accum_ndigits = accum_ndigits + (val_rscale - accum_rscale);
   12077                 :             : 
   12078   [ +  +  -  + ]:     1570442 :     if (accum_ndigits != old_ndigits ||
   12079                 :             :         accum_weight != old_weight)
   12080                 :             :     {
   12081                 :             :         int32      *new_pos_digits;
   12082                 :             :         int32      *new_neg_digits;
   12083                 :             :         int         weightdiff;
   12084                 :             : 
   12085                 :      175058 :         weightdiff = accum_weight - old_weight;
   12086                 :             : 
   12087                 :      175058 :         new_pos_digits = palloc0(accum_ndigits * sizeof(int32));
   12088                 :      175058 :         new_neg_digits = palloc0(accum_ndigits * sizeof(int32));
   12089                 :             : 
   12090         [ +  + ]:      175058 :         if (accum->pos_digits)
   12091                 :             :         {
   12092                 :       60290 :             memcpy(&new_pos_digits[weightdiff], accum->pos_digits,
   12093                 :             :                    old_ndigits * sizeof(int32));
   12094                 :       60290 :             pfree(accum->pos_digits);
   12095                 :             : 
   12096                 :       60290 :             memcpy(&new_neg_digits[weightdiff], accum->neg_digits,
   12097                 :             :                    old_ndigits * sizeof(int32));
   12098                 :       60290 :             pfree(accum->neg_digits);
   12099                 :             :         }
   12100                 :             : 
   12101                 :      175058 :         accum->pos_digits = new_pos_digits;
   12102                 :      175058 :         accum->neg_digits = new_neg_digits;
   12103                 :             : 
   12104                 :      175058 :         accum->weight = accum_weight;
   12105                 :      175058 :         accum->ndigits = accum_ndigits;
   12106                 :             : 
   12107                 :             :         Assert(accum->pos_digits[0] == 0 && accum->neg_digits[0] == 0);
   12108                 :      175058 :         accum->have_carry_space = true;
   12109                 :             :     }
   12110                 :             : 
   12111         [ +  + ]:     1570442 :     if (val->dscale > accum->dscale)
   12112                 :         200 :         accum->dscale = val->dscale;
   12113                 :     1570442 : }
   12114                 :             : 
   12115                 :             : /*
   12116                 :             :  * Return the current value of the accumulator.  This perform final carry
   12117                 :             :  * propagation, and adds together the positive and negative sums.
   12118                 :             :  *
   12119                 :             :  * Unlike all the other routines, the caller is not required to switch to
   12120                 :             :  * the memory context that holds the accumulator.
   12121                 :             :  */
   12122                 :             : static void
   12123                 :      115052 : accum_sum_final(NumericSumAccum *accum, NumericVar *result)
   12124                 :             : {
   12125                 :             :     int         i;
   12126                 :             :     NumericVar  pos_var;
   12127                 :             :     NumericVar  neg_var;
   12128                 :             : 
   12129         [ -  + ]:      115052 :     if (accum->ndigits == 0)
   12130                 :             :     {
   12131                 :           0 :         set_var_from_var(&const_zero, result);
   12132                 :           0 :         return;
   12133                 :             :     }
   12134                 :             : 
   12135                 :             :     /* Perform final carry */
   12136                 :      115052 :     accum_sum_carry(accum);
   12137                 :             : 
   12138                 :             :     /* Create NumericVars representing the positive and negative sums */
   12139                 :      115052 :     init_var(&pos_var);
   12140                 :      115052 :     init_var(&neg_var);
   12141                 :             : 
   12142                 :      115052 :     pos_var.ndigits = neg_var.ndigits = accum->ndigits;
   12143                 :      115052 :     pos_var.weight = neg_var.weight = accum->weight;
   12144                 :      115052 :     pos_var.dscale = neg_var.dscale = accum->dscale;
   12145                 :      115052 :     pos_var.sign = NUMERIC_POS;
   12146                 :      115052 :     neg_var.sign = NUMERIC_NEG;
   12147                 :             : 
   12148                 :      115052 :     pos_var.buf = pos_var.digits = digitbuf_alloc(accum->ndigits);
   12149                 :      115052 :     neg_var.buf = neg_var.digits = digitbuf_alloc(accum->ndigits);
   12150                 :             : 
   12151         [ +  + ]:     1736687 :     for (i = 0; i < accum->ndigits; i++)
   12152                 :             :     {
   12153                 :             :         Assert(accum->pos_digits[i] < NBASE);
   12154                 :     1621635 :         pos_var.digits[i] = (int16) accum->pos_digits[i];
   12155                 :             : 
   12156                 :             :         Assert(accum->neg_digits[i] < NBASE);
   12157                 :     1621635 :         neg_var.digits[i] = (int16) accum->neg_digits[i];
   12158                 :             :     }
   12159                 :             : 
   12160                 :             :     /* And add them together */
   12161                 :      115052 :     add_var(&pos_var, &neg_var, result);
   12162                 :             : 
   12163                 :             :     /* Remove leading/trailing zeroes */
   12164                 :      115052 :     strip_var(result);
   12165                 :             : }
   12166                 :             : 
   12167                 :             : /*
   12168                 :             :  * Copy an accumulator's state.
   12169                 :             :  *
   12170                 :             :  * 'dst' is assumed to be uninitialized beforehand.  No attempt is made at
   12171                 :             :  * freeing old values.
   12172                 :             :  */
   12173                 :             : static void
   12174                 :          28 : accum_sum_copy(NumericSumAccum *dst, NumericSumAccum *src)
   12175                 :             : {
   12176                 :          28 :     dst->pos_digits = palloc(src->ndigits * sizeof(int32));
   12177                 :          28 :     dst->neg_digits = palloc(src->ndigits * sizeof(int32));
   12178                 :             : 
   12179                 :          28 :     memcpy(dst->pos_digits, src->pos_digits, src->ndigits * sizeof(int32));
   12180                 :          28 :     memcpy(dst->neg_digits, src->neg_digits, src->ndigits * sizeof(int32));
   12181                 :          28 :     dst->num_uncarried = src->num_uncarried;
   12182                 :          28 :     dst->ndigits = src->ndigits;
   12183                 :          28 :     dst->weight = src->weight;
   12184                 :          28 :     dst->dscale = src->dscale;
   12185                 :          28 : }
   12186                 :             : 
   12187                 :             : /*
   12188                 :             :  * Add the current value of 'accum2' into 'accum'.
   12189                 :             :  */
   12190                 :             : static void
   12191                 :          33 : accum_sum_combine(NumericSumAccum *accum, NumericSumAccum *accum2)
   12192                 :             : {
   12193                 :             :     NumericVar  tmp_var;
   12194                 :             : 
   12195                 :          33 :     init_var(&tmp_var);
   12196                 :             : 
   12197                 :          33 :     accum_sum_final(accum2, &tmp_var);
   12198                 :          33 :     accum_sum_add(accum, &tmp_var);
   12199                 :             : 
   12200                 :          33 :     free_var(&tmp_var);
   12201                 :          33 : }
        

Generated by: LCOV version 2.0-1