From 43c315182dc281dd8120dd75bb35b9407e4c5981 Mon Sep 17 00:00:00 2001
From: Josh Hurst <joshhurst77@gmail.com>
Date: Fri, 27 Nov 2026 18:51:33 -0500
Subject: [PATCH] Use fixed-width arithmetic for short numeric operands

Test both varlena lengths and numeric headers before reading digits.
Add and subtract a four-digit span in int64. For multiplication, split
each operand into digit pairs so the partial products fit in uint64.

For larger operands use the regular arithmetic functions. Adapt the
local-buffer conversion from Andrei Lepikhov's November 24 v2 to align
packed heap arguments for those functions without a palloc per input.
---
 src/backend/utils/adt/numeric.c       | 343 ++++++++++++++++++++++++--
 src/test/regress/expected/numeric.out |  86 +++++++
 src/test/regress/sql/numeric.sql      |  27 ++
 src/tools/pgindent/typedefs.list      |   2 +
 4 files changed, 442 insertions(+), 16 deletions(-)

diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c
index ff6dec4..ff2c7d6 100644
--- a/src/backend/utils/adt/numeric.c
+++ b/src/backend/utils/adt/numeric.c
@@ -608,6 +608,91 @@ 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);
 
+#if DEC_DIGITS == 4
+
+/*
+ * Unpacked representation of an inline (uncompressed, non-external)
+ * NUMERIC_SHORT datum.  Long, special (NaN/Inf), and TOASTed values return
+ * false from numeric_is_small() and fall back to the general paths.
+ */
+typedef struct UnpackedNumeric
+{
+	int			sign;			/* NUMERIC_POS or NUMERIC_NEG */
+	int			weight;
+	int			dscale;
+	int			ndigits;
+	const char *digits_ptr;		/* raw NumericDigit bytes (may be unaligned) */
+} UnpackedNumeric;
+
+/*
+ * unpacked_digit() -
+ *
+ *	Fetch the i'th base-NBASE digit from an UnpackedNumeric.  Uses memcpy
+ *	because a 1-byte-header varlena may not be aligned to NumericDigit.
+ */
+static inline NumericDigit
+unpacked_digit(const UnpackedNumeric *u, int i)
+{
+	NumericDigit d;
+
+	Assert(i >= 0 && i < u->ndigits);
+	memcpy(&d, u->digits_ptr + i * sizeof(NumericDigit), sizeof(NumericDigit));
+	return d;
+}
+
+/*
+ * Test the varlena size before reading the numeric header.  In particular,
+ * VARSIZE_SHORT is zero for an external pointer.
+ */
+static inline bool
+numeric_is_small(Datum d)
+{
+	const char *p = DatumGetPointer(d);
+	const char *body;
+	Size		len;
+	uint16		hdr;
+
+	if (VARATT_IS_SHORT(p))
+	{
+		len = VARSIZE_SHORT(p) - VARHDRSZ_SHORT;
+		body = VARDATA_SHORT(p);
+	}
+	else if (!VARATT_IS_EXTENDED(p))
+	{
+		len = VARSIZE_4B(p) - VARHDRSZ;
+		body = VARDATA_4B(p);
+	}
+	else
+		return false;
+
+	if (len > sizeof(hdr) + 4 * sizeof(NumericDigit))
+		return false;
+	memcpy(&hdr, body, sizeof(hdr));
+	return (hdr & NUMERIC_SIGN_MASK) == NUMERIC_SHORT;
+}
+
+/* Decode a datum already checked by numeric_is_small(). */
+static inline void
+unpack_numeric_short(Datum d, UnpackedNumeric *u)
+{
+	const char *p = DatumGetPointer(d);
+	const char *body = VARDATA_ANY(p);
+	Size		len = VARATT_IS_SHORT(p) ? VARSIZE_SHORT(p) - VARHDRSZ_SHORT :
+		VARSIZE_4B(p) - VARHDRSZ;
+	uint16		hdr;
+
+	memcpy(&hdr, body, sizeof(hdr));
+	u->ndigits = (len - sizeof(hdr)) / sizeof(NumericDigit);
+	u->sign = (hdr & NUMERIC_SHORT_SIGN_MASK) ? NUMERIC_NEG : NUMERIC_POS;
+	u->dscale = (hdr & NUMERIC_SHORT_DSCALE_MASK) >>
+		NUMERIC_SHORT_DSCALE_SHIFT;
+	u->weight = (hdr & NUMERIC_SHORT_WEIGHT_SIGN_MASK ?
+				 ~NUMERIC_SHORT_WEIGHT_MASK : 0) |
+		(hdr & NUMERIC_SHORT_WEIGHT_MASK);
+	u->digits_ptr = body + sizeof(uint16);
+}
+
+#endif							/* DEC_DIGITS == 4 */
 
 /* ----------------------------------------------------------------------
  *
@@ -2859,24 +2944,241 @@ hash_numeric_extended(PG_FUNCTION_ARGS)
  * ----------------------------------------------------------------------
  */
 
