PostgreSQL Source Code  git master
numeric.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include "catalog/pg_type.h"
#include "common/hashfn.h"
#include "common/int.h"
#include "funcapi.h"
#include "lib/hyperloglog.h"
#include "libpq/pqformat.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "nodes/supportnodes.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/numeric.h"
#include "utils/pg_lsn.h"
#include "utils/sortsupport.h"
Include dependency graph for numeric.c:

Go to the source code of this file.

Data Structures

struct  NumericShort
 
struct  NumericLong
 
union  NumericChoice
 
struct  NumericData
 
struct  NumericVar
 
struct  generate_series_numeric_fctx
 
struct  NumericSortSupport
 
struct  NumericSumAccum
 
struct  NumericAggState
 
struct  Int8TransTypeData
 

Macros

#define NBASE   10000
 
#define HALF_NBASE   5000
 
#define DEC_DIGITS   4 /* decimal digits per NBASE digit */
 
#define MUL_GUARD_DIGITS   2 /* these are measured in NBASE digits */
 
#define DIV_GUARD_DIGITS   4
 
#define NUMERIC_SIGN_MASK   0xC000
 
#define NUMERIC_POS   0x0000
 
#define NUMERIC_NEG   0x4000
 
#define NUMERIC_SHORT   0x8000
 
#define NUMERIC_SPECIAL   0xC000
 
#define NUMERIC_FLAGBITS(n)   ((n)->choice.n_header & NUMERIC_SIGN_MASK)
 
#define NUMERIC_IS_SHORT(n)   (NUMERIC_FLAGBITS(n) == NUMERIC_SHORT)
 
#define NUMERIC_IS_SPECIAL(n)   (NUMERIC_FLAGBITS(n) == NUMERIC_SPECIAL)
 
#define NUMERIC_HDRSZ   (VARHDRSZ + sizeof(uint16) + sizeof(int16))
 
#define NUMERIC_HDRSZ_SHORT   (VARHDRSZ + sizeof(uint16))
 
#define NUMERIC_HEADER_IS_SHORT(n)   (((n)->choice.n_header & 0x8000) != 0)
 
#define NUMERIC_HEADER_SIZE(n)
 
#define NUMERIC_EXT_SIGN_MASK   0xF000 /* high bits plus NaN/Inf flag bits */
 
#define NUMERIC_NAN   0xC000
 
#define NUMERIC_PINF   0xD000
 
#define NUMERIC_NINF   0xF000
 
#define NUMERIC_INF_SIGN_MASK   0x2000
 
#define NUMERIC_EXT_FLAGBITS(n)   ((n)->choice.n_header & NUMERIC_EXT_SIGN_MASK)
 
#define NUMERIC_IS_NAN(n)   ((n)->choice.n_header == NUMERIC_NAN)
 
#define NUMERIC_IS_PINF(n)   ((n)->choice.n_header == NUMERIC_PINF)
 
#define NUMERIC_IS_NINF(n)   ((n)->choice.n_header == NUMERIC_NINF)
 
#define NUMERIC_IS_INF(n)    (((n)->choice.n_header & ~NUMERIC_INF_SIGN_MASK) == NUMERIC_PINF)
 
#define NUMERIC_SHORT_SIGN_MASK   0x2000
 
#define NUMERIC_SHORT_DSCALE_MASK   0x1F80
 
#define NUMERIC_SHORT_DSCALE_SHIFT   7
 
#define NUMERIC_SHORT_DSCALE_MAX    (NUMERIC_SHORT_DSCALE_MASK >> NUMERIC_SHORT_DSCALE_SHIFT)
 
#define NUMERIC_SHORT_WEIGHT_SIGN_MASK   0x0040
 
#define NUMERIC_SHORT_WEIGHT_MASK   0x003F
 
#define NUMERIC_SHORT_WEIGHT_MAX   NUMERIC_SHORT_WEIGHT_MASK
 
#define NUMERIC_SHORT_WEIGHT_MIN   (-(NUMERIC_SHORT_WEIGHT_MASK+1))
 
#define NUMERIC_DSCALE_MASK   0x3FFF
 
#define NUMERIC_DSCALE_MAX   NUMERIC_DSCALE_MASK
 
#define NUMERIC_SIGN(n)
 
#define NUMERIC_DSCALE(n)
 
#define NUMERIC_WEIGHT(n)
 
#define NUMERIC_ABBREV_BITS   (SIZEOF_DATUM * BITS_PER_BYTE)
 
#define NumericAbbrevGetDatum(X)   ((Datum) (X))
 
#define DatumGetNumericAbbrev(X)   ((int32) (X))
 
#define NUMERIC_ABBREV_NAN   NumericAbbrevGetDatum(PG_INT32_MIN)
 
#define NUMERIC_ABBREV_PINF   NumericAbbrevGetDatum(-PG_INT32_MAX)
 
#define NUMERIC_ABBREV_NINF   NumericAbbrevGetDatum(PG_INT32_MAX)
 
#define dump_numeric(s, n)
 
#define dump_var(s, v)
 
#define digitbuf_alloc(ndigits)    ((NumericDigit *) palloc((ndigits) * sizeof(NumericDigit)))
 
#define digitbuf_free(buf)
 
#define init_var(v)   memset(v, 0, sizeof(NumericVar))
 
#define NUMERIC_DIGITS(num)
 
#define NUMERIC_NDIGITS(num)    ((VARSIZE(num) - NUMERIC_HEADER_SIZE(num)) / sizeof(NumericDigit))
 
#define NUMERIC_CAN_BE_SHORT(scale, weight)
 
#define NA_TOTAL_COUNT(na)    ((na)->N + (na)->NaNcount + (na)->pInfcount + (na)->nInfcount)
 
#define makePolyNumAggState   makeNumericAggState
 
#define makePolyNumAggStateCurrentContext   makeNumericAggStateCurrentContext
 

Typedefs

typedef int16 NumericDigit
 
typedef struct NumericVar NumericVar
 
typedef struct NumericSumAccum NumericSumAccum
 
typedef struct NumericAggState NumericAggState
 
typedef NumericAggState PolyNumAggState
 
typedef struct Int8TransTypeData Int8TransTypeData
 

Functions

static void alloc_var (NumericVar *var, int ndigits)
 
static void free_var (NumericVar *var)
 
static void zero_var (NumericVar *var)
 
static bool set_var_from_str (const char *str, const char *cp, NumericVar *dest, const char **endptr, Node *escontext)
 
static bool set_var_from_non_decimal_integer_str (const char *str, const char *cp, int sign, int base, NumericVar *dest, const char **endptr, Node *escontext)
 
static void set_var_from_num (Numeric num, NumericVar *dest)
 
static void init_var_from_num (Numeric num, NumericVar *dest)
 
static void set_var_from_var (const NumericVar *value, NumericVar *dest)
 
static char * get_str_from_var (const NumericVar *var)
 
static char * get_str_from_var_sci (const NumericVar *var, int rscale)
 
static void numericvar_serialize (StringInfo buf, const NumericVar *var)
 
static void numericvar_deserialize (StringInfo buf, NumericVar *var)
 
static Numeric duplicate_numeric (Numeric num)
 
static Numeric make_result (const NumericVar *var)
 
static Numeric make_result_opt_error (const NumericVar *var, bool *have_error)
 
static bool apply_typmod (NumericVar *var, int32 typmod, Node *escontext)
 
static bool apply_typmod_special (Numeric num, int32 typmod, Node *escontext)
 
static bool numericvar_to_int32 (const NumericVar *var, int32 *result)
 
static bool numericvar_to_int64 (const NumericVar *var, int64 *result)
 
static void int64_to_numericvar (int64 val, NumericVar *var)
 
static bool numericvar_to_uint64 (const NumericVar *var, uint64 *result)
 
static double numericvar_to_double_no_overflow (const NumericVar *var)
 
static Datum numeric_abbrev_convert (Datum original_datum, SortSupport ssup)
 
static bool numeric_abbrev_abort (int memtupcount, SortSupport ssup)
 
static int numeric_fast_cmp (Datum x, Datum y, SortSupport ssup)
 
static int numeric_cmp_abbrev (Datum x, Datum y, SortSupport ssup)
 
static Datum numeric_abbrev_convert_var (const NumericVar *var, NumericSortSupport *nss)
 
static int cmp_numerics (Numeric num1, Numeric num2)
 
static int cmp_var (const NumericVar *var1, const NumericVar *var2)
 
static int cmp_var_common (const NumericDigit *var1digits, int var1ndigits, int var1weight, int var1sign, const NumericDigit *var2digits, int var2ndigits, int var2weight, int var2sign)
 
static void add_var (const NumericVar *var1, const NumericVar *var2, NumericVar *result)
 
static void sub_var (const NumericVar *var1, const NumericVar *var2, NumericVar *result)
 
static void mul_var (const NumericVar *var1, const NumericVar *var2, NumericVar *result, int rscale)
 
static void div_var (const NumericVar *var1, const NumericVar *var2, NumericVar *result, int rscale, bool round)
 
static void div_var_fast (const NumericVar *var1, const NumericVar *var2, NumericVar *result, int rscale, bool round)
 
static void div_var_int (const NumericVar *var, int ival, int ival_weight, NumericVar *result, int rscale, bool round)
 
static int select_div_scale (const NumericVar *var1, const NumericVar *var2)
 
static void mod_var (const NumericVar *var1, const NumericVar *var2, NumericVar *result)
 
static void div_mod_var (const NumericVar *var1, const NumericVar *var2, NumericVar *quot, NumericVar *rem)
 
static void ceil_var (const NumericVar *var, NumericVar *result)
 
static void floor_var (const NumericVar *var, NumericVar *result)
 
static void gcd_var (const NumericVar *var1, const NumericVar *var2, NumericVar *result)
 
static void sqrt_var (const NumericVar *arg, NumericVar *result, int rscale)
 
static void exp_var (const NumericVar *arg, NumericVar *result, int rscale)
 
static int estimate_ln_dweight (const NumericVar *var)
 
static void ln_var (const NumericVar *arg, NumericVar *result, int rscale)
 
static void log_var (const NumericVar *base, const NumericVar *num, NumericVar *result)
 
static void power_var (const NumericVar *base, const NumericVar *exp, NumericVar *result)
 
static void power_var_int (const NumericVar *base, int exp, int exp_dscale, NumericVar *result)
 
static void power_ten_int (int exp, NumericVar *result)
 
static int cmp_abs (const NumericVar *var1, const NumericVar *var2)
 
static int cmp_abs_common (const NumericDigit *var1digits, int var1ndigits, int var1weight, const NumericDigit *var2digits, int var2ndigits, int var2weight)
 
static void add_abs (const NumericVar *var1, const NumericVar *var2, NumericVar *result)
 
static void sub_abs (const NumericVar *var1, const NumericVar *var2, NumericVar *result)
 
static void round_var (NumericVar *var, int rscale)
 
static void trunc_var (NumericVar *var, int rscale)
 
static void strip_var (NumericVar *var)
 
static void compute_bucket (Numeric operand, Numeric bound1, Numeric bound2, const NumericVar *count_var, bool reversed_bounds, NumericVar *result_var)
 
static void accum_sum_add (NumericSumAccum *accum, const NumericVar *val)
 
static void accum_sum_rescale (NumericSumAccum *accum, const NumericVar *val)
 
static void accum_sum_carry (NumericSumAccum *accum)
 
static void accum_sum_reset (NumericSumAccum *accum)
 
static void accum_sum_final (NumericSumAccum *accum, NumericVar *result)
 
static void accum_sum_copy (NumericSumAccum *dst, NumericSumAccum *src)
 
static void accum_sum_combine (NumericSumAccum *accum, NumericSumAccum *accum2)
 
Datum numeric_in (PG_FUNCTION_ARGS)
 
Datum numeric_out (PG_FUNCTION_ARGS)
 
bool numeric_is_nan (Numeric num)
 
bool numeric_is_inf (Numeric num)
 
static bool numeric_is_integral (Numeric num)
 
static int32 make_numeric_typmod (int precision, int scale)
 
static bool is_valid_numeric_typmod (int32 typmod)
 
static int numeric_typmod_precision (int32 typmod)
 
static int numeric_typmod_scale (int32 typmod)
 
int32 numeric_maximum_size (int32 typmod)
 
char * numeric_out_sci (Numeric num, int scale)
 
char * numeric_normalize (Numeric num)
 
Datum numeric_recv (PG_FUNCTION_ARGS)
 
Datum numeric_send (PG_FUNCTION_ARGS)
 
Datum numeric_support (PG_FUNCTION_ARGS)
 
Datum numeric (PG_FUNCTION_ARGS)
 
Datum numerictypmodin (PG_FUNCTION_ARGS)
 
Datum numerictypmodout (PG_FUNCTION_ARGS)
 
Datum numeric_abs (PG_FUNCTION_ARGS)
 
Datum numeric_uminus (PG_FUNCTION_ARGS)
 
Datum numeric_uplus (PG_FUNCTION_ARGS)
 
static int numeric_sign_internal (Numeric num)
 
Datum numeric_sign (PG_FUNCTION_ARGS)
 
Datum numeric_round (PG_FUNCTION_ARGS)
 
Datum numeric_trunc (PG_FUNCTION_ARGS)
 
Datum numeric_ceil (PG_FUNCTION_ARGS)
 
Datum numeric_floor (PG_FUNCTION_ARGS)
 
Datum generate_series_numeric (PG_FUNCTION_ARGS)
 
Datum generate_series_step_numeric (PG_FUNCTION_ARGS)
 
Datum width_bucket_numeric (PG_FUNCTION_ARGS)
 
Datum numeric_sortsupport (PG_FUNCTION_ARGS)
 
Datum numeric_cmp (PG_FUNCTION_ARGS)
 
Datum numeric_eq (PG_FUNCTION_ARGS)
 
Datum numeric_ne (PG_FUNCTION_ARGS)
 
Datum numeric_gt (PG_FUNCTION_ARGS)
 
Datum numeric_ge (PG_FUNCTION_ARGS)
 
Datum numeric_lt (PG_FUNCTION_ARGS)
 
Datum numeric_le (PG_FUNCTION_ARGS)
 
Datum in_range_numeric_numeric (PG_FUNCTION_ARGS)
 
Datum hash_numeric (PG_FUNCTION_ARGS)
 
Datum hash_numeric_extended (PG_FUNCTION_ARGS)
 
Datum numeric_add (PG_FUNCTION_ARGS)
 
Numeric numeric_add_opt_error (Numeric num1, Numeric num2, bool *have_error)
 
Datum numeric_sub (PG_FUNCTION_ARGS)
 
Numeric numeric_sub_opt_error (Numeric num1, Numeric num2, bool *have_error)
 
Datum numeric_mul (PG_FUNCTION_ARGS)
 
Numeric numeric_mul_opt_error (Numeric num1, Numeric num2, bool *have_error)
 
Datum numeric_div (PG_FUNCTION_ARGS)
 
Numeric numeric_div_opt_error (Numeric num1, Numeric num2, bool *have_error)
 
Datum numeric_div_trunc (PG_FUNCTION_ARGS)
 
Datum numeric_mod (PG_FUNCTION_ARGS)
 
Numeric numeric_mod_opt_error (Numeric num1, Numeric num2, bool *have_error)
 
Datum numeric_inc (PG_FUNCTION_ARGS)
 
Datum numeric_smaller (PG_FUNCTION_ARGS)
 
Datum numeric_larger (PG_FUNCTION_ARGS)
 
Datum numeric_gcd (PG_FUNCTION_ARGS)
 
Datum numeric_lcm (PG_FUNCTION_ARGS)
 
Datum numeric_fac (PG_FUNCTION_ARGS)
 
Datum numeric_sqrt (PG_FUNCTION_ARGS)
 
Datum numeric_exp (PG_FUNCTION_ARGS)
 
Datum numeric_ln (PG_FUNCTION_ARGS)
 
Datum numeric_log (PG_FUNCTION_ARGS)
 
Datum numeric_power (PG_FUNCTION_ARGS)
 
Datum numeric_scale (PG_FUNCTION_ARGS)
 
static int get_min_scale (NumericVar *var)
 
Datum numeric_min_scale (PG_FUNCTION_ARGS)
 
Datum numeric_trim_scale (PG_FUNCTION_ARGS)
 
Numeric int64_to_numeric (int64 val)
 
Numeric int64_div_fast_to_numeric (int64 val1, int log10val2)
 
Datum int4_numeric (PG_FUNCTION_ARGS)
 
int32 numeric_int4_opt_error (Numeric num, bool *have_error)
 
Datum numeric_int4 (PG_FUNCTION_ARGS)
 
Datum int8_numeric (PG_FUNCTION_ARGS)
 
Datum numeric_int8 (PG_FUNCTION_ARGS)
 
Datum int2_numeric (PG_FUNCTION_ARGS)
 
Datum numeric_int2 (PG_FUNCTION_ARGS)
 
Datum float8_numeric (PG_FUNCTION_ARGS)
 
Datum numeric_float8 (PG_FUNCTION_ARGS)
 
Datum numeric_float8_no_overflow (PG_FUNCTION_ARGS)
 
Datum float4_numeric (PG_FUNCTION_ARGS)
 
Datum numeric_float4 (PG_FUNCTION_ARGS)
 
Datum numeric_pg_lsn (PG_FUNCTION_ARGS)
 
static NumericAggStatemakeNumericAggState (FunctionCallInfo fcinfo, bool calcSumX2)
 
static NumericAggStatemakeNumericAggStateCurrentContext (bool calcSumX2)
 
static void do_numeric_accum (NumericAggState *state, Numeric newval)
 
static bool do_numeric_discard (NumericAggState *state, Numeric newval)
 
Datum numeric_accum (PG_FUNCTION_ARGS)
 
Datum numeric_combine (PG_FUNCTION_ARGS)
 
Datum numeric_avg_accum (PG_FUNCTION_ARGS)
 
Datum numeric_avg_combine (PG_FUNCTION_ARGS)
 
Datum numeric_avg_serialize (PG_FUNCTION_ARGS)
 
Datum numeric_avg_deserialize (PG_FUNCTION_ARGS)
 
Datum numeric_serialize (PG_FUNCTION_ARGS)
 
Datum numeric_deserialize (PG_FUNCTION_ARGS)
 
Datum numeric_accum_inv (PG_FUNCTION_ARGS)
 
Datum int2_accum (PG_FUNCTION_ARGS)
 
Datum int4_accum (PG_FUNCTION_ARGS)
 
Datum int8_accum (PG_FUNCTION_ARGS)
 
Datum numeric_poly_combine (PG_FUNCTION_ARGS)
 
Datum numeric_poly_serialize (PG_FUNCTION_ARGS)
 
Datum numeric_poly_deserialize (PG_FUNCTION_ARGS)
 
Datum int8_avg_accum (PG_FUNCTION_ARGS)
 
Datum int8_avg_combine (PG_FUNCTION_ARGS)
 
Datum int8_avg_serialize (PG_FUNCTION_ARGS)
 
Datum int8_avg_deserialize (PG_FUNCTION_ARGS)
 
Datum int2_accum_inv (PG_FUNCTION_ARGS)
 
Datum int4_accum_inv (PG_FUNCTION_ARGS)
 
Datum int8_accum_inv (PG_FUNCTION_ARGS)
 
Datum int8_avg_accum_inv (PG_FUNCTION_ARGS)
 
Datum numeric_poly_sum (PG_FUNCTION_ARGS)
 
Datum numeric_poly_avg (PG_FUNCTION_ARGS)
 
Datum numeric_avg (PG_FUNCTION_ARGS)
 
Datum numeric_sum (PG_FUNCTION_ARGS)
 
static Numeric numeric_stddev_internal (NumericAggState *state, bool variance, bool sample, bool *is_null)
 
Datum numeric_var_samp (PG_FUNCTION_ARGS)
 
Datum numeric_stddev_samp (PG_FUNCTION_ARGS)
 
Datum numeric_var_pop (PG_FUNCTION_ARGS)
 
Datum numeric_stddev_pop (PG_FUNCTION_ARGS)
 
Datum numeric_poly_var_samp (PG_FUNCTION_ARGS)
 
Datum numeric_poly_stddev_samp (PG_FUNCTION_ARGS)
 
Datum numeric_poly_var_pop (PG_FUNCTION_ARGS)
 
Datum numeric_poly_stddev_pop (PG_FUNCTION_ARGS)
 
Datum int2_sum (PG_FUNCTION_ARGS)
 
Datum int4_sum (PG_FUNCTION_ARGS)
 
Datum int8_sum (PG_FUNCTION_ARGS)
 
Datum int2_avg_accum (PG_FUNCTION_ARGS)
 
Datum int4_avg_accum (PG_FUNCTION_ARGS)
 
Datum int4_avg_combine (PG_FUNCTION_ARGS)
 
Datum int2_avg_accum_inv (PG_FUNCTION_ARGS)
 
Datum int4_avg_accum_inv (PG_FUNCTION_ARGS)
 
Datum int8_avg (PG_FUNCTION_ARGS)
 
Datum int2int4_sum (PG_FUNCTION_ARGS)
 
static int xdigit_value (char dig)
 

Variables

static const NumericDigit const_zero_data [1] = {0}
 
static const NumericVar const_zero
 
static const NumericDigit const_one_data [1] = {1}
 
static const NumericVar const_one
 
static const NumericVar const_minus_one
 
static const NumericDigit const_two_data [1] = {2}
 
static const NumericVar const_two
 
static const NumericDigit const_zero_point_nine_data [1] = {9000}
 
static const NumericVar const_zero_point_nine
 
static const NumericDigit const_one_point_one_data [2] = {1, 1000}
 
static const NumericVar const_one_point_one
 
static const NumericVar const_nan
 
static const NumericVar const_pinf
 
static const NumericVar const_ninf
 
static const int round_powers [4] = {0, 1000, 100, 10}
 

Macro Definition Documentation

◆ DatumGetNumericAbbrev

#define DatumGetNumericAbbrev (   X)    ((int32) (X))

Definition at line 404 of file numeric.c.

◆ DEC_DIGITS

#define DEC_DIGITS   4 /* decimal digits per NBASE digit */

Definition at line 98 of file numeric.c.

◆ digitbuf_alloc

#define digitbuf_alloc (   ndigits)     ((NumericDigit *) palloc((ndigits) * sizeof(NumericDigit)))

Definition at line 477 of file numeric.c.

◆ digitbuf_free

#define digitbuf_free (   buf)
Value:
do { \
if ((buf) != NULL) \
pfree(buf); \
} while (0)
static char * buf
Definition: pg_test_fsync.c:73

Definition at line 479 of file numeric.c.

◆ DIV_GUARD_DIGITS

#define DIV_GUARD_DIGITS   4

Definition at line 100 of file numeric.c.

◆ dump_numeric

#define dump_numeric (   s,
 
)

Definition at line 473 of file numeric.c.

◆ dump_var

#define dump_var (   s,
 
)

Definition at line 474 of file numeric.c.

◆ HALF_NBASE

#define HALF_NBASE   5000

Definition at line 97 of file numeric.c.

◆ init_var

#define init_var (   v)    memset(v, 0, sizeof(NumericVar))

