1 /*-------------------------------------------------------------------------
4 * This file contains some support routines required for array functions.
6 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/utils/adt/arrayutils.c,v 1.18 2004/12/31 22:01:21 pgsql Exp $
13 *-------------------------------------------------------------------------
18 #include "utils/array.h"
21 /* Convert subscript list into linear element number (from 0) */
23 ArrayGetOffset(int n, int *dim, int *lb, int *indx)
29 for (i = n - 1; i >= 0; i--)
31 offset += (indx[i] - lb[i]) * scale;
37 /* Same, but subscripts are assumed 0-based, and use a scale array
38 * instead of raw dimension data (see mda_get_prod to create scale array)
41 ArrayGetOffset0(int n, int *tup, int *scale)
46 for (i = 0; i < n; i++)
47 lin += tup[i] * scale[i];
51 /* Convert array dimensions into number of elements */
53 ArrayGetNItems(int ndim, int *dims)
61 for (i = 0; i < ndim; i++)
66 /* Compute ranges (sub-array dimensions) for an array slice */
68 mda_get_range(int n, int *span, int *st, int *endp)
72 for (i = 0; i < n; i++)
73 span[i] = endp[i] - st[i] + 1;
76 /* Compute products of array dimensions, ie, scale factors for subscripts */
78 mda_get_prod(int n, int *range, int *prod)
83 for (i = n - 2; i >= 0; i--)
84 prod[i] = prod[i + 1] * range[i + 1];
87 /* From products of whole-array dimensions and spans of a sub-array,
88 * compute offset distances needed to step through subarray within array
91 mda_get_offset_values(int n, int *dist, int *prod, int *span)
97 for (j = n - 2; j >= 0; j--)
99 dist[j] = prod[j] - 1;
100 for (i = j + 1; i < n; i++)
101 dist[j] -= (span[i] - 1) * prod[i];
105 /*-----------------------------------------------------------------------------
106 generates the tuple that is lexicographically one greater than the current
107 n-tuple in "curr", with the restriction that the i-th element of "curr" is
108 less than the i-th element of "span".
109 Returns -1 if no next tuple exists, else the subscript position (0..n-1)
110 corresponding to the dimension to advance along.
111 -----------------------------------------------------------------------------
114 mda_next_tuple(int n, int *curr, int *span)
121 curr[n - 1] = (curr[n - 1] + 1) % span[n - 1];
122 for (i = n - 1; i && curr[i] == 0; i--)
123 curr[i - 1] = (curr[i - 1] + 1) % span[i - 1];