+#if DEC_DIGITS == 4
+
+/* Use the usual normalization and overflow checks for the result. */
+static inline Numeric
+make_result_from_digits(NumericDigit *digits, int n, int weight,
+						int sign, int dscale)
+{
+	NumericVar	var = {n, weight, sign, dscale, NULL, digits};
+
+	return make_result(&var);
+}
 
 /*
- * numeric_add() -
+ * unpacked_to_scaled_i64() -
  *
- *	Add two numerics
+ *	Convert an UnpackedNumeric whose least significant digit has weight 'low'
+ *	into a signed int64 scaled to base-NBASE weight 'low_w'.  Caller must
+ *	guarantee that the scaled value fits within 4 NBASE digits (< 10^16).
  */
-Datum
-numeric_add(PG_FUNCTION_ARGS)
+static inline int64
+unpacked_to_scaled_i64(const UnpackedNumeric *u, int low, int low_w)
 {
-	Numeric		num1 = PG_GETARG_NUMERIC(0);
-	Numeric		num2 = PG_GETARG_NUMERIC(1);
+	int64		v = 0;
+
+	for (int i = 0; i < u->ndigits; i++)
+		v = v * NBASE + unpacked_digit(u, i);
+	for (int s = low; s > low_w; s--)
+		v *= NBASE;
+	return (u->sign == NUMERIC_NEG) ? -v : v;
+}
+
+/*
+ * numeric_addsub_short() -
+ *
+ *	Fast path for adding or subtracting two unpacked NUMERIC_SHORT values
+ *	whose combined digit span fits in 4 base-10000 digits.  Each scaled
+ *	operand is bounded by 10^16 - 1, so the sum/difference fits in int64
+ *	without overflow and produces at most 5 NBASE digits.  Returns NULL if
+ *	the combined span exceeds 4 digits so the caller can fall back.
+ */
+static pg_noinline Numeric
+numeric_addsub_short(Datum d1, Datum d2, bool is_sub)
+{
+	UnpackedNumeric u1,
+				u2;
+	int			res_dscale;
+	int			low1,
+				low2,
+				low_w,
+				hi_w;
+	int			pos = 5;
+	int			ndigits;
+	int64		v1,
+				v2,
+				sum;
+	uint64		mag;
+	NumericDigit buf[5];
+
+	unpack_numeric_short(d1, &u1);
+	unpack_numeric_short(d2, &u2);
+	res_dscale = Max(u1.dscale, u2.dscale);
+
+	if (u1.ndigits == 0 && u2.ndigits == 0)
+		return make_result_from_digits(NULL, 0, 0, NUMERIC_POS,
+									   res_dscale);
+
+	if (u1.ndigits > 0)
+		low1 = u1.weight - u1.ndigits + 1;
+	else
+		low1 = u2.weight - u2.ndigits + 1;
+
+	if (u2.ndigits > 0)
+		low2 = u2.weight - u2.ndigits + 1;
+	else
+		low2 = low1;
+
+	low_w = Min(low1, low2);
+	if (u1.ndigits == 0)
+		hi_w = u2.weight;
+	else if (u2.ndigits == 0)
+		hi_w = u1.weight;
+	else
+		hi_w = Max(u1.weight, u2.weight);
+
+	if (hi_w - low_w > 3)
+		return NULL;
+
+	v1 = unpacked_to_scaled_i64(&u1, low1, low_w);
+	v2 = unpacked_to_scaled_i64(&u2, low2, low_w);
+	sum = is_sub ? (v1 - v2) : (v1 + v2);
+	if (sum == 0)
+		return make_result_from_digits(NULL, 0, 0, NUMERIC_POS,
+									   res_dscale);
+
+	mag = (uint64) (sum < 0 ? -sum : sum);
+	do
+	{
+		buf[--pos] = (NumericDigit) (mag % NBASE);
+		mag /= NBASE;
+	} while (mag > 0);
+	ndigits = 5 - pos;
+	return make_result_from_digits(&buf[pos], ndigits, low_w + ndigits - 1,
+								   sum < 0 ? NUMERIC_NEG : NUMERIC_POS,
+								   res_dscale);
+}
+
+/*
+ * Split a product into base-10000 digits.  Multiplying two base-10000
+ * digit pairs fits in uint64, including the two middle partial products
+ * and the carry from the low pair.  This avoids wide integer division.
+ */
+static pg_noinline Numeric
+numeric_mul_short(Datum d1, Datum d2)
+{
+	UnpackedNumeric a,
+				b;
+	NumericDigit buf[8];
+	int			pos = lengthof(buf);
+	int			weight;
+	int			sign;
+	uint64		x = 0,
+				y = 0,
+				product;
+
+	unpack_numeric_short(d1, &a);
+	unpack_numeric_short(d2, &b);
+	sign = a.sign == b.sign ? NUMERIC_POS : NUMERIC_NEG;
+	for (int i = 0; i < a.ndigits; i++)
+		x = x * NBASE + unpacked_digit(&a, i);
+	for (int i = 0; i < b.ndigits; i++)
+		y = y * NBASE + unpacked_digit(&b, i);
+
+	if (a.ndigits + b.ndigits <= 4)
+		product = x * y;
+	else
+	{
+		uint64		xhi = x / NBASE_SQR,
+					xlo = x % NBASE_SQR;
+		uint64		yhi = y / NBASE_SQR,
+					ylo = y % NBASE_SQR;
+		uint64		lo = xlo * ylo;
+		uint64		mid = xhi * ylo + xlo * yhi + lo / NBASE_SQR;
+
+		lo %= NBASE_SQR;
+		buf[--pos] = lo % NBASE;
+		buf[--pos] = lo / NBASE;
+		product = xhi * yhi + mid / NBASE_SQR;
+		mid %= NBASE_SQR;
+		buf[--pos] = mid % NBASE;
+		buf[--pos] = mid / NBASE;
+	}
+	while (product)
+	{
+		buf[--pos] = product % NBASE;
+		product /= NBASE;
+	}
+
+	weight = a.weight + b.weight + 1 - a.ndigits - b.ndigits +
+		(int) lengthof(buf) - pos;
+	return make_result_from_digits(buf + pos, lengthof(buf) - pos, weight,
+								   sign, a.dscale + b.dscale);
+}
+
+#endif							/* DEC_DIGITS == 4 */
+
+
+/* An aligned Numeric large enough for any inline one-byte varlena. */
+typedef union NumericLocalBuf
+{
+	struct NumericData num;
+	char		data[VARHDRSZ + VARATT_SHORT_MAX - VARHDRSZ_SHORT];
+} NumericLocalBuf;
+
+/*
+ * Provide aligned operands for the ordinary numeric arithmetic functions.
+ * A result pointing into the local buffer is valid only during this call.
+ */
+static inline Numeric
+DatumGetNumericLocal(Datum d, NumericLocalBuf *buf)
+{
+	const char *p = DatumGetPointer(d);
+
+	if (VARATT_IS_SHORT(p) && !VARATT_IS_EXTERNAL(p))
+	{
+		Size		len = VARSIZE_SHORT(p) - VARHDRSZ_SHORT;
+
+		SET_VARSIZE(&buf->num, VARHDRSZ + len);
+		memcpy(VARDATA(&buf->num), VARDATA_SHORT(p), len);
+		return &buf->num;
+	}
+	return DatumGetNumeric(d);
+}
+
+
+/* The two operators also share the same operand preparation on fallback. */
+static Datum
+numeric_addsub(FunctionCallInfo fcinfo, bool subtract)
+{
+	NumericLocalBuf buf1,
+				buf2;
+	Numeric		num1;
+	Numeric		num2;
 	Numeric		res;
 
-	res = numeric_add_safe(num1, num2, NULL);
+#if DEC_DIGITS == 4
+	Datum		d1 = PG_GETARG_DATUM(0);
+	Datum		d2 = PG_GETARG_DATUM(1);
+
+	if (numeric_is_small(d1) && numeric_is_small(d2))
+	{
+		res = numeric_addsub_short(d1, d2, subtract);
+		if (res != NULL)
+			PG_RETURN_NUMERIC(res);
+	}
+#endif
+
+	num1 = DatumGetNumericLocal(PG_GETARG_DATUM(0), &buf1);
+	num2 = DatumGetNumericLocal(PG_GETARG_DATUM(1), &buf2);
+	res = subtract ? numeric_sub_safe(num1, num2, NULL) :
+		numeric_add_safe(num1, num2, NULL);
 
 	PG_RETURN_NUMERIC(res);
 }
 