Definition at line 485 of file numeric.c.

◆ makePolyNumAggState

#define makePolyNumAggState   makeNumericAggState

Definition at line 5467 of file numeric.c.

◆ makePolyNumAggStateCurrentContext

#define makePolyNumAggStateCurrentContext   makeNumericAggStateCurrentContext

Definition at line 5468 of file numeric.c.

◆ MUL_GUARD_DIGITS

#define MUL_GUARD_DIGITS   2 /* these are measured in NBASE digits */

Definition at line 99 of file numeric.c.

◆ NA_TOTAL_COUNT

#define NA_TOTAL_COUNT (   na)     ((na)->N + (na)->NaNcount + (na)->pInfcount + (na)->nInfcount)

Definition at line 4731 of file numeric.c.

◆ NBASE

#define NBASE   10000

Definition at line 96 of file numeric.c.

◆ NUMERIC_ABBREV_BITS

#define NUMERIC_ABBREV_BITS   (SIZEOF_DATUM * BITS_PER_BYTE)

Definition at line 395 of file numeric.c.

◆ NUMERIC_ABBREV_NAN

#define NUMERIC_ABBREV_NAN   NumericAbbrevGetDatum(PG_INT32_MIN)

Definition at line 405 of file numeric.c.

◆ NUMERIC_ABBREV_NINF

#define NUMERIC_ABBREV_NINF   NumericAbbrevGetDatum(PG_INT32_MAX)

Definition at line 407 of file numeric.c.

◆ NUMERIC_ABBREV_PINF

#define NUMERIC_ABBREV_PINF   NumericAbbrevGetDatum(-PG_INT32_MAX)

Definition at line 406 of file numeric.c.

◆ NUMERIC_CAN_BE_SHORT

#define NUMERIC_CAN_BE_SHORT (   scale,
  weight 
)
Value:
(weight) <= NUMERIC_SHORT_WEIGHT_MAX && \
#define NUMERIC_SHORT_DSCALE_MAX
Definition: numeric.c:217
#define NUMERIC_SHORT_WEIGHT_MIN
Definition: numeric.c:222
#define NUMERIC_SHORT_WEIGHT_MAX
Definition: numeric.c:221
int scale
Definition: pgbench.c:181

Definition at line 491 of file numeric.c.

◆ NUMERIC_DIGITS

#define NUMERIC_DIGITS (   num)
Value:
(num)->choice.n_short.n_data : (num)->choice.n_long.n_data)
#define NUMERIC_HEADER_IS_SHORT(n)
Definition: numeric.c:183

Definition at line 487 of file numeric.c.

◆ NUMERIC_DSCALE

#define NUMERIC_DSCALE (   n)
Value:
((n)->choice.n_short.n_header & NUMERIC_SHORT_DSCALE_MASK) \
: ((n)->choice.n_long.n_sign_dscale & NUMERIC_DSCALE_MASK))
#define NUMERIC_DSCALE_MASK
Definition: numeric.c:234
#define NUMERIC_SHORT_DSCALE_MASK
Definition: numeric.c:215
#define NUMERIC_SHORT_DSCALE_SHIFT
Definition: numeric.c:216

Definition at line 243 of file numeric.c.

◆ NUMERIC_DSCALE_MASK

#define NUMERIC_DSCALE_MASK   0x3FFF

Definition at line 234 of file numeric.c.

◆ NUMERIC_DSCALE_MAX

#define NUMERIC_DSCALE_MAX   NUMERIC_DSCALE_MASK

Definition at line 235 of file numeric.c.

◆ NUMERIC_EXT_FLAGBITS

#define NUMERIC_EXT_FLAGBITS (   n)    ((n)->choice.n_header & NUMERIC_EXT_SIGN_MASK)

Definition at line 203 of file numeric.c.

◆ NUMERIC_EXT_SIGN_MASK

#define NUMERIC_EXT_SIGN_MASK   0xF000 /* high bits plus NaN/Inf flag bits */

Definition at line 197 of file numeric.c.

◆ NUMERIC_FLAGBITS

#define NUMERIC_FLAGBITS (   n)    ((n)->choice.n_header & NUMERIC_SIGN_MASK)

Definition at line 171 of file numeric.c.

◆ NUMERIC_HDRSZ

#define NUMERIC_HDRSZ   (VARHDRSZ + sizeof(uint16) + sizeof(int16))

Definition at line 175 of file numeric.c.

◆ NUMERIC_HDRSZ_SHORT

#define NUMERIC_HDRSZ_SHORT   (VARHDRSZ + sizeof(uint16))

Definition at line 176 of file numeric.c.

◆ NUMERIC_HEADER_IS_SHORT

#define NUMERIC_HEADER_IS_SHORT (   n)    (((n)->choice.n_header & 0x8000) != 0)

Definition at line 183 of file numeric.c.

◆ NUMERIC_HEADER_SIZE

#define NUMERIC_HEADER_SIZE (   n)
Value:
(VARHDRSZ + sizeof(uint16) + \
(NUMERIC_HEADER_IS_SHORT(n) ? 0 : sizeof(int16)))
unsigned short uint16
Definition: c.h:494
signed short int16
Definition: c.h:482
#define VARHDRSZ
Definition: c.h:681

Definition at line 184 of file numeric.c.

◆ NUMERIC_INF_SIGN_MASK

#define NUMERIC_INF_SIGN_MASK   0x2000

Definition at line 201 of file numeric.c.

◆ NUMERIC_IS_INF

#define NUMERIC_IS_INF (   n)     (((n)->choice.n_header & ~NUMERIC_INF_SIGN_MASK) == NUMERIC_PINF)

Definition at line 207 of file numeric.c.

◆ NUMERIC_IS_NAN

#define NUMERIC_IS_NAN (   n)    ((n)->choice.n_header == NUMERIC_NAN)

Definition at line 204 of file numeric.c.

◆ NUMERIC_IS_NINF

#define NUMERIC_IS_NINF (   n)    ((n)->choice.n_header == NUMERIC_NINF)

Definition at line 206 of file numeric.c.

◆ NUMERIC_IS_PINF

#define NUMERIC_IS_PINF (   n)    ((n)->choice.n_header == NUMERIC_PINF)

Definition at line 205 of file numeric.c.

◆ NUMERIC_IS_SHORT

#define NUMERIC_IS_SHORT (   n)    (NUMERIC_FLAGBITS(n) == NUMERIC_SHORT)

Definition at line 172 of file numeric.c.

◆ NUMERIC_IS_SPECIAL

#define NUMERIC_IS_SPECIAL (   n)    (NUMERIC_FLAGBITS(n) == NUMERIC_SPECIAL)

Definition at line 173 of file numeric.c.

◆ NUMERIC_NAN

#define NUMERIC_NAN   0xC000

Definition at line 198 of file numeric.c.

◆ NUMERIC_NDIGITS

#define NUMERIC_NDIGITS (   num)     ((VARSIZE(num) - NUMERIC_HEADER_SIZE(num)) / sizeof(NumericDigit))

Definition at line 489 of file numeric.c.

◆ NUMERIC_NEG

#define NUMERIC_NEG   0x4000

Definition at line 167 of file numeric.c.

◆ NUMERIC_NINF

#define NUMERIC_NINF   0xF000

Definition at line 200 of file numeric.c.

◆ NUMERIC_PINF

#define NUMERIC_PINF   0xD000

Definition at line 199 of file numeric.c.

◆ NUMERIC_POS

#define NUMERIC_POS   0x0000

Definition at line 166 of file numeric.c.

◆ NUMERIC_SHORT

#define NUMERIC_SHORT   0x8000

Definition at line 168 of file numeric.c.

◆ NUMERIC_SHORT_DSCALE_MASK

#define NUMERIC_SHORT_DSCALE_MASK   0x1F80

Definition at line 215 of file numeric.c.

◆ NUMERIC_SHORT_DSCALE_MAX

#define NUMERIC_SHORT_DSCALE_MAX    (NUMERIC_SHORT_DSCALE_MASK >> NUMERIC_SHORT_DSCALE_SHIFT)

Definition at line 217 of file numeric.c.

◆ NUMERIC_SHORT_DSCALE_SHIFT

#define NUMERIC_SHORT_DSCALE_SHIFT   7

Definition at line 216 of file numeric.c.

◆ NUMERIC_SHORT_SIGN_MASK

#define NUMERIC_SHORT_SIGN_MASK   0x2000

Definition at line 214 of file numeric.c.

◆ NUMERIC_SHORT_WEIGHT_MASK

#define NUMERIC_SHORT_WEIGHT_MASK   0x003F

Definition at line 220 of file numeric.c.

◆ NUMERIC_SHORT_WEIGHT_MAX

#define NUMERIC_SHORT_WEIGHT_MAX   NUMERIC_SHORT_WEIGHT_MASK

Definition at line 221 of file numeric.c.

◆ NUMERIC_SHORT_WEIGHT_MIN

#define NUMERIC_SHORT_WEIGHT_MIN   (-(NUMERIC_SHORT_WEIGHT_MASK+1))

Definition at line 222 of file numeric.c.

◆ NUMERIC_SHORT_WEIGHT_SIGN_MASK

#define NUMERIC_SHORT_WEIGHT_SIGN_MASK   0x0040

Definition at line 219 of file numeric.c.

◆ NUMERIC_SIGN

#define NUMERIC_SIGN (   n)
Value:
(((n)->choice.n_short.n_header & NUMERIC_SHORT_SIGN_MASK) ? \
NUMERIC_NEG : NUMERIC_POS) : \
NUMERIC_EXT_FLAGBITS(n) : NUMERIC_FLAGBITS(n)))
#define NUMERIC_IS_SPECIAL(n)
Definition: numeric.c:173
#define NUMERIC_FLAGBITS(n)
Definition: numeric.c:171
#define NUMERIC_SHORT_SIGN_MASK
Definition: numeric.c:214
#define NUMERIC_IS_SHORT(n)
Definition: numeric.c:172
#define NUMERIC_POS
Definition: numeric.c:166

Definition at line 237 of file numeric.c.

◆ NUMERIC_SIGN_MASK

#define NUMERIC_SIGN_MASK   0xC000

Definition at line 165 of file numeric.c.

◆ NUMERIC_SPECIAL

#define NUMERIC_SPECIAL   0xC000

Definition at line 169 of file numeric.c.

◆ NUMERIC_WEIGHT

#define NUMERIC_WEIGHT (   n)
Value:
(((n)->choice.n_short.n_header & NUMERIC_SHORT_WEIGHT_SIGN_MASK ? \
| ((n)->choice.n_short.n_header & NUMERIC_SHORT_WEIGHT_MASK)) \
: ((n)->choice.n_long.n_weight))
#define NUMERIC_SHORT_WEIGHT_MASK
Definition: numeric.c:220
#define NUMERIC_SHORT_WEIGHT_SIGN_MASK
Definition: numeric.c:219

Definition at line 247 of file numeric.c.

◆ NumericAbbrevGetDatum

#define NumericAbbrevGetDatum (   X)    ((Datum) (X))

Definition at line 403 of file numeric.c.

Typedef Documentation

◆ Int8TransTypeData

◆ NumericAggState

◆ NumericDigit

Definition at line 102 of file numeric.c.

◆ NumericSumAccum

◆ NumericVar

typedef struct NumericVar NumericVar

◆ PolyNumAggState

Definition at line 5466 of file numeric.c.

Function Documentation

◆ accum_sum_add()

static void accum_sum_add ( NumericSumAccum accum,
const NumericVar val 
)
static

Definition at line 11729 of file numeric.c.

11730 {
11731  int32 *accum_digits;
11732  int i,
11733  val_i;
11734  int val_ndigits;
11735  NumericDigit *val_digits;
11736 
11737  /*
11738  * If we have accumulated too many values since the last carry
11739  * propagation, do it now, to avoid overflowing. (We could allow more
11740  * than NBASE - 1, if we reserved two extra digits, rather than one, for
11741  * carry propagation. But even with NBASE - 1, this needs to be done so
11742  * seldom, that the performance difference is negligible.)
11743  */
11744  if (accum->num_uncarried == NBASE - 1)
11745  accum_sum_carry(accum);
11746 
11747  /*
11748  * Adjust the weight or scale of the old value, so that it can accommodate
11749  * the new value.
11750  */
11751  accum_sum_rescale(accum, val);
11752 
11753  /* */
11754  if (val->sign == NUMERIC_POS)
11755  accum_digits = accum->pos_digits;
11756  else
11757  accum_digits = accum->neg_digits;
11758 
11759  /* copy these values into local vars for speed in loop */
11760  val_ndigits = val->ndigits;
11761  val_digits = val->digits;
11762 
11763  i = accum->weight - val->weight;
11764  for (val_i = 0; val_i < val_ndigits; val_i++)
11765  {
11766  accum_digits[i] += (int32) val_digits[val_i];
11767  i++;
11768  }
11769 
11770  accum->num_uncarried++;
11771 }
static void accum_sum_carry(NumericSumAccum *accum)
Definition: numeric.c:11777
int16 NumericDigit
Definition: numeric.c:102
#define NBASE
Definition: numeric.c:96
static void accum_sum_rescale(NumericSumAccum *accum, const NumericVar *val)
Definition: numeric.c:11850
signed int int32
Definition: c.h:483
long val
Definition: informix.c:664
int i
Definition: isn.c:73
int32 * pos_digits
Definition: numeric.c:378
int num_uncarried
Definition: numeric.c:376
int32 * neg_digits
Definition: numeric.c:379

References accum_sum_carry(), accum_sum_rescale(), i, NBASE, NumericSumAccum::neg_digits, NumericSumAccum::num_uncarried, NUMERIC_POS, NumericSumAccum::pos_digits, val, and NumericSumAccum::weight.

Referenced by accum_sum_combine(), do_numeric_accum(), do_numeric_discard(), int8_avg_deserialize(), numeric_avg_deserialize(), numeric_deserialize(), and numeric_poly_deserialize().

◆ accum_sum_carry()

static void accum_sum_carry ( NumericSumAccum accum)
static

Definition at line 11777 of file numeric.c.

11778 {
11779  int i;
11780  int ndigits;
11781  int32 *dig;
11782  int32 carry;
11783  int32 newdig = 0;
11784 
11785  /*
11786  * If no new values have been added since last carry propagation, nothing
11787  * to do.
11788  */
11789  if (accum->num_uncarried == 0)
11790  return;
11791 
11792  /*
11793  * We maintain that the weight of the accumulator is always one larger
11794  * than needed to hold the current value, before carrying, to make sure
11795  * there is enough space for the possible extra digit when carry is
11796  * propagated. We cannot expand the buffer here, unless we require
11797  * callers of accum_sum_final() to switch to the right memory context.
11798  */
11799  Assert(accum->pos_digits[0] == 0 && accum->neg_digits[0] == 0);
11800 
11801  ndigits = accum->ndigits;
11802 
11803  /* Propagate carry in the positive sum */
11804  dig = accum->pos_digits;
11805  carry = 0;
11806  for (i = ndigits - 1; i >= 0; i--)
11807  {
11808  newdig = dig[i] + carry;
11809  if (newdig >= NBASE)
11810  {
11811  carry = newdig / NBASE;
11812  newdig -= carry * NBASE;
11813  }
11814  else
11815  carry = 0;
11816  dig[i] = newdig;
11817  }
11818  /* Did we use up the digit reserved for carry propagation? */
11819  if (newdig > 0)
11820  accum->have_carry_space = false;
11821 
11822  /* And the same for the negative sum */
11823  dig = accum->neg_digits;
11824  carry = 0;
11825  for (i = ndigits - 1; i >= 0; i--)
11826  {
11827  newdig = dig[i] + carry;
11828  if (newdig >= NBASE)
11829  {
11830  carry = newdig / NBASE;
11831  newdig -= carry * NBASE;
11832  }
11833  else
11834  carry = 0;
11835  dig[i] = newdig;
11836  }
11837  if (newdig > 0)
11838  accum->have_carry_space = false;
11839 
11840  accum->num_uncarried = 0;
11841 }
Assert(fmt[strlen(fmt) - 1] !='\n')
bool have_carry_space
Definition: numeric.c:377

References Assert(), NumericSumAccum::have_carry_space, i, NBASE, NumericSumAccum::ndigits, NumericSumAccum::neg_digits, NumericSumAccum::num_uncarried, and NumericSumAccum::pos_digits.

Referenced by accum_sum_add(), and accum_sum_final().

◆ accum_sum_combine()

static void accum_sum_combine ( NumericSumAccum accum,
NumericSumAccum accum2 
)
static

Definition at line 12007 of file numeric.c.

12008 {
12009  NumericVar tmp_var;
12010 
12011  init_var(&tmp_var);
12012 
12013  accum_sum_final(accum2, &tmp_var);
12014  accum_sum_add(accum, &tmp_var);
12015 
12016  free_var(&tmp_var);
12017 }
static void accum_sum_final(NumericSumAccum *accum, NumericVar *result)
Definition: numeric.c:11939
static void free_var(NumericVar *var)
Definition: numeric.c:6891
static void accum_sum_add(NumericSumAccum *accum, const NumericVar *val)
Definition: numeric.c:11729
#define init_var(v)
Definition: numeric.c:485

References accum_sum_add(), accum_sum_final(), free_var(), and init_var.

Referenced by int8_avg_combine(), numeric_avg_combine(), numeric_combine(), and numeric_poly_combine().

◆ accum_sum_copy()

static void accum_sum_copy ( NumericSumAccum dst,
NumericSumAccum src 
)
static

Definition at line 11990 of file numeric.c.

11991 {
11992  dst->pos_digits = palloc(src->ndigits * sizeof(int32));
11993  dst->neg_digits = palloc(src->ndigits * sizeof(int32));
11994 
11995  memcpy(dst->pos_digits, src->pos_digits, src->ndigits * sizeof(int32));
11996  memcpy(dst->neg_digits, src->neg_digits, src->ndigits * sizeof(int32));
11997  dst->num_uncarried = src->num_uncarried;
11998  dst->ndigits = src->ndigits;
11999  dst->weight = src->weight;
12000  dst->dscale = src->dscale;
12001 }
void * palloc(Size size)
Definition: mcxt.c:1226

References NumericSumAccum::dscale, NumericSumAccum::ndigits, NumericSumAccum::neg_digits, NumericSumAccum::num_uncarried, palloc(), NumericSumAccum::pos_digits, and NumericSumAccum::weight.

Referenced by int8_avg_combine(), numeric_avg_combine(), numeric_combine(), and numeric_poly_combine().

◆ accum_sum_final()

static void accum_sum_final ( NumericSumAccum accum,
NumericVar result 
)
static

Definition at line 11939 of file numeric.c.

11940 {
11941  int i;
11942  NumericVar pos_var;
11943  NumericVar neg_var;
11944 
11945  if (accum->ndigits == 0)
11946  {
11947  set_var_from_var(&const_zero, result);
11948  return;
11949  }
11950 
11951  /* Perform final carry */
11952  accum_sum_carry(accum);
11953 
11954  /* Create NumericVars representing the positive and negative sums */
11955  init_var(&pos_var);
11956  init_var(&neg_var);
11957 
11958  pos_var.ndigits = neg_var.ndigits = accum->ndigits;
11959  pos_var.weight = neg_var.weight = accum->weight;
11960  pos_var.dscale = neg_var.dscale = accum->dscale;
11961  pos_var.sign = NUMERIC_POS;
11962  neg_var.sign = NUMERIC_NEG;
11963 
11964  pos_var.buf = pos_var.digits = digitbuf_alloc(accum->ndigits);
11965  neg_var.buf = neg_var.digits = digitbuf_alloc(accum->ndigits);
11966 
11967  for (i = 0; i < accum->ndigits; i++)
11968  {
11969  Assert(accum->pos_digits[i] < NBASE);
11970  pos_var.digits[i] = (int16) accum->pos_digits[i];
11971 
11972  Assert(accum->neg_digits[i] < NBASE);
11973  neg_var.digits[i] = (int16) accum->neg_digits[i];
11974  }
11975 
11976  /* And add them together */
11977  add_var(&pos_var, &neg_var, result);
11978 
11979  /* Remove leading/trailing zeroes */
11980  strip_var(result);
11981 }
static void add_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
Definition: numeric.c:8353
#define NUMERIC_NEG
Definition: numeric.c:167
#define digitbuf_alloc(ndigits)
Definition: numeric.c:477
static const NumericVar const_zero
Definition: numeric.c:416
static void set_var_from_var(const NumericVar *value, NumericVar *dest)
Definition: numeric.c:7390
static void strip_var(NumericVar *var)
Definition: numeric.c:11672
int ndigits
Definition: numeric.c:306
NumericDigit * digits
Definition: numeric.c:311
int dscale
Definition: numeric.c:309
int sign
Definition: numeric.c:308
NumericDigit * buf
Definition: numeric.c:310
int weight
Definition: numeric.c:307

References accum_sum_carry(), add_var(), Assert(), NumericVar::buf, const_zero, digitbuf_alloc, NumericVar::digits, NumericVar::dscale, NumericSumAccum::dscale, i, init_var, NBASE, NumericVar::ndigits, NumericSumAccum::ndigits, NumericSumAccum::neg_digits, NUMERIC_NEG, NUMERIC_POS, NumericSumAccum::pos_digits, set_var_from_var(), NumericVar::sign, strip_var(), NumericVar::weight, and NumericSumAccum::weight.

Referenced by accum_sum_combine(), int8_avg_serialize(), numeric_avg(), numeric_avg_serialize(), numeric_poly_serialize(), numeric_serialize(), numeric_stddev_internal(), and numeric_sum().

◆ accum_sum_rescale()

static void accum_sum_rescale ( NumericSumAccum accum,
const NumericVar val 
)
static

Definition at line 11850 of file numeric.c.

11851 {
11852  int old_weight = accum->weight;
11853  int old_ndigits = accum->ndigits;
11854  int accum_ndigits;
11855  int accum_weight;
11856  int accum_rscale;
11857  int val_rscale;
11858 
11859  accum_weight = old_weight;
11860  accum_ndigits = old_ndigits;
11861 
11862  /*
11863  * Does the new value have a larger weight? If so, enlarge the buffers,
11864  * and shift the existing value to the new weight, by adding leading
11865  * zeros.
11866  *
11867  * We enforce that the accumulator always has a weight one larger than
11868  * needed for the inputs, so that we have space for an extra digit at the
11869  * final carry-propagation phase, if necessary.
11870  */
11871  if (val->weight >= accum_weight)
11872  {
11873  accum_weight = val->weight + 1;
11874  accum_ndigits = accum_ndigits + (accum_weight - old_weight);
11875  }
11876 
11877  /*
11878  * Even though the new value is small, we might've used up the space
11879  * reserved for the carry digit in the last call to accum_sum_carry(). If
11880  * so, enlarge to make room for another one.
11881  */
11882  else if (!accum->have_carry_space)
11883  {
11884  accum_weight++;
11885  accum_ndigits++;
11886  }
11887 
11888  /* Is the new value wider on the right side? */
11889  accum_rscale = accum_ndigits - accum_weight - 1;
11890  val_rscale = val->ndigits - val->weight - 1;
11891  if (val_rscale > accum_rscale)
11892  accum_ndigits = accum_ndigits + (val_rscale - accum_rscale);
11893 
11894  if (accum_ndigits != old_ndigits ||
11895  accum_weight != old_weight)
11896  {
11897  int32 *new_pos_digits;
11898  int32 *new_neg_digits;
11899  int weightdiff;
11900 
11901  weightdiff = accum_weight - old_weight;
11902 
11903  new_pos_digits = palloc0(accum_ndigits * sizeof(int32));
11904  new_neg_digits = palloc0(accum_ndigits * sizeof(int32));
11905 
11906  if (accum->pos_digits)
11907  {
11908  memcpy(&new_pos_digits[weightdiff], accum->pos_digits,
11909  old_ndigits * sizeof(int32));
11910  pfree(accum->pos_digits);
11911 
11912  memcpy(&new_neg_digits[weightdiff], accum->neg_digits,
11913  old_ndigits * sizeof(int32));
11914  pfree(accum->neg_digits);
11915  }
11916 
11917  accum->pos_digits = new_pos_digits;
11918  accum->neg_digits = new_neg_digits;
11919 
11920  accum->weight = accum_weight;
11921  accum->ndigits = accum_ndigits;
11922 
11923  Assert(accum->pos_digits[0] == 0 && accum->neg_digits[0] == 0);
11924  accum->have_carry_space = true;
11925  }
11926 
11927  if (val->dscale > accum->dscale)
11928  accum->dscale = val->dscale;
11929 }
void pfree(void *pointer)
Definition: mcxt.c:1456
void * palloc0(Size size)
Definition: mcxt.c:1257

References Assert(), NumericSumAccum::dscale, NumericSumAccum::have_carry_space, NumericSumAccum::ndigits, NumericSumAccum::neg_digits, palloc0(), pfree(), NumericSumAccum::pos_digits, val, and NumericSumAccum::weight.

Referenced by accum_sum_add().

◆ accum_sum_reset()

static void accum_sum_reset ( NumericSumAccum accum)
static

Definition at line 11713 of file numeric.c.

11714 {
11715  int i;
11716 
11717  accum->dscale = 0;
11718  for (i = 0; i < accum->ndigits; i++)
11719  {
11720  accum->pos_digits[i] = 0;
11721  accum->neg_digits[i] = 0;
11722  }
11723 }

References NumericSumAccum::dscale, i, NumericSumAccum::ndigits, NumericSumAccum::neg_digits, and NumericSumAccum::pos_digits.

Referenced by do_numeric_discard().

◆ add_abs()

static void add_abs ( const NumericVar var1,
const NumericVar var2,
NumericVar result 
)
static

Definition at line 11337 of file numeric.c.

11338 {
11339  NumericDigit *res_buf;
11340  NumericDigit *res_digits;
11341  int res_ndigits;
11342  int res_weight;
11343  int res_rscale,
11344  rscale1,
11345  rscale2;
11346  int res_dscale;
11347  int i,
11348  i1,
11349  i2;
11350  int carry = 0;
11351 
11352  /* copy these values into local vars for speed in inner loop */
11353  int var1ndigits = var1->ndigits;
11354  int var2ndigits = var2->ndigits;
11355  NumericDigit *var1digits = var1->digits;
11356  NumericDigit *var2digits = var2->digits;
11357 
11358  res_weight = Max(var1->weight, var2->weight) + 1;
11359 
11360  res_dscale = Max(var1->dscale, var2->dscale);
11361 
11362  /* Note: here we are figuring rscale in base-NBASE digits */
11363  rscale1 = var1->ndigits - var1->weight - 1;
11364  rscale2 = var2->ndigits - var2->weight - 1;
11365  res_rscale = Max(rscale1, rscale2);
11366 
11367  res_ndigits = res_rscale + res_weight + 1;
11368  if (res_ndigits <= 0)
11369  res_ndigits = 1;
11370 
11371  res_buf = digitbuf_alloc(res_ndigits + 1);
11372  res_buf[0] = 0; /* spare digit for later rounding */
11373  res_digits = res_buf + 1;
11374 
11375  i1 = res_rscale + var1->weight + 1;
11376  i2 = res_rscale + var2->weight + 1;
11377  for (i = res_ndigits - 1; i >= 0; i--)
11378  {
11379  i1--;
11380  i2--;
11381  if (i1 >= 0 && i1 < var1ndigits)
11382  carry += var1digits[i1];
11383  if (i2 >= 0 && i2 < var2ndigits)
11384  carry += var2digits[i2];
11385 
11386  if (carry >= NBASE)
11387  {
11388  res_digits[i] = carry - NBASE;
11389  carry = 1;
11390  }
11391  else
11392  {
11393  res_digits[i] = carry;
11394  carry = 0;
11395  }
11396  }
11397 
11398  Assert(carry == 0); /* else we failed to allow for carry out */
11399 
11400  digitbuf_free(result->buf);
11401  result->ndigits = res_ndigits;
11402  result->buf = res_buf;
11403  result->digits = res_digits;
11404  result->weight = res_weight;
11405  result->dscale = res_dscale;
11406 
11407  /* Remove leading/trailing zeroes */
11408  strip_var(result);
11409 }
#define digitbuf_free(buf)
Definition: numeric.c:479
#define Max(x, y)
Definition: numeric.c:13

References Assert(), NumericVar::buf, digitbuf_alloc, digitbuf_free, NumericVar::digits, NumericVar::dscale, i, Max, NBASE, NumericVar::ndigits, strip_var(), and NumericVar::weight.

Referenced by add_var(), and sub_var().

◆ add_var()

static void add_var ( const NumericVar var1,
const NumericVar var2,
NumericVar result 
)
static

Definition at line 8353 of file numeric.c.

8354 {
8355  /*
8356  * Decide on the signs of the two variables what to do
8357  */
8358  if (var1->sign == NUMERIC_POS)
8359  {
8360  if (var2->sign == NUMERIC_POS)
8361  {
8362  /*
8363  * Both are positive result = +(ABS(var1) + ABS(var2))
8364  */
8365  add_abs(var1, var2, result);
8366  result->sign = NUMERIC_POS;
8367  }
8368  else
8369  {
8370  /*
8371  * var1 is positive, var2 is negative Must compare absolute values
8372  */
8373  switch (cmp_abs(var1, var2))
8374  {
8375  case 0:
8376  /* ----------
8377  * ABS(var1) == ABS(var2)
8378  * result = ZERO
8379  * ----------
8380  */
8381  zero_var(result);
8382  result->dscale = Max(var1->dscale, var2->dscale);
8383  break;
8384 
8385  case 1:
8386  /* ----------
8387  * ABS(var1) > ABS(var2)
8388  * result = +(ABS(var1) - ABS(var2))
8389  * ----------
8390  */
8391  sub_abs(var1, var2, result);
8392  result->sign = NUMERIC_POS;
8393  break;
8394 
8395  case -1:
8396  /* ----------
8397  * ABS(var1) < ABS(var2)
8398  * result = -(ABS(var2) - ABS(var1))
8399  * ----------
8400  */
8401  sub_abs(var2, var1, result);
8402  result->sign = NUMERIC_NEG;
8403  break;
8404  }
8405  }
8406  }
8407  else
8408  {
8409  if (var2->sign == NUMERIC_POS)
8410  {
8411  /* ----------
8412  * var1 is negative, var2 is positive
8413  * Must compare absolute values
8414  * ----------
8415  */
8416  switch (cmp_abs(var1, var2))
8417  {
8418  case 0:
8419  /* ----------
8420  * ABS(var1) == ABS(var2)
8421  * result = ZERO
8422  * ----------
8423  */
8424  zero_var(result);
8425  result->dscale = Max(var1->dscale, var2->dscale);
8426  break;
8427 
8428  case 1:
8429  /* ----------
8430  * ABS(var1) > ABS(var2)
8431  * result = -(ABS(var1) - ABS(var2))
8432  * ----------
8433  */
8434  sub_abs(var1, var2, result);
8435  result->sign = NUMERIC_NEG;
8436  break;
8437 
8438  case -1:
8439  /* ----------
8440  * ABS(var1) < ABS(var2)
8441  * result = +(ABS(var2) - ABS(var1))
8442  * ----------
8443  */
8444  sub_abs(var2, var1, result);
8445  result->sign = NUMERIC_POS;
8446  break;
8447  }
8448  }
8449  else
8450  {
8451  /* ----------
8452  * Both are negative
8453  * result = -(ABS(var1) + ABS(var2))
8454  * ----------
8455  */
8456  add_abs(var1, var2, result);
8457  result->sign = NUMERIC_NEG;
8458  }
8459  }
8460 }
static void sub_abs(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
Definition: numeric.c:11422
static void add_abs(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
Definition: numeric.c:11337
static void zero_var(NumericVar *var)
Definition: numeric.c:6907
static int cmp_abs(const NumericVar *var1, const NumericVar *var2)
Definition: numeric.c:11259

References add_abs(), cmp_abs(), NumericVar::dscale, Max, NUMERIC_NEG, NUMERIC_POS, NumericVar::sign, sub_abs(), and zero_var().

Referenced by accum_sum_final(), ceil_var(), compute_bucket(), div_mod_var(), exp_var(), generate_series_step_numeric(), in_range_numeric_numeric(), ln_var(), numeric_add_opt_error(), numeric_inc(), set_var_from_non_decimal_integer_str(), sqrt_var(), and width_bucket_numeric().

◆ alloc_var()

static void alloc_var ( NumericVar var,
int  ndigits 
)
static

Definition at line 6875 of file numeric.c.

6876 {
6877  digitbuf_free(var->buf);
6878  var->buf = digitbuf_alloc(ndigits + 1);
6879  var->buf[0] = 0; /* spare digit for rounding */
6880  var->digits = var->buf + 1;
6881  var->ndigits = ndigits;
6882 }

References NumericVar::buf, digitbuf_alloc, digitbuf_free, NumericVar::digits, and NumericVar::ndigits.

Referenced by div_var(), div_var_fast(), int64_to_numericvar(), mul_var(), numeric_recv(), numericvar_deserialize(), set_var_from_num(), set_var_from_str(), and sqrt_var().

◆ apply_typmod()

static bool apply_typmod ( NumericVar var,
int32  typmod,
Node escontext 
)
static

Definition at line 7829 of file numeric.c.

7830 {
7831  int precision;
7832  int scale;
7833  int maxdigits;
7834  int ddigits;
7835  int i;
7836 
7837  /* Do nothing if we have an invalid typmod */
7838  if (!is_valid_numeric_typmod(typmod))
7839  return true;
7840 
7841  precision = numeric_typmod_precision(typmod);
7842  scale = numeric_typmod_scale(typmod);
7843  maxdigits = precision - scale;
7844 
7845  /* Round to target scale (and set var->dscale) */
7846  round_var(var, scale);
7847 
7848  /* but don't allow var->dscale to be negative */
7849  if (var->dscale < 0)
7850  var->dscale = 0;
7851 
7852  /*
7853  * Check for overflow - note we can't do this before rounding, because
7854  * rounding could raise the weight. Also note that the var's weight could
7855  * be inflated by leading zeroes, which will be stripped before storage
7856  * but perhaps might not have been yet. In any case, we must recognize a
7857  * true zero, whose weight doesn't mean anything.
7858  */
7859  ddigits = (var->weight + 1) * DEC_DIGITS;
7860  if (ddigits > maxdigits)
7861  {
7862  /* Determine true weight; and check for all-zero result */
7863  for (i = 0; i < var->ndigits; i++)
7864  {
7865  NumericDigit dig = var->digits[i];
7866 
7867  if (dig)
7868  {
7869  /* Adjust for any high-order decimal zero digits */
7870 #if DEC_DIGITS == 4
7871  if (dig < 10)
7872  ddigits -= 3;
7873  else if (dig < 100)
7874  ddigits -= 2;
7875  else if (dig < 1000)
7876  ddigits -= 1;
7877 #elif DEC_DIGITS == 2
7878  if (dig < 10)
7879  ddigits -= 1;
7880 #elif DEC_DIGITS == 1
7881  /* no adjustment */
7882 #else
7883 #error unsupported NBASE
7884 #endif
7885  if (ddigits > maxdigits)
7886  ereturn(escontext, false,
7887  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7888  errmsg("numeric field overflow"),
7889  errdetail("A field with precision %d, scale %d must round to an absolute value less than %s%d.",
7890  precision, scale,
7891  /* Display 10^0 as 1 */
7892  maxdigits ? "10^" : "",
7893  maxdigits ? maxdigits : 1
7894  )));
7895  break;
7896  }
7897  ddigits -= DEC_DIGITS;
7898  }
7899  }
7900 
7901  return true;
7902 }
static bool is_valid_numeric_typmod(int32 typmod)
Definition: numeric.c:906
static int numeric_typmod_scale(int32 typmod)
Definition: numeric.c:932
static int numeric_typmod_precision(int32 typmod)
Definition: numeric.c:917
static void round_var(NumericVar *var, int rscale)
Definition: numeric.c:11504
#define DEC_DIGITS
Definition: numeric.c:98
int errdetail(const char *fmt,...)
Definition: elog.c:1202
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ereturn(context, dummy_value,...)
Definition: elog.h:276
int maxdigits
Definition: informix.c:665

References DEC_DIGITS, NumericVar::digits, NumericVar::dscale, ereturn, errcode(), errdetail(), errmsg(), i, is_valid_numeric_typmod(), maxdigits, NumericVar::ndigits, numeric_typmod_precision(), numeric_typmod_scale(), round_var(), scale, and NumericVar::weight.

Referenced by numeric(), numeric_in(), and numeric_recv().

◆ apply_typmod_special()

static bool apply_typmod_special ( Numeric  num,
int32  typmod,
Node escontext 
)
static

Definition at line 7914 of file numeric.c.

7915 {
7916  int precision;
7917  int scale;
7918 
7919  Assert(NUMERIC_IS_SPECIAL(num)); /* caller error if not */
7920 
7921  /*
7922  * NaN is allowed regardless of the typmod; that's rather dubious perhaps,
7923  * but it's a longstanding behavior. Inf is rejected if we have any
7924  * typmod restriction, since an infinity shouldn't be claimed to fit in
7925  * any finite number of digits.
7926  */
7927  if (NUMERIC_IS_NAN(num))
7928  return true;
7929 
7930  /* Do nothing if we have a default typmod (-1) */
7931  if (!is_valid_numeric_typmod(typmod))
7932  return true;
7933 
7934  precision = numeric_typmod_precision(typmod);
7935  scale = numeric_typmod_scale(typmod);
7936 
7937  ereturn(escontext, false,
7938  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
7939  errmsg("numeric field overflow"),
7940  errdetail("A field with precision %d, scale %d cannot hold an infinite value.",
7941  precision, scale)));
7942 }
#define NUMERIC_IS_NAN(n)
Definition: numeric.c:204

References Assert(), ereturn, errcode(), errdetail(), errmsg(), is_valid_numeric_typmod(), NUMERIC_IS_NAN, NUMERIC_IS_SPECIAL, numeric_typmod_precision(), numeric_typmod_scale(), and scale.

Referenced by numeric(), numeric_in(), and numeric_recv().

◆ ceil_var()

static void ceil_var ( const NumericVar var,
NumericVar result 
)
static

Definition at line 9867 of file numeric.c.

9868 {
9869  NumericVar tmp;
9870 
9871  init_var(&tmp);
9872  set_var_from_var(var, &tmp);
9873 
9874  trunc_var(&tmp, 0);
9875 
9876  if (var->sign == NUMERIC_POS && cmp_var(var, &tmp) != 0)
9877  add_var(&tmp, &const_one, &tmp);
9878 
9879  set_var_from_var(&tmp, result);
9880  free_var(&tmp);
9881 }
static void trunc_var(NumericVar *var, int rscale)
Definition: numeric.c:11610
static int cmp_var(const NumericVar *var1, const NumericVar *var2)
Definition: numeric.c:8295
static const NumericVar const_one
Definition: numeric.c:420

References add_var(), cmp_var(), const_one, free_var(), init_var, NUMERIC_POS, set_var_from_var(), NumericVar::sign, and trunc_var().

Referenced by numeric_ceil().

◆ cmp_abs()

static int cmp_abs ( const NumericVar var1,
const NumericVar var2 
)
static

Definition at line 11259 of file numeric.c.

11260 {
11261  return cmp_abs_common(var1->digits, var1->ndigits, var1->weight,
11262  var2->digits, var2->ndigits, var2->weight);
11263 }
static int cmp_abs_common(const NumericDigit *var1digits, int var1ndigits, int var1weight, const NumericDigit *var2digits, int var2ndigits, int var2weight)
Definition: numeric.c:11273

References cmp_abs_common(), NumericVar::digits, NumericVar::ndigits, and NumericVar::weight.

Referenced by add_var(), div_mod_var(), gcd_var(), and sub_var().

◆ cmp_abs_common()

static int cmp_abs_common ( const NumericDigit var1digits,
int  var1ndigits,
int  var1weight,
const NumericDigit var2digits,
int  var2ndigits,
int  var2weight 
)
static

Definition at line 11273 of file numeric.c.

11275 {
11276  int i1 = 0;
11277  int i2 = 0;
11278 
11279  /* Check any digits before the first common digit */
11280 
11281  while (var1weight > var2weight && i1 < var1ndigits)
11282  {
11283  if (var1digits[i1++] != 0)
11284  return 1;
11285  var1weight--;
11286  }
11287  while (var2weight > var1weight && i2 < var2ndigits)
11288  {
11289  if (var2digits[i2++] != 0)
11290  return -1;
11291  var2weight--;
11292  }
11293 
11294  /* At this point, either w1 == w2 or we've run out of digits */
11295 
11296  if (var1weight == var2weight)
11297  {
11298  while (i1 < var1ndigits && i2 < var2ndigits)
11299  {
11300  int stat = var1digits[i1++] - var2digits[i2++];
11301 
11302  if (stat)
11303  {
11304  if (stat > 0)
11305  return 1;
11306  return -1;
11307  }
11308  }
11309  }
11310 
11311  /*
11312  * At this point, we've run out of digits on one side or the other; so any
11313  * remaining nonzero digits imply that side is larger
11314  */
11315  while (i1 < var1ndigits)
11316  {
11317  if (var1digits[i1++] != 0)
11318  return 1;
11319  }
11320  while (i2 < var2ndigits)
11321  {
11322  if (var2digits[i2++] != 0)
11323  return -1;
11324  }
11325 
11326  return 0;
11327 }

Referenced by cmp_abs(), and cmp_var_common().

◆ cmp_numerics()

static int cmp_numerics ( Numeric  num1,
Numeric  num2 
)
static

Definition at line 2504 of file numeric.c.

2505 {
2506  int result;
2507 
2508  /*
2509  * We consider all NANs to be equal and larger than any non-NAN (including
2510  * Infinity). This is somewhat arbitrary; the important thing is to have
2511  * a consistent sort order.
2512  */
2513  if (NUMERIC_IS_SPECIAL(num1))
2514  {
2515  if (NUMERIC_IS_NAN(num1))
2516  {
2517  if (NUMERIC_IS_NAN(num2))
2518  result = 0; /* NAN = NAN */
2519  else
2520  result = 1; /* NAN > non-NAN */
2521  }
2522  else if (NUMERIC_IS_PINF(num1))
2523  {
2524  if (NUMERIC_IS_NAN(num2))
2525  result = -1; /* PINF < NAN */
2526  else if (NUMERIC_IS_PINF(num2))
2527  result = 0; /* PINF = PINF */
2528  else
2529  result = 1; /* PINF > anything else */
2530  }
2531  else /* num1 must be NINF */
2532  {
2533  if (NUMERIC_IS_NINF(num2))
2534  result = 0; /* NINF = NINF */
2535  else
2536  result = -1; /* NINF < anything else */
2537  }
2538  }
2539  else if (NUMERIC_IS_SPECIAL(num2))
2540  {
2541  if (NUMERIC_IS_NINF(num2))
2542  result = 1; /* normal > NINF */
2543  else
2544  result = -1; /* normal < NAN or PINF */
2545  }
2546  else
2547  {
2548  result = cmp_var_common(NUMERIC_DIGITS(num1), NUMERIC_NDIGITS(num1),
2549  NUMERIC_WEIGHT(num1), NUMERIC_SIGN(num1),
2550  NUMERIC_DIGITS(num2), NUMERIC_NDIGITS(num2),
2551  NUMERIC_WEIGHT(num2), NUMERIC_SIGN(num2));
2552  }
2553 
2554  return result;
2555 }
#define NUMERIC_SIGN(n)
Definition: numeric.c:237
#define NUMERIC_IS_PINF(n)
Definition: numeric.c:205
#define NUMERIC_IS_NINF(n)
Definition: numeric.c:206
#define NUMERIC_WEIGHT(n)
Definition: numeric.c:247
#define NUMERIC_DIGITS(num)
Definition: numeric.c:487
#define NUMERIC_NDIGITS(num)
Definition: numeric.c:489
static int cmp_var_common(const NumericDigit *var1digits, int var1ndigits, int var1weight, int var1sign, const NumericDigit *var2digits, int var2ndigits, int var2weight, int var2sign)
Definition: numeric.c:8310

References cmp_var_common(), NUMERIC_DIGITS, NUMERIC_IS_NAN, NUMERIC_IS_NINF, NUMERIC_IS_PINF, NUMERIC_IS_SPECIAL, NUMERIC_NDIGITS, NUMERIC_SIGN, and NUMERIC_WEIGHT.

Referenced by numeric_cmp(), numeric_eq(), numeric_fast_cmp(), numeric_ge(), numeric_gt(), numeric_larger(), numeric_le(), numeric_lt(), numeric_ne(), numeric_smaller(), and width_bucket_numeric().

◆ cmp_var()

static int cmp_var ( const NumericVar var1,
const NumericVar var2 
)
static

◆ cmp_var_common()

static int cmp_var_common ( const NumericDigit var1digits,
int  var1ndigits,
int  var1weight,
int  var1sign,
const NumericDigit var2digits,
int  var2ndigits,
int  var2weight,
int  var2sign 
)
static

Definition at line 8310 of file numeric.c.

8314 {
8315  if (var1ndigits == 0)
8316  {
8317  if (var2ndigits == 0)
8318  return 0;
8319  if (var2sign == NUMERIC_NEG)
8320  return 1;
8321  return -1;
8322  }
8323  if (var2ndigits == 0)
8324  {
8325  if (var1sign == NUMERIC_POS)
8326  return 1;
8327  return -1;
8328  }
8329 
8330  if (var1sign == NUMERIC_POS)
8331  {
8332  if (var2sign == NUMERIC_NEG)
8333  return 1;
8334  return cmp_abs_common(var1digits, var1ndigits, var1weight,
8335  var2digits, var2ndigits, var2weight);
8336  }
8337 
8338  if (var2sign == NUMERIC_POS)
8339  return -1;
8340 
8341  return cmp_abs_common(var2digits, var2ndigits, var2weight,
8342  var1digits, var1ndigits, var1weight);
8343 }

References cmp_abs_common(), NUMERIC_NEG, and NUMERIC_POS.