+/*
+ * numeric_add() -
+ *
+ *	Add two numerics
+ */
+Datum
+numeric_add(PG_FUNCTION_ARGS)
+{
+	return numeric_addsub(fcinfo, false);
+}
+
 /*
  * numeric_add_safe() -
  *
@@ -2943,13 +3245,7 @@ numeric_add_safe(Numeric num1, Numeric num2, Node *escontext)
 Datum
 numeric_sub(PG_FUNCTION_ARGS)
 {
-	Numeric		num1 = PG_GETARG_NUMERIC(0);
-	Numeric		num2 = PG_GETARG_NUMERIC(1);
-	Numeric		res;
-
-	res = numeric_sub_safe(num1, num2, NULL);
-
-	PG_RETURN_NUMERIC(res);
+	return numeric_addsub(fcinfo, true);
 }
 
 
@@ -3019,10 +3315,25 @@ numeric_sub_safe(Numeric num1, Numeric num2, Node *escontext)
 Datum
 numeric_mul(PG_FUNCTION_ARGS)
 {
-	Numeric		num1 = PG_GETARG_NUMERIC(0);
-	Numeric		num2 = PG_GETARG_NUMERIC(1);
+	NumericLocalBuf buf1,
+				buf2;
+	Numeric		num1;
+	Numeric		num2;
 	Numeric		res;
 
+#if DEC_DIGITS == 4
+	Datum		d1 = PG_GETARG_DATUM(0);
+	Datum		d2 = PG_GETARG_DATUM(1);
+
+	if (fcinfo->context == NULL &&
+		numeric_is_small(d1) && numeric_is_small(d2))
+	{
+		PG_RETURN_NUMERIC(numeric_mul_short(d1, d2));
+	}
+#endif
+
+	num1 = DatumGetNumericLocal(PG_GETARG_DATUM(0), &buf1);
+	num2 = DatumGetNumericLocal(PG_GETARG_DATUM(1), &buf2);
 	res = numeric_mul_safe(num1, num2, fcinfo->context);
 
 	if (unlikely(SOFT_ERROR_OCCURRED(fcinfo->context)))
diff --git a/src/test/regress/expected/numeric.out b/src/test/regress/expected/numeric.out
index 8e6b5ec..7427920 100644
--- a/src/test/regress/expected/numeric.out
+++ b/src/test/regress/expected/numeric.out
@@ -3933,3 +3933,89 @@ SELECT pg_lsn(18446744073709551616::numeric);
 ERROR:  pg_lsn out of range
 SELECT pg_lsn('NaN'::numeric);
 ERROR:  cannot convert NaN to pg_lsn
+-- Arithmetic across the four-base-digit limit, including a carry or borrow.
+SELECT 9999999999999999::numeric + 9999999999999999,
+       -9999999999999999::numeric - 1;
+     ?column?      |      ?column?      
+-------------------+--------------------
+ 19999999999999998 | -10000000000000000
+(1 row)
+
+SELECT 100000000::numeric + 0.0001, 1000000000000::numeric + 0.0001;
+    ?column?    |      ?column?      
+----------------+--------------------
+ 100000000.0001 | 1000000000000.0001
+(1 row)
+
+SELECT 0.0001::numeric - 100000000, 123.4500::numeric - 123.45;
+    ?column?    | ?column? 
+----------------+----------
+ -99999999.9999 |   0.0000
+(1 row)
+
+SELECT 0.00::numeric + 0.0000, 9999e252::numeric + 9999e252 = 19998e252;
+ ?column? | ?column? 
+----------+----------
+   0.0000 | t
+(1 row)
+
+SELECT (1e-256::numeric + 1e-264) - 1e-256 = 1e-264;
+ ?column? 
+----------
+ t
+(1 row)
+
+SELECT 9999::numeric * 9999, 99999999::numeric * 99999999;
+ ?column? |     ?column?     
+----------+------------------
+ 99980001 | 9999999800000001
+(1 row)
+
+SELECT 9999999999999999::numeric * 9999999999999999;
+             ?column?             
+----------------------------------
+ 99999999999999980000000000000001
+(1 row)
+
+SELECT 10000000000000001::numeric * 10000000000000001;
+             ?column?              
+-----------------------------------
+ 100000000000000020000000000000001
+(1 row)
+
+SELECT -12345.6789::numeric * 9876.5432, -12345.6789::numeric * -9876.5432;
+      ?column?       |      ?column?      
+---------------------+--------------------
+ -121932630.98917848 | 121932630.98917848
+(1 row)
+
+SELECT 0.00::numeric * 123.456, scale(1e-40::numeric * 1e-40);
+ ?column? | scale 
+----------+-------
+  0.00000 |    80
+(1 row)
+
+SELECT 'NaN'::numeric + 1, 'Infinity'::numeric - 'Infinity',
+       0 * 'Inf'::numeric;
+ ?column? | ?column? | ?column? 
+----------+----------+----------
+      NaN |      NaN |      NaN
+(1 row)
+
+SELECT 1e70000::numeric * 1e70000::numeric;
+ERROR:  value overflows numeric format
+-- Check both operand orders with compressed and external inputs.
+CREATE TEMP TABLE num_toast_arith (
+    s numeric, e numeric STORAGE EXTERNAL, c numeric STORAGE MAIN
+);
+INSERT INTO num_toast_arith
+SELECT 42.50, v, 2 * v FROM (SELECT repeat('1234567890', 1000)::numeric v) t;
+SELECT pg_column_compression(c) IS NOT NULL AS compressed,
+       (e + s) - e AS delta, (s - c) + c AS diff, 2 * e = c AS product
+FROM num_toast_arith;
+ compressed | delta | diff  | product 
+------------+-------+-------+---------
+ t          | 42.50 | 42.50 | t
+(1 row)
+
+DROP TABLE num_toast_arith;
diff --git a/src/test/regress/sql/numeric.sql b/src/test/regress/sql/numeric.sql
index 9bb6feb..19b0420 100644
--- a/src/test/regress/sql/numeric.sql
+++ b/src/test/regress/sql/numeric.sql
@@ -1598,3 +1598,30 @@ SELECT pg_lsn(18446744073709551615::numeric);
 SELECT pg_lsn(-1::numeric);
 SELECT pg_lsn(18446744073709551616::numeric);
 SELECT pg_lsn('NaN'::numeric);
+
+-- Arithmetic across the four-base-digit limit, including a carry or borrow.
+SELECT 9999999999999999::numeric + 9999999999999999,
+       -9999999999999999::numeric - 1;
+SELECT 100000000::numeric + 0.0001, 1000000000000::numeric + 0.0001;
+SELECT 0.0001::numeric - 100000000, 123.4500::numeric - 123.45;
+SELECT 0.00::numeric + 0.0000, 9999e252::numeric + 9999e252 = 19998e252;
+SELECT (1e-256::numeric + 1e-264) - 1e-256 = 1e-264;
+SELECT 9999::numeric * 9999, 99999999::numeric * 99999999;
+SELECT 9999999999999999::numeric * 9999999999999999;
+SELECT 10000000000000001::numeric * 10000000000000001;
+SELECT -12345.6789::numeric * 9876.5432, -12345.6789::numeric * -9876.5432;
+SELECT 0.00::numeric * 123.456, scale(1e-40::numeric * 1e-40);
+SELECT 'NaN'::numeric + 1, 'Infinity'::numeric - 'Infinity',
+       0 * 'Inf'::numeric;
+SELECT 1e70000::numeric * 1e70000::numeric;
+
+-- Check both operand orders with compressed and external inputs.
+CREATE TEMP TABLE num_toast_arith (
+    s numeric, e numeric STORAGE EXTERNAL, c numeric STORAGE MAIN
+);
+INSERT INTO num_toast_arith
+SELECT 42.50, v, 2 * v FROM (SELECT repeat('1234567890', 1000)::numeric v) t;
+SELECT pg_column_compression(c) IS NOT NULL AS compressed,
+       (e + s) - e AS delta, (s - c) + c AS diff, 2 * e = c AS product
+FROM num_toast_arith;
+DROP TABLE num_toast_arith;
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index f10eb46..8183d06 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -1845,6 +1845,7 @@ NullingRelsMatch
 Numeric
 NumericAggState
 NumericDigit
+NumericLocalBuf
 NumericSortSupport
 NumericSumAccum
 NumericVar
@@ -3321,6 +3322,7 @@ UniquePath
 UniqueRelInfo
 UniqueState
 UnlistenStmt
+UnpackedNumeric
 UnresolvedTup
 UnresolvedTupData
 UpdateContext
-- 
2.54.0 (Apple Git-157)