Referenced by cmp_numerics(), and cmp_var().

◆ compute_bucket()

static void compute_bucket ( Numeric  operand,
Numeric  bound1,
Numeric  bound2,
const NumericVar count_var,
bool  reversed_bounds,
NumericVar result_var 
)
static

Definition at line 1916 of file numeric.c.

1919 {
1920  NumericVar bound1_var;
1921  NumericVar bound2_var;
1922  NumericVar operand_var;
1923 
1924  init_var_from_num(bound1, &bound1_var);
1925  init_var_from_num(bound2, &bound2_var);
1926  init_var_from_num(operand, &operand_var);
1927 
1928  if (!reversed_bounds)
1929  {
1930  sub_var(&operand_var, &bound1_var, &operand_var);
1931  sub_var(&bound2_var, &bound1_var, &bound2_var);
1932  }
1933  else
1934  {
1935  sub_var(&bound1_var, &operand_var, &operand_var);
1936  sub_var(&bound1_var, &bound2_var, &bound2_var);
1937  }
1938 
1939  mul_var(&operand_var, count_var, &operand_var,
1940  operand_var.dscale + count_var->dscale);
1941  div_var(&operand_var, &bound2_var, result_var,
1942  select_div_scale(&operand_var, &bound2_var), true);
1943 
1944  /*
1945  * Roundoff in the division could give us a quotient exactly equal to
1946  * "count", which is too large. Clamp so that we do not emit a result
1947  * larger than "count".
1948  */
1949  if (cmp_var(result_var, count_var) >= 0)
1950  set_var_from_var(count_var, result_var);
1951  else
1952  {
1953  add_var(result_var, &const_one, result_var);
1954  floor_var(result_var, result_var);
1955  }
1956 
1957  free_var(&bound1_var);
1958  free_var(&bound2_var);
1959  free_var(&operand_var);
1960 }
static void sub_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
Definition: numeric.c:8470
static void floor_var(const NumericVar *var, NumericVar *result)
Definition: numeric.c:9891
static void init_var_from_num(Numeric num, NumericVar *dest)
Definition: numeric.c:7373
static void mul_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result, int rscale)
Definition: numeric.c:8591
static int select_div_scale(const NumericVar *var1, const NumericVar *var2)
Definition: numeric.c:9699
static void div_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result, int rscale, bool round)
Definition: numeric.c:8799

References add_var(), cmp_var(), const_one, div_var(), NumericVar::dscale, floor_var(), free_var(), init_var_from_num(), mul_var(), select_div_scale(), set_var_from_var(), and sub_var().

Referenced by width_bucket_numeric().

◆ div_mod_var()

static void div_mod_var ( const NumericVar var1,
const NumericVar var2,
NumericVar quot,
NumericVar rem 
)
static

Definition at line 9797 of file numeric.c.

9799 {
9800  NumericVar q;
9801  NumericVar r;
9802 
9803  init_var(&q);
9804  init_var(&r);
9805 
9806  /*
9807  * Use div_var_fast() to get an initial estimate for the integer quotient.
9808  * This might be inaccurate (per the warning in div_var_fast's comments),
9809  * but we can correct it below.
9810  */
9811  div_var_fast(var1, var2, &q, 0, false);
9812 
9813  /* Compute initial estimate of remainder using the quotient estimate. */
9814  mul_var(var2, &q, &r, var2->dscale);
9815  sub_var(var1, &r, &r);
9816 
9817  /*
9818  * Adjust the results if necessary --- the remainder should have the same
9819  * sign as var1, and its absolute value should be less than the absolute
9820  * value of var2.
9821  */
9822  while (r.ndigits != 0 && r.sign != var1->sign)
9823  {
9824  /* The absolute value of the quotient is too large */
9825  if (var1->sign == var2->sign)
9826  {
9827  sub_var(&q, &const_one, &q);
9828  add_var(&r, var2, &r);
9829  }
9830  else
9831  {
9832  add_var(&q, &const_one, &q);
9833  sub_var(&r, var2, &r);
9834  }
9835  }
9836 
9837  while (cmp_abs(&r, var2) >= 0)
9838  {
9839  /* The absolute value of the quotient is too small */
9840  if (var1->sign == var2->sign)
9841  {
9842  add_var(&q, &const_one, &q);
9843  sub_var(&r, var2, &r);
9844  }
9845  else
9846  {
9847  sub_var(&q, &const_one, &q);
9848  add_var(&r, var2, &r);
9849  }
9850  }
9851 
9852  set_var_from_var(&q, quot);
9853  set_var_from_var(&r, rem);
9854 
9855  free_var(&q);
9856  free_var(&r);
9857 }
static void div_var_fast(const NumericVar *var1, const NumericVar *var2, NumericVar *result, int rscale, bool round)
Definition: numeric.c:9107

References add_var(), cmp_abs(), const_one, div_var_fast(), NumericVar::dscale, free_var(), init_var, mul_var(), NumericVar::ndigits, set_var_from_var(), NumericVar::sign, and sub_var().

Referenced by sqrt_var().

◆ div_var()

static void div_var ( const NumericVar var1,
const NumericVar var2,
NumericVar result,
int  rscale,
bool  round 
)
static

Definition at line 8799 of file numeric.c.

8801 {
8802  int div_ndigits;
8803  int res_ndigits;
8804  int res_sign;
8805  int res_weight;
8806  int carry;
8807  int borrow;
8808  int divisor1;
8809  int divisor2;
8810  NumericDigit *dividend;
8811  NumericDigit *divisor;
8812  NumericDigit *res_digits;
8813  int i;
8814  int j;
8815 
8816  /* copy these values into local vars for speed in inner loop */
8817  int var1ndigits = var1->ndigits;
8818  int var2ndigits = var2->ndigits;
8819 
8820  /*
8821  * First of all division by zero check; we must not be handed an
8822  * unnormalized divisor.
8823  */
8824  if (var2ndigits == 0 || var2->digits[0] == 0)
8825  ereport(ERROR,
8826  (errcode(ERRCODE_DIVISION_BY_ZERO),
8827  errmsg("division by zero")));
8828 
8829  /*
8830  * If the divisor has just one or two digits, delegate to div_var_int(),
8831  * which uses fast short division.
8832  *
8833  * Similarly, on platforms with 128-bit integer support, delegate to
8834  * div_var_int64() for divisors with three or four digits.
8835  */
8836  if (var2ndigits <= 2)
8837  {
8838  int idivisor;
8839  int idivisor_weight;
8840 
8841  idivisor = var2->digits[0];
8842  idivisor_weight = var2->weight;
8843  if (var2ndigits == 2)
8844  {
8845  idivisor = idivisor * NBASE + var2->digits[1];
8846  idivisor_weight--;
8847  }
8848  if (var2->sign == NUMERIC_NEG)
8849  idivisor = -idivisor;
8850 
8851  div_var_int(var1, idivisor, idivisor_weight, result, rscale, round);
8852  return;
8853  }
8854 #ifdef HAVE_INT128
8855  if (var2ndigits <= 4)
8856  {
8857  int64 idivisor;
8858  int idivisor_weight;
8859 
8860  idivisor = var2->digits[0];
8861  idivisor_weight = var2->weight;
8862  for (i = 1; i < var2ndigits; i++)
8863  {
8864  idivisor = idivisor * NBASE + var2->digits[i];
8865  idivisor_weight--;
8866  }
8867  if (var2->sign == NUMERIC_NEG)
8868  idivisor = -idivisor;
8869 
8870  div_var_int64(var1, idivisor, idivisor_weight, result, rscale, round);
8871  return;
8872  }
8873 #endif
8874 
8875  /*
8876  * Otherwise, perform full long division.
8877  */
8878 
8879  /* Result zero check */
8880  if (var1ndigits == 0)
8881  {
8882  zero_var(result);
8883  result->dscale = rscale;
8884  return;
8885  }
8886 
8887  /*
8888  * Determine the result sign, weight and number of digits to calculate.
8889  * The weight figured here is correct if the emitted quotient has no
8890  * leading zero digits; otherwise strip_var() will fix things up.
8891  */
8892  if (var1->sign == var2->sign)
8893  res_sign = NUMERIC_POS;
8894  else
8895  res_sign = NUMERIC_NEG;
8896  res_weight = var1->weight - var2->weight;
8897  /* The number of accurate result digits we need to produce: */
8898  res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
8899  /* ... but always at least 1 */
8900  res_ndigits = Max(res_ndigits, 1);
8901  /* If rounding needed, figure one more digit to ensure correct result */
8902  if (round)
8903  res_ndigits++;
8904 
8905  /*
8906  * The working dividend normally requires res_ndigits + var2ndigits
8907  * digits, but make it at least var1ndigits so we can load all of var1
8908  * into it. (There will be an additional digit dividend[0] in the
8909  * dividend space, but for consistency with Knuth's notation we don't
8910  * count that in div_ndigits.)
8911  */
8912  div_ndigits = res_ndigits + var2ndigits;
8913  div_ndigits = Max(div_ndigits, var1ndigits);
8914 
8915  /*
8916  * We need a workspace with room for the working dividend (div_ndigits+1
8917  * digits) plus room for the possibly-normalized divisor (var2ndigits
8918  * digits). It is convenient also to have a zero at divisor[0] with the
8919  * actual divisor data in divisor[1 .. var2ndigits]. Transferring the
8920  * digits into the workspace also allows us to realloc the result (which
8921  * might be the same as either input var) before we begin the main loop.
8922  * Note that we use palloc0 to ensure that divisor[0], dividend[0], and
8923  * any additional dividend positions beyond var1ndigits, start out 0.
8924  */
8925  dividend = (NumericDigit *)
8926  palloc0((div_ndigits + var2ndigits + 2) * sizeof(NumericDigit));
8927  divisor = dividend + (div_ndigits + 1);
8928  memcpy(dividend + 1, var1->digits, var1ndigits * sizeof(NumericDigit));
8929  memcpy(divisor + 1, var2->digits, var2ndigits * sizeof(NumericDigit));
8930 
8931  /*
8932  * Now we can realloc the result to hold the generated quotient digits.
8933  */
8934  alloc_var(result, res_ndigits);
8935  res_digits = result->digits;
8936 
8937  /*
8938  * The full multiple-place algorithm is taken from Knuth volume 2,
8939  * Algorithm 4.3.1D.
8940  *
8941  * We need the first divisor digit to be >= NBASE/2. If it isn't, make it
8942  * so by scaling up both the divisor and dividend by the factor "d". (The
8943  * reason for allocating dividend[0] above is to leave room for possible
8944  * carry here.)
8945  */
8946  if (divisor[1] < HALF_NBASE)
8947  {
8948  int d = NBASE / (divisor[1] + 1);
8949 
8950  carry = 0;
8951  for (i = var2ndigits; i > 0; i--)
8952  {
8953  carry += divisor[i] * d;
8954  divisor[i] = carry % NBASE;
8955  carry = carry / NBASE;
8956  }
8957  Assert(carry == 0);
8958  carry = 0;
8959  /* at this point only var1ndigits of dividend can be nonzero */
8960  for (i = var1ndigits; i >= 0; i--)
8961  {
8962  carry += dividend[i] * d;
8963  dividend[i] = carry % NBASE;
8964  carry = carry / NBASE;
8965  }
8966  Assert(carry == 0);
8967  Assert(divisor[1] >= HALF_NBASE);
8968  }
8969  /* First 2 divisor digits are used repeatedly in main loop */
8970  divisor1 = divisor[1];
8971  divisor2 = divisor[2];
8972 
8973  /*
8974  * Begin the main loop. Each iteration of this loop produces the j'th
8975  * quotient digit by dividing dividend[j .. j + var2ndigits] by the
8976  * divisor; this is essentially the same as the common manual procedure
8977  * for long division.
8978  */
8979  for (j = 0; j < res_ndigits; j++)
8980  {
8981  /* Estimate quotient digit from the first two dividend digits */
8982  int next2digits = dividend[j] * NBASE + dividend[j + 1];
8983  int qhat;
8984 
8985  /*
8986  * If next2digits are 0, then quotient digit must be 0 and there's no
8987  * need to adjust the working dividend. It's worth testing here to
8988  * fall out ASAP when processing trailing zeroes in a dividend.
8989  */
8990  if (next2digits == 0)
8991  {
8992  res_digits[j] = 0;
8993  continue;
8994  }
8995 
8996  if (dividend[j] == divisor1)
8997  qhat = NBASE - 1;
8998  else
8999  qhat = next2digits / divisor1;
9000 
9001  /*
9002  * Adjust quotient digit if it's too large. Knuth proves that after
9003  * this step, the quotient digit will be either correct or just one
9004  * too large. (Note: it's OK to use dividend[j+2] here because we
9005  * know the divisor length is at least 2.)
9006  */
9007  while (divisor2 * qhat >
9008  (next2digits - qhat * divisor1) * NBASE + dividend[j + 2])
9009  qhat--;
9010 
9011  /* As above, need do nothing more when quotient digit is 0 */
9012  if (qhat > 0)
9013  {
9014  NumericDigit *dividend_j = &dividend[j];
9015 
9016  /*
9017  * Multiply the divisor by qhat, and subtract that from the
9018  * working dividend. The multiplication and subtraction are
9019  * folded together here, noting that qhat <= NBASE (since it might
9020  * be one too large), and so the intermediate result "tmp_result"
9021  * is in the range [-NBASE^2, NBASE - 1], and "borrow" is in the
9022  * range [0, NBASE].
9023  */
9024  borrow = 0;
9025  for (i = var2ndigits; i >= 0; i--)
9026  {
9027  int tmp_result;
9028 
9029  tmp_result = dividend_j[i] - borrow - divisor[i] * qhat;
9030  borrow = (NBASE - 1 - tmp_result) / NBASE;
9031  dividend_j[i] = tmp_result + borrow * NBASE;
9032  }
9033 
9034  /*
9035  * If we got a borrow out of the top dividend digit, then indeed
9036  * qhat was one too large. Fix it, and add back the divisor to
9037  * correct the working dividend. (Knuth proves that this will
9038  * occur only about 3/NBASE of the time; hence, it's a good idea
9039  * to test this code with small NBASE to be sure this section gets
9040  * exercised.)
9041  */
9042  if (borrow)
9043  {
9044  qhat--;
9045  carry = 0;
9046  for (i = var2ndigits; i >= 0; i--)
9047  {
9048  carry += dividend_j[i] + divisor[i];
9049  if (carry >= NBASE)
9050  {
9051  dividend_j[i] = carry - NBASE;
9052  carry = 1;
9053  }
9054  else
9055  {
9056  dividend_j[i] = carry;
9057  carry = 0;
9058  }
9059  }
9060  /* A carry should occur here to cancel the borrow above */
9061  Assert(carry == 1);
9062  }
9063  }
9064 
9065  /* And we're done with this quotient digit */
9066  res_digits[j] = qhat;
9067  }
9068 
9069  pfree(dividend);
9070 
9071  /*
9072  * Finally, round or truncate the result to the requested precision.
9073  */
9074  result->weight = res_weight;
9075  result->sign = res_sign;
9076 
9077  /* Round or truncate to target rscale (and set result->dscale) */
9078  if (round)
9079  round_var(result, rscale);
9080  else
9081  trunc_var(result, rscale);
9082 
9083  /* Strip leading and trailing zeroes */
9084  strip_var(result);
9085 }
static void div_var_int(const NumericVar *var, int ival, int ival_weight, NumericVar *result, int rscale, bool round)
Definition: numeric.c:9471
static void alloc_var(NumericVar *var, int ndigits)
Definition: numeric.c:6875
#define HALF_NBASE
Definition: numeric.c:97
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
int j
Definition: isn.c:74

References alloc_var(), Assert(), DEC_DIGITS, NumericVar::digits, div_var_int(), NumericVar::dscale, ereport, errcode(), errmsg(), ERROR, HALF_NBASE, i, j, Max, NBASE, NumericVar::ndigits, NUMERIC_NEG, NUMERIC_POS, palloc0(), pfree(), round_var(), NumericVar::sign, strip_var(), trunc_var(), NumericVar::weight, and zero_var().

Referenced by compute_bucket(), get_str_from_var_sci(), mod_var(), numeric_div_opt_error(), numeric_div_trunc(), numeric_lcm(), numeric_stddev_internal(), and power_var_int().

◆ div_var_fast()

static void div_var_fast ( const NumericVar var1,
const NumericVar var2,
NumericVar result,
int  rscale,
bool  round 
)
static

Definition at line 9107 of file numeric.c.

9109 {
9110  int div_ndigits;
9111  int load_ndigits;
9112  int res_sign;
9113  int res_weight;
9114  int *div;
9115  int qdigit;
9116  int carry;
9117  int maxdiv;
9118  int newdig;
9119  NumericDigit *res_digits;
9120  double fdividend,
9121  fdivisor,
9122  fdivisorinverse,
9123  fquotient;
9124  int qi;
9125  int i;
9126 
9127  /* copy these values into local vars for speed in inner loop */
9128  int var1ndigits = var1->ndigits;
9129  int var2ndigits = var2->ndigits;
9130  NumericDigit *var1digits = var1->digits;
9131  NumericDigit *var2digits = var2->digits;
9132 
9133  /*
9134  * First of all division by zero check; we must not be handed an
9135  * unnormalized divisor.
9136  */
9137  if (var2ndigits == 0 || var2digits[0] == 0)
9138  ereport(ERROR,
9139  (errcode(ERRCODE_DIVISION_BY_ZERO),
9140  errmsg("division by zero")));
9141 
9142  /*
9143  * If the divisor has just one or two digits, delegate to div_var_int(),
9144  * which uses fast short division.
9145  *
9146  * Similarly, on platforms with 128-bit integer support, delegate to
9147  * div_var_int64() for divisors with three or four digits.
9148  */
9149  if (var2ndigits <= 2)
9150  {
9151  int idivisor;
9152  int idivisor_weight;
9153 
9154  idivisor = var2->digits[0];
9155  idivisor_weight = var2->weight;
9156  if (var2ndigits == 2)
9157  {
9158  idivisor = idivisor * NBASE + var2->digits[1];
9159  idivisor_weight--;
9160  }
9161  if (var2->sign == NUMERIC_NEG)
9162  idivisor = -idivisor;
9163 
9164  div_var_int(var1, idivisor, idivisor_weight, result, rscale, round);
9165  return;
9166  }
9167 #ifdef HAVE_INT128
9168  if (var2ndigits <= 4)
9169  {
9170  int64 idivisor;
9171  int idivisor_weight;
9172 
9173  idivisor = var2->digits[0];
9174  idivisor_weight = var2->weight;
9175  for (i = 1; i < var2ndigits; i++)
9176  {
9177  idivisor = idivisor * NBASE + var2->digits[i];
9178  idivisor_weight--;
9179  }
9180  if (var2->sign == NUMERIC_NEG)
9181  idivisor = -idivisor;
9182 
9183  div_var_int64(var1, idivisor, idivisor_weight, result, rscale, round);
9184  return;
9185  }
9186 #endif
9187 
9188  /*
9189  * Otherwise, perform full long division.
9190  */
9191 
9192  /* Result zero check */
9193  if (var1ndigits == 0)
9194  {
9195  zero_var(result);
9196  result->dscale = rscale;
9197  return;
9198  }
9199 
9200  /*
9201  * Determine the result sign, weight and number of digits to calculate
9202  */
9203  if (var1->sign == var2->sign)
9204  res_sign = NUMERIC_POS;
9205  else
9206  res_sign = NUMERIC_NEG;
9207  res_weight = var1->weight - var2->weight + 1;
9208  /* The number of accurate result digits we need to produce: */
9209  div_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
9210  /* Add guard digits for roundoff error */
9211  div_ndigits += DIV_GUARD_DIGITS;
9212  if (div_ndigits < DIV_GUARD_DIGITS)
9213  div_ndigits = DIV_GUARD_DIGITS;
9214 
9215  /*
9216  * We do the arithmetic in an array "div[]" of signed int's. Since
9217  * INT_MAX is noticeably larger than NBASE*NBASE, this gives us headroom
9218  * to avoid normalizing carries immediately.
9219  *
9220  * We start with div[] containing one zero digit followed by the
9221  * dividend's digits (plus appended zeroes to reach the desired precision
9222  * including guard digits). Each step of the main loop computes an
9223  * (approximate) quotient digit and stores it into div[], removing one
9224  * position of dividend space. A final pass of carry propagation takes
9225  * care of any mistaken quotient digits.
9226  *
9227  * Note that div[] doesn't necessarily contain all of the digits from the
9228  * dividend --- the desired precision plus guard digits might be less than
9229  * the dividend's precision. This happens, for example, in the square
9230  * root algorithm, where we typically divide a 2N-digit number by an
9231  * N-digit number, and only require a result with N digits of precision.
9232  */
9233  div = (int *) palloc0((div_ndigits + 1) * sizeof(int));
9234  load_ndigits = Min(div_ndigits, var1ndigits);
9235  for (i = 0; i < load_ndigits; i++)
9236  div[i + 1] = var1digits[i];
9237 
9238  /*
9239  * We estimate each quotient digit using floating-point arithmetic, taking
9240  * the first four digits of the (current) dividend and divisor. This must
9241  * be float to avoid overflow. The quotient digits will generally be off
9242  * by no more than one from the exact answer.
9243  */
9244  fdivisor = (double) var2digits[0];
9245  for (i = 1; i < 4; i++)
9246  {
9247  fdivisor *= NBASE;
9248  if (i < var2ndigits)
9249  fdivisor += (double) var2digits[i];
9250  }
9251  fdivisorinverse = 1.0 / fdivisor;
9252 
9253  /*
9254  * maxdiv tracks the maximum possible absolute value of any div[] entry;
9255  * when this threatens to exceed INT_MAX, we take the time to propagate
9256  * carries. Furthermore, we need to ensure that overflow doesn't occur
9257  * during the carry propagation passes either. The carry values may have
9258  * an absolute value as high as INT_MAX/NBASE + 1, so really we must
9259  * normalize when digits threaten to exceed INT_MAX - INT_MAX/NBASE - 1.
9260  *
9261  * To avoid overflow in maxdiv itself, it represents the max absolute
9262  * value divided by NBASE-1, ie, at the top of the loop it is known that
9263  * no div[] entry has an absolute value exceeding maxdiv * (NBASE-1).
9264  *
9265  * Actually, though, that holds good only for div[] entries after div[qi];
9266  * the adjustment done at the bottom of the loop may cause div[qi + 1] to
9267  * exceed the maxdiv limit, so that div[qi] in the next iteration is
9268  * beyond the limit. This does not cause problems, as explained below.
9269  */
9270  maxdiv = 1;
9271 
9272  /*
9273  * Outer loop computes next quotient digit, which will go into div[qi]
9274  */
9275  for (qi = 0; qi < div_ndigits; qi++)
9276  {
9277  /* Approximate the current dividend value */
9278  fdividend = (double) div[qi];
9279  for (i = 1; i < 4; i++)
9280  {
9281  fdividend *= NBASE;
9282  if (qi + i <= div_ndigits)
9283  fdividend += (double) div[qi + i];
9284  }
9285  /* Compute the (approximate) quotient digit */
9286  fquotient = fdividend * fdivisorinverse;
9287  qdigit = (fquotient >= 0.0) ? ((int) fquotient) :
9288  (((int) fquotient) - 1); /* truncate towards -infinity */
9289 
9290  if (qdigit != 0)
9291  {
9292  /* Do we need to normalize now? */
9293  maxdiv += abs(qdigit);
9294  if (maxdiv > (INT_MAX - INT_MAX / NBASE - 1) / (NBASE - 1))
9295  {
9296  /*
9297  * Yes, do it. Note that if var2ndigits is much smaller than
9298  * div_ndigits, we can save a significant amount of effort
9299  * here by noting that we only need to normalise those div[]
9300  * entries touched where prior iterations subtracted multiples
9301  * of the divisor.
9302  */
9303  carry = 0;
9304  for (i = Min(qi + var2ndigits - 2, div_ndigits); i > qi; i--)
9305  {
9306  newdig = div[i] + carry;
9307  if (newdig < 0)
9308  {
9309  carry = -((-newdig - 1) / NBASE) - 1;
9310  newdig -= carry * NBASE;
9311  }
9312  else if (newdig >= NBASE)
9313  {
9314  carry = newdig / NBASE;
9315  newdig -= carry * NBASE;
9316  }
9317  else
9318  carry = 0;
9319  div[i] = newdig;
9320  }
9321  newdig = div[qi] + carry;
9322  div[qi] = newdig;
9323 
9324  /*
9325  * All the div[] digits except possibly div[qi] are now in the
9326  * range 0..NBASE-1. We do not need to consider div[qi] in
9327  * the maxdiv value anymore, so we can reset maxdiv to 1.
9328  */
9329  maxdiv = 1;
9330 
9331  /*
9332  * Recompute the quotient digit since new info may have
9333  * propagated into the top four dividend digits
9334  */
9335  fdividend = (double) div[qi];
9336  for (i = 1; i < 4; i++)
9337  {
9338  fdividend *= NBASE;
9339  if (qi + i <= div_ndigits)
9340  fdividend += (double) div[qi + i];
9341  }
9342  /* Compute the (approximate) quotient digit */
9343  fquotient = fdividend * fdivisorinverse;
9344  qdigit = (fquotient >= 0.0) ? ((int) fquotient) :
9345  (((int) fquotient) - 1); /* truncate towards -infinity */
9346  maxdiv += abs(qdigit);
9347  }
9348 
9349  /*
9350  * Subtract off the appropriate multiple of the divisor.
9351  *
9352  * The digits beyond div[qi] cannot overflow, because we know they
9353  * will fall within the maxdiv limit. As for div[qi] itself, note
9354  * that qdigit is approximately trunc(div[qi] / vardigits[0]),
9355  * which would make the new value simply div[qi] mod vardigits[0].
9356  * The lower-order terms in qdigit can change this result by not
9357  * more than about twice INT_MAX/NBASE, so overflow is impossible.
9358  *
9359  * This inner loop is the performance bottleneck for division, so
9360  * code it in the same way as the inner loop of mul_var() so that
9361  * it can be auto-vectorized. We cast qdigit to NumericDigit
9362  * before multiplying to allow the compiler to generate more
9363  * efficient code (using 16-bit multiplication), which is safe
9364  * since we know that the quotient digit is off by at most one, so
9365  * there is no overflow risk.
9366  */
9367  if (qdigit != 0)
9368  {
9369  int istop = Min(var2ndigits, div_ndigits - qi + 1);
9370  int *div_qi = &div[qi];
9371 
9372  for (i = 0; i < istop; i++)
9373  div_qi[i] -= ((NumericDigit) qdigit) * var2digits[i];
9374  }
9375  }
9376 
9377  /*
9378  * The dividend digit we are about to replace might still be nonzero.
9379  * Fold it into the next digit position.
9380  *
9381  * There is no risk of overflow here, although proving that requires
9382  * some care. Much as with the argument for div[qi] not overflowing,
9383  * if we consider the first two terms in the numerator and denominator
9384  * of qdigit, we can see that the final value of div[qi + 1] will be
9385  * approximately a remainder mod (vardigits[0]*NBASE + vardigits[1]).
9386  * Accounting for the lower-order terms is a bit complicated but ends
9387  * up adding not much more than INT_MAX/NBASE to the possible range.
9388  * Thus, div[qi + 1] cannot overflow here, and in its role as div[qi]
9389  * in the next loop iteration, it can't be large enough to cause
9390  * overflow in the carry propagation step (if any), either.
9391  *
9392  * But having said that: div[qi] can be more than INT_MAX/NBASE, as
9393  * noted above, which means that the product div[qi] * NBASE *can*
9394  * overflow. When that happens, adding it to div[qi + 1] will always
9395  * cause a canceling overflow so that the end result is correct. We
9396  * could avoid the intermediate overflow by doing the multiplication
9397  * and addition in int64 arithmetic, but so far there appears no need.
9398  */
9399  div[qi + 1] += div[qi] * NBASE;
9400 
9401  div[qi] = qdigit;
9402  }
9403 
9404  /*
9405  * Approximate and store the last quotient digit (div[div_ndigits])
9406  */
9407  fdividend = (double) div[qi];
9408  for (i = 1; i < 4; i++)
9409  fdividend *= NBASE;
9410  fquotient = fdividend * fdivisorinverse;
9411  qdigit = (fquotient >= 0.0) ? ((int) fquotient) :
9412  (((int) fquotient) - 1); /* truncate towards -infinity */
9413  div[qi] = qdigit;
9414 
9415  /*
9416  * Because the quotient digits might be off by one, some of them might be
9417  * -1 or NBASE at this point. The represented value is correct in a
9418  * mathematical sense, but it doesn't look right. We do a final carry
9419  * propagation pass to normalize the digits, which we combine with storing
9420  * the result digits into the output. Note that this is still done at
9421  * full precision w/guard digits.
9422  */
9423  alloc_var(result, div_ndigits + 1);
9424  res_digits = result->digits;
9425  carry = 0;
9426  for (i = div_ndigits; i >= 0; i--)
9427  {
9428  newdig = div[i] + carry;
9429  if (newdig < 0)
9430  {
9431  carry = -((-newdig - 1) / NBASE) - 1;
9432  newdig -= carry * NBASE;
9433  }
9434  else if (newdig >= NBASE)
9435  {
9436  carry = newdig / NBASE;
9437  newdig -= carry * NBASE;
9438  }
9439  else
9440  carry = 0;
9441  res_digits[i] = newdig;
9442  }
9443  Assert(carry == 0);
9444 
9445  pfree(div);
9446 
9447  /*
9448  * Finally, round the result to the requested precision.
9449  */
9450  result->weight = res_weight;
9451  result->sign = res_sign;
9452 
9453  /* Round to target rscale (and set result->dscale) */
9454  if (round)
9455  round_var(result, rscale);
9456  else
9457  trunc_var(result, rscale);
9458 
9459  /* Strip leading and trailing zeroes */
9460  strip_var(result);
9461 }
#define DIV_GUARD_DIGITS
Definition: numeric.c:100
#define Min(x, y)
Definition: numeric.c:14

References alloc_var(), Assert(), DEC_DIGITS, NumericVar::digits, DIV_GUARD_DIGITS, div_var_int(), NumericVar::dscale, ereport, errcode(), errmsg(), ERROR, i, Min, NBASE, NumericVar::ndigits, NUMERIC_NEG, NUMERIC_POS, palloc0(), pfree(), round_var(), NumericVar::sign, strip_var(), trunc_var(), NumericVar::weight, and zero_var().

Referenced by div_mod_var(), ln_var(), log_var(), and power_var_int().

◆ div_var_int()

static void div_var_int ( const NumericVar var,
int  ival,
int  ival_weight,
NumericVar result,
int  rscale,
bool  round 
)
static

Definition at line 9471 of file numeric.c.

9473 {
9474  NumericDigit *var_digits = var->digits;
9475  int var_ndigits = var->ndigits;
9476  int res_sign;
9477  int res_weight;
9478  int res_ndigits;
9479  NumericDigit *res_buf;
9480  NumericDigit *res_digits;
9481  uint32 divisor;
9482  int i;
9483 
9484  /* Guard against division by zero */
9485  if (ival == 0)
9486  ereport(ERROR,
9487  errcode(ERRCODE_DIVISION_BY_ZERO),
9488  errmsg("division by zero"));
9489 
9490  /* Result zero check */
9491  if (var_ndigits == 0)
9492  {
9493  zero_var(result);
9494  result->dscale = rscale;
9495  return;
9496  }
9497 
9498  /*
9499  * Determine the result sign, weight and number of digits to calculate.
9500  * The weight figured here is correct if the emitted quotient has no
9501  * leading zero digits; otherwise strip_var() will fix things up.
9502  */
9503  if (var->sign == NUMERIC_POS)
9504  res_sign = ival > 0 ? NUMERIC_POS : NUMERIC_NEG;
9505  else
9506  res_sign = ival > 0 ? NUMERIC_NEG : NUMERIC_POS;
9507  res_weight = var->weight - ival_weight;
9508  /* The number of accurate result digits we need to produce: */
9509  res_ndigits = res_weight + 1 + (rscale + DEC_DIGITS - 1) / DEC_DIGITS;
9510  /* ... but always at least 1 */
9511  res_ndigits = Max(res_ndigits, 1);
9512  /* If rounding needed, figure one more digit to ensure correct result */
9513  if (round)
9514  res_ndigits++;
9515 
9516  res_buf = digitbuf_alloc(res_ndigits + 1);
9517  res_buf[0] = 0; /* spare digit for later rounding */
9518  res_digits = res_buf + 1;
9519 
9520  /*
9521  * Now compute the quotient digits. This is the short division algorithm
9522  * described in Knuth volume 2, section 4.3.1 exercise 16, except that we
9523  * allow the divisor to exceed the internal base.
9524  *
9525  * In this algorithm, the carry from one digit to the next is at most
9526  * divisor - 1. Therefore, while processing the next digit, carry may
9527  * become as large as divisor * NBASE - 1, and so it requires a 64-bit
9528  * integer if this exceeds UINT_MAX.
9529  */
9530  divisor = abs(ival);
9531 
9532  if (divisor <= UINT_MAX / NBASE)
9533  {
9534  /* carry cannot overflow 32 bits */
9535  uint32 carry = 0;
9536 
9537  for (i = 0; i < res_ndigits; i++)
9538  {
9539  carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
9540  res_digits[i] = (NumericDigit) (carry / divisor);
9541  carry = carry % divisor;
9542  }
9543  }
9544  else
9545  {
9546  /* carry may exceed 32 bits */
9547  uint64 carry = 0;
9548 
9549  for (i = 0; i < res_ndigits; i++)
9550  {
9551  carry = carry * NBASE + (i < var_ndigits ? var_digits[i] : 0);
9552  res_digits[i] = (NumericDigit) (carry / divisor);
9553  carry = carry % divisor;
9554  }
9555  }
9556 
9557  /* Store the quotient in result */
9558  digitbuf_free(result->buf);
9559  result->ndigits = res_ndigits;
9560  result->buf = res_buf;
9561  result->digits = res_digits;
9562  result->weight = res_weight;
9563  result->sign = res_sign;
9564 
9565  /* Round or truncate to target rscale (and set result->dscale) */
9566  if (round)
9567  round_var(result, rscale);
9568  else
9569  trunc_var(result, rscale);
9570 
9571  /* Strip leading/trailing zeroes */
9572  strip_var(result);
9573 }
unsigned int uint32
Definition: c.h:495

References NumericVar::buf, DEC_DIGITS, digitbuf_alloc, digitbuf_free, NumericVar::digits, NumericVar::dscale, ereport, errcode(), errmsg(), ERROR, i, Max, NBASE, NumericVar::ndigits, NUMERIC_NEG, NUMERIC_POS, round_var(), NumericVar::sign, strip_var(), trunc_var(), NumericVar::weight, and zero_var().

Referenced by div_var(), div_var_fast(), exp_var(), and ln_var().

◆ do_numeric_accum()

static void do_numeric_accum ( NumericAggState state,
Numeric  newval 
)
static

Definition at line 4779 of file numeric.c.

4780 {
4781  NumericVar X;
4782  NumericVar X2;
4783  MemoryContext old_context;
4784 
4785  /* Count NaN/infinity inputs separately from all else */
4787  {
4788  if (NUMERIC_IS_PINF(newval))
4789  state->pInfcount++;
4790  else if (NUMERIC_IS_NINF(newval))
4791  state->nInfcount++;
4792  else
4793  state->NaNcount++;
4794  return;
4795  }
4796 
4797  /* load processed number in short-lived context */
4799 
4800  /*
4801  * Track the highest input dscale that we've seen, to support inverse
4802  * transitions (see do_numeric_discard).
4803  */
4804  if (X.dscale > state->maxScale)
4805  {
4806  state->maxScale = X.dscale;
4807  state->maxScaleCount = 1;
4808  }
4809  else if (X.dscale == state->maxScale)
4810  state->maxScaleCount++;
4811 
4812  /* if we need X^2, calculate that in short-lived context */
4813  if (state->calcSumX2)
4814  {
4815  init_var(&X2);
4816  mul_var(&X, &X, &X2, X.dscale * 2);
4817  }
4818 
4819  /* The rest of this needs to work in the aggregate context */
4820  old_context = MemoryContextSwitchTo(state->agg_context);
4821 
4822  state->N++;
4823 
4824  /* Accumulate sums */
4825  accum_sum_add(&(state->sumX), &X);
4826 
4827  if (state->calcSumX2)
4828  accum_sum_add(&(state->sumX2), &X2);
4829 
4830  MemoryContextSwitchTo(old_context);
4831 }
#define newval
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
Definition: regguts.h:323

References accum_sum_add(), NumericVar::dscale, init_var, init_var_from_num(), MemoryContextSwitchTo(), mul_var(), newval, NUMERIC_IS_NINF, NUMERIC_IS_PINF, and NUMERIC_IS_SPECIAL.

Referenced by int2_accum(), int4_accum(), int8_accum(), int8_avg_accum(), numeric_accum(), and numeric_avg_accum().

◆ do_numeric_discard()

static bool do_numeric_discard ( NumericAggState state,
Numeric  newval 
)
static

Definition at line 4849 of file numeric.c.

4850 {
4851  NumericVar X;
4852  NumericVar X2;
4853  MemoryContext old_context;
4854 
4855  /* Count NaN/infinity inputs separately from all else */
4857  {
4858  if (NUMERIC_IS_PINF(newval))
4859  state->pInfcount--;
4860  else if (NUMERIC_IS_NINF(newval))
4861  state->nInfcount--;
4862  else
4863  state->NaNcount--;
4864  return true;
4865  }
4866 
4867  /* load processed number in short-lived context */
4869 
4870  /*
4871  * state->sumX's dscale is the maximum dscale of any of the inputs.
4872  * Removing the last input with that dscale would require us to recompute
4873  * the maximum dscale of the *remaining* inputs, which we cannot do unless
4874  * no more non-NaN inputs remain at all. So we report a failure instead,
4875  * and force the aggregation to be redone from scratch.
4876  */
4877  if (X.dscale == state->maxScale)
4878  {
4879  if (state->maxScaleCount > 1 || state->maxScale == 0)
4880  {
4881  /*
4882  * Some remaining inputs have same dscale, or dscale hasn't gotten
4883  * above zero anyway
4884  */
4885  state->maxScaleCount--;
4886  }
4887  else if (state->N == 1)
4888  {
4889  /* No remaining non-NaN inputs at all, so reset maxScale */
4890  state->maxScale = 0;
4891  state->maxScaleCount = 0;
4892  }
4893  else
4894  {
4895  /* Correct new maxScale is uncertain, must fail */
4896  return false;
4897  }
4898  }
4899 
4900  /* if we need X^2, calculate that in short-lived context */
4901  if (state->calcSumX2)
4902  {
4903  init_var(&X2);
4904  mul_var(&X, &X, &X2, X.dscale * 2);
4905  }
4906 
4907  /* The rest of this needs to work in the aggregate context */
4908  old_context = MemoryContextSwitchTo(state->agg_context);
4909 
4910  if (state->N-- > 1)
4911  {
4912  /* Negate X, to subtract it from the sum */
4913  X.sign = (X.sign == NUMERIC_POS ? NUMERIC_NEG : NUMERIC_POS);
4914  accum_sum_add(&(state->sumX), &X);
4915 
4916  if (state->calcSumX2)
4917  {
4918  /* Negate X^2. X^2 is always positive */
4919  X2.sign = NUMERIC_NEG;
4920  accum_sum_add(&(state->sumX2), &X2);
4921  }
4922  }
4923  else
4924  {
4925  /* Zero the sums */
4926  Assert(state->N == 0);
4927 
4928  accum_sum_reset(&state->sumX);
4929  if (state->calcSumX2)
4930  accum_sum_reset(&state->sumX2);
4931  }
4932 
4933  MemoryContextSwitchTo(old_context);
4934 
4935  return true;
4936 }
static void accum_sum_reset(NumericSumAccum *accum)
Definition: numeric.c:11713

References accum_sum_add(), accum_sum_reset(), Assert(), NumericVar::dscale, init_var, init_var_from_num(), MemoryContextSwitchTo(), mul_var(), newval, NUMERIC_IS_NINF, NUMERIC_IS_PINF, NUMERIC_IS_SPECIAL, NUMERIC_NEG, NUMERIC_POS, and NumericVar::sign.

Referenced by int2_accum_inv(), int4_accum_inv(), int8_accum_inv(), int8_avg_accum_inv(), and numeric_accum_inv().

◆ duplicate_numeric()

static Numeric duplicate_numeric ( Numeric  num)
static

Definition at line 7685 of file numeric.c.

7686 {
7687  Numeric res;
7688 
7689  res = (Numeric) palloc(VARSIZE(num));
7690  memcpy(res, num, VARSIZE(num));
7691  return res;
7692 }
struct NumericData * Numeric
Definition: numeric.h:53
#define VARSIZE(PTR)
Definition: varatt.h:279

References palloc(), res, and VARSIZE.

Referenced by numeric(), numeric_abs(), numeric_ceil(), numeric_exp(), numeric_floor(), numeric_inc(), numeric_ln(), numeric_mod_opt_error(), numeric_round(), numeric_sqrt(), numeric_trim_scale(), numeric_trunc(), numeric_uminus(), and numeric_uplus().

◆ estimate_ln_dweight()

static int estimate_ln_dweight ( const NumericVar var)
static

Definition at line 10593 of file numeric.c.

10594 {
10595  int ln_dweight;
10596 
10597  /* Caller should fail on ln(negative), but for the moment return zero */
10598  if (var->sign != NUMERIC_POS)
10599  return 0;
10600 
10601  if (cmp_var(var, &const_zero_point_nine) >= 0 &&
10602  cmp_var(var, &const_one_point_one) <= 0)
10603  {
10604  /*
10605  * 0.9 <= var <= 1.1
10606  *
10607  * ln(var) has a negative weight (possibly very large). To get a
10608  * reasonably accurate result, estimate it using ln(1+x) ~= x.
10609  */
10610  NumericVar x;
10611 
10612  init_var(&x);
10613  sub_var(var, &const_one, &x);
10614 
10615  if (x.ndigits > 0)
10616  {
10617  /* Use weight of most significant decimal digit of x */
10618  ln_dweight = x.weight * DEC_DIGITS + (int) log10(x.digits[0]);
10619  }
10620  else
10621  {
10622  /* x = 0. Since ln(1) = 0 exactly, we don't need extra digits */
10623  ln_dweight = 0;
10624  }
10625 
10626  free_var(&x);
10627  }
10628  else
10629  {
10630  /*
10631  * Estimate the logarithm using the first couple of digits from the
10632  * input number. This will give an accurate result whenever the input
10633  * is not too close to 1.
10634  */
10635  if (var->ndigits > 0)
10636  {
10637  int digits;
10638  int dweight;
10639  double ln_var;
10640 
10641  digits = var->digits[0];
10642  dweight = var->weight * DEC_DIGITS;
10643 
10644  if (var->ndigits > 1)
10645  {
10646  digits = digits * NBASE + var->digits[1];
10647  dweight -= DEC_DIGITS;
10648  }
10649 
10650  /*----------
10651  * We have var ~= digits * 10^dweight
10652  * so ln(var) ~= ln(digits) + dweight * ln(10)
10653  *----------
10654  */
10655  ln_var = log((double) digits) + dweight * 2.302585092994046;
10656  ln_dweight = (int) log10(fabs(ln_var));
10657  }
10658  else
10659  {
10660  /* Caller should fail on ln(0), but for the moment return zero */
10661  ln_dweight = 0;
10662  }
10663  }
10664 
10665  return ln_dweight;
10666 }
static const NumericVar const_zero_point_nine
Definition: numeric.c:437
static const NumericVar const_one_point_one
Definition: numeric.c:447
static void ln_var(const NumericVar *arg, NumericVar *result, int rscale)
Definition: numeric.c:10675
int digits
Definition: informix.c:666
int x
Definition: isn.c:71

References cmp_var(), const_one, const_one_point_one, const_zero_point_nine, DEC_DIGITS, NumericVar::digits, digits, free_var(), init_var, ln_var(), NBASE, NumericVar::ndigits, NUMERIC_POS, NumericVar::sign, sub_var(), NumericVar::weight, and x.

Referenced by log_var(), numeric_ln(), and power_var().

◆ exp_var()

static void exp_var ( const NumericVar arg,
NumericVar result,
int  rscale 
)
static

Definition at line 10464 of file numeric.c.

10465 {
10466  NumericVar x;
10467  NumericVar elem;
10468  int ni;
10469  double val;
10470  int dweight;
10471  int ndiv2;
10472  int sig_digits;
10473  int local_rscale;
10474 
10475  init_var(&x);
10476  init_var(&elem);
10477 
10478  set_var_from_var(arg, &x);
10479 
10480  /*
10481  * Estimate the dweight of the result using floating point arithmetic, so
10482  * that we can choose an appropriate local rscale for the calculation.
10483  */
10485 
10486  /* Guard against overflow/underflow */
10487  /* If you change this limit, see also power_var()'s limit */
10488  if (fabs(val) >= NUMERIC_MAX_RESULT_SCALE * 3)
10489  {
10490  if (val > 0)
10491  ereport(ERROR,
10492  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
10493  errmsg("value overflows numeric format")));
10494  zero_var(result);
10495  result->dscale = rscale;
10496  return;
10497  }
10498 
10499  /* decimal weight = log10(e^x) = x * log10(e) */
10500  dweight = (int) (val * 0.434294481903252);
10501 
10502  /*
10503  * Reduce x to the range -0.01 <= x <= 0.01 (approximately) by dividing by
10504  * 2^ndiv2, to improve the convergence rate of the Taylor series.
10505  *
10506  * Note that the overflow check above ensures that fabs(x) < 6000, which
10507  * means that ndiv2 <= 20 here.
10508  */
10509  if (fabs(val) > 0.01)
10510  {
10511  ndiv2 = 1;
10512  val /= 2;
10513 
10514  while (fabs(val) > 0.01)
10515  {
10516  ndiv2++;
10517  val /= 2;
10518  }
10519 
10520  local_rscale = x.dscale + ndiv2;
10521  div_var_int(&x, 1 << ndiv2, 0, &x, local_rscale, true);
10522  }
10523  else
10524  ndiv2 = 0;
10525 
10526  /*
10527  * Set the scale for the Taylor series expansion. The final result has
10528  * (dweight + rscale + 1) significant digits. In addition, we have to
10529  * raise the Taylor series result to the power 2^ndiv2, which introduces
10530  * an error of up to around log10(2^ndiv2) digits, so work with this many
10531  * extra digits of precision (plus a few more for good measure).
10532  */
10533  sig_digits = 1 + dweight + rscale + (int) (ndiv2 * 0.301029995663981);
10534  sig_digits = Max(sig_digits, 0) + 8;
10535 
10536  local_rscale = sig_digits - 1;
10537 
10538  /*
10539  * Use the Taylor series
10540  *
10541  * exp(x) = 1 + x + x^2/2! + x^3/3! + ...
10542  *
10543  * Given the limited range of x, this should converge reasonably quickly.
10544  * We run the series until the terms fall below the local_rscale limit.
10545  */
10546  add_var(&const_one, &x, result);
10547 
10548  mul_var(&x, &x, &elem, local_rscale);
10549  ni = 2;
10550  div_var_int(&elem, ni, 0, &elem, local_rscale, true);
10551 
10552  while (elem.ndigits != 0)
10553  {
10554  add_var(result, &elem, result);
10555 
10556  mul_var(&elem, &x, &elem, local_rscale);
10557  ni++;
10558  div_var_int(&elem, ni, 0, &elem, local_rscale, true);
10559  }
10560 
10561  /*
10562  * Compensate for the argument range reduction. Since the weight of the
10563  * result doubles with each multiplication, we can reduce the local rscale
10564  * as we proceed.
10565  */
10566  while (ndiv2-- > 0)
10567  {
10568  local_rscale = sig_digits - result->weight * 2 * DEC_DIGITS;
10569  local_rscale = Max(local_rscale, NUMERIC_MIN_DISPLAY_SCALE);
10570  mul_var(result, result, result, local_rscale);
10571  }
10572 
10573  /* Round to requested rscale */
10574  round_var(result, rscale);
10575 
10576  free_var(&x);
10577  free_var(&elem);
10578 }
static double numericvar_to_double_no_overflow(const NumericVar *var)
Definition: numeric.c:8263
#define NUMERIC_MAX_RESULT_SCALE
Definition: numeric.h:42
#define NUMERIC_MIN_DISPLAY_SCALE
Definition: numeric.h:40
void * arg

References add_var(), arg, const_one, DEC_DIGITS, div_var_int(), NumericVar::dscale, ereport, errcode(), errmsg(), ERROR, free_var(), init_var, Max, mul_var(), NumericVar::ndigits, NUMERIC_MAX_RESULT_SCALE, NUMERIC_MIN_DISPLAY_SCALE, numericvar_to_double_no_overflow(), round_var(), set_var_from_var(), val, NumericVar::weight, x, and zero_var().

Referenced by numeric_exp(), and power_var().

◆ float4_numeric()

Datum float4_numeric ( PG_FUNCTION_ARGS  )

Definition at line 4609 of file numeric.c.

4610 {
4612  Numeric res;
4613  NumericVar result;
4614  char buf[FLT_DIG + 100];
4615  const char *endptr;
4616 
4617  if (isnan(val))
4619 
4620  if (isinf(val))
4621  {
4622  if (val < 0)
4624  else
4626  }
4627 
4628  snprintf(buf, sizeof(buf), "%.*g", FLT_DIG, val);
4629 
4630  init_var(&result);
4631 
4632  /* Assume we need not worry about leading/trailing spaces */
4633  (void) set_var_from_str(buf, buf, &result, &endptr, NULL);
4634 
4635  res = make_result(&result);
4636 
4637  free_var(&result);
4638 
4640 }
static const NumericVar const_pinf
Definition: numeric.c:453
static const NumericVar const_ninf
Definition: numeric.c:456
static bool set_var_from_str(const char *str, const char *cp, NumericVar *dest, const char **endptr, Node *escontext)
Definition: numeric.c:6934
static Numeric make_result(const NumericVar *var)
Definition: numeric.c:7813
static const NumericVar const_nan
Definition: numeric.c:450
float float4
Definition: c.h:618
#define PG_GETARG_FLOAT4(n)
Definition: fmgr.h:281
#define PG_RETURN_NUMERIC(x)
Definition: numeric.h:79
#define snprintf
Definition: port.h:238

References buf, const_nan, const_ninf, const_pinf, free_var(), init_var, make_result(), PG_GETARG_FLOAT4, PG_RETURN_NUMERIC, res, set_var_from_str(), snprintf, and val.

◆ float8_numeric()

Datum float8_numeric ( PG_FUNCTION_ARGS  )

Definition at line 4515 of file numeric.c.

4516 {
4518  Numeric res;
4519  NumericVar result;
4520  char buf[DBL_DIG + 100];
4521  const char *endptr;
4522 
4523  if (isnan(val))
4525 
4526  if (isinf(val))
4527  {
4528  if (val < 0)
4530  else
4532  }
4533 
4534  snprintf(buf, sizeof(buf), "%.*g", DBL_DIG, val);
4535 
4536  init_var(&result);
4537 
4538  /* Assume we need not worry about leading/trailing spaces */
4539  (void) set_var_from_str(buf, buf, &result, &endptr, NULL);
4540 
4541  res = make_result(&result);
4542 
4543  free_var(&result);
4544 
4546 }
double float8
Definition: c.h:619
#define PG_GETARG_FLOAT8(n)
Definition: fmgr.h:282

References buf, const_nan, const_ninf, const_pinf, free_var(), init_var, make_result(), PG_GETARG_FLOAT8, PG_RETURN_NUMERIC, res, set_var_from_str(), snprintf, and val.

Referenced by executeItemOptUnwrapTarget(), and SV_to_JsonbValue().

◆ floor_var()

static void floor_var ( const NumericVar var,
NumericVar result 
)
static

Definition at line 9891 of file numeric.c.

9892 {
9893  NumericVar tmp;
9894 
9895  init_var(&tmp);
9896  set_var_from_var(var, &tmp);
9897 
9898  trunc_var(&tmp, 0);
9899 
9900  if (var->sign == NUMERIC_NEG && cmp_var(var, &tmp) != 0)
9901  sub_var(&tmp, &const_one, &tmp);
9902 
9903  set_var_from_var(&tmp, result);
9904  free_var(&tmp);
9905 }

References cmp_var(), const_one, free_var(), init_var, NUMERIC_NEG, set_var_from_var(), NumericVar::sign, sub_var(), and trunc_var().

Referenced by compute_bucket(), and numeric_floor().

◆ free_var()

static void free_var ( NumericVar var)
static

Definition at line 6891 of file numeric.c.

6892 {
6893  digitbuf_free(var->buf);
6894  var->buf = NULL;
6895  var->digits = NULL;
6896  var->sign = NUMERIC_NAN;
6897 }
#define NUMERIC_NAN
Definition: numeric.c:198

References NumericVar::buf, digitbuf_free, NumericVar::digits, NUMERIC_NAN, and NumericVar::sign.

Referenced by accum_sum_combine(), ceil_var(), compute_bucket(), div_mod_var(), estimate_ln_dweight(), exp_var(), float4_numeric(), float8_numeric(), floor_var(), gcd_var(), get_str_from_var_sci(), in_range_numeric_numeric(), int64_div_fast_to_numeric(), int64_to_numeric(), int8_avg_deserialize(), int8_avg_serialize(), ln_var(), log_var(), mod_var(), numeric(), numeric_add_opt_error(), numeric_avg(), numeric_avg_deserialize(), numeric_avg_serialize(), numeric_ceil(), numeric_deserialize(), numeric_div_opt_error(), numeric_div_trunc(), numeric_exp(), numeric_fac(), numeric_floor(), numeric_gcd(), numeric_in(), numeric_inc(), numeric_lcm(), numeric_ln(), numeric_log(), numeric_min_scale(), numeric_mod_opt_error(), numeric_mul_opt_error(), numeric_poly_avg(), numeric_poly_deserialize(), numeric_poly_serialize(), numeric_poly_sum(), numeric_power(), numeric_recv(), numeric_round(), numeric_serialize(), numeric_sqrt(), numeric_stddev_internal(), numeric_sub_opt_error(), numeric_sum(), numeric_trim_scale(), numeric_trunc(), numericvar_to_int64(), numericvar_to_uint64(), power_var(), power_var_int(), set_var_from_non_decimal_integer_str(), sqrt_var(), and width_bucket_numeric().

◆ gcd_var()

static void gcd_var ( const NumericVar var1,
const NumericVar var2,
NumericVar result 
)
static

Definition at line 9914 of file numeric.c.

9915 {
9916  int res_dscale;
9917  int cmp;
9918  NumericVar tmp_arg;
9919  NumericVar mod;
9920 
9921  res_dscale = Max(var1->dscale, var2->dscale);
9922 
9923  /*
9924  * Arrange for var1 to be the number with the greater absolute value.
9925  *
9926  * This would happen automatically in the loop below, but avoids an
9927  * expensive modulo operation.
9928  */
9929  cmp = cmp_abs(var1, var2);
9930  if (cmp < 0)
9931  {
9932  const NumericVar *tmp = var1;
9933 
9934  var1 = var2;
9935  var2 = tmp;
9936  }
9937 
9938  /*
9939  * Also avoid the taking the modulo if the inputs have the same absolute
9940  * value, or if the smaller input is zero.
9941  */
9942  if (cmp == 0 || var2->ndigits == 0)
9943  {
9944  set_var_from_var(var1, result);
9945  result->sign = NUMERIC_POS;
9946  result->dscale = res_dscale;
9947  return;
9948  }
9949 
9950  init_var(&tmp_arg);
9951  init_var(&mod);
9952 
9953  /* Use the Euclidean algorithm to find the GCD */
9954  set_var_from_var(var1, &tmp_arg);
9955  set_var_from_var(var2, result);
9956 
9957  for (;;)
9958  {
9959  /* this loop can take a while, so allow it to be interrupted */
9961 
9962  mod_var(&tmp_arg, result, &mod);
9963  if (mod.ndigits == 0)
9964  break;
9965  set_var_from_var(result, &tmp_arg);
9966  set_var_from_var(&mod, result);
9967  }
9968  result->sign = NUMERIC_POS;
9969  result->dscale = res_dscale;
9970 
9971  free_var(&tmp_arg);
9972  free_var(&mod);
9973 }
static void mod_var(const NumericVar *var1, const NumericVar *var2, NumericVar *result)
Definition: numeric.c:9768
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
static int cmp(const chr *x, const chr *y, size_t len)
Definition: regc_locale.c:743

References CHECK_FOR_INTERRUPTS, cmp(), cmp_abs(), NumericVar::dscale, free_var(), init_var, Max, mod_var(), NumericVar::ndigits, NUMERIC_POS, set_var_from_var(), and NumericVar::sign.

Referenced by numeric_gcd(), and numeric_lcm().

◆ generate_series_numeric()

Datum generate_series_numeric ( PG_FUNCTION_ARGS  )

Definition at line 1685 of file numeric.c.

1686 {
1687  return generate_series_step_numeric(fcinfo);
1688 }
Datum generate_series_step_numeric(PG_FUNCTION_ARGS)
Definition: numeric.c:1691

References generate_series_step_numeric().

◆ generate_series_step_numeric()

Datum generate_series_step_numeric ( PG_FUNCTION_ARGS  )

Definition at line 1691 of file numeric.c.

1692 {
1694  FuncCallContext *funcctx;
1695  MemoryContext oldcontext;
1696 
1697  if (SRF_IS_FIRSTCALL())
1698  {
1699  Numeric start_num = PG_GETARG_NUMERIC(0);
1700  Numeric stop_num = PG_GETARG_NUMERIC(1);
1701  NumericVar steploc = const_one;
1702 
1703  /* Reject NaN and infinities in start and stop values */
1704  if (NUMERIC_IS_SPECIAL(start_num))
1705  {
1706  if (NUMERIC_IS_NAN(start_num))
1707  ereport(ERROR,
1708  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1709  errmsg("start value cannot be NaN")));
1710  else
1711  ereport(ERROR,
1712  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1713  errmsg("start value cannot be infinity")));
1714  }
1715  if (NUMERIC_IS_SPECIAL(stop_num))
1716  {
1717  if (NUMERIC_IS_NAN(stop_num))
1718  ereport(ERROR,
1719  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1720  errmsg("stop value cannot be NaN")));
1721  else
1722  ereport(ERROR,
1723  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1724  errmsg("stop value cannot be infinity")));
1725  }
1726 
1727  /* see if we were given an explicit step size */
1728  if (PG_NARGS() == 3)
1729  {
1730  Numeric step_num = PG_GETARG_NUMERIC(2);
1731 
1732  if (NUMERIC_IS_SPECIAL(step_num))
1733  {
1734  if (NUMERIC_IS_NAN(step_num))
1735  ereport(ERROR,
1736  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1737  errmsg("step size cannot be NaN")));
1738  else
1739  ereport(ERROR,
1740  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1741  errmsg("step size cannot be infinity")));
1742  }
1743 
1744  init_var_from_num(step_num, &steploc);
1745 
1746  if (cmp_var(&steploc, &const_zero) == 0)
1747  ereport(ERROR,
1748  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1749  errmsg("step size cannot equal zero")));
1750  }
1751 
1752  /* create a function context for cross-call persistence */
1753  funcctx = SRF_FIRSTCALL_INIT();
1754 
1755  /*
1756  * Switch to memory context appropriate for multiple function calls.
1757  */
1758  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1759 
1760  /* allocate memory for user context */
1761  fctx = (generate_series_numeric_fctx *)
1763 
1764  /*
1765  * Use fctx to keep state from call to call. Seed current with the
1766  * original start value. We must copy the start_num and stop_num
1767  * values rather than pointing to them, since we may have detoasted
1768  * them in the per-call context.
1769  */
1770  init_var(&fctx->current);
1771  init_var(&fctx->stop);
1772  init_var(&fctx->step);
1773 
1774  set_var_from_num(start_num, &fctx->current);
1775  set_var_from_num(stop_num, &fctx->stop);
1776  set_var_from_var(&steploc, &fctx->step);
1777 
1778  funcctx->user_fctx = fctx;
1779  MemoryContextSwitchTo(oldcontext);
1780  }
1781 
1782  /* stuff done on every call of the function */
1783  funcctx = SRF_PERCALL_SETUP();
1784 
1785  /*
1786  * Get the saved state and use current state as the result of this
1787  * iteration.
1788  */
1789  fctx = funcctx->user_fctx;
1790 
1791  if ((fctx->step.sign == NUMERIC_POS &&
1792  cmp_var(&fctx->current, &fctx->stop) <= 0) ||
1793  (fctx->step.sign == NUMERIC_NEG &&
1794  cmp_var(&fctx->current, &fctx->stop) >= 0))
1795  {
1796  Numeric result = make_result(&fctx->current);
1797 
1798  /* switch to memory context appropriate for iteration calculation */
1799  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
1800 
1801  /* increment current in preparation for next iteration */
1802  add_var(&fctx->current, &fctx->step, &fctx->current);
1803  MemoryContextSwitchTo(oldcontext);
1804 
1805  /* do when there is more left to send */
1806  SRF_RETURN_NEXT(funcctx, NumericGetDatum(result));
1807  }
1808  else
1809  /* do when there is no more left */
1810  SRF_RETURN_DONE(funcctx);
1811 }
static void set_var_from_num(Numeric num, NumericVar *dest)
Definition: numeric.c:7342
#define PG_NARGS()
Definition: fmgr.h:203
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:304
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:308
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:310
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:306
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:328
#define PG_GETARG_NUMERIC(n)
Definition: numeric.h:77
static Datum NumericGetDatum(Numeric X)
Definition: numeric.h:72
void * user_fctx
Definition: funcapi.h:82
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101

References add_var(), cmp_var(), const_one, const_zero, generate_series_numeric_fctx::current, ereport, errcode(), errmsg(), ERROR, init_var, init_var_from_num(), make_result(), MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, NUMERIC_IS_NAN, NUMERIC_IS_SPECIAL, NUMERIC_NEG, NUMERIC_POS, NumericGetDatum(), palloc(), PG_GETARG_NUMERIC, PG_NARGS, set_var_from_num(), set_var_from_var(), NumericVar::sign, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, generate_series_numeric_fctx::step, generate_series_numeric_fctx::stop, and FuncCallContext::user_fctx.

Referenced by generate_series_numeric().

◆ get_min_scale()

static int get_min_scale ( NumericVar var)
static

Definition at line 4135 of file numeric.c.

4136 {
4137  int min_scale;
4138  int last_digit_pos;
4139 
4140  /*
4141  * Ordinarily, the input value will be "stripped" so that the last
4142  * NumericDigit is nonzero. But we don't want to get into an infinite
4143  * loop if it isn't, so explicitly find the last nonzero digit.
4144  */
4145  last_digit_pos = var->ndigits - 1;
4146  while (last_digit_pos >= 0 &&
4147  var->digits[last_digit_pos] == 0)
4148  last_digit_pos--;
4149 
4150  if (last_digit_pos >= 0)
4151  {
4152  /* compute min_scale assuming that last ndigit has no zeroes */
4153  min_scale = (last_digit_pos - var->weight) * DEC_DIGITS;
4154 
4155  /*
4156  * We could get a negative result if there are no digits after the
4157  * decimal point. In this case the min_scale must be zero.
4158  */
4159  if (min_scale > 0)
4160  {
4161  /*
4162  * Reduce min_scale if trailing digit(s) in last NumericDigit are
4163  * zero.
4164  */
4165  NumericDigit last_digit = var->digits[last_digit_pos];
4166 
4167  while (last_digit % 10 == 0)
4168  {
4169  min_scale--;
4170  last_digit /= 10;
4171  }
4172  }
4173  else
4174  min_scale = 0;
4175  }
4176  else
4177  min_scale = 0; /* result if input is zero */
4178 
4179  return min_scale;
4180 }

References DEC_DIGITS, NumericVar::digits, NumericVar::ndigits, and NumericVar::weight.

Referenced by numeric_min_scale(), and numeric_trim_scale().

◆ get_str_from_var()

static char * get_str_from_var ( const NumericVar var)
static

Definition at line 7416 of file numeric.c.

7417 {
7418  int dscale;
7419  char *str;
7420  char *cp;
7421  char *endcp;
7422  int i;
7423  int d;
7424  NumericDigit dig;
7425 
7426 #if DEC_DIGITS > 1
7427  NumericDigit d1;
7428 #endif
7429 
7430  dscale = var->dscale;
7431 
7432  /*
7433  * Allocate space for the result.
7434  *
7435  * i is set to the # of decimal digits before decimal point. dscale is the
7436  * # of decimal digits we will print after decimal point. We may generate
7437  * as many as DEC_DIGITS-1 excess digits at the end, and in addition we
7438  * need room for sign, decimal point, null terminator.
7439  */
7440  i = (var->weight + 1) * DEC_DIGITS;
7441  if (i <= 0)
7442  i = 1;
7443 
7444  str = palloc(i + dscale + DEC_DIGITS + 2);
7445  cp = str;
7446 
7447  /*
7448  * Output a dash for negative values
7449  */
7450  if (var->sign == NUMERIC_NEG)
7451  *cp++ = '-';
7452 
7453  /*
7454  * Output all digits before the decimal point
7455  */
7456  if (var->weight < 0)
7457  {
7458  d = var->weight + 1;
7459  *cp++ = '0';
7460  }
7461  else
7462  {
7463  for (d = 0; d <= var->weight; d++)
7464  {
7465  dig = (d < var->ndigits) ? var->digits[d] : 0;
7466  /* In the first digit, suppress extra leading decimal zeroes */
7467 #if DEC_DIGITS == 4
7468  {
7469  bool putit = (d > 0);
7470 
7471  d1 = dig / 1000;
7472  dig -= d1 * 1000;
7473  putit |= (d1 > 0);
7474  if (putit)
7475  *cp++ = d1 + '0';
7476  d1 = dig / 100;
7477  dig -= d1 * 100;
7478  putit |= (d1 > 0);
7479  if (putit)
7480  *cp++ = d1 + '0';
7481  d1 = dig / 10;
7482  dig -= d1 * 10;
7483  putit |= (d1 > 0);
7484  if (putit)
7485  *cp++ = d1 + '0';
7486  *cp++ = dig + '0';
7487  }
7488 #elif DEC_DIGITS == 2
7489  d1 = dig / 10;
7490  dig -= d1 * 10;
7491  if (d1 > 0 || d > 0)
7492  *cp++ = d1 + '0';
7493  *cp++ = dig + '0';
7494 #elif DEC_DIGITS == 1
7495  *cp++ = dig + '0';
7496 #else
7497 #error unsupported NBASE
7498 #endif
7499  }
7500  }
7501 
7502  /*
7503  * If requested, output a decimal point and all the digits that follow it.
7504  * We initially put out a multiple of DEC_DIGITS digits, then truncate if
7505  * needed.
7506  */
7507  if (dscale > 0)
7508  {
7509  *cp++ = '.';
7510  endcp = cp + dscale;
7511  for (i = 0; i < dscale; d++, i += DEC_DIGITS)
7512  {
7513  dig = (d >= 0 && d < var->ndigits) ? var->digits[d] : 0;
7514 #if DEC_DIGITS == 4
7515  d1 = dig / 1000;
7516  dig -= d1 * 1000;
7517  *cp++ = d1 + '0';
7518  d1 = dig / 100;
7519  dig -= d1 * 100;
7520  *cp++ = d1 + '0';
7521  d1 = dig / 10;
7522  dig -= d1 * 10;
7523  *cp++ = d1 + '0';
7524  *cp++ = dig + '0';
7525 #elif DEC_DIGITS == 2
7526  d1 = dig / 10;
7527  dig -= d1 * 10;
7528  *cp++ = d1 + '0';
7529  *cp++ = dig + '0';
7530 #elif DEC_DIGITS == 1
7531  *cp++ = dig + '0';
7532 #else
7533 #error unsupported NBASE
7534 #endif
7535  }
7536  cp = endcp;
7537  }
7538 
7539  /*
7540  * terminate the string and return it
7541  */
7542  *cp = '\0';
7543  return str;
7544 }
static void error(void)
Definition: sql-dyntest.c:147

References DEC_DIGITS, NumericVar::digits, NumericVar::dscale, i, NumericVar::ndigits, NUMERIC_NEG, palloc(), NumericVar::sign, generate_unaccent_rules::str, and NumericVar::weight.

Referenced by get_str_from_var_sci(), numeric_normalize(), numeric_out(), and numericvar_to_double_no_overflow().

◆ get_str_from_var_sci()

static char * get_str_from_var_sci ( const NumericVar var,
int  rscale 
)
static

Definition at line 7569 of file numeric.c.

7570 {
7571  int32 exponent;
7572  NumericVar tmp_var;
7573  size_t len;
7574  char *str;
7575  char *sig_out;
7576 
7577  if (rscale < 0)
7578  rscale = 0;
7579 
7580  /*
7581  * Determine the exponent of this number in normalised form.
7582  *
7583  * This is the exponent required to represent the number with only one
7584  * significant digit before the decimal place.
7585  */
7586  if (var->ndigits > 0)
7587  {
7588  exponent = (var->weight + 1) * DEC_DIGITS;
7589 
7590  /*
7591  * Compensate for leading decimal zeroes in the first numeric digit by
7592  * decrementing the exponent.
7593  */
7594  exponent -= DEC_DIGITS - (int) log10(var->digits[0]);
7595  }
7596  else
7597  {
7598  /*
7599  * If var has no digits, then it must be zero.
7600  *
7601  * Zero doesn't technically have a meaningful exponent in normalised
7602  * notation, but we just display the exponent as zero for consistency
7603  * of output.
7604  */
7605  exponent = 0;
7606  }
7607 
7608  /*
7609  * Divide var by 10^exponent to get the significand, rounding to rscale
7610  * decimal digits in the process.
7611  */
7612  init_var(&tmp_var);
7613 
7614  power_ten_int(exponent, &tmp_var);
7615  div_var(var, &tmp_var, &tmp_var, rscale, true);
7616  sig_out = get_str_from_var(&tmp_var);
7617 
7618  free_var(&tmp_var);
7619 
7620  /*
7621  * Allocate space for the result.
7622  *
7623  * In addition to the significand, we need room for the exponent
7624  * decoration ("e"), the sign of the exponent, up to 10 digits for the
7625  * exponent itself, and of course the null terminator.
7626  */
7627  len = strlen(sig_out) + 13;
7628  str = palloc(len);
7629  snprintf(str, len, "%se%+03d", sig_out, exponent);
7630 
7631  pfree(sig_out);
7632 
7633  return str;
7634 }
static char * get_str_from_var(const NumericVar *var)
Definition: numeric.c:7416
static void power_ten_int(int exp, NumericVar *result)
Definition: numeric.c:11218
const void size_t len

References DEC_DIGITS, NumericVar::digits, div_var(), free_var(), get_str_from_var(), init_var, len, NumericVar::ndigits, palloc(), pfree(), power_ten_int(), snprintf, generate_unaccent_rules::str, and NumericVar::weight.

Referenced by numeric_out_sci().

◆ hash_numeric()

Datum hash_numeric ( PG_FUNCTION_ARGS  )

Definition at line 2696 of file numeric.c.

2697 {
2699  Datum digit_hash;
2700  Datum result;
2701  int weight;
2702  int start_offset;
2703  int end_offset;
2704  int i;
2705  int hash_len;
2707 
2708  /* If it's NaN or infinity, don't try to hash the rest of the fields */
2709  if (NUMERIC_IS_SPECIAL(key))
2710  PG_RETURN_UINT32(0);
2711 
2712  weight = NUMERIC_WEIGHT(key);
2713  start_offset = 0;
2714  end_offset = 0;
2715 
2716  /*
2717  * Omit any leading or trailing zeros from the input to the hash. The
2718  * numeric implementation *should* guarantee that leading and trailing
2719  * zeros are suppressed, but we're paranoid. Note that we measure the
2720  * starting and ending offsets in units of NumericDigits, not bytes.
2721  */
2723  for (i = 0; i < NUMERIC_NDIGITS(key); i++)
2724  {
2725  if (digits[i] != (NumericDigit) 0)
2726  break;
2727 
2728  start_offset++;
2729 
2730  /*
2731  * The weight is effectively the # of digits before the decimal point,
2732  * so decrement it for each leading zero we skip.
2733  */
2734  weight--;
2735  }
2736 
2737  /*
2738  * If there are no non-zero digits, then the value of the number is zero,
2739  * regardless of any other fields.
2740  */
2741  if (NUMERIC_NDIGITS(key) == start_offset)
2742  PG_RETURN_UINT32(-1);
2743 
2744  for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--)
2745  {
2746  if (digits[i] != (NumericDigit) 0)
2747  break;
2748 
2749  end_offset++;
2750  }
2751 
2752  /* If we get here, there should be at least one non-zero digit */
2753  Assert(start_offset + end_offset < NUMERIC_NDIGITS(key));
2754 
2755  /*
2756  * Note that we don't hash on the Numeric's scale, since two numerics can
2757  * compare equal but have different scales. We also don't hash on the
2758  * sign, although we could: since a sign difference implies inequality,
2759  * this shouldn't affect correctness.
2760  */
2761  hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset;
2762  digit_hash = hash_any((unsigned char *) (NUMERIC_DIGITS(key) + start_offset),
2763  hash_len * sizeof(NumericDigit));
2764 
2765  /* Mix in the weight, via XOR */
2766  result = digit_hash ^ weight;
2767 
2768  PG_RETURN_DATUM(result);
2769 }
#define PG_RETURN_UINT32(x)
Definition: fmgr.h:355
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
static Datum hash_any(const unsigned char *k, int keylen)
Definition: hashfn.h:31
uintptr_t Datum
Definition: postgres.h:64

References Assert(), digits, hash_any(), i, sort-test::key, NUMERIC_DIGITS, NUMERIC_IS_SPECIAL, NUMERIC_NDIGITS, NUMERIC_WEIGHT, PG_GETARG_NUMERIC, PG_RETURN_DATUM, and PG_RETURN_UINT32.

Referenced by JsonbHashScalarValue().

◆ hash_numeric_extended()

Datum hash_numeric_extended ( PG_FUNCTION_ARGS  )

Definition at line 2776 of file numeric.c.

2777 {
2779  uint64 seed = PG_GETARG_INT64(1);
2780  Datum digit_hash;
2781  Datum result;
2782  int weight;
2783  int start_offset;
2784  int end_offset;
2785  int i;
2786  int hash_len;
2788 
2789  /* If it's NaN or infinity, don't try to hash the rest of the fields */
2790  if (NUMERIC_IS_SPECIAL(key))
2791  PG_RETURN_UINT64(seed);
2792 
2793  weight = NUMERIC_WEIGHT(key);
2794  start_offset = 0;
2795  end_offset = 0;
2796 
2798  for (i = 0; i < NUMERIC_NDIGITS(key); i++)
2799  {
2800  if (digits[i] != (NumericDigit) 0)
2801  break;
2802 
2803  start_offset++;
2804 
2805  weight--;
2806  }
2807 
2808  if (NUMERIC_NDIGITS(key) == start_offset)
2809  PG_RETURN_UINT64(seed - 1);
2810 
2811  for (i = NUMERIC_NDIGITS(key) - 1; i >= 0; i--)
2812  {
2813  if (digits[i] != (NumericDigit) 0)
2814  break;
2815 
2816  end_offset++;
2817  }
2818 
2819  Assert(start_offset + end_offset < NUMERIC_NDIGITS(key));
2820 
2821  hash_len = NUMERIC_NDIGITS(key) - start_offset - end_offset;
2822  digit_hash = hash_any_extended((unsigned char *) (NUMERIC_DIGITS(key)
2823  + start_offset),
2824  hash_len * sizeof(NumericDigit),
2825  seed);
2826 
2827  result = UInt64GetDatum(DatumGetUInt64(digit_hash) ^ weight);
2828 
2829  PG_RETURN_DATUM(result);
2830 }
#define PG_GETARG_INT64(n)
Definition: fmgr.h:283
#define PG_RETURN_UINT64(x)
Definition: fmgr.h:369
static Datum hash_any_extended(const unsigned char *k, int keylen, uint64 seed)
Definition: hashfn.h:37
static uint64 DatumGetUInt64(Datum X)
Definition: postgres.h:419
static Datum UInt64GetDatum(uint64 X)
Definition: postgres.h:436

References Assert(), DatumGetUInt64(), digits, hash_any_extended(), i, sort-test::key, NUMERIC_DIGITS, NUMERIC_IS_SPECIAL, NUMERIC_NDIGITS, NUMERIC_WEIGHT, PG_GETARG_INT64, PG_GETARG_NUMERIC, PG_RETURN_DATUM, PG_RETURN_UINT64, and UInt64GetDatum().

Referenced by JsonbHashScalarValueExtended().

◆ in_range_numeric_numeric()

Datum in_range_numeric_numeric ( PG_FUNCTION_ARGS  )

Definition at line 2561 of file numeric.c.

2562 {
2564  Numeric base = PG_GETARG_NUMERIC(1);
2565  Numeric offset = PG_GETARG_NUMERIC(2);
2566  bool sub = PG_GETARG_BOOL(3);
2567  bool less = PG_GETARG_BOOL(4);
2568  bool result;
2569 
2570  /*
2571  * Reject negative (including -Inf) or NaN offset. Negative is per spec,
2572  * and NaN is because appropriate semantics for that seem non-obvious.
2573  */
2574  if (NUMERIC_IS_NAN(offset) ||
2575  NUMERIC_IS_NINF(offset) ||
2576  NUMERIC_SIGN(offset) == NUMERIC_NEG)
2577  ereport(ERROR,
2578  (errcode(ERRCODE_INVALID_PRECEDING_OR_FOLLOWING_SIZE),
2579  errmsg("invalid preceding or following size in window function")));
2580 
2581  /*
2582  * Deal with cases where val and/or base is NaN, following the rule that
2583  * NaN sorts after non-NaN (cf cmp_numerics). The offset cannot affect
2584  * the conclusion.
2585  */
2586  if (NUMERIC_IS_NAN(val))
2587  {
2588  if (NUMERIC_IS_NAN(base))
2589  result = true; /* NAN = NAN */
2590  else
2591  result = !less; /* NAN > non-NAN */
2592  }
2593  else if (NUMERIC_IS_NAN(base))
2594  {
2595  result = less; /* non-NAN < NAN */
2596  }
2597 
2598  /*
2599  * Deal with infinite offset (necessarily +Inf, at this point).
2600  */
2601  else if (NUMERIC_IS_SPECIAL(offset))
2602  {
2603  Assert(NUMERIC_IS_PINF(offset));
2604  if (sub ? NUMERIC_IS_PINF(base) : NUMERIC_IS_NINF(base))
2605  {
2606  /*
2607  * base +/- offset would produce NaN, so return true for any val
2608  * (see in_range_float8_float8() for reasoning).
2609  */
2610  result = true;
2611  }
2612  else if (sub)
2613  {
2614  /* base - offset must be -inf */
2615  if (less)
2616  result = NUMERIC_IS_NINF(val); /* only -inf is <= sum */
2617  else
2618  result = true; /* any val is >= sum */
2619  }
2620  else
2621  {
2622  /* base + offset must be +inf */
2623  if (less)
2624  result = true; /* any val is <= sum */
2625  else
2626  result = NUMERIC_IS_PINF(val); /* only +inf is >= sum */
2627  }
2628  }
2629 
2630  /*
2631  * Deal with cases where val and/or base is infinite. The offset, being
2632  * now known finite, cannot affect the conclusion.
2633  */
2634  else if (NUMERIC_IS_SPECIAL(val))
2635  {
2636  if (NUMERIC_IS_PINF(val))
2637  {
2638  if (NUMERIC_IS_PINF(base))
2639  result = true; /* PINF = PINF */
2640  else
2641  result = !less; /* PINF > any other non-NAN */
2642  }
2643  else /* val must be NINF */
2644  {
2645  if (NUMERIC_IS_NINF(base))
2646  result = true; /* NINF = NINF */
2647  else
2648  result = less; /* NINF < anything else */
2649  }
2650  }
2651  else if (NUMERIC_IS_SPECIAL(base))
2652  {
2653  if (NUMERIC_IS_NINF(base))
2654  result = !less; /* normal > NINF */
2655  else
2656  result = less; /* normal < PINF */
2657  }
2658  else
2659  {
2660  /*
2661  * Otherwise go ahead and compute base +/- offset. While it's
2662  * possible for this to overflow the numeric format, it's unlikely
2663  * enough that we don't take measures to prevent it.
2664  */
2665  NumericVar valv;
2666  NumericVar basev;
2667  NumericVar offsetv;
2668  NumericVar sum;
2669 
2670  init_var_from_num(val, &valv);
2671  init_var_from_num(base, &basev);
2672  init_var_from_num(offset, &offsetv);
2673  init_var(&sum);
2674 
2675  if (sub)
2676  sub_var(&basev, &offsetv, &sum);
2677  else
2678  add_var(&basev, &offsetv, &sum);
2679 
2680  if (less)
2681  result = (cmp_var(&valv, &sum) <= 0);
2682  else
2683  result = (cmp_var(&valv, &sum) >= 0);
2684 
2685  free_var(&sum);
2686  }
2687 
2688  PG_FREE_IF_COPY(val, 0);
2689  PG_FREE_IF_COPY(base, 1);
2690  PG_FREE_IF_COPY(offset, 2);
2691 
2692  PG_RETURN_BOOL(result);
2693 }
#define PG_FREE_IF_COPY(ptr, n)
Definition: fmgr.h:260
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
#define PG_RETURN_BOOL(x)
Definition: fmgr.h:359

References add_var(), Assert(), cmp_var(), ereport, errcode(), errmsg(), ERROR, free_var(), init_var, init_var_from_num(), NUMERIC_IS_NAN, NUMERIC_IS_NINF, NUMERIC_IS_PINF, NUMERIC_IS_SPECIAL, NUMERIC_NEG, NUMERIC_SIGN, PG_FREE_IF_COPY, PG_GETARG_BOOL, PG_GETARG_NUMERIC, PG_RETURN_BOOL, sub_var(), and val.

◆ init_var_from_num()

◆ int2_accum()

Datum int2_accum ( PG_FUNCTION_ARGS  )

Definition at line 5472 of file numeric.c.

5473 {
5475 
5476  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
5477 
5478  /* Create the state data on the first call */
5479  if (state == NULL)
5480  state = makePolyNumAggState(fcinfo, true);
5481 
5482  if (!PG_ARGISNULL(1))
5483  {
5484 #ifdef HAVE_INT128
5485  do_int128_accum(state, (int128) PG_GETARG_INT16(1));
5486 #else
5488 #endif
5489  }
5490 
5492 }
#define makePolyNumAggState
Definition: numeric.c:5467
Numeric int64_to_numeric(int64 val)
Definition: numeric.c:4232
static void do_numeric_accum(NumericAggState *state, Numeric newval)
Definition: numeric.c:4779
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
#define PG_RETURN_POINTER(x)
Definition: fmgr.h:361
#define PG_GETARG_INT16(n)
Definition: fmgr.h:271

References do_numeric_accum(), int64_to_numeric(), makePolyNumAggState, PG_ARGISNULL, PG_GETARG_INT16, PG_GETARG_POINTER, and PG_RETURN_POINTER.

◆ int2_accum_inv()

Datum int2_accum_inv ( PG_FUNCTION_ARGS  )

Definition at line 5896 of file numeric.c.

5897 {
5899 
5900  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
5901 
5902  /* Should not get here with no state */
5903  if (state == NULL)
5904  elog(ERROR, "int2_accum_inv called with NULL state");
5905 
5906  if (!PG_ARGISNULL(1))
5907  {
5908 #ifdef HAVE_INT128
5909  do_int128_discard(state, (int128) PG_GETARG_INT16(1));
5910 #else
5911  /* Should never fail, all inputs have dscale 0 */
5913  elog(ERROR, "do_numeric_discard failed unexpectedly");
5914 #endif
5915  }
5916 
5918 }
static bool do_numeric_discard(NumericAggState *state, Numeric newval)
Definition: numeric.c:4849

References do_numeric_discard(), elog(), ERROR, int64_to_numeric(), PG_ARGISNULL, PG_GETARG_INT16, PG_GETARG_POINTER, and PG_RETURN_POINTER.

◆ int2_avg_accum()

Datum int2_avg_accum ( PG_FUNCTION_ARGS  )

Definition at line 6579 of file numeric.c.

6580 {
6581  ArrayType *transarray;
6583  Int8TransTypeData *transdata;
6584 
6585  /*
6586  * If we're invoked as an aggregate, we can cheat and modify our first
6587  * parameter in-place to reduce palloc overhead. Otherwise we need to make
6588  * a copy of it before scribbling on it.
6589  */
6590  if (AggCheckCallContext(fcinfo, NULL))
6591  transarray = PG_GETARG_ARRAYTYPE_P(0);
6592  else
6593  transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6594 
6595  if (ARR_HASNULL(transarray) ||
6596  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6597  elog(ERROR, "expected 2-element int8 array");
6598 
6599  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6600  transdata->count++;
6601  transdata->sum += newval;
6602 
6603  PG_RETURN_ARRAYTYPE_P(transarray);
6604 }
#define PG_GETARG_ARRAYTYPE_P_COPY(n)
Definition: array.h:264
#define PG_GETARG_ARRAYTYPE_P(n)
Definition: array.h:263
#define ARR_DATA_PTR(a)
Definition: array.h:322
#define PG_RETURN_ARRAYTYPE_P(x)
Definition: array.h:265
#define ARR_SIZE(a)
Definition: array.h:289
#define ARR_OVERHEAD_NONULLS(ndims)
Definition: array.h:310
#define ARR_HASNULL(a)
Definition: array.h:291
int AggCheckCallContext(FunctionCallInfo fcinfo, MemoryContext *aggcontext)
Definition: nodeAgg.c:4512

References AggCheckCallContext(), ARR_DATA_PTR, ARR_HASNULL, ARR_OVERHEAD_NONULLS, ARR_SIZE, Int8TransTypeData::count, elog(), ERROR, newval, PG_GETARG_ARRAYTYPE_P, PG_GETARG_ARRAYTYPE_P_COPY, PG_GETARG_INT16, PG_RETURN_ARRAYTYPE_P, and Int8TransTypeData::sum.

◆ int2_avg_accum_inv()

Datum int2_avg_accum_inv ( PG_FUNCTION_ARGS  )

Definition at line 6666 of file numeric.c.

6667 {
6668  ArrayType *transarray;
6670  Int8TransTypeData *transdata;
6671 
6672  /*
6673  * If we're invoked as an aggregate, we can cheat and modify our first
6674  * parameter in-place to reduce palloc overhead. Otherwise we need to make
6675  * a copy of it before scribbling on it.
6676  */
6677  if (AggCheckCallContext(fcinfo, NULL))
6678  transarray = PG_GETARG_ARRAYTYPE_P(0);
6679  else
6680  transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6681 
6682  if (ARR_HASNULL(transarray) ||
6683  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6684  elog(ERROR, "expected 2-element int8 array");
6685 
6686  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6687  transdata->count--;
6688  transdata->sum -= newval;
6689 
6690  PG_RETURN_ARRAYTYPE_P(transarray);
6691 }

References AggCheckCallContext(), ARR_DATA_PTR, ARR_HASNULL, ARR_OVERHEAD_NONULLS, ARR_SIZE, Int8TransTypeData::count, elog(), ERROR, newval, PG_GETARG_ARRAYTYPE_P, PG_GETARG_ARRAYTYPE_P_COPY, PG_GETARG_INT16, PG_RETURN_ARRAYTYPE_P, and Int8TransTypeData::sum.

◆ int2_numeric()

Datum int2_numeric ( PG_FUNCTION_ARGS  )

Definition at line 4466 of file numeric.c.

4467 {
4468  int16 val = PG_GETARG_INT16(0);
4469 
4471 }

References int64_to_numeric(), PG_GETARG_INT16, PG_RETURN_NUMERIC, and val.

◆ int2_sum()

Datum int2_sum ( PG_FUNCTION_ARGS  )

Definition at line 6430 of file numeric.c.

6431 {
6432  int64 newval;
6433 
6434  if (PG_ARGISNULL(0))
6435  {
6436  /* No non-null input seen so far... */
6437  if (PG_ARGISNULL(1))
6438  PG_RETURN_NULL(); /* still no non-null */
6439  /* This is the first non-null input. */
6440  newval = (int64) PG_GETARG_INT16(1);
6442  }
6443 
6444  /*
6445  * If we're invoked as an aggregate, we can cheat and modify our first
6446  * parameter in-place to avoid palloc overhead. If not, we need to return
6447  * the new value of the transition variable. (If int8 is pass-by-value,
6448  * then of course this is useless as well as incorrect, so just ifdef it
6449  * out.)
6450  */
6451 #ifndef USE_FLOAT8_BYVAL /* controls int8 too */
6452  if (AggCheckCallContext(fcinfo, NULL))
6453  {
6454  int64 *oldsum = (int64 *) PG_GETARG_POINTER(0);
6455 
6456  /* Leave the running sum unchanged in the new input is null */
6457  if (!PG_ARGISNULL(1))
6458  *oldsum = *oldsum + (int64) PG_GETARG_INT16(1);
6459 
6460  PG_RETURN_POINTER(oldsum);
6461  }
6462  else
6463 #endif
6464  {
6465  int64 oldsum = PG_GETARG_INT64(0);
6466 
6467  /* Leave sum unchanged if new input is null. */
6468  if (PG_ARGISNULL(1))
6469  PG_RETURN_INT64(oldsum);
6470 
6471  /* OK to do the addition. */
6472  newval = oldsum + (int64) PG_GETARG_INT16(1);
6473 
6475  }
6476 }
#define PG_RETURN_INT64(x)
Definition: fmgr.h:368
#define PG_RETURN_NULL()
Definition: fmgr.h:345

References AggCheckCallContext(), newval, PG_ARGISNULL, PG_GETARG_INT16, PG_GETARG_INT64, PG_GETARG_POINTER, PG_RETURN_INT64, PG_RETURN_NULL, and PG_RETURN_POINTER.

◆ int2int4_sum()

Datum int2int4_sum ( PG_FUNCTION_ARGS  )

Definition at line 6749 of file numeric.c.

6750 {
6751  ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
6752  Int8TransTypeData *transdata;
6753 
6754  if (ARR_HASNULL(transarray) ||
6755  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6756  elog(ERROR, "expected 2-element int8 array");
6757  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6758 
6759  /* SQL defines SUM of no values to be NULL */
6760  if (transdata->count == 0)
6761  PG_RETURN_NULL();
6762 
6763  PG_RETURN_DATUM(Int64GetDatumFast(transdata->sum));
6764 }
#define Int64GetDatumFast(X)
Definition: postgres.h:554

References ARR_DATA_PTR, ARR_HASNULL, ARR_OVERHEAD_NONULLS, ARR_SIZE, Int8TransTypeData::count, elog(), ERROR, Int64GetDatumFast, PG_GETARG_ARRAYTYPE_P, PG_RETURN_DATUM, PG_RETURN_NULL, and Int8TransTypeData::sum.

◆ int4_accum()

Datum int4_accum ( PG_FUNCTION_ARGS  )

Definition at line 5495 of file numeric.c.

5496 {
5498 
5499  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
5500 
5501  /* Create the state data on the first call */
5502  if (state == NULL)
5503  state = makePolyNumAggState(fcinfo, true);
5504 
5505  if (!PG_ARGISNULL(1))
5506  {
5507 #ifdef HAVE_INT128
5508  do_int128_accum(state, (int128) PG_GETARG_INT32(1));
5509 #else
5511 #endif
5512  }
5513 
5515 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269

References do_numeric_accum(), int64_to_numeric(), makePolyNumAggState, PG_ARGISNULL, PG_GETARG_INT32, PG_GETARG_POINTER, and PG_RETURN_POINTER.

◆ int4_accum_inv()

Datum int4_accum_inv ( PG_FUNCTION_ARGS  )

Definition at line 5921 of file numeric.c.

5922 {
5924 
5925  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
5926 
5927  /* Should not get here with no state */
5928  if (state == NULL)
5929  elog(ERROR, "int4_accum_inv called with NULL state");
5930 
5931  if (!PG_ARGISNULL(1))
5932  {
5933 #ifdef HAVE_INT128
5934  do_int128_discard(state, (int128) PG_GETARG_INT32(1));
5935 #else
5936  /* Should never fail, all inputs have dscale 0 */
5938  elog(ERROR, "do_numeric_discard failed unexpectedly");
5939 #endif
5940  }
5941 
5943 }

References do_numeric_discard(), elog(), ERROR, int64_to_numeric(), PG_ARGISNULL, PG_GETARG_INT32, PG_GETARG_POINTER, and PG_RETURN_POINTER.

◆ int4_avg_accum()

Datum int4_avg_accum ( PG_FUNCTION_ARGS  )

Definition at line 6607 of file numeric.c.

6608 {
6609  ArrayType *transarray;
6611  Int8TransTypeData *transdata;
6612 
6613  /*
6614  * If we're invoked as an aggregate, we can cheat and modify our first
6615  * parameter in-place to reduce palloc overhead. Otherwise we need to make
6616  * a copy of it before scribbling on it.
6617  */
6618  if (AggCheckCallContext(fcinfo, NULL))
6619  transarray = PG_GETARG_ARRAYTYPE_P(0);
6620  else
6621  transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6622 
6623  if (ARR_HASNULL(transarray) ||
6624  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6625  elog(ERROR, "expected 2-element int8 array");
6626 
6627  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6628  transdata->count++;
6629  transdata->sum += newval;
6630 
6631  PG_RETURN_ARRAYTYPE_P(transarray);
6632 }

References AggCheckCallContext(), ARR_DATA_PTR, ARR_HASNULL, ARR_OVERHEAD_NONULLS, ARR_SIZE, Int8TransTypeData::count, elog(), ERROR, newval, PG_GETARG_ARRAYTYPE_P, PG_GETARG_ARRAYTYPE_P_COPY, PG_GETARG_INT32, PG_RETURN_ARRAYTYPE_P, and Int8TransTypeData::sum.

◆ int4_avg_accum_inv()

Datum int4_avg_accum_inv ( PG_FUNCTION_ARGS  )

Definition at line 6694 of file numeric.c.

6695 {
6696  ArrayType *transarray;
6698  Int8TransTypeData *transdata;
6699 
6700  /*
6701  * If we're invoked as an aggregate, we can cheat and modify our first
6702  * parameter in-place to reduce palloc overhead. Otherwise we need to make
6703  * a copy of it before scribbling on it.
6704  */
6705  if (AggCheckCallContext(fcinfo, NULL))
6706  transarray = PG_GETARG_ARRAYTYPE_P(0);
6707  else
6708  transarray = PG_GETARG_ARRAYTYPE_P_COPY(0);
6709 
6710  if (ARR_HASNULL(transarray) ||
6711  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6712  elog(ERROR, "expected 2-element int8 array");
6713 
6714  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6715  transdata->count--;
6716  transdata->sum -= newval;
6717 
6718  PG_RETURN_ARRAYTYPE_P(transarray);
6719 }

References AggCheckCallContext(), ARR_DATA_PTR, ARR_HASNULL, ARR_OVERHEAD_NONULLS, ARR_SIZE, Int8TransTypeData::count, elog(), ERROR, newval, PG_GETARG_ARRAYTYPE_P, PG_GETARG_ARRAYTYPE_P_COPY, PG_GETARG_INT32, PG_RETURN_ARRAYTYPE_P, and Int8TransTypeData::sum.

◆ int4_avg_combine()

Datum int4_avg_combine ( PG_FUNCTION_ARGS  )

Definition at line 6635 of file numeric.c.

6636 {
6637  ArrayType *transarray1;
6638  ArrayType *transarray2;
6639  Int8TransTypeData *state1;
6640  Int8TransTypeData *state2;
6641 
6642  if (!AggCheckCallContext(fcinfo, NULL))
6643  elog(ERROR, "aggregate function called in non-aggregate context");
6644 
6645  transarray1 = PG_GETARG_ARRAYTYPE_P(0);
6646  transarray2 = PG_GETARG_ARRAYTYPE_P(1);
6647 
6648  if (ARR_HASNULL(transarray1) ||
6649  ARR_SIZE(transarray1) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6650  elog(ERROR, "expected 2-element int8 array");
6651 
6652  if (ARR_HASNULL(transarray2) ||
6653  ARR_SIZE(transarray2) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6654  elog(ERROR, "expected 2-element int8 array");
6655 
6656  state1 = (Int8TransTypeData *) ARR_DATA_PTR(transarray1);
6657  state2 = (Int8TransTypeData *) ARR_DATA_PTR(transarray2);
6658 
6659  state1->count += state2->count;
6660  state1->sum += state2->sum;
6661 
6662  PG_RETURN_ARRAYTYPE_P(transarray1);
6663 }

References AggCheckCallContext(), ARR_DATA_PTR, ARR_HASNULL, ARR_OVERHEAD_NONULLS, ARR_SIZE, Int8TransTypeData::count, elog(), ERROR, PG_GETARG_ARRAYTYPE_P, PG_RETURN_ARRAYTYPE_P, and Int8TransTypeData::sum.

◆ int4_numeric()

Datum int4_numeric ( PG_FUNCTION_ARGS  )

Definition at line 4338 of file numeric.c.

4339 {
4340  int32 val = PG_GETARG_INT32(0);
4341 
4343 }

References int64_to_numeric(), PG_GETARG_INT32, PG_RETURN_NUMERIC, and val.

◆ int4_sum()

Datum int4_sum ( PG_FUNCTION_ARGS  )

Definition at line 6479 of file numeric.c.

6480 {
6481  int64 newval;
6482 
6483  if (PG_ARGISNULL(0))
6484  {
6485  /* No non-null input seen so far... */
6486  if (PG_ARGISNULL(1))
6487  PG_RETURN_NULL(); /* still no non-null */
6488  /* This is the first non-null input. */
6489  newval = (int64) PG_GETARG_INT32(1);
6491  }
6492 
6493  /*
6494  * If we're invoked as an aggregate, we can cheat and modify our first
6495  * parameter in-place to avoid palloc overhead. If not, we need to return
6496  * the new value of the transition variable. (If int8 is pass-by-value,
6497  * then of course this is useless as well as incorrect, so just ifdef it
6498  * out.)
6499  */
6500 #ifndef USE_FLOAT8_BYVAL /* controls int8 too */
6501  if (AggCheckCallContext(fcinfo, NULL))
6502  {
6503  int64 *oldsum = (int64 *) PG_GETARG_POINTER(0);
6504 
6505  /* Leave the running sum unchanged in the new input is null */
6506  if (!PG_ARGISNULL(1))
6507  *oldsum = *oldsum + (int64) PG_GETARG_INT32(1);
6508 
6509  PG_RETURN_POINTER(oldsum);
6510  }
6511  else
6512 #endif
6513  {
6514  int64 oldsum = PG_GETARG_INT64(0);
6515 
6516  /* Leave sum unchanged if new input is null. */
6517  if (PG_ARGISNULL(1))
6518  PG_RETURN_INT64(oldsum);
6519 
6520  /* OK to do the addition. */
6521  newval = oldsum + (int64) PG_GETARG_INT32(1);
6522 
6524  }
6525 }

References AggCheckCallContext(), newval, PG_ARGISNULL, PG_GETARG_INT32, PG_GETARG_INT64, PG_GETARG_POINTER, PG_RETURN_INT64, PG_RETURN_NULL, and PG_RETURN_POINTER.

◆ int64_div_fast_to_numeric()

Numeric int64_div_fast_to_numeric ( int64  val1,
int  log10val2 
)

Definition at line 4253 of file numeric.c.

4254 {
4255  Numeric res;
4256  NumericVar result;
4257  int rscale;
4258  int w;
4259  int m;
4260 
4261  init_var(&result);
4262 
4263  /* result scale */
4264  rscale = log10val2 < 0 ? 0 : log10val2;
4265 
4266  /* how much to decrease the weight by */
4267  w = log10val2 / DEC_DIGITS;
4268  /* how much is left to divide by */
4269  m = log10val2 % DEC_DIGITS;
4270  if (m < 0)
4271  {
4272  m += DEC_DIGITS;
4273  w--;
4274  }
4275 
4276  /*
4277  * If there is anything left to divide by (10^m with 0 < m < DEC_DIGITS),
4278  * multiply the dividend by 10^(DEC_DIGITS - m), and shift the weight by
4279  * one more.
4280  */
4281  if (m > 0)
4282  {
4283 #if DEC_DIGITS == 4
4284  static const int pow10[] = {1, 10, 100, 1000};
4285 #elif DEC_DIGITS == 2
4286  static const int pow10[] = {1, 10};
4287 #elif DEC_DIGITS == 1
4288  static const int pow10[] = {1};
4289 #else
4290 #error unsupported NBASE
4291 #endif
4292  int64 factor = pow10[DEC_DIGITS - m];
4293  int64 new_val1;
4294 
4295  StaticAssertDecl(lengthof(pow10) == DEC_DIGITS, "mismatch with DEC_DIGITS");
4296 
4297  if (unlikely(pg_mul_s64_overflow(val1, factor, &new_val1)))
4298  {
4299 #ifdef HAVE_INT128
4300  /* do the multiplication using 128-bit integers */
4301  int128 tmp;
4302 
4303  tmp = (int128) val1 * (int128) factor;
4304 
4305  int128_to_numericvar(tmp, &result);
4306 #else
4307  /* do the multiplication using numerics */
4308  NumericVar tmp;
4309 
4310  init_var(&tmp);
4311 
4312  int64_to_numericvar(val1, &result);
4313  int64_to_numericvar(factor, &tmp);
4314  mul_var(&result, &tmp, &result, 0);
4315 
4316  free_var(&tmp);
4317 #endif
4318  }
4319  else
4320  int64_to_numericvar(new_val1, &result);
4321 
4322  w++;
4323  }
4324  else
4325  int64_to_numericvar(val1, &result);
4326 
4327  result.weight -= w;
4328  result.dscale = rscale;
4329 
4330  res = make_result(&result);
4331 
4332  free_var(&result);
4333 
4334  return res;
4335 }
static void int64_to_numericvar(int64 val, NumericVar *var)
Definition: numeric.c:8026
#define unlikely(x)
Definition: c.h:300
#define lengthof(array)
Definition: c.h:777
#define StaticAssertDecl(condition, errmessage)
Definition: c.h:925
static bool pg_mul_s64_overflow(int64 a, int64 b, int64 *result)
Definition: int.h:219

References DEC_DIGITS, NumericVar::dscale, free_var(), init_var, int64_to_numericvar(), lengthof, make_result(), mul_var(), pg_mul_s64_overflow(), res, StaticAssertDecl, unlikely, and NumericVar::weight.

Referenced by interval_part_common(), time_part_common(), timestamp_part_common(), timestamptz_part_common(), and timetz_part_common().

◆ int64_to_numeric()

◆ int64_to_numericvar()

static void int64_to_numericvar ( int64  val,
NumericVar var 
)
static

Definition at line 8026 of file numeric.c.

8027 {
8028  uint64 uval,
8029  newuval;
8030  NumericDigit *ptr;
8031  int ndigits;
8032 
8033  /* int64 can require at most 19 decimal digits; add one for safety */
8034  alloc_var(var, 20 / DEC_DIGITS);
8035  if (val < 0)
8036  {
8037  var->sign = NUMERIC_NEG;
8038  uval = -val;
8039  }
8040  else
8041  {
8042  var->sign = NUMERIC_POS;
8043  uval = val;
8044  }
8045  var->dscale = 0;
8046  if (val == 0)
8047  {
8048  var->ndigits = 0;
8049  var->weight = 0;
8050  return;
8051  }
8052  ptr = var->digits + var->ndigits;
8053  ndigits = 0;
8054  do
8055  {
8056  ptr--;
8057  ndigits++;
8058  newuval = uval / NBASE;
8059  *ptr = uval - newuval * NBASE;
8060  uval = newuval;
8061  } while (uval);
8062  var->digits = ptr;
8063  var->ndigits = ndigits;
8064  var->weight = ndigits - 1;
8065 }

References alloc_var(), DEC_DIGITS, NumericVar::digits, NumericVar::dscale, NBASE, NumericVar::ndigits, NUMERIC_NEG, NUMERIC_POS, NumericVar::sign, val, and NumericVar::weight.

Referenced by int64_div_fast_to_numeric(), int64_to_numeric(), numeric_fac(), numeric_stddev_internal(), set_var_from_non_decimal_integer_str(), sqrt_var(), and width_bucket_numeric().

◆ int8_accum()

Datum int8_accum ( PG_FUNCTION_ARGS  )

Definition at line 5518 of file numeric.c.

5519 {
5521 
5522  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5523 
5524  /* Create the state data on the first call */
5525  if (state == NULL)
5526  state = makeNumericAggState(fcinfo, true);
5527 
5528  if (!PG_ARGISNULL(1))
5530 
5532 }
static NumericAggState * makeNumericAggState(FunctionCallInfo fcinfo, bool calcSumX2)
Definition: numeric.c:4739

References do_numeric_accum(), int64_to_numeric(), makeNumericAggState(), PG_ARGISNULL, PG_GETARG_INT64, PG_GETARG_POINTER, and PG_RETURN_POINTER.

◆ int8_accum_inv()

Datum int8_accum_inv ( PG_FUNCTION_ARGS  )

Definition at line 5946 of file numeric.c.

5947 {
5949 
5950  state = PG_ARGISNULL(0) ? NULL : (NumericAggState *) PG_GETARG_POINTER(0);
5951 
5952  /* Should not get here with no state */
5953  if (state == NULL)
5954  elog(ERROR, "int8_accum_inv called with NULL state");
5955 
5956  if (!PG_ARGISNULL(1))
5957  {
5958  /* Should never fail, all inputs have dscale 0 */
5960  elog(ERROR, "do_numeric_discard failed unexpectedly");
5961  }
5962 
5964 }

References do_numeric_discard(), elog(), ERROR, int64_to_numeric(), PG_ARGISNULL, PG_GETARG_INT64, PG_GETARG_POINTER, and PG_RETURN_POINTER.

◆ int8_avg()

Datum int8_avg ( PG_FUNCTION_ARGS  )

Definition at line 6722 of file numeric.c.

6723 {
6724  ArrayType *transarray = PG_GETARG_ARRAYTYPE_P(0);
6725  Int8TransTypeData *transdata;
6726  Datum countd,
6727  sumd;
6728 
6729  if (ARR_HASNULL(transarray) ||
6730  ARR_SIZE(transarray) != ARR_OVERHEAD_NONULLS(1) + sizeof(Int8TransTypeData))
6731  elog(ERROR, "expected 2-element int8 array");
6732  transdata = (Int8TransTypeData *) ARR_DATA_PTR(transarray);
6733 
6734  /* SQL defines AVG of no values to be NULL */
6735  if (transdata->count == 0)
6736  PG_RETURN_NULL();
6737 
6738  countd = NumericGetDatum(int64_to_numeric(transdata->count));
6739  sumd = NumericGetDatum(int64_to_numeric(transdata->sum));
6740 
6742 }
Datum numeric_div(PG_FUNCTION_ARGS)
Definition: numeric.c:3123
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:644

References ARR_DATA_PTR, ARR_HASNULL, ARR_OVERHEAD_NONULLS, ARR_SIZE, Int8TransTypeData::count, DirectFunctionCall2, elog(), ERROR, int64_to_numeric(), numeric_div(), NumericGetDatum(), PG_GETARG_ARRAYTYPE_P, PG_RETURN_DATUM, PG_RETURN_NULL, and Int8TransTypeData::sum.

◆ int8_avg_accum()

Datum int8_avg_accum ( PG_FUNCTION_ARGS  )

Definition at line 5714 of file numeric.c.

5715 {
5717 
5718  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
5719 
5720  /* Create the state data on the first call */
5721  if (state == NULL)
5722  state = makePolyNumAggState(fcinfo, false);
5723 
5724  if (!PG_ARGISNULL(1))
5725  {
5726 #ifdef HAVE_INT128
5727  do_int128_accum(state, (int128) PG_GETARG_INT64(1));
5728 #else
5730 #endif
5731  }
5732 
5734 }

References do_numeric_accum(), int64_to_numeric(), makePolyNumAggState, PG_ARGISNULL, PG_GETARG_INT64, PG_GETARG_POINTER, and PG_RETURN_POINTER.

◆ int8_avg_accum_inv()

Datum int8_avg_accum_inv ( PG_FUNCTION_ARGS  )

Definition at line 5967 of file numeric.c.

5968 {
5970 
5971  state = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
5972 
5973  /* Should not get here with no state */
5974  if (state == NULL)
5975  elog(ERROR, "int8_avg_accum_inv called with NULL state");
5976 
5977  if (!PG_ARGISNULL(1))
5978  {
5979 #ifdef HAVE_INT128
5980  do_int128_discard(state, (int128) PG_GETARG_INT64(1));
5981 #else
5982  /* Should never fail, all inputs have dscale 0 */
5984  elog(ERROR, "do_numeric_discard failed unexpectedly");
5985 #endif
5986  }
5987 
5989 }

References do_numeric_discard(), elog(), ERROR, int64_to_numeric(), PG_ARGISNULL, PG_GETARG_INT64, PG_GETARG_POINTER, and PG_RETURN_POINTER.

◆ int8_avg_combine()

Datum int8_avg_combine ( PG_FUNCTION_ARGS  )

Definition at line 5741 of file numeric.c.

5742 {
5743  PolyNumAggState *state1;
5744  PolyNumAggState *state2;
5745  MemoryContext agg_context;
5746  MemoryContext old_context;
5747 
5748  if (!AggCheckCallContext(fcinfo, &agg_context))
5749  elog(ERROR, "aggregate function called in non-aggregate context");
5750 
5751  state1 = PG_ARGISNULL(0) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(0);
5752  state2 = PG_ARGISNULL(1) ? NULL : (PolyNumAggState *) PG_GETARG_POINTER(1);
5753 
5754  if (state2 == NULL)
5755  PG_RETURN_POINTER(state1);
5756 
5757  /* manually copy all fields from state2 to state1 */
5758  if (state1 == NULL)
5759  {
5760  old_context = MemoryContextSwitchTo(agg_context);
5761 
5762  state1 = makePolyNumAggState(fcinfo, false);
5763  state1->N = state2->N;
5764 
5765 #ifdef HAVE_INT128
5766  state1->sumX = state2->sumX;
5767 #else
5768  accum_sum_copy(&state1->sumX, &state2->sumX);
5769 #endif
5770  MemoryContextSwitchTo(old_context);
5771 
5772  PG_RETURN_POINTER(state1);
5773  }
5774 
5775  if (state2->N > 0)
5776  {
5777  state1->N += state2->N;
5778 
5779 #ifdef HAVE_INT128
5780  state1->sumX += state2->sumX;
5781 #else
5782  /* The rest of this needs to work in the aggregate context */
5783  old_context = MemoryContextSwitchTo(agg_context);
5784 
5785  /* Accumulate sums */
5786  accum_sum_combine(&state1->sumX, &state2->sumX);
5787 
5788  MemoryContextSwitchTo(old_context);
5789 #endif
5790 
5791  }
5792  PG_RETURN_POINTER(state1);
5793 }
static void accum_sum_combine(NumericSumAccum *accum, NumericSumAccum *accum2)
Definition: numeric.c:12007
static void accum_sum_copy(NumericSumAccum *dst, NumericSumAccum *src)
Definition: numeric.c:11990
NumericSumAccum sumX
Definition: numeric.c:4721

References accum_sum_combine(), accum_sum_copy(), AggCheckCallContext(), elog(), ERROR, makePolyNumAggState, MemoryContextSwitchTo(), NumericAggState::N, PG_ARGISNULL, PG_GETARG_POINTER, PG_RETURN_POINTER, and NumericAggState::sumX.

◆ int8_avg_deserialize()

Datum int8_avg_deserialize ( PG_FUNCTION_ARGS  )

Definition at line 5850 of file numeric.c.

5851 {
5852  bytea *sstate;
5853  PolyNumAggState *result;
5855  NumericVar tmp_var;
5856 
5857  if (!AggCheckCallContext(fcinfo, NULL))
5858  elog(ERROR, "aggregate function called in non-aggregate context");
5859 
5860  sstate = PG_GETARG_BYTEA_PP(0);
5861 
5862  init_var(&tmp_var);
5863 
5864  /*
5865  * Initialize a StringInfo so that we can "receive" it using the standard
5866  * recv-function infrastructure.
5867  */
5869  VARSIZE_ANY_EXHDR(sstate));
5870 
5871  result = makePolyNumAggStateCurrentContext(false);
5872 
5873  /* N */
5874  result->N = pq_getmsgint64(&buf);
5875 
5876  /* sumX */
5877  numericvar_deserialize(&buf, &tmp_var);
5878 #ifdef HAVE_INT128
5879  numericvar_to_int128(&tmp_var, &result->sumX);
5880 #else
5881  accum_sum_add(&result->sumX, &tmp_var);
5882 #endif
5883 
5884  pq_getmsgend(&buf);
5885 
5886  free_var(&tmp_var);
5887 
5888  PG_RETURN_POINTER(result);
5889 }
static void numericvar_deserialize(StringInfo buf, NumericVar *var)
Definition: numeric.c:7662
#define makePolyNumAggStateCurrentContext
Definition: numeric.c:5468
#define PG_GETARG_BYTEA_PP(n)
Definition: fmgr.h:308
void pq_getmsgend(StringInfo msg)
Definition: pqformat.c:638
int64 pq_getmsgint64(StringInfo msg)
Definition: pqformat.c:456
static void initReadOnlyStringInfo(StringInfo str, char *data, int len)
Definition: stringinfo.h:129
Definition: c.h:676
#define VARDATA_ANY(PTR)
Definition: varatt.h:324
#define VARSIZE_ANY_EXHDR(PTR)
Definition: varatt.h:317

References accum_sum_add(), AggCheckCallContext(), buf, elog(), ERROR, free_var(), init_var, initReadOnlyStringInfo(), makePolyNumAggStateCurrentContext, NumericAggState::N, numericvar_deserialize(), PG_GETARG_BYTEA_PP, PG_RETURN_POINTER, pq_getmsgend(), pq_getmsgint64(), NumericAggState::sumX, VARDATA_ANY, and VARSIZE_ANY_EXHDR.

◆ int8_avg_serialize()

Datum int8_avg_serialize ( PG_FUNCTION_ARGS  )

Definition at line 5801 of file numeric.c.

5802 {