LCOV - code coverage report
Current view: top level - src/backend/utils/adt - arrayfuncs.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 94.1 % 2360 2221
Test Date: 2026-08-19 13:15:47 Functions: 100.0 % 90 90
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 73.4 % 1800 1322

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * arrayfuncs.c
       4                 :             :  *    Support functions for arrays.
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
       8                 :             :  *
       9                 :             :  *
      10                 :             :  * IDENTIFICATION
      11                 :             :  *    src/backend/utils/adt/arrayfuncs.c
      12                 :             :  *
      13                 :             :  *-------------------------------------------------------------------------
      14                 :             :  */
      15                 :             : #include "postgres.h"
      16                 :             : 
      17                 :             : #include <ctype.h>
      18                 :             : #include <math.h>
      19                 :             : 
      20                 :             : #include "access/transam.h"
      21                 :             : #include "catalog/pg_type.h"
      22                 :             : #include "common/int.h"
      23                 :             : #include "funcapi.h"
      24                 :             : #include "libpq/pqformat.h"
      25                 :             : #include "nodes/nodeFuncs.h"
      26                 :             : #include "nodes/supportnodes.h"
      27                 :             : #include "optimizer/optimizer.h"
      28                 :             : #include "parser/scansup.h"
      29                 :             : #include "port/pg_bitutils.h"
      30                 :             : #include "utils/array.h"
      31                 :             : #include "utils/arrayaccess.h"
      32                 :             : #include "utils/builtins.h"
      33                 :             : #include "utils/datum.h"
      34                 :             : #include "utils/fmgroids.h"
      35                 :             : #include "utils/lsyscache.h"
      36                 :             : #include "utils/memutils.h"
      37                 :             : #include "utils/selfuncs.h"
      38                 :             : #include "utils/typcache.h"
      39                 :             : 
      40                 :             : 
      41                 :             : /*
      42                 :             :  * GUC parameter
      43                 :             :  */
      44                 :             : bool        Array_nulls = true;
      45                 :             : 
      46                 :             : /*
      47                 :             :  * Local definitions
      48                 :             :  */
      49                 :             : #define ASSGN    "="
      50                 :             : 
      51                 :             : #define AARR_FREE_IF_COPY(array,n) \
      52                 :             :     do { \
      53                 :             :         if (!VARATT_IS_EXPANDED_HEADER(array)) \
      54                 :             :             PG_FREE_IF_COPY(array, n); \
      55                 :             :     } while (0)
      56                 :             : 
      57                 :             : /* ReadArrayToken return type */
      58                 :             : typedef enum
      59                 :             : {
      60                 :             :     ATOK_LEVEL_START,
      61                 :             :     ATOK_LEVEL_END,
      62                 :             :     ATOK_DELIM,
      63                 :             :     ATOK_ELEM,
      64                 :             :     ATOK_ELEM_NULL,
      65                 :             :     ATOK_ERROR,
      66                 :             : } ArrayToken;
      67                 :             : 
      68                 :             : /* Working state for array_iterate() */
      69                 :             : typedef struct ArrayIteratorData
      70                 :             : {
      71                 :             :     /* basic info about the array, set up during array_create_iterator() */
      72                 :             :     ArrayType  *arr;            /* array we're iterating through */
      73                 :             :     uint8      *nullbitmap;     /* its null bitmap, if any */
      74                 :             :     int         nitems;         /* total number of elements in array */
      75                 :             :     int16       typlen;         /* element type's length */
      76                 :             :     bool        typbyval;       /* element type's byval property */
      77                 :             :     char        typalign;       /* element type's align property */
      78                 :             :     uint8       typalignby;     /* typalign mapped to numeric alignment */
      79                 :             : 
      80                 :             :     /* information about the requested slice size */
      81                 :             :     int         slice_ndim;     /* slice dimension, or 0 if not slicing */
      82                 :             :     int         slice_len;      /* number of elements per slice */
      83                 :             :     int        *slice_dims;     /* slice dims array */
      84                 :             :     int        *slice_lbound;   /* slice lbound array */
      85                 :             :     Datum      *slice_values;   /* workspace of length slice_len */
      86                 :             :     bool       *slice_nulls;    /* workspace of length slice_len */
      87                 :             : 
      88                 :             :     /* current position information, updated on each iteration */
      89                 :             :     char       *data_ptr;       /* our current position in the array */
      90                 :             :     int         current_item;   /* the item # we're at in the array */
      91                 :             : } ArrayIteratorData;
      92                 :             : 
      93                 :             : static bool ReadArrayDimensions(char **srcptr, int *ndim_p,
      94                 :             :                                 int *dim, int *lBound,
      95                 :             :                                 const char *origStr, Node *escontext);
      96                 :             : static bool ReadDimensionInt(char **srcptr, int *result,
      97                 :             :                              const char *origStr, Node *escontext);
      98                 :             : static bool ReadArrayStr(char **srcptr,
      99                 :             :                          FmgrInfo *inputproc, Oid typioparam, int32 typmod,
     100                 :             :                          char typdelim,
     101                 :             :                          int typlen, bool typbyval, char typalign,
     102                 :             :                          int *ndim_p, int *dim,
     103                 :             :                          int *nitems_p,
     104                 :             :                          Datum **values_p, bool **nulls_p,
     105                 :             :                          const char *origStr, Node *escontext);
     106                 :             : static ArrayToken ReadArrayToken(char **srcptr, StringInfo elembuf, char typdelim,
     107                 :             :                                  const char *origStr, Node *escontext);
     108                 :             : static void ReadArrayBinary(StringInfo buf, int nitems,
     109                 :             :                             FmgrInfo *receiveproc, Oid typioparam, int32 typmod,
     110                 :             :                             int typlen, bool typbyval, char typalign,
     111                 :             :                             Datum *values, bool *nulls,
     112                 :             :                             bool *hasnulls, int32 *nbytes);
     113                 :             : static Datum array_get_element_expanded(Datum arraydatum,
     114                 :             :                                         int nSubscripts, int *indx,
     115                 :             :                                         int arraytyplen,
     116                 :             :                                         int elmlen, bool elmbyval, char elmalign,
     117                 :             :                                         bool *isNull);
     118                 :             : static Datum array_set_element_expanded(Datum arraydatum,
     119                 :             :                                         int nSubscripts, int *indx,
     120                 :             :                                         Datum dataValue, bool isNull,
     121                 :             :                                         int arraytyplen,
     122                 :             :                                         int elmlen, bool elmbyval, char elmalign);
     123                 :             : static bool array_get_isnull(const uint8 *nullbitmap, int offset);
     124                 :             : static void array_set_isnull(uint8 *nullbitmap, int offset, bool isNull);
     125                 :             : static Datum ArrayCast(char *value, bool byval, int len);
     126                 :             : static int  ArrayCastAndSet(Datum src,
     127                 :             :                             int typlen, bool typbyval, uint8 typalignby,
     128                 :             :                             char *dest);
     129                 :             : static char *array_seek(char *ptr, int offset, uint8 *nullbitmap, int nitems,
     130                 :             :                         int typlen, bool typbyval, char typalign);
     131                 :             : static int  array_nelems_size(char *ptr, int offset, uint8 *nullbitmap,
     132                 :             :                               int nitems, int typlen, bool typbyval, char typalign);
     133                 :             : static int  array_copy(char *destptr, int nitems,
     134                 :             :                        char *srcptr, int offset, uint8 *nullbitmap,
     135                 :             :                        int typlen, bool typbyval, char typalign);
     136                 :             : static int  array_slice_size(char *arraydataptr, uint8 *arraynullsptr,
     137                 :             :                              int ndim, int *dim, int *lb,
     138                 :             :                              int *st, int *endp,
     139                 :             :                              int typlen, bool typbyval, char typalign);
     140                 :             : static void array_extract_slice(ArrayType *newarray,
     141                 :             :                                 int ndim, int *dim, int *lb,
     142                 :             :                                 char *arraydataptr, uint8 *arraynullsptr,
     143                 :             :                                 int *st, int *endp,
     144                 :             :                                 int typlen, bool typbyval, char typalign);
     145                 :             : static void array_insert_slice(ArrayType *destArray, ArrayType *origArray,
     146                 :             :                                ArrayType *srcArray,
     147                 :             :                                int ndim, int *dim, int *lb,
     148                 :             :                                int *st, int *endp,
     149                 :             :                                int typlen, bool typbyval, char typalign);
     150                 :             : static int  array_cmp(FunctionCallInfo fcinfo);
     151                 :             : static ArrayType *create_array_envelope(int ndims, int *dimv, int *lbsv, int nbytes,
     152                 :             :                                         Oid elmtype, int dataoffset);
     153                 :             : static ArrayType *array_fill_internal(ArrayType *dims, ArrayType *lbs,
     154                 :             :                                       Datum value, bool isnull, Oid elmtype,
     155                 :             :                                       FunctionCallInfo fcinfo);
     156                 :             : static ArrayType *array_replace_internal(ArrayType *array,
     157                 :             :                                          Datum search, bool search_isnull,
     158                 :             :                                          Datum replace, bool replace_isnull,
     159                 :             :                                          bool remove, Oid collation,
     160                 :             :                                          FunctionCallInfo fcinfo);
     161                 :             : static int  width_bucket_array_float8(Datum operand, ArrayType *thresholds);
     162                 :             : static int  width_bucket_array_fixed(Datum operand,
     163                 :             :                                      ArrayType *thresholds,
     164                 :             :                                      Oid collation,
     165                 :             :                                      TypeCacheEntry *typentry);
     166                 :             : static int  width_bucket_array_variable(Datum operand,
     167                 :             :                                         ArrayType *thresholds,
     168                 :             :                                         Oid collation,
     169                 :             :                                         TypeCacheEntry *typentry);
     170                 :             : 
     171                 :             : 
     172                 :             : /*
     173                 :             :  * array_in :
     174                 :             :  *        converts an array from the external format in "string" to
     175                 :             :  *        its internal format.
     176                 :             :  *
     177                 :             :  * return value :
     178                 :             :  *        the internal representation of the input array
     179                 :             :  */
     180                 :             : Datum
     181                 :      152335 : array_in(PG_FUNCTION_ARGS)
     182                 :             : {
     183                 :      152335 :     char       *string = PG_GETARG_CSTRING(0);  /* external form */
     184                 :      152335 :     Oid         element_type = PG_GETARG_OID(1);    /* type of an array
     185                 :             :                                                      * element */
     186                 :      152335 :     int32       typmod = PG_GETARG_INT32(2);    /* typmod for array elements */
     187                 :      152335 :     Node       *escontext = fcinfo->context;
     188                 :             :     int         typlen;
     189                 :             :     bool        typbyval;
     190                 :             :     char        typalign;
     191                 :             :     uint8       typalignby;
     192                 :             :     char        typdelim;
     193                 :             :     Oid         typioparam;
     194                 :             :     char       *p;
     195                 :             :     int         nitems;
     196                 :             :     Datum      *values;
     197                 :             :     bool       *nulls;
     198                 :             :     bool        hasnulls;
     199                 :             :     int32       nbytes;
     200                 :             :     int32       dataoffset;
     201                 :             :     ArrayType  *retval;
     202                 :             :     int         ndim,
     203                 :             :                 dim[MAXDIM],
     204                 :             :                 lBound[MAXDIM];
     205                 :             :     ArrayMetaState *my_extra;
     206                 :             : 
     207                 :             :     /*
     208                 :             :      * We arrange to look up info about element type, including its input
     209                 :             :      * conversion proc, only once per series of calls, assuming the element
     210                 :             :      * type doesn't change underneath us.
     211                 :             :      */
     212                 :      152335 :     my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
     213         [ +  + ]:      152335 :     if (my_extra == NULL)
     214                 :             :     {
     215                 :       53768 :         fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
     216                 :             :                                                       sizeof(ArrayMetaState));
     217                 :       53768 :         my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
     218                 :       53768 :         my_extra->element_type = ~element_type;
     219                 :             :     }
     220                 :             : 
     221         [ +  + ]:      152335 :     if (my_extra->element_type != element_type)
     222                 :             :     {
     223                 :             :         /*
     224                 :             :          * Get info about element type, including its input conversion proc
     225                 :             :          */
     226                 :       53928 :         get_type_io_data(element_type, IOFunc_input,
     227                 :             :                          &my_extra->typlen, &my_extra->typbyval,
     228                 :             :                          &my_extra->typalign, &my_extra->typdelim,
     229                 :             :                          &my_extra->typioparam, &my_extra->typiofunc);
     230                 :       53928 :         fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
     231                 :       53928 :                       fcinfo->flinfo->fn_mcxt);
     232                 :       53928 :         my_extra->element_type = element_type;
     233                 :             :     }
     234                 :      152335 :     typlen = my_extra->typlen;
     235                 :      152335 :     typbyval = my_extra->typbyval;
     236                 :      152335 :     typalign = my_extra->typalign;
     237                 :      152335 :     typalignby = typalign_to_alignby(typalign);
     238                 :      152335 :     typdelim = my_extra->typdelim;
     239                 :      152335 :     typioparam = my_extra->typioparam;
     240                 :             : 
     241                 :             :     /*
     242                 :             :      * Initialize dim[] and lBound[] for ReadArrayStr, in case there is no
     243                 :             :      * explicit dimension info.  (If there is, ReadArrayDimensions will
     244                 :             :      * overwrite this.)
     245                 :             :      */
     246         [ +  + ]:     1066345 :     for (int i = 0; i < MAXDIM; i++)
     247                 :             :     {
     248                 :      914010 :         dim[i] = -1;            /* indicates "not yet known" */
     249                 :      914010 :         lBound[i] = 1;          /* default lower bound */
     250                 :             :     }
     251                 :             : 
     252                 :             :     /*
     253                 :             :      * Start processing the input string.
     254                 :             :      *
     255                 :             :      * If the input string starts with dimension info, read and use that.
     256                 :             :      * Otherwise, we'll determine the dimensions during ReadArrayStr.
     257                 :             :      */
     258                 :      152335 :     p = string;
     259         [ -  + ]:      152335 :     if (!ReadArrayDimensions(&p, &ndim, dim, lBound, string, escontext))
     260                 :           0 :         return (Datum) 0;
     261                 :             : 
     262         [ +  + ]:      152307 :     if (ndim == 0)
     263                 :             :     {
     264                 :             :         /* No array dimensions, so next character should be a left brace */
     265         [ +  + ]:      152210 :         if (*p != '{')
     266         [ +  + ]:           9 :             ereturn(escontext, (Datum) 0,
     267                 :             :                     (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     268                 :             :                      errmsg("malformed array literal: \"%s\"", string),
     269                 :             :                      errdetail("Array value must start with \"{\" or dimension information.")));
     270                 :             :     }
     271                 :             :     else
     272                 :             :     {
     273                 :             :         /* If array dimensions are given, expect '=' operator */
     274         [ -  + ]:          97 :         if (strncmp(p, ASSGN, strlen(ASSGN)) != 0)
     275         [ #  # ]:           0 :             ereturn(escontext, (Datum) 0,
     276                 :             :                     (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     277                 :             :                      errmsg("malformed array literal: \"%s\"", string),
     278                 :             :                      errdetail("Missing \"%s\" after array dimensions.",
     279                 :             :                                ASSGN)));
     280                 :          97 :         p += strlen(ASSGN);
     281                 :             :         /* Allow whitespace after it */
     282         [ -  + ]:          97 :         while (scanner_isspace(*p))
     283                 :           0 :             p++;
     284                 :             : 
     285         [ -  + ]:          97 :         if (*p != '{')
     286         [ #  # ]:           0 :             ereturn(escontext, (Datum) 0,
     287                 :             :                     (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     288                 :             :                      errmsg("malformed array literal: \"%s\"", string),
     289                 :             :                      errdetail("Array contents must start with \"{\".")));
     290                 :             :     }
     291                 :             : 
     292                 :             :     /* Parse the value part, in the curly braces: { ... } */
     293         [ +  + ]:      152298 :     if (!ReadArrayStr(&p,
     294                 :             :                       &my_extra->proc, typioparam, typmod,
     295                 :             :                       typdelim,
     296                 :             :                       typlen, typbyval, typalign,
     297                 :             :                       &ndim,
     298                 :             :                       dim,
     299                 :             :                       &nitems,
     300                 :             :                       &values, &nulls,
     301                 :             :                       string,
     302                 :             :                       escontext))
     303                 :          56 :         return (Datum) 0;
     304                 :             : 
     305                 :             :     /* only whitespace is allowed after the closing brace */
     306         [ +  + ]:      152143 :     while (*p)
     307                 :             :     {
     308         [ +  - ]:           8 :         if (!scanner_isspace(*p++))
     309         [ +  - ]:           8 :             ereturn(escontext, (Datum) 0,
     310                 :             :                     (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     311                 :             :                      errmsg("malformed array literal: \"%s\"", string),
     312                 :             :                      errdetail("Junk after closing right brace.")));
     313                 :             :     }
     314                 :             : 
     315                 :             :     /* Empty array? */
     316         [ +  + ]:      152135 :     if (nitems == 0)
     317                 :        2757 :         PG_RETURN_ARRAYTYPE_P(construct_empty_array(element_type));
     318                 :             : 
     319                 :             :     /*
     320                 :             :      * Check for nulls, compute total data space needed
     321                 :             :      */
     322                 :      149378 :     hasnulls = false;
     323                 :      149378 :     nbytes = 0;
     324         [ +  + ]:      865217 :     for (int i = 0; i < nitems; i++)
     325                 :             :     {
     326         [ +  + ]:      715839 :         if (nulls[i])
     327                 :         501 :             hasnulls = true;
     328                 :             :         else
     329                 :             :         {
     330                 :             :             /* let's just make sure data is not toasted */
     331         [ +  + ]:      715338 :             if (typlen == -1)
     332                 :      406645 :                 values[i] = PointerGetDatum(PG_DETOAST_DATUM(values[i]));
     333   [ +  +  +  + ]:      715338 :             nbytes = att_addlength_datum(nbytes, typlen, values[i]);
     334                 :      715338 :             nbytes = att_nominal_alignby(nbytes, typalignby);
     335                 :             :             /* check for overflow of total request */
     336         [ -  + ]:      715338 :             if (!AllocSizeIsValid(nbytes))
     337         [ #  # ]:           0 :                 ereturn(escontext, (Datum) 0,
     338                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     339                 :             :                          errmsg("array size exceeds the maximum allowed (%zu)",
     340                 :             :                                 MaxAllocSize)));
     341                 :             :         }
     342                 :             :     }
     343         [ +  + ]:      149378 :     if (hasnulls)
     344                 :             :     {
     345                 :         452 :         dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
     346                 :         452 :         nbytes += dataoffset;
     347                 :             :     }
     348                 :             :     else
     349                 :             :     {
     350                 :      148926 :         dataoffset = 0;         /* marker for no null bitmap */
     351                 :      148926 :         nbytes += ARR_OVERHEAD_NONULLS(ndim);
     352                 :             :     }
     353                 :             : 
     354                 :             :     /*
     355                 :             :      * Construct the final array datum
     356                 :             :      */
     357                 :      149378 :     retval = (ArrayType *) palloc0(nbytes);
     358                 :      149378 :     SET_VARSIZE(retval, nbytes);
     359                 :      149378 :     retval->ndim = ndim;
     360                 :      149378 :     retval->dataoffset = dataoffset;
     361                 :             : 
     362                 :             :     /*
     363                 :             :      * This comes from the array's pg_type.typelem (which points to the base
     364                 :             :      * data type's pg_type.oid) and stores system oids in user tables. This
     365                 :             :      * oid must be preserved by binary upgrades.
     366                 :             :      */
     367                 :      149378 :     retval->elemtype = element_type;
     368                 :      149378 :     memcpy(ARR_DIMS(retval), dim, ndim * sizeof(int));
     369                 :      149378 :     memcpy(ARR_LBOUND(retval), lBound, ndim * sizeof(int));
     370                 :             : 
     371                 :      149378 :     CopyArrayEls(retval,
     372                 :             :                  values, nulls, nitems,
     373                 :             :                  typlen, typbyval, typalign,
     374                 :             :                  true);
     375                 :             : 
     376                 :      149378 :     pfree(values);
     377                 :      149378 :     pfree(nulls);
     378                 :             : 
     379                 :      149378 :     PG_RETURN_ARRAYTYPE_P(retval);
     380                 :             : }
     381                 :             : 
     382                 :             : /*
     383                 :             :  * ReadArrayDimensions
     384                 :             :  *   parses the array dimensions part of the input and converts the values
     385                 :             :  *   to internal format.
     386                 :             :  *
     387                 :             :  * On entry, *srcptr points to the string to parse. It is advanced to point
     388                 :             :  * after whitespace (if any) and dimension info (if any).
     389                 :             :  *
     390                 :             :  * *ndim_p, dim[], and lBound[] are output variables. They are filled with the
     391                 :             :  * number of dimensions (<= MAXDIM), the lengths of each dimension, and the
     392                 :             :  * lower subscript bounds, respectively.  If no dimension info appears,
     393                 :             :  * *ndim_p will be set to zero, and dim[] and lBound[] are unchanged.
     394                 :             :  *
     395                 :             :  * 'origStr' is the original input string, used only in error messages.
     396                 :             :  * If *escontext points to an ErrorSaveContext, details of any error are
     397                 :             :  * reported there.
     398                 :             :  *
     399                 :             :  * Result:
     400                 :             :  *  true for success, false for failure (if escontext is provided).
     401                 :             :  *
     402                 :             :  * Note that dim[] and lBound[] are allocated by the caller, and must have
     403                 :             :  * MAXDIM elements.
     404                 :             :  */
     405                 :             : static bool
     406                 :      152335 : ReadArrayDimensions(char **srcptr, int *ndim_p, int *dim, int *lBound,
     407                 :             :                     const char *origStr, Node *escontext)
     408                 :             : {
     409                 :      152335 :     char       *p = *srcptr;
     410                 :             :     int         ndim;
     411                 :             : 
     412                 :             :     /*
     413                 :             :      * Dimension info takes the form of one or more [n] or [m:n] items.  This
     414                 :             :      * loop iterates once per dimension item.
     415                 :             :      */
     416                 :      152335 :     ndim = 0;
     417                 :             :     for (;;)
     418                 :         134 :     {
     419                 :             :         char       *q;
     420                 :             :         int         ub;
     421                 :             :         int         i;
     422                 :             : 
     423                 :             :         /*
     424                 :             :          * Note: we currently allow whitespace between, but not within,
     425                 :             :          * dimension items.
     426                 :             :          */
     427         [ +  + ]:      152477 :         while (scanner_isspace(*p))
     428                 :           8 :             p++;
     429         [ +  + ]:      152469 :         if (*p != '[')
     430                 :      152307 :             break;              /* no more dimension items */
     431                 :         162 :         p++;
     432         [ -  + ]:         162 :         if (ndim >= MAXDIM)
     433         [ #  # ]:           0 :             ereturn(escontext, false,
     434                 :             :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     435                 :             :                      errmsg("number of array dimensions exceeds the maximum allowed (%d)",
     436                 :             :                             MAXDIM)));
     437                 :             : 
     438                 :         162 :         q = p;
     439         [ -  + ]:         162 :         if (!ReadDimensionInt(&p, &i, origStr, escontext))
     440                 :           0 :             return false;
     441         [ +  + ]:         154 :         if (p == q)             /* no digits? */
     442         [ +  - ]:           4 :             ereturn(escontext, false,
     443                 :             :                     (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     444                 :             :                      errmsg("malformed array literal: \"%s\"", origStr),
     445                 :             :                      errdetail("\"[\" must introduce explicitly-specified array dimensions.")));
     446                 :             : 
     447         [ +  + ]:         150 :         if (*p == ':')
     448                 :             :         {
     449                 :             :             /* [m:n] format */
     450                 :         142 :             lBound[ndim] = i;
     451                 :         142 :             p++;
     452                 :         142 :             q = p;
     453         [ -  + ]:         142 :             if (!ReadDimensionInt(&p, &ub, origStr, escontext))
     454                 :           0 :                 return false;
     455         [ +  + ]:         142 :             if (p == q)         /* no digits? */
     456         [ +  - ]:           4 :                 ereturn(escontext, false,
     457                 :             :                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     458                 :             :                          errmsg("malformed array literal: \"%s\"", origStr),
     459                 :             :                          errdetail("Missing array dimension value.")));
     460                 :             :         }
     461                 :             :         else
     462                 :             :         {
     463                 :             :             /* [n] format */
     464                 :           8 :             lBound[ndim] = 1;
     465                 :           8 :             ub = i;
     466                 :             :         }
     467         [ -  + ]:         146 :         if (*p != ']')
     468         [ #  # ]:           0 :             ereturn(escontext, false,
     469                 :             :                     (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     470                 :             :                      errmsg("malformed array literal: \"%s\"", origStr),
     471                 :             :                      errdetail("Missing \"%s\" after array dimensions.",
     472                 :             :                                "]")));
     473                 :         146 :         p++;
     474                 :             : 
     475                 :             :         /*
     476                 :             :          * Note: we could accept ub = lb-1 to represent a zero-length
     477                 :             :          * dimension.  However, that would result in an empty array, for which
     478                 :             :          * we don't keep any dimension data, so that e.g. [1:0] and [101:100]
     479                 :             :          * would be equivalent.  Given the lack of field demand, there seems
     480                 :             :          * little point in allowing such cases.
     481                 :             :          */
     482         [ +  + ]:         146 :         if (ub < lBound[ndim])
     483         [ +  - ]:           8 :             ereturn(escontext, false,
     484                 :             :                     (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
     485                 :             :                      errmsg("upper bound cannot be less than lower bound")));
     486                 :             : 
     487                 :             :         /* Upper bound of INT_MAX must be disallowed, cf ArrayCheckBounds() */
     488         [ +  + ]:         138 :         if (ub == INT_MAX)
     489         [ +  - ]:           4 :             ereturn(escontext, false,
     490                 :             :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     491                 :             :                      errmsg("array upper bound is too large: %d", ub)));
     492                 :             : 
     493                 :             :         /* Compute "ub - lBound[ndim] + 1", detecting overflow */
     494   [ +  -  -  + ]:         268 :         if (pg_sub_s32_overflow(ub, lBound[ndim], &ub) ||
     495                 :         134 :             pg_add_s32_overflow(ub, 1, &ub))
     496         [ #  # ]:           0 :             ereturn(escontext, false,
     497                 :             :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     498                 :             :                      errmsg("array size exceeds the maximum allowed (%zu)",
     499                 :             :                             MaxArraySize)));
     500                 :             : 
     501                 :         134 :         dim[ndim] = ub;
     502                 :         134 :         ndim++;
     503                 :             :     }
     504                 :             : 
     505                 :      152307 :     *srcptr = p;
     506                 :      152307 :     *ndim_p = ndim;
     507                 :      152307 :     return true;
     508                 :             : }
     509                 :             : 
     510                 :             : /*
     511                 :             :  * ReadDimensionInt
     512                 :             :  *   parse an integer, for the array dimensions
     513                 :             :  *
     514                 :             :  * On entry, *srcptr points to the string to parse. It is advanced past the
     515                 :             :  * digits of the integer. If there are no digits, returns true and leaves
     516                 :             :  * *srcptr unchanged.
     517                 :             :  *
     518                 :             :  * Result:
     519                 :             :  *  true for success, false for failure (if escontext is provided).
     520                 :             :  *  On success, the parsed integer is returned in *result.
     521                 :             :  */
     522                 :             : static bool
     523                 :         304 : ReadDimensionInt(char **srcptr, int *result,
     524                 :             :                  const char *origStr, Node *escontext)
     525                 :             : {
     526                 :         304 :     char       *p = *srcptr;
     527                 :             :     long        l;
     528                 :             : 
     529                 :             :     /* don't accept leading whitespace */
     530   [ +  +  +  +  :         304 :     if (!isdigit((unsigned char) *p) && *p != '-' && *p != '+')
                   +  - ]
     531                 :             :     {
     532                 :           8 :         *result = 0;
     533                 :           8 :         return true;
     534                 :             :     }
     535                 :             : 
     536                 :         296 :     errno = 0;
     537                 :         296 :     l = strtol(p, srcptr, 10);
     538                 :             : 
     539   [ +  -  +  +  :         296 :     if (errno == ERANGE || l > PG_INT32_MAX || l < PG_INT32_MIN)
                   +  + ]
     540         [ +  - ]:           8 :         ereturn(escontext, false,
     541                 :             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     542                 :             :                  errmsg("array bound is out of integer range")));
     543                 :             : 
     544                 :         288 :     *result = (int) l;
     545                 :         288 :     return true;
     546                 :             : }
     547                 :             : 
     548                 :             : /*
     549                 :             :  * ReadArrayStr :
     550                 :             :  *   parses the array string pointed to by *srcptr and converts the values
     551                 :             :  *   to internal format.  Determines the array dimensions as it goes.
     552                 :             :  *
     553                 :             :  * On entry, *srcptr points to the string to parse (it must point to a '{').
     554                 :             :  * On successful return, it is advanced to point past the closing '}'.
     555                 :             :  *
     556                 :             :  * If dimensions were specified explicitly, they are passed in *ndim_p and
     557                 :             :  * dim[].  This function will check that the array values match the specified
     558                 :             :  * dimensions.  If dimensions were not given, caller must pass *ndim_p == 0
     559                 :             :  * and initialize all elements of dim[] to -1.  Then this function will
     560                 :             :  * deduce the dimensions from the structure of the input and store them in
     561                 :             :  * *ndim_p and the dim[] array.
     562                 :             :  *
     563                 :             :  * Element type information:
     564                 :             :  *  inputproc: type-specific input procedure for element datatype.
     565                 :             :  *  typioparam, typmod: auxiliary values to pass to inputproc.
     566                 :             :  *  typdelim: the value delimiter (type-specific).
     567                 :             :  *  typlen, typbyval, typalign: storage parameters of element datatype.
     568                 :             :  *
     569                 :             :  * Outputs:
     570                 :             :  *  *ndim_p, dim: dimensions deduced from the input structure.
     571                 :             :  *  *nitems_p: total number of elements.
     572                 :             :  *  *values_p[]: palloc'd array, filled with converted data values.
     573                 :             :  *  *nulls_p[]: palloc'd array, filled with is-null markers.
     574                 :             :  *
     575                 :             :  * 'origStr' is the original input string, used only in error messages.
     576                 :             :  * If *escontext points to an ErrorSaveContext, details of any error are
     577                 :             :  * reported there.
     578                 :             :  *
     579                 :             :  * Result:
     580                 :             :  *  true for success, false for failure (if escontext is provided).
     581                 :             :  */
     582                 :             : static bool
     583                 :      152298 : ReadArrayStr(char **srcptr,
     584                 :             :              FmgrInfo *inputproc,
     585                 :             :              Oid typioparam,
     586                 :             :              int32 typmod,
     587                 :             :              char typdelim,
     588                 :             :              int typlen,
     589                 :             :              bool typbyval,
     590                 :             :              char typalign,
     591                 :             :              int *ndim_p,
     592                 :             :              int *dim,
     593                 :             :              int *nitems_p,
     594                 :             :              Datum **values_p,
     595                 :             :              bool **nulls_p,
     596                 :             :              const char *origStr,
     597                 :             :              Node *escontext)
     598                 :             : {
     599                 :      152298 :     int         ndim = *ndim_p;
     600                 :      152298 :     bool        dimensions_specified = (ndim != 0);
     601                 :             :     int         maxitems;
     602                 :             :     Datum      *values;
     603                 :             :     bool       *nulls;
     604                 :             :     StringInfoData elembuf;
     605                 :             :     int         nest_level;
     606                 :             :     int         nitems;
     607                 :             :     bool        ndim_frozen;
     608                 :             :     bool        expect_delim;
     609                 :             :     int         nelems[MAXDIM];
     610                 :             : 
     611                 :             :     /* Allocate some starting output workspace; we'll enlarge as needed */
     612                 :      152298 :     maxitems = 16;
     613                 :      152298 :     values = palloc_array(Datum, maxitems);
     614                 :      152298 :     nulls = palloc_array(bool, maxitems);
     615                 :             : 
     616                 :             :     /* Allocate workspace to hold (string representation of) one element */
     617                 :      152298 :     initStringInfo(&elembuf);
     618                 :             : 
     619                 :             :     /* Loop below assumes first token is ATOK_LEVEL_START */
     620                 :             :     Assert(**srcptr == '{');
     621                 :             : 
     622                 :             :     /* Parse tokens until we reach the matching right brace */
     623                 :      152298 :     nest_level = 0;
     624                 :      152298 :     nitems = 0;
     625                 :      152298 :     ndim_frozen = dimensions_specified;
     626                 :      152298 :     expect_delim = false;
     627                 :             :     do
     628                 :             :     {
     629                 :             :         ArrayToken  tok;
     630                 :             : 
     631                 :     1589382 :         tok = ReadArrayToken(srcptr, &elembuf, typdelim, origStr, escontext);
     632                 :             : 
     633   [ +  +  +  +  :     1589362 :         switch (tok)
                   +  - ]
     634                 :             :         {
     635                 :      153493 :             case ATOK_LEVEL_START:
     636                 :             :                 /* Can't write left brace where delim is expected */
     637         [ +  + ]:      153493 :                 if (expect_delim)
     638         [ +  - ]:           4 :                     ereturn(escontext, false,
     639                 :             :                             (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     640                 :             :                              errmsg("malformed array literal: \"%s\"", origStr),
     641                 :             :                              errdetail("Unexpected \"%c\" character.", '{')));
     642                 :             : 
     643                 :             :                 /* Initialize element counting in the new level */
     644         [ +  + ]:      153489 :                 if (nest_level >= MAXDIM)
     645         [ +  - ]:           1 :                     ereturn(escontext, false,
     646                 :             :                             (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     647                 :             :                              errmsg("number of array dimensions exceeds the maximum allowed (%d)",
     648                 :             :                                     MAXDIM)));
     649                 :             : 
     650                 :      153488 :                 nelems[nest_level] = 0;
     651                 :      153488 :                 nest_level++;
     652         [ +  + ]:      153488 :                 if (nest_level > ndim)
     653                 :             :                 {
     654                 :             :                     /* Can't increase ndim once it's frozen */
     655         [ +  + ]:      152600 :                     if (ndim_frozen)
     656                 :           8 :                         goto dimension_error;
     657                 :      152592 :                     ndim = nest_level;
     658                 :             :                 }
     659                 :      153480 :                 break;
     660                 :             : 
     661                 :      153311 :             case ATOK_LEVEL_END:
     662                 :             :                 /* Can't get here with nest_level == 0 */
     663                 :             :                 Assert(nest_level > 0);
     664                 :             : 
     665                 :             :                 /*
     666                 :             :                  * We allow a right brace to terminate an empty sub-array,
     667                 :             :                  * otherwise it must occur where we expect a delimiter.
     668                 :             :                  */
     669   [ +  +  +  + ]:      153311 :                 if (nelems[nest_level - 1] > 0 && !expect_delim)
     670         [ +  - ]:          16 :                     ereturn(escontext, false,
     671                 :             :                             (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     672                 :             :                              errmsg("malformed array literal: \"%s\"", origStr),
     673                 :             :                              errdetail("Unexpected \"%c\" character.",
     674                 :             :                                        '}')));
     675                 :      153295 :                 nest_level--;
     676                 :             :                 /* Nested sub-arrays count as elements of outer level */
     677         [ +  + ]:      153295 :                 if (nest_level > 0)
     678                 :        1148 :                     nelems[nest_level - 1]++;
     679                 :             : 
     680                 :             :                 /*
     681                 :             :                  * Note: if we had dimensionality info, then dim[nest_level]
     682                 :             :                  * is initially non-negative, and we'll check each sub-array's
     683                 :             :                  * length against that.
     684                 :             :                  */
     685         [ +  + ]:      153295 :                 if (dim[nest_level] < 0)
     686                 :             :                 {
     687                 :             :                     /* Save length of first sub-array of this level */
     688                 :      152415 :                     dim[nest_level] = nelems[nest_level];
     689                 :             :                 }
     690         [ +  + ]:         880 :                 else if (nelems[nest_level] != dim[nest_level])
     691                 :             :                 {
     692                 :             :                     /* Subsequent sub-arrays must have same length */
     693                 :          21 :                     goto dimension_error;
     694                 :             :                 }
     695                 :             : 
     696                 :             :                 /*
     697                 :             :                  * Must have a delim or another right brace following, unless
     698                 :             :                  * we have reached nest_level 0, where this won't matter.
     699                 :             :                  */
     700                 :      153274 :                 expect_delim = true;
     701                 :      153274 :                 break;
     702                 :             : 
     703                 :      566551 :             case ATOK_DELIM:
     704         [ +  + ]:      566551 :                 if (!expect_delim)
     705         [ +  - ]:           4 :                     ereturn(escontext, false,
     706                 :             :                             (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     707                 :             :                              errmsg("malformed array literal: \"%s\"", origStr),
     708                 :             :                              errdetail("Unexpected \"%c\" character.",
     709                 :             :                                        typdelim)));
     710                 :      566547 :                 expect_delim = false;
     711                 :      566547 :                 break;
     712                 :             : 
     713                 :      716003 :             case ATOK_ELEM:
     714                 :             :             case ATOK_ELEM_NULL:
     715                 :             :                 /* Can't get here with nest_level == 0 */
     716                 :             :                 Assert(nest_level > 0);
     717                 :             : 
     718                 :             :                 /* Disallow consecutive ELEM tokens */
     719         [ +  + ]:      716003 :                 if (expect_delim)
     720         [ +  - ]:           4 :                     ereturn(escontext, false,
     721                 :             :                             (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     722                 :             :                              errmsg("malformed array literal: \"%s\"", origStr),
     723                 :             :                              errdetail("Unexpected array element.")));
     724                 :             : 
     725                 :             :                 /* Enlarge the values/nulls arrays if needed */
     726         [ +  + ]:      715999 :                 if (nitems >= maxitems)
     727                 :             :                 {
     728         [ -  + ]:        3258 :                     if (maxitems >= MaxArraySize)
     729         [ #  # ]:           0 :                         ereturn(escontext, false,
     730                 :             :                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     731                 :             :                                  errmsg("array size exceeds the maximum allowed (%zu)",
     732                 :             :                                         MaxArraySize)));
     733         [ +  - ]:        3258 :                     maxitems = Min(maxitems * 2, MaxArraySize);
     734                 :        3258 :                     values = repalloc_array(values, Datum, maxitems);
     735                 :        3258 :                     nulls = repalloc_array(nulls, bool, maxitems);
     736                 :             :                 }
     737                 :             : 
     738                 :             :                 /* Read the element's value, or check that NULL is allowed */
     739         [ +  + ]:      715999 :                 if (!InputFunctionCallSafe(inputproc,
     740                 :             :                                            (tok == ATOK_ELEM_NULL) ? NULL : elembuf.data,
     741                 :             :                                            typioparam, typmod,
     742                 :             :                                            escontext,
     743         [ +  + ]:      715999 :                                            &values[nitems]))
     744                 :          52 :                     return false;
     745                 :      715934 :                 nulls[nitems] = (tok == ATOK_ELEM_NULL);
     746                 :      715934 :                 nitems++;
     747                 :             : 
     748                 :             :                 /*
     749                 :             :                  * Once we have found an element, the number of dimensions can
     750                 :             :                  * no longer increase, and subsequent elements must all be at
     751                 :             :                  * the same nesting depth.
     752                 :             :                  */
     753                 :      715934 :                 ndim_frozen = true;
     754         [ +  + ]:      715934 :                 if (nest_level != ndim)
     755                 :           8 :                     goto dimension_error;
     756                 :             :                 /* Count the new element */
     757                 :      715926 :                 nelems[nest_level - 1]++;
     758                 :             : 
     759                 :             :                 /* Must have a delim or a right brace following */
     760                 :      715926 :                 expect_delim = true;
     761                 :      715926 :                 break;
     762                 :             : 
     763                 :           4 :             case ATOK_ERROR:
     764                 :           4 :                 return false;
     765                 :             :         }
     766         [ +  + ]:     1589227 :     } while (nest_level > 0);
     767                 :             : 
     768                 :             :     /* Clean up and return results */
     769                 :      152143 :     pfree(elembuf.data);
     770                 :             : 
     771                 :      152143 :     *ndim_p = ndim;
     772                 :      152143 :     *nitems_p = nitems;
     773                 :      152143 :     *values_p = values;
     774                 :      152143 :     *nulls_p = nulls;
     775                 :      152143 :     return true;
     776                 :             : 
     777                 :          37 : dimension_error:
     778         [ +  + ]:          37 :     if (dimensions_specified)
     779         [ +  - ]:           4 :         ereturn(escontext, false,
     780                 :             :                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     781                 :             :                  errmsg("malformed array literal: \"%s\"", origStr),
     782                 :             :                  errdetail("Specified array dimensions do not match array contents.")));
     783                 :             :     else
     784         [ +  - ]:          33 :         ereturn(escontext, false,
     785                 :             :                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     786                 :             :                  errmsg("malformed array literal: \"%s\"", origStr),
     787                 :             :                  errdetail("Multidimensional arrays must have sub-arrays with matching dimensions.")));
     788                 :             : }
     789                 :             : 
     790                 :             : /*
     791                 :             :  * ReadArrayToken
     792                 :             :  *   read one token from an array value string
     793                 :             :  *
     794                 :             :  * Starts scanning from *srcptr.  On non-error return, *srcptr is
     795                 :             :  * advanced past the token.
     796                 :             :  *
     797                 :             :  * If the token is ATOK_ELEM, the de-escaped string is returned in elembuf.
     798                 :             :  */
     799                 :             : static ArrayToken
     800                 :     1589382 : ReadArrayToken(char **srcptr, StringInfo elembuf, char typdelim,
     801                 :             :                const char *origStr, Node *escontext)
     802                 :             : {
     803                 :     1589382 :     char       *p = *srcptr;
     804                 :             :     int         dstlen;
     805                 :             :     bool        has_escapes;
     806                 :             : 
     807                 :     1589382 :     resetStringInfo(elembuf);
     808                 :             : 
     809                 :             :     /* Identify token type.  Loop advances over leading whitespace. */
     810                 :             :     for (;;)
     811                 :             :     {
     812   [ -  +  +  +  :     1605929 :         switch (*p)
                      + ]
     813                 :             :         {
     814                 :           0 :             case '\0':
     815                 :           0 :                 goto ending_error;
     816                 :      153493 :             case '{':
     817                 :      153493 :                 *srcptr = p + 1;
     818                 :      153493 :                 return ATOK_LEVEL_START;
     819                 :      153311 :             case '}':
     820                 :      153311 :                 *srcptr = p + 1;
     821                 :      153311 :                 return ATOK_LEVEL_END;
     822                 :      318933 :             case '"':
     823                 :      318933 :                 p++;
     824                 :      318933 :                 goto quoted_element;
     825                 :      980192 :             default:
     826         [ +  + ]:      980192 :                 if (*p == typdelim)
     827                 :             :                 {
     828                 :      566551 :                     *srcptr = p + 1;
     829                 :      566551 :                     return ATOK_DELIM;
     830                 :             :                 }
     831         [ +  + ]:      413641 :                 if (scanner_isspace(*p))
     832                 :             :                 {
     833                 :       16547 :                     p++;
     834                 :       16547 :                     continue;
     835                 :             :                 }
     836                 :      397094 :                 goto unquoted_element;
     837                 :             :         }
     838                 :             :     }
     839                 :             : 
     840                 :      318933 : quoted_element:
     841                 :             :     for (;;)
     842                 :             :     {
     843   [ -  +  +  + ]:     2395176 :         switch (*p)
     844                 :             :         {
     845                 :           0 :             case '\0':
     846                 :           0 :                 goto ending_error;
     847                 :         714 :             case '\\':
     848                 :             :                 /* Skip backslash, copy next character as-is. */
     849                 :         714 :                 p++;
     850         [ -  + ]:         714 :                 if (*p == '\0')
     851                 :           0 :                     goto ending_error;
     852                 :         714 :                 appendStringInfoChar(elembuf, *p++);
     853                 :         714 :                 break;
     854                 :      318933 :             case '"':
     855                 :             : 
     856                 :             :                 /*
     857                 :             :                  * If next non-whitespace isn't typdelim or a brace, complain
     858                 :             :                  * about incorrect quoting.  While we could leave such cases
     859                 :             :                  * to be detected as incorrect token sequences, the resulting
     860                 :             :                  * message wouldn't be as helpful.  (We could also give the
     861                 :             :                  * incorrect-quoting error when next is '{', but treating that
     862                 :             :                  * as a token sequence error seems better.)
     863                 :             :                  */
     864         [ +  - ]:      318957 :                 while (*(++p) != '\0')
     865                 :             :                 {
     866   [ +  +  +  +  :      318957 :                     if (*p == typdelim || *p == '}' || *p == '{')
                   +  + ]
     867                 :             :                     {
     868                 :      318921 :                         *srcptr = p;
     869                 :      318921 :                         return ATOK_ELEM;
     870                 :             :                     }
     871         [ +  + ]:          36 :                     if (!scanner_isspace(*p))
     872         [ +  - ]:          12 :                         ereturn(escontext, ATOK_ERROR,
     873                 :             :                                 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     874                 :             :                                  errmsg("malformed array literal: \"%s\"", origStr),
     875                 :             :                                  errdetail("Incorrectly quoted array element.")));
     876                 :             :                 }
     877                 :           0 :                 goto ending_error;
     878                 :     2075529 :             default:
     879                 :     2075529 :                 appendStringInfoChar(elembuf, *p++);
     880                 :     2075529 :                 break;
     881                 :             :         }
     882                 :             :     }
     883                 :             : 
     884                 :      397094 : unquoted_element:
     885                 :             : 
     886                 :             :     /*
     887                 :             :      * We don't include trailing whitespace in the result.  dstlen tracks how
     888                 :             :      * much of the output string is known to not be trailing whitespace.
     889                 :             :      */
     890                 :      397094 :     dstlen = 0;
     891                 :      397094 :     has_escapes = false;
     892                 :             :     for (;;)
     893                 :             :     {
     894   [ +  +  +  +  :     2229490 :         switch (*p)
                      + ]
     895                 :             :         {
     896                 :           4 :             case '\0':
     897                 :           4 :                 goto ending_error;
     898                 :           4 :             case '{':
     899         [ +  - ]:           4 :                 ereturn(escontext, ATOK_ERROR,
     900                 :             :                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     901                 :             :                          errmsg("malformed array literal: \"%s\"", origStr),
     902                 :             :                          errdetail("Unexpected \"%c\" character.",
     903                 :             :                                    '{')));
     904                 :           4 :             case '"':
     905                 :             :                 /* Must double-quote all or none of an element. */
     906         [ +  - ]:           4 :                 ereturn(escontext, ATOK_ERROR,
     907                 :             :                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     908                 :             :                          errmsg("malformed array literal: \"%s\"", origStr),
     909                 :             :                          errdetail("Incorrectly quoted array element.")));
     910                 :          12 :             case '\\':
     911                 :             :                 /* Skip backslash, copy next character as-is. */
     912                 :          12 :                 p++;
     913         [ -  + ]:          12 :                 if (*p == '\0')
     914                 :           0 :                     goto ending_error;
     915                 :          12 :                 appendStringInfoChar(elembuf, *p++);
     916                 :          12 :                 dstlen = elembuf->len;   /* treat it as non-whitespace */
     917                 :          12 :                 has_escapes = true;
     918                 :          12 :                 break;
     919                 :     2229466 :             default:
     920                 :             :                 /* End of elem? */
     921   [ +  +  +  + ]:     2229466 :                 if (*p == typdelim || *p == '}')
     922                 :             :                 {
     923                 :             :                     /* hack: truncate the output string to dstlen */
     924                 :      397082 :                     elembuf->data[dstlen] = '\0';
     925                 :      397082 :                     elembuf->len = dstlen;
     926                 :      397082 :                     *srcptr = p;
     927                 :             :                     /* Check if it's unquoted "NULL" */
     928   [ +  -  +  +  :      794152 :                     if (Array_nulls && !has_escapes &&
                   +  + ]
     929                 :      397070 :                         pg_strcasecmp(elembuf->data, "NULL") == 0)
     930                 :         501 :                         return ATOK_ELEM_NULL;
     931                 :             :                     else
     932                 :      396581 :                         return ATOK_ELEM;
     933                 :             :                 }
     934                 :     1832384 :                 appendStringInfoChar(elembuf, *p);
     935         [ +  + ]:     1832384 :                 if (!scanner_isspace(*p))
     936                 :     1831800 :                     dstlen = elembuf->len;
     937                 :     1832384 :                 p++;
     938                 :     1832384 :                 break;
     939                 :             :         }
     940                 :             :     }
     941                 :             : 
     942                 :           4 : ending_error:
     943         [ -  + ]:           4 :     ereturn(escontext, ATOK_ERROR,
     944                 :             :             (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     945                 :             :              errmsg("malformed array literal: \"%s\"", origStr),
     946                 :             :              errdetail("Unexpected end of input.")));
     947                 :             : }
     948                 :             : 
     949                 :             : /*
     950                 :             :  * Copy data into an array object from a temporary array of Datums.
     951                 :             :  *
     952                 :             :  * array: array object (with header fields already filled in)
     953                 :             :  * values: array of Datums to be copied
     954                 :             :  * nulls: array of is-null flags (can be NULL if no nulls)
     955                 :             :  * nitems: number of Datums to be copied
     956                 :             :  * typbyval, typlen, typalign: info about element datatype
     957                 :             :  * freedata: if true and element type is pass-by-ref, pfree data values
     958                 :             :  * referenced by Datums after copying them.
     959                 :             :  *
     960                 :             :  * If the input data is of varlena type, the caller must have ensured that
     961                 :             :  * the values are not toasted.  (Doing it here doesn't work since the
     962                 :             :  * caller has already allocated space for the array...)
     963                 :             :  */
     964                 :             : void
     965                 :     1170025 : CopyArrayEls(ArrayType *array,
     966                 :             :              const Datum *values,
     967                 :             :              const bool *nulls,
     968                 :             :              int nitems,
     969                 :             :              int typlen,
     970                 :             :              bool typbyval,
     971                 :             :              char typalign,
     972                 :             :              bool freedata)
     973                 :             : {
     974         [ +  + ]:     1170025 :     char       *p = ARR_DATA_PTR(array);
     975         [ +  + ]:     1170025 :     uint8      *bitmap = ARR_NULLBITMAP(array);
     976                 :     1170025 :     int         bitval = 0;
     977                 :     1170025 :     int         bitmask = 1;
     978                 :     1170025 :     uint8       typalignby = typalign_to_alignby(typalign);
     979                 :             :     int         i;
     980                 :             : 
     981         [ +  + ]:     1170025 :     if (typbyval)
     982                 :      782732 :         freedata = false;
     983                 :             : 
     984         [ +  + ]:     8824450 :     for (i = 0; i < nitems; i++)
     985                 :             :     {
     986   [ +  +  +  + ]:     7654425 :         if (nulls && nulls[i])
     987                 :             :         {
     988         [ -  + ]:       22705 :             if (!bitmap)        /* shouldn't happen */
     989         [ #  # ]:           0 :                 elog(ERROR, "null array element where not supported");
     990                 :             :             /* bitmap bit stays 0 */
     991                 :             :         }
     992                 :             :         else
     993                 :             :         {
     994                 :     7631720 :             bitval |= bitmask;
     995                 :     7631720 :             p += ArrayCastAndSet(values[i], typlen, typbyval, typalignby, p);
     996         [ +  + ]:     7631720 :             if (freedata)
     997                 :      417904 :                 pfree(DatumGetPointer(values[i]));
     998                 :             :         }
     999         [ +  + ]:     7654425 :         if (bitmap)
    1000                 :             :         {
    1001                 :      525284 :             bitmask <<= 1;
    1002         [ +  + ]:      525284 :             if (bitmask == 0x100)
    1003                 :             :             {
    1004                 :       63479 :                 *bitmap++ = bitval;
    1005                 :       63479 :                 bitval = 0;
    1006                 :       63479 :                 bitmask = 1;
    1007                 :             :             }
    1008                 :             :         }
    1009                 :             :     }
    1010                 :             : 
    1011   [ +  +  +  + ]:     1170025 :     if (bitmap && bitmask != 1)
    1012                 :       12320 :         *bitmap = bitval;
    1013                 :     1170025 : }
    1014                 :             : 
    1015                 :             : /*
    1016                 :             :  * array_out :
    1017                 :             :  *         takes the internal representation of an array and returns a string
    1018                 :             :  *        containing the array in its external format.
    1019                 :             :  */
    1020                 :             : Datum
    1021                 :      435192 : array_out(PG_FUNCTION_ARGS)
    1022                 :             : {
    1023                 :      435192 :     AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
    1024         [ +  + ]:      435192 :     Oid         element_type = AARR_ELEMTYPE(v);
    1025                 :             :     int         typlen;
    1026                 :             :     bool        typbyval;
    1027                 :             :     char        typalign;
    1028                 :             :     char        typdelim;
    1029                 :             :     char       *p,
    1030                 :             :                *tmp,
    1031                 :             :                *retval,
    1032                 :             :               **values,
    1033                 :             :                 dims_str[(MAXDIM * 33) + 2];
    1034                 :             : 
    1035                 :             :     /*
    1036                 :             :      * 33 per dim since we assume 15 digits per number + ':' +'[]'
    1037                 :             :      *
    1038                 :             :      * +2 allows for assignment operator + trailing null
    1039                 :             :      */
    1040                 :             :     bool       *needquotes,
    1041                 :      435192 :                 needdims = false;
    1042                 :             :     size_t      overall_length;
    1043                 :             :     int         nitems,
    1044                 :             :                 i,
    1045                 :             :                 j,
    1046                 :             :                 k,
    1047                 :             :                 indx[MAXDIM];
    1048                 :             :     int         ndim,
    1049                 :             :                *dims,
    1050                 :             :                *lb;
    1051                 :             :     array_iter  iter;
    1052                 :             :     ArrayMetaState *my_extra;
    1053                 :             : 
    1054                 :             :     /*
    1055                 :             :      * We arrange to look up info about element type, including its output
    1056                 :             :      * conversion proc, only once per series of calls, assuming the element
    1057                 :             :      * type doesn't change underneath us.
    1058                 :             :      */
    1059                 :      435192 :     my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
    1060         [ +  + ]:      435192 :     if (my_extra == NULL)
    1061                 :             :     {
    1062                 :       16526 :         fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
    1063                 :             :                                                       sizeof(ArrayMetaState));
    1064                 :       16526 :         my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
    1065                 :       16526 :         my_extra->element_type = ~element_type;
    1066                 :             :     }
    1067                 :             : 
    1068         [ +  + ]:      435192 :     if (my_extra->element_type != element_type)
    1069                 :             :     {
    1070                 :             :         /*
    1071                 :             :          * Get info about element type, including its output conversion proc
    1072                 :             :          */
    1073                 :       18923 :         get_type_io_data(element_type, IOFunc_output,
    1074                 :             :                          &my_extra->typlen, &my_extra->typbyval,
    1075                 :             :                          &my_extra->typalign, &my_extra->typdelim,
    1076                 :             :                          &my_extra->typioparam, &my_extra->typiofunc);
    1077                 :       18923 :         fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
    1078                 :       18923 :                       fcinfo->flinfo->fn_mcxt);
    1079                 :       18923 :         my_extra->element_type = element_type;
    1080                 :             :     }
    1081                 :      435192 :     typlen = my_extra->typlen;
    1082                 :      435192 :     typbyval = my_extra->typbyval;
    1083                 :      435192 :     typalign = my_extra->typalign;
    1084                 :      435192 :     typdelim = my_extra->typdelim;
    1085                 :             : 
    1086         [ +  + ]:      435192 :     ndim = AARR_NDIM(v);
    1087         [ +  + ]:      435192 :     dims = AARR_DIMS(v);
    1088         [ +  + ]:      435192 :     lb = AARR_LBOUND(v);
    1089                 :      435192 :     nitems = ArrayGetNItems(ndim, dims);
    1090                 :             : 
    1091         [ +  + ]:      435192 :     if (nitems == 0)
    1092                 :             :     {
    1093                 :        2174 :         retval = pstrdup("{}");
    1094                 :        2174 :         PG_RETURN_CSTRING(retval);
    1095                 :             :     }
    1096                 :             : 
    1097                 :             :     /*
    1098                 :             :      * we will need to add explicit dimensions if any dimension has a lower
    1099                 :             :      * bound other than one
    1100                 :             :      */
    1101         [ +  + ]:      866508 :     for (i = 0; i < ndim; i++)
    1102                 :             :     {
    1103         [ +  + ]:      433692 :         if (lb[i] != 1)
    1104                 :             :         {
    1105                 :         202 :             needdims = true;
    1106                 :         202 :             break;
    1107                 :             :         }
    1108                 :             :     }
    1109                 :             : 
    1110                 :             :     /*
    1111                 :             :      * Convert all values to string form, count total space needed (including
    1112                 :             :      * any overhead such as escaping backslashes), and detect whether each
    1113                 :             :      * item needs double quotes.
    1114                 :             :      */
    1115                 :      433018 :     values = palloc_array(char *, nitems);
    1116                 :      433018 :     needquotes = palloc_array(bool, nitems);
    1117                 :      433018 :     overall_length = 0;
    1118                 :             : 
    1119                 :      433018 :     array_iter_setup(&iter, v, typlen, typbyval, typalign);
    1120                 :             : 
    1121         [ +  + ]:     1691228 :     for (i = 0; i < nitems; i++)
    1122                 :             :     {
    1123                 :             :         Datum       itemvalue;
    1124                 :             :         bool        isnull;
    1125                 :             :         bool        needquote;
    1126                 :             : 
    1127                 :             :         /* Get source element, checking for NULL */
    1128                 :     1258210 :         itemvalue = array_iter_next(&iter, &isnull, i);
    1129                 :             : 
    1130         [ +  + ]:     1258210 :         if (isnull)
    1131                 :             :         {
    1132                 :        1544 :             values[i] = pstrdup("NULL");
    1133                 :        1544 :             overall_length += 4;
    1134                 :        1544 :             needquote = false;
    1135                 :             :         }
    1136                 :             :         else
    1137                 :             :         {
    1138                 :     1256666 :             values[i] = OutputFunctionCall(&my_extra->proc, itemvalue);
    1139                 :             : 
    1140                 :             :             /* count data plus backslashes; detect chars needing quotes */
    1141         [ +  + ]:     1256666 :             if (values[i][0] == '\0')
    1142                 :         316 :                 needquote = true;   /* force quotes for empty string */
    1143         [ +  + ]:     1256350 :             else if (pg_strcasecmp(values[i], "NULL") == 0)
    1144                 :          12 :                 needquote = true;   /* force quotes for literal NULL */
    1145                 :             :             else
    1146                 :     1256338 :                 needquote = false;
    1147                 :             : 
    1148         [ +  + ]:    17677775 :             for (tmp = values[i]; *tmp != '\0'; tmp++)
    1149                 :             :             {
    1150                 :    16421109 :                 char        ch = *tmp;
    1151                 :             : 
    1152                 :    16421109 :                 overall_length += 1;
    1153   [ +  +  +  + ]:    16421109 :                 if (ch == '"' || ch == '\\')
    1154                 :             :                 {
    1155                 :        2462 :                     needquote = true;
    1156                 :        2462 :                     overall_length += 1;
    1157                 :             :                 }
    1158   [ +  +  +  +  :    32807330 :                 else if (ch == '{' || ch == '}' || ch == typdelim ||
             +  +  +  + ]
    1159                 :    16388683 :                          scanner_isspace(ch))
    1160                 :      134336 :                     needquote = true;
    1161                 :             :             }
    1162                 :             :         }
    1163                 :             : 
    1164                 :     1258210 :         needquotes[i] = needquote;
    1165                 :             : 
    1166                 :             :         /* Count the pair of double quotes, if needed */
    1167         [ +  + ]:     1258210 :         if (needquote)
    1168                 :       16596 :             overall_length += 2;
    1169                 :             :         /* and the comma (or other typdelim delimiter) */
    1170                 :     1258210 :         overall_length += 1;
    1171                 :             :     }
    1172                 :             : 
    1173                 :             :     /*
    1174                 :             :      * The very last array element doesn't have a typdelim delimiter after it,
    1175                 :             :      * but that's OK; that space is needed for the trailing '\0'.
    1176                 :             :      *
    1177                 :             :      * Now count total number of curly brace pairs in output string.
    1178                 :             :      */
    1179         [ +  + ]:      866754 :     for (i = j = 0, k = 1; i < ndim; i++)
    1180                 :             :     {
    1181                 :      433736 :         j += k, k *= dims[i];
    1182                 :             :     }
    1183                 :      433018 :     overall_length += 2 * j;
    1184                 :             : 
    1185                 :             :     /* Format explicit dimensions if required */
    1186                 :      433018 :     dims_str[0] = '\0';
    1187         [ +  + ]:      433018 :     if (needdims)
    1188                 :             :     {
    1189                 :         202 :         char       *ptr = dims_str;
    1190                 :             : 
    1191         [ +  + ]:         449 :         for (i = 0; i < ndim; i++)
    1192                 :             :         {
    1193                 :         247 :             sprintf(ptr, "[%d:%d]", lb[i], lb[i] + dims[i] - 1);
    1194                 :         247 :             ptr += strlen(ptr);
    1195                 :             :         }
    1196                 :         202 :         *ptr++ = *ASSGN;
    1197                 :         202 :         *ptr = '\0';
    1198                 :         202 :         overall_length += ptr - dims_str;
    1199                 :             :     }
    1200                 :             : 
    1201                 :             :     /* Now construct the output string */
    1202                 :      433018 :     retval = (char *) palloc(overall_length);
    1203                 :      433018 :     p = retval;
    1204                 :             : 
    1205                 :             : #define APPENDSTR(str)  (strcpy(p, (str)), p += strlen(p))
    1206                 :             : #define APPENDCHAR(ch)  (*p++ = (ch), *p = '\0')
    1207                 :             : 
    1208         [ +  + ]:      433018 :     if (needdims)
    1209                 :         202 :         APPENDSTR(dims_str);
    1210                 :      433018 :     APPENDCHAR('{');
    1211         [ +  + ]:      866754 :     for (i = 0; i < ndim; i++)
    1212                 :      433736 :         indx[i] = 0;
    1213                 :      433018 :     j = 0;
    1214                 :      433018 :     k = 0;
    1215                 :             :     do
    1216                 :             :     {
    1217         [ +  + ]:     1263441 :         for (i = j; i < ndim - 1; i++)
    1218                 :        5231 :             APPENDCHAR('{');
    1219                 :             : 
    1220         [ +  + ]:     1258210 :         if (needquotes[k])
    1221                 :             :         {
    1222                 :       16596 :             APPENDCHAR('"');
    1223         [ +  + ]:      709636 :             for (tmp = values[k]; *tmp; tmp++)
    1224                 :             :             {
    1225                 :      693040 :                 char        ch = *tmp;
    1226                 :             : 
    1227   [ +  +  +  + ]:      693040 :                 if (ch == '"' || ch == '\\')
    1228                 :        2462 :                     *p++ = '\\';
    1229                 :      693040 :                 *p++ = ch;
    1230                 :             :             }
    1231                 :       16596 :             *p = '\0';
    1232                 :       16596 :             APPENDCHAR('"');
    1233                 :             :         }
    1234                 :             :         else
    1235                 :     1241614 :             APPENDSTR(values[k]);
    1236                 :     1258210 :         pfree(values[k++]);
    1237                 :             : 
    1238         [ +  + ]:     1696459 :         for (i = ndim - 1; i >= 0; i--)
    1239                 :             :         {
    1240         [ +  + ]:     1263441 :             if (++(indx[i]) < dims[i])
    1241                 :             :             {
    1242                 :      825192 :                 APPENDCHAR(typdelim);
    1243                 :      825192 :                 break;
    1244                 :             :             }
    1245                 :             :             else
    1246                 :             :             {
    1247                 :      438249 :                 indx[i] = 0;
    1248                 :      438249 :                 APPENDCHAR('}');
    1249                 :             :             }
    1250                 :             :         }
    1251                 :     1258210 :         j = i;
    1252         [ +  + ]:     1258210 :     } while (j != -1);
    1253                 :             : 
    1254                 :             : #undef APPENDSTR
    1255                 :             : #undef APPENDCHAR
    1256                 :             : 
    1257                 :             :     /* Assert that we calculated the string length accurately */
    1258                 :             :     Assert(overall_length == (p - retval + 1));
    1259                 :             : 
    1260                 :      433018 :     pfree(values);
    1261                 :      433018 :     pfree(needquotes);
    1262                 :             : 
    1263                 :      433018 :     PG_RETURN_CSTRING(retval);
    1264                 :             : }
    1265                 :             : 
    1266                 :             : /*
    1267                 :             :  * array_recv :
    1268                 :             :  *        converts an array from the external binary format to
    1269                 :             :  *        its internal format.
    1270                 :             :  *
    1271                 :             :  * return value :
    1272                 :             :  *        the internal representation of the input array
    1273                 :             :  */
    1274                 :             : Datum
    1275                 :          31 : array_recv(PG_FUNCTION_ARGS)
    1276                 :             : {
    1277                 :          31 :     StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
    1278                 :          31 :     Oid         spec_element_type = PG_GETARG_OID(1);   /* type of an array
    1279                 :             :                                                          * element */
    1280                 :          31 :     int32       typmod = PG_GETARG_INT32(2);    /* typmod for array elements */
    1281                 :             :     Oid         element_type;
    1282                 :             :     int         typlen;
    1283                 :             :     bool        typbyval;
    1284                 :             :     char        typalign;
    1285                 :             :     Oid         typioparam;
    1286                 :             :     int         i,
    1287                 :             :                 nitems;
    1288                 :             :     Datum      *dataPtr;
    1289                 :             :     bool       *nullsPtr;
    1290                 :             :     bool        hasnulls;
    1291                 :             :     int32       nbytes;
    1292                 :             :     int32       dataoffset;
    1293                 :             :     ArrayType  *retval;
    1294                 :             :     int         ndim,
    1295                 :             :                 flags,
    1296                 :             :                 dim[MAXDIM],
    1297                 :             :                 lBound[MAXDIM];
    1298                 :             :     ArrayMetaState *my_extra;
    1299                 :             : 
    1300                 :             :     /* Get the array header information */
    1301                 :          31 :     ndim = pq_getmsgint(buf, 4);
    1302         [ -  + ]:          31 :     if (ndim < 0)                /* we do allow zero-dimension arrays */
    1303         [ #  # ]:           0 :         ereport(ERROR,
    1304                 :             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
    1305                 :             :                  errmsg("invalid number of dimensions: %d", ndim)));
    1306         [ -  + ]:          31 :     if (ndim > MAXDIM)
    1307         [ #  # ]:           0 :         ereport(ERROR,
    1308                 :             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    1309                 :             :                  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
    1310                 :             :                         ndim, MAXDIM)));
    1311                 :             : 
    1312                 :          31 :     flags = pq_getmsgint(buf, 4);
    1313   [ -  +  -  - ]:          31 :     if (flags != 0 && flags != 1)
    1314         [ #  # ]:           0 :         ereport(ERROR,
    1315                 :             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
    1316                 :             :                  errmsg("invalid array flags")));
    1317                 :             : 
    1318                 :             :     /* Check element type recorded in the data */
    1319                 :          31 :     element_type = pq_getmsgint(buf, sizeof(Oid));
    1320                 :             : 
    1321                 :             :     /*
    1322                 :             :      * From a security standpoint, it doesn't matter whether the input's
    1323                 :             :      * element type matches what we expect: the element type's receive
    1324                 :             :      * function has to be robust enough to cope with invalid data.  However,
    1325                 :             :      * from a user-friendliness standpoint, it's nicer to complain about type
    1326                 :             :      * mismatches than to throw "improper binary format" errors.  But there's
    1327                 :             :      * a problem: only built-in types have OIDs that are stable enough to
    1328                 :             :      * believe that a mismatch is a real issue.  So complain only if both OIDs
    1329                 :             :      * are in the built-in range.  Otherwise, carry on with the element type
    1330                 :             :      * we "should" be getting.
    1331                 :             :      */
    1332         [ -  + ]:          31 :     if (element_type != spec_element_type)
    1333                 :             :     {
    1334   [ #  #  #  # ]:           0 :         if (element_type < FirstGenbkiObjectId &&
    1335                 :             :             spec_element_type < FirstGenbkiObjectId)
    1336         [ #  # ]:           0 :             ereport(ERROR,
    1337                 :             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    1338                 :             :                      errmsg("binary data has array element type %u (%s) instead of expected %u (%s)",
    1339                 :             :                             element_type,
    1340                 :             :                             format_type_extended(element_type, -1,
    1341                 :             :                                                  FORMAT_TYPE_ALLOW_INVALID),
    1342                 :             :                             spec_element_type,
    1343                 :             :                             format_type_extended(spec_element_type, -1,
    1344                 :             :                                                  FORMAT_TYPE_ALLOW_INVALID))));
    1345                 :           0 :         element_type = spec_element_type;
    1346                 :             :     }
    1347                 :             : 
    1348         [ +  + ]:          62 :     for (i = 0; i < ndim; i++)
    1349                 :             :     {
    1350                 :          31 :         dim[i] = pq_getmsgint(buf, 4);
    1351                 :          31 :         lBound[i] = pq_getmsgint(buf, 4);
    1352                 :             :     }
    1353                 :             : 
    1354                 :             :     /* This checks for overflow of array dimensions */
    1355                 :          31 :     nitems = ArrayGetNItems(ndim, dim);
    1356                 :          31 :     ArrayCheckBounds(ndim, dim, lBound);
    1357                 :             : 
    1358                 :             :     /*
    1359                 :             :      * We arrange to look up info about element type, including its receive
    1360                 :             :      * conversion proc, only once per series of calls, assuming the element
    1361                 :             :      * type doesn't change underneath us.
    1362                 :             :      */
    1363                 :          31 :     my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
    1364         [ +  + ]:          31 :     if (my_extra == NULL)
    1365                 :             :     {
    1366                 :          28 :         fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
    1367                 :             :                                                       sizeof(ArrayMetaState));
    1368                 :          28 :         my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
    1369                 :          28 :         my_extra->element_type = ~element_type;
    1370                 :             :     }
    1371                 :             : 
    1372         [ +  + ]:          31 :     if (my_extra->element_type != element_type)
    1373                 :             :     {
    1374                 :             :         /* Get info about element type, including its receive proc */
    1375                 :          28 :         get_type_io_data(element_type, IOFunc_receive,
    1376                 :             :                          &my_extra->typlen, &my_extra->typbyval,
    1377                 :             :                          &my_extra->typalign, &my_extra->typdelim,
    1378                 :             :                          &my_extra->typioparam, &my_extra->typiofunc);
    1379         [ -  + ]:          28 :         if (!OidIsValid(my_extra->typiofunc))
    1380         [ #  # ]:           0 :             ereport(ERROR,
    1381                 :             :                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
    1382                 :             :                      errmsg("no binary input function available for type %s",
    1383                 :             :                             format_type_be(element_type))));
    1384                 :          28 :         fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
    1385                 :          28 :                       fcinfo->flinfo->fn_mcxt);
    1386                 :          28 :         my_extra->element_type = element_type;
    1387                 :             :     }
    1388                 :             : 
    1389         [ -  + ]:          31 :     if (nitems == 0)
    1390                 :             :     {
    1391                 :             :         /* Return empty array ... but not till we've validated element_type */
    1392                 :           0 :         PG_RETURN_ARRAYTYPE_P(construct_empty_array(element_type));
    1393                 :             :     }
    1394                 :             : 
    1395                 :          31 :     typlen = my_extra->typlen;
    1396                 :          31 :     typbyval = my_extra->typbyval;
    1397                 :          31 :     typalign = my_extra->typalign;
    1398                 :          31 :     typioparam = my_extra->typioparam;
    1399                 :             : 
    1400                 :          31 :     dataPtr = palloc_array(Datum, nitems);
    1401                 :          31 :     nullsPtr = palloc_array(bool, nitems);
    1402                 :          31 :     ReadArrayBinary(buf, nitems,
    1403                 :             :                     &my_extra->proc, typioparam, typmod,
    1404                 :             :                     typlen, typbyval, typalign,
    1405                 :             :                     dataPtr, nullsPtr,
    1406                 :             :                     &hasnulls, &nbytes);
    1407         [ -  + ]:          31 :     if (hasnulls)
    1408                 :             :     {
    1409                 :           0 :         dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
    1410                 :           0 :         nbytes += dataoffset;
    1411                 :             :     }
    1412                 :             :     else
    1413                 :             :     {
    1414                 :          31 :         dataoffset = 0;         /* marker for no null bitmap */
    1415                 :          31 :         nbytes += ARR_OVERHEAD_NONULLS(ndim);
    1416                 :             :     }
    1417                 :          31 :     retval = (ArrayType *) palloc0(nbytes);
    1418                 :          31 :     SET_VARSIZE(retval, nbytes);
    1419                 :          31 :     retval->ndim = ndim;
    1420                 :          31 :     retval->dataoffset = dataoffset;
    1421                 :          31 :     retval->elemtype = element_type;
    1422                 :          31 :     memcpy(ARR_DIMS(retval), dim, ndim * sizeof(int));
    1423                 :          31 :     memcpy(ARR_LBOUND(retval), lBound, ndim * sizeof(int));
    1424                 :             : 
    1425                 :          31 :     CopyArrayEls(retval,
    1426                 :             :                  dataPtr, nullsPtr, nitems,
    1427                 :             :                  typlen, typbyval, typalign,
    1428                 :             :                  true);
    1429                 :             : 
    1430                 :          31 :     pfree(dataPtr);
    1431                 :          31 :     pfree(nullsPtr);
    1432                 :             : 
    1433                 :          31 :     PG_RETURN_ARRAYTYPE_P(retval);
    1434                 :             : }
    1435                 :             : 
    1436                 :             : /*
    1437                 :             :  * ReadArrayBinary:
    1438                 :             :  *   collect the data elements of an array being read in binary style.
    1439                 :             :  *
    1440                 :             :  * Inputs:
    1441                 :             :  *  buf: the data buffer to read from.
    1442                 :             :  *  nitems: total number of array elements (already read).
    1443                 :             :  *  receiveproc: type-specific receive procedure for element datatype.
    1444                 :             :  *  typioparam, typmod: auxiliary values to pass to receiveproc.
    1445                 :             :  *  typlen, typbyval, typalign: storage parameters of element datatype.
    1446                 :             :  *
    1447                 :             :  * Outputs:
    1448                 :             :  *  values[]: filled with converted data values.
    1449                 :             :  *  nulls[]: filled with is-null markers.
    1450                 :             :  *  *hasnulls: set true iff there are any null elements.
    1451                 :             :  *  *nbytes: set to total size of data area needed (including alignment
    1452                 :             :  *      padding but not including array header overhead).
    1453                 :             :  *
    1454                 :             :  * Note that values[] and nulls[] are allocated by the caller, and must have
    1455                 :             :  * nitems elements.
    1456                 :             :  */
    1457                 :             : static void
    1458                 :          31 : ReadArrayBinary(StringInfo buf,
    1459                 :             :                 int nitems,
    1460                 :             :                 FmgrInfo *receiveproc,
    1461                 :             :                 Oid typioparam,
    1462                 :             :                 int32 typmod,
    1463                 :             :                 int typlen,
    1464                 :             :                 bool typbyval,
    1465                 :             :                 char typalign,
    1466                 :             :                 Datum *values,
    1467                 :             :                 bool *nulls,
    1468                 :             :                 bool *hasnulls,
    1469                 :             :                 int32 *nbytes)
    1470                 :             : {
    1471                 :             :     int         i;
    1472                 :             :     bool        hasnull;
    1473                 :             :     int32       totbytes;
    1474                 :          31 :     uint8       typalignby = typalign_to_alignby(typalign);
    1475                 :             : 
    1476         [ +  + ]:         124 :     for (i = 0; i < nitems; i++)
    1477                 :             :     {
    1478                 :             :         int         itemlen;
    1479                 :             :         StringInfoData elem_buf;
    1480                 :             : 
    1481                 :             :         /* Get and check the item length */
    1482                 :          93 :         itemlen = pq_getmsgint(buf, 4);
    1483   [ +  -  -  + ]:          93 :         if (itemlen < -1 || itemlen > (buf->len - buf->cursor))
    1484         [ #  # ]:           0 :             ereport(ERROR,
    1485                 :             :                     (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
    1486                 :             :                      errmsg("insufficient data left in message")));
    1487                 :             : 
    1488         [ -  + ]:          93 :         if (itemlen == -1)
    1489                 :             :         {
    1490                 :             :             /* -1 length means NULL */
    1491                 :           0 :             values[i] = ReceiveFunctionCall(receiveproc, NULL,
    1492                 :             :                                             typioparam, typmod);
    1493                 :           0 :             nulls[i] = true;
    1494                 :           0 :             continue;
    1495                 :             :         }
    1496                 :             : 
    1497                 :             :         /*
    1498                 :             :          * Rather than copying data around, we just initialize a StringInfo
    1499                 :             :          * pointing to the correct portion of the message buffer.
    1500                 :             :          */
    1501                 :          93 :         initReadOnlyStringInfo(&elem_buf, &buf->data[buf->cursor], itemlen);
    1502                 :             : 
    1503                 :          93 :         buf->cursor += itemlen;
    1504                 :             : 
    1505                 :             :         /* Now call the element's receiveproc */
    1506                 :          93 :         values[i] = ReceiveFunctionCall(receiveproc, &elem_buf,
    1507                 :             :                                         typioparam, typmod);
    1508                 :          93 :         nulls[i] = false;
    1509                 :             : 
    1510                 :             :         /* Trouble if it didn't eat the whole buffer */
    1511         [ -  + ]:          93 :         if (elem_buf.cursor != itemlen)
    1512         [ #  # ]:           0 :             ereport(ERROR,
    1513                 :             :                     (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
    1514                 :             :                      errmsg("improper binary format in array element %d",
    1515                 :             :                             i + 1)));
    1516                 :             :     }
    1517                 :             : 
    1518                 :             :     /*
    1519                 :             :      * Check for nulls, compute total data space needed
    1520                 :             :      */
    1521                 :          31 :     hasnull = false;
    1522                 :          31 :     totbytes = 0;
    1523         [ +  + ]:         124 :     for (i = 0; i < nitems; i++)
    1524                 :             :     {
    1525         [ -  + ]:          93 :         if (nulls[i])
    1526                 :           0 :             hasnull = true;
    1527                 :             :         else
    1528                 :             :         {
    1529                 :             :             /* let's just make sure data is not toasted */
    1530         [ +  + ]:          93 :             if (typlen == -1)
    1531                 :          54 :                 values[i] = PointerGetDatum(PG_DETOAST_DATUM(values[i]));
    1532   [ +  +  +  - ]:          93 :             totbytes = att_addlength_datum(totbytes, typlen, values[i]);
    1533                 :          93 :             totbytes = att_nominal_alignby(totbytes, typalignby);
    1534                 :             :             /* check for overflow of total request */
    1535         [ -  + ]:          93 :             if (!AllocSizeIsValid(totbytes))
    1536         [ #  # ]:           0 :                 ereport(ERROR,
    1537                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    1538                 :             :                          errmsg("array size exceeds the maximum allowed (%zu)",
    1539                 :             :                                 MaxAllocSize)));
    1540                 :             :         }
    1541                 :             :     }
    1542                 :          31 :     *hasnulls = hasnull;
    1543                 :          31 :     *nbytes = totbytes;
    1544                 :          31 : }
    1545                 :             : 
    1546                 :             : 
    1547                 :             : /*
    1548                 :             :  * array_send :
    1549                 :             :  *        takes the internal representation of an array and returns a bytea
    1550                 :             :  *        containing the array in its external binary format.
    1551                 :             :  */
    1552                 :             : Datum
    1553                 :          23 : array_send(PG_FUNCTION_ARGS)
    1554                 :             : {
    1555                 :          23 :     AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
    1556         [ -  + ]:          23 :     Oid         element_type = AARR_ELEMTYPE(v);
    1557                 :             :     int         typlen;
    1558                 :             :     bool        typbyval;
    1559                 :             :     char        typalign;
    1560                 :             :     int         nitems,
    1561                 :             :                 i;
    1562                 :             :     int         ndim,
    1563                 :             :                *dim,
    1564                 :             :                *lb;
    1565                 :             :     StringInfoData buf;
    1566                 :             :     array_iter  iter;
    1567                 :             :     ArrayMetaState *my_extra;
    1568                 :             : 
    1569                 :             :     /*
    1570                 :             :      * We arrange to look up info about element type, including its send
    1571                 :             :      * conversion proc, only once per series of calls, assuming the element
    1572                 :             :      * type doesn't change underneath us.
    1573                 :             :      */
    1574                 :          23 :     my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
    1575         [ +  + ]:          23 :     if (my_extra == NULL)
    1576                 :             :     {
    1577                 :          20 :         fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
    1578                 :             :                                                       sizeof(ArrayMetaState));
    1579                 :          20 :         my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
    1580                 :          20 :         my_extra->element_type = ~element_type;
    1581                 :             :     }
    1582                 :             : 
    1583         [ +  + ]:          23 :     if (my_extra->element_type != element_type)
    1584                 :             :     {
    1585                 :             :         /* Get info about element type, including its send proc */
    1586                 :          20 :         get_type_io_data(element_type, IOFunc_send,
    1587                 :             :                          &my_extra->typlen, &my_extra->typbyval,
    1588                 :             :                          &my_extra->typalign, &my_extra->typdelim,
    1589                 :             :                          &my_extra->typioparam, &my_extra->typiofunc);
    1590         [ -  + ]:          20 :         if (!OidIsValid(my_extra->typiofunc))
    1591         [ #  # ]:           0 :             ereport(ERROR,
    1592                 :             :                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
    1593                 :             :                      errmsg("no binary output function available for type %s",
    1594                 :             :                             format_type_be(element_type))));
    1595                 :          20 :         fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
    1596                 :          20 :                       fcinfo->flinfo->fn_mcxt);
    1597                 :          20 :         my_extra->element_type = element_type;
    1598                 :             :     }
    1599                 :          23 :     typlen = my_extra->typlen;
    1600                 :          23 :     typbyval = my_extra->typbyval;
    1601                 :          23 :     typalign = my_extra->typalign;
    1602                 :             : 
    1603         [ -  + ]:          23 :     ndim = AARR_NDIM(v);
    1604         [ -  + ]:          23 :     dim = AARR_DIMS(v);
    1605         [ -  + ]:          23 :     lb = AARR_LBOUND(v);
    1606                 :          23 :     nitems = ArrayGetNItems(ndim, dim);
    1607                 :             : 
    1608                 :          23 :     pq_begintypsend(&buf);
    1609                 :             : 
    1610                 :             :     /* Send the array header information */
    1611                 :          23 :     pq_sendint32(&buf, ndim);
    1612   [ -  +  -  - ]:          23 :     pq_sendint32(&buf, AARR_HASNULL(v) ? 1 : 0);
    1613                 :          23 :     pq_sendint32(&buf, element_type);
    1614         [ +  + ]:          46 :     for (i = 0; i < ndim; i++)
    1615                 :             :     {
    1616                 :          23 :         pq_sendint32(&buf, dim[i]);
    1617                 :          23 :         pq_sendint32(&buf, lb[i]);
    1618                 :             :     }
    1619                 :             : 
    1620                 :             :     /* Send the array elements using the element's own sendproc */
    1621                 :          23 :     array_iter_setup(&iter, v, typlen, typbyval, typalign);
    1622                 :             : 
    1623         [ +  + ]:          92 :     for (i = 0; i < nitems; i++)
    1624                 :             :     {
    1625                 :             :         Datum       itemvalue;
    1626                 :             :         bool        isnull;
    1627                 :             : 
    1628                 :             :         /* Get source element, checking for NULL */
    1629                 :          69 :         itemvalue = array_iter_next(&iter, &isnull, i);
    1630                 :             : 
    1631         [ -  + ]:          69 :         if (isnull)
    1632                 :             :         {
    1633                 :             :             /* -1 length means a NULL */
    1634                 :           0 :             pq_sendint32(&buf, -1);
    1635                 :             :         }
    1636                 :             :         else
    1637                 :             :         {
    1638                 :             :             bytea      *outputbytes;
    1639                 :             : 
    1640                 :          69 :             outputbytes = SendFunctionCall(&my_extra->proc, itemvalue);
    1641                 :          69 :             pq_sendint32(&buf, VARSIZE(outputbytes) - VARHDRSZ);
    1642                 :          69 :             pq_sendbytes(&buf, VARDATA(outputbytes),
    1643                 :          69 :                          VARSIZE(outputbytes) - VARHDRSZ);
    1644                 :          69 :             pfree(outputbytes);
    1645                 :             :         }
    1646                 :             :     }
    1647                 :             : 
    1648                 :          23 :     PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
    1649                 :             : }
    1650                 :             : 
    1651                 :             : /*
    1652                 :             :  * array_ndims :
    1653                 :             :  *        returns the number of dimensions of the array pointed to by "v"
    1654                 :             :  */
    1655                 :             : Datum
    1656                 :        1702 : array_ndims(PG_FUNCTION_ARGS)
    1657                 :             : {
    1658                 :        1702 :     AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
    1659                 :             : 
    1660                 :             :     /* Sanity check: does it look like an array at all? */
    1661   [ -  +  -  -  :        1702 :     if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
          +  +  -  +  -  
                -  -  + ]
    1662                 :           8 :         PG_RETURN_NULL();
    1663                 :             : 
    1664         [ -  + ]:        1694 :     PG_RETURN_INT32(AARR_NDIM(v));
    1665                 :             : }
    1666                 :             : 
    1667                 :             : /*
    1668                 :             :  * array_dims :
    1669                 :             :  *        returns the dimensions of the array pointed to by "v", as a "text"
    1670                 :             :  */
    1671                 :             : Datum
    1672                 :        6737 : array_dims(PG_FUNCTION_ARGS)
    1673                 :             : {
    1674                 :        6737 :     AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
    1675                 :             :     char       *p;
    1676                 :             :     int         i;
    1677                 :             :     int        *dimv,
    1678                 :             :                *lb;
    1679                 :             : 
    1680                 :             :     /*
    1681                 :             :      * 33 since we assume 15 digits per number + ':' +'[]'
    1682                 :             :      *
    1683                 :             :      * +1 for trailing null
    1684                 :             :      */
    1685                 :             :     char        buf[MAXDIM * 33 + 1];
    1686                 :             : 
    1687                 :             :     /* Sanity check: does it look like an array at all? */
    1688   [ -  +  -  -  :        6737 :     if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
          +  +  -  +  -  
                -  -  + ]
    1689                 :          48 :         PG_RETURN_NULL();
    1690                 :             : 
    1691         [ -  + ]:        6689 :     dimv = AARR_DIMS(v);
    1692         [ -  + ]:        6689 :     lb = AARR_LBOUND(v);
    1693                 :             : 
    1694                 :        6689 :     p = buf;
    1695   [ -  +  +  + ]:       13450 :     for (i = 0; i < AARR_NDIM(v); i++)
    1696                 :             :     {
    1697                 :        6761 :         sprintf(p, "[%d:%d]", lb[i], dimv[i] + lb[i] - 1);
    1698                 :        6761 :         p += strlen(p);
    1699                 :             :     }
    1700                 :             : 
    1701                 :        6689 :     PG_RETURN_TEXT_P(cstring_to_text(buf));
    1702                 :             : }
    1703                 :             : 
    1704                 :             : /*
    1705                 :             :  * array_lower :
    1706                 :             :  *      returns the lower dimension, of the DIM requested, for
    1707                 :             :  *      the array pointed to by "v", as an int4
    1708                 :             :  */
    1709                 :             : Datum
    1710                 :       17683 : array_lower(PG_FUNCTION_ARGS)
    1711                 :             : {
    1712                 :       17683 :     AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
    1713                 :       17683 :     int         reqdim = PG_GETARG_INT32(1);
    1714                 :             :     int        *lb;
    1715                 :             :     int         result;
    1716                 :             : 
    1717                 :             :     /* Sanity check: does it look like an array at all? */
    1718   [ +  +  +  -  :       17683 :     if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
          +  -  +  +  -  
                +  -  + ]
    1719                 :           0 :         PG_RETURN_NULL();
    1720                 :             : 
    1721                 :             :     /* Sanity check: was the requested dim valid */
    1722   [ +  -  +  +  :       17683 :     if (reqdim <= 0 || reqdim > AARR_NDIM(v))
                   -  + ]
    1723                 :           0 :         PG_RETURN_NULL();
    1724                 :             : 
    1725         [ +  + ]:       17683 :     lb = AARR_LBOUND(v);
    1726                 :       17683 :     result = lb[reqdim - 1];
    1727                 :             : 
    1728                 :       17683 :     PG_RETURN_INT32(result);
    1729                 :             : }
    1730                 :             : 
    1731                 :             : /*
    1732                 :             :  * array_upper :
    1733                 :             :  *      returns the upper dimension, of the DIM requested, for
    1734                 :             :  *      the array pointed to by "v", as an int4
    1735                 :             :  */
    1736                 :             : Datum
    1737                 :       18113 : array_upper(PG_FUNCTION_ARGS)
    1738                 :             : {
    1739                 :       18113 :     AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
    1740                 :       18113 :     int         reqdim = PG_GETARG_INT32(1);
    1741                 :             :     int        *dimv,
    1742                 :             :                *lb;
    1743                 :             :     int         result;
    1744                 :             : 
    1745                 :             :     /* Sanity check: does it look like an array at all? */
    1746   [ +  +  +  -  :       18113 :     if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
          +  +  +  +  -  
                +  -  + ]
    1747                 :          21 :         PG_RETURN_NULL();
    1748                 :             : 
    1749                 :             :     /* Sanity check: was the requested dim valid */
    1750   [ +  -  +  +  :       18092 :     if (reqdim <= 0 || reqdim > AARR_NDIM(v))
                   -  + ]
    1751                 :           0 :         PG_RETURN_NULL();
    1752                 :             : 
    1753         [ +  + ]:       18092 :     lb = AARR_LBOUND(v);
    1754         [ +  + ]:       18092 :     dimv = AARR_DIMS(v);
    1755                 :             : 
    1756                 :       18092 :     result = dimv[reqdim - 1] + lb[reqdim - 1] - 1;
    1757                 :             : 
    1758                 :       18092 :     PG_RETURN_INT32(result);
    1759                 :             : }
    1760                 :             : 
    1761                 :             : /*
    1762                 :             :  * array_length :
    1763                 :             :  *      returns the length, of the dimension requested, for
    1764                 :             :  *      the array pointed to by "v", as an int4
    1765                 :             :  */
    1766                 :             : Datum
    1767                 :       80797 : array_length(PG_FUNCTION_ARGS)
    1768                 :             : {
    1769                 :       80797 :     AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
    1770                 :       80797 :     int         reqdim = PG_GETARG_INT32(1);
    1771                 :             :     int        *dimv;
    1772                 :             :     int         result;
    1773                 :             : 
    1774                 :             :     /* Sanity check: does it look like an array at all? */
    1775   [ +  +  +  -  :       80797 :     if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
          +  -  +  +  -  
                +  -  + ]
    1776                 :           0 :         PG_RETURN_NULL();
    1777                 :             : 
    1778                 :             :     /* Sanity check: was the requested dim valid */
    1779   [ +  +  +  +  :       80797 :     if (reqdim <= 0 || reqdim > AARR_NDIM(v))
                   +  + ]
    1780                 :          10 :         PG_RETURN_NULL();
    1781                 :             : 
    1782         [ +  + ]:       80787 :     dimv = AARR_DIMS(v);
    1783                 :             : 
    1784                 :       80787 :     result = dimv[reqdim - 1];
    1785                 :             : 
    1786                 :       80787 :     PG_RETURN_INT32(result);
    1787                 :             : }
    1788                 :             : 
    1789                 :             : /*
    1790                 :             :  * array_cardinality:
    1791                 :             :  *      returns the total number of elements in an array
    1792                 :             :  */
    1793                 :             : Datum
    1794                 :        1694 : array_cardinality(PG_FUNCTION_ARGS)
    1795                 :             : {
    1796                 :        1694 :     AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
    1797                 :             : 
    1798   [ -  +  -  + ]:        1694 :     PG_RETURN_INT32(ArrayGetNItems(AARR_NDIM(v), AARR_DIMS(v)));
    1799                 :             : }
    1800                 :             : 
    1801                 :             : 
    1802                 :             : /*
    1803                 :             :  * array_get_element :
    1804                 :             :  *    This routine takes an array datum and a subscript array and returns
    1805                 :             :  *    the referenced item as a Datum.  Note that for a pass-by-reference
    1806                 :             :  *    datatype, the returned Datum is a pointer into the array object.
    1807                 :             :  *
    1808                 :             :  * This handles both ordinary varlena arrays and fixed-length arrays.
    1809                 :             :  *
    1810                 :             :  * Inputs:
    1811                 :             :  *  arraydatum: the array object (mustn't be NULL)
    1812                 :             :  *  nSubscripts: number of subscripts supplied
    1813                 :             :  *  indx[]: the subscript values
    1814                 :             :  *  arraytyplen: pg_type.typlen for the array type
    1815                 :             :  *  elmlen: pg_type.typlen for the array's element type
    1816                 :             :  *  elmbyval: pg_type.typbyval for the array's element type
    1817                 :             :  *  elmalign: pg_type.typalign for the array's element type
    1818                 :             :  *
    1819                 :             :  * Outputs:
    1820                 :             :  *  The return value is the element Datum.
    1821                 :             :  *  *isNull is set to indicate whether the element is NULL.
    1822                 :             :  */
    1823                 :             : Datum
    1824                 :      552044 : array_get_element(Datum arraydatum,
    1825                 :             :                   int nSubscripts,
    1826                 :             :                   int *indx,
    1827                 :             :                   int arraytyplen,
    1828                 :             :                   int elmlen,
    1829                 :             :                   bool elmbyval,
    1830                 :             :                   char elmalign,
    1831                 :             :                   bool *isNull)
    1832                 :             : {
    1833                 :             :     int         i,
    1834                 :             :                 ndim,
    1835                 :             :                *dim,
    1836                 :             :                *lb,
    1837                 :             :                 offset,
    1838                 :             :                 fixedDim[1],
    1839                 :             :                 fixedLb[1];
    1840                 :             :     char       *arraydataptr,
    1841                 :             :                *retptr;
    1842                 :             :     uint8      *arraynullsptr;
    1843                 :             : 
    1844         [ +  + ]:      552044 :     if (arraytyplen > 0)
    1845                 :             :     {
    1846                 :             :         /*
    1847                 :             :          * fixed-length arrays -- these are assumed to be 1-d, 0-based
    1848                 :             :          */
    1849                 :      186757 :         ndim = 1;
    1850                 :      186757 :         fixedDim[0] = arraytyplen / elmlen;
    1851                 :      186757 :         fixedLb[0] = 0;
    1852                 :      186757 :         dim = fixedDim;
    1853                 :      186757 :         lb = fixedLb;
    1854                 :      186757 :         arraydataptr = (char *) DatumGetPointer(arraydatum);
    1855                 :      186757 :         arraynullsptr = NULL;
    1856                 :             :     }
    1857         [ +  + ]:      365287 :     else if (VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(arraydatum)))
    1858                 :             :     {
    1859                 :             :         /* expanded array: let's do this in a separate function */
    1860                 :        3421 :         return array_get_element_expanded(arraydatum,
    1861                 :             :                                           nSubscripts,
    1862                 :             :                                           indx,
    1863                 :             :                                           arraytyplen,
    1864                 :             :                                           elmlen,
    1865                 :             :                                           elmbyval,
    1866                 :             :                                           elmalign,
    1867                 :             :                                           isNull);
    1868                 :             :     }
    1869                 :             :     else
    1870                 :             :     {
    1871                 :             :         /* detoast array if necessary, producing normal varlena input */
    1872                 :      361866 :         ArrayType  *array = DatumGetArrayTypeP(arraydatum);
    1873                 :             : 
    1874                 :      361866 :         ndim = ARR_NDIM(array);
    1875                 :      361866 :         dim = ARR_DIMS(array);
    1876                 :      361866 :         lb = ARR_LBOUND(array);
    1877         [ +  + ]:      361866 :         arraydataptr = ARR_DATA_PTR(array);
    1878         [ +  + ]:      361866 :         arraynullsptr = ARR_NULLBITMAP(array);
    1879                 :             :     }
    1880                 :             : 
    1881                 :             :     /*
    1882                 :             :      * Return NULL for invalid subscript
    1883                 :             :      */
    1884   [ +  +  +  -  :      548623 :     if (ndim != nSubscripts || ndim <= 0 || ndim > MAXDIM)
                   -  + ]
    1885                 :             :     {
    1886                 :          64 :         *isNull = true;
    1887                 :          64 :         return (Datum) 0;
    1888                 :             :     }
    1889         [ +  + ]:     1061826 :     for (i = 0; i < ndim; i++)
    1890                 :             :     {
    1891   [ +  +  +  + ]:      548627 :         if (indx[i] < lb[i] || indx[i] >= (dim[i] + lb[i]))
    1892                 :             :         {
    1893                 :       35360 :             *isNull = true;
    1894                 :       35360 :             return (Datum) 0;
    1895                 :             :         }
    1896                 :             :     }
    1897                 :             : 
    1898                 :             :     /*
    1899                 :             :      * Calculate the element number
    1900                 :             :      */
    1901                 :      513199 :     offset = ArrayGetOffset(nSubscripts, dim, lb, indx);
    1902                 :             : 
    1903                 :             :     /*
    1904                 :             :      * Check for NULL array element
    1905                 :             :      */
    1906         [ +  + ]:      513199 :     if (array_get_isnull(arraynullsptr, offset))
    1907                 :             :     {
    1908                 :          48 :         *isNull = true;
    1909                 :          48 :         return (Datum) 0;
    1910                 :             :     }
    1911                 :             : 
    1912                 :             :     /*
    1913                 :             :      * OK, get the element
    1914                 :             :      */
    1915                 :      513151 :     *isNull = false;
    1916                 :      513151 :     retptr = array_seek(arraydataptr, 0, arraynullsptr, offset,
    1917                 :             :                         elmlen, elmbyval, elmalign);
    1918                 :      513151 :     return ArrayCast(retptr, elmbyval, elmlen);
    1919                 :             : }
    1920                 :             : 
    1921                 :             : /*
    1922                 :             :  * Implementation of array_get_element() for an expanded array
    1923                 :             :  */
    1924                 :             : static Datum
    1925                 :        3421 : array_get_element_expanded(Datum arraydatum,
    1926                 :             :                            int nSubscripts, int *indx,
    1927                 :             :                            int arraytyplen,
    1928                 :             :                            int elmlen, bool elmbyval, char elmalign,
    1929                 :             :                            bool *isNull)
    1930                 :             : {
    1931                 :             :     ExpandedArrayHeader *eah;
    1932                 :             :     int         i,
    1933                 :             :                 ndim,
    1934                 :             :                *dim,
    1935                 :             :                *lb,
    1936                 :             :                 offset;
    1937                 :             :     Datum      *dvalues;
    1938                 :             :     bool       *dnulls;
    1939                 :             : 
    1940                 :        3421 :     eah = (ExpandedArrayHeader *) DatumGetEOHP(arraydatum);
    1941                 :             :     Assert(eah->ea_magic == EA_MAGIC);
    1942                 :             : 
    1943                 :             :     /* sanity-check caller's info against object */
    1944                 :             :     Assert(arraytyplen == -1);
    1945                 :             :     Assert(elmlen == eah->typlen);
    1946                 :             :     Assert(elmbyval == eah->typbyval);
    1947                 :             :     Assert(elmalign == eah->typalign);
    1948                 :             : 
    1949                 :        3421 :     ndim = eah->ndims;
    1950                 :        3421 :     dim = eah->dims;
    1951                 :        3421 :     lb = eah->lbound;
    1952                 :             : 
    1953                 :             :     /*
    1954                 :             :      * Return NULL for invalid subscript
    1955                 :             :      */
    1956   [ +  +  +  -  :        3421 :     if (ndim != nSubscripts || ndim <= 0 || ndim > MAXDIM)
                   -  + ]
    1957                 :             :     {
    1958                 :           4 :         *isNull = true;
    1959                 :           4 :         return (Datum) 0;
    1960                 :             :     }
    1961         [ +  + ]:        6834 :     for (i = 0; i < ndim; i++)
    1962                 :             :     {
    1963   [ +  -  -  + ]:        3417 :         if (indx[i] < lb[i] || indx[i] >= (dim[i] + lb[i]))
    1964                 :             :         {
    1965                 :           0 :             *isNull = true;
    1966                 :           0 :             return (Datum) 0;
    1967                 :             :         }
    1968                 :             :     }
    1969                 :             : 
    1970                 :             :     /*
    1971                 :             :      * Calculate the element number
    1972                 :             :      */
    1973                 :        3417 :     offset = ArrayGetOffset(nSubscripts, dim, lb, indx);
    1974                 :             : 
    1975                 :             :     /*
    1976                 :             :      * Deconstruct array if we didn't already.  Note that we apply this even
    1977                 :             :      * if the input is nominally read-only: it should be safe enough.
    1978                 :             :      */
    1979                 :        3417 :     deconstruct_expanded_array(eah);
    1980                 :             : 
    1981                 :        3417 :     dvalues = eah->dvalues;
    1982                 :        3417 :     dnulls = eah->dnulls;
    1983                 :             : 
    1984                 :             :     /*
    1985                 :             :      * Check for NULL array element
    1986                 :             :      */
    1987   [ -  +  -  - ]:        3417 :     if (dnulls && dnulls[offset])
    1988                 :             :     {
    1989                 :           0 :         *isNull = true;
    1990                 :           0 :         return (Datum) 0;
    1991                 :             :     }
    1992                 :             : 
    1993                 :             :     /*
    1994                 :             :      * OK, get the element.  It's OK to return a pass-by-ref value as a
    1995                 :             :      * pointer into the expanded array, for the same reason that regular
    1996                 :             :      * array_get_element can return a pointer into flat arrays: the value is
    1997                 :             :      * assumed not to change for as long as the Datum reference can exist.
    1998                 :             :      */
    1999                 :        3417 :     *isNull = false;
    2000                 :        3417 :     return dvalues[offset];
    2001                 :             : }
    2002                 :             : 
    2003                 :             : /*
    2004                 :             :  * array_get_slice :
    2005                 :             :  *         This routine takes an array and a range of indices (upperIndx and
    2006                 :             :  *         lowerIndx), creates a new array structure for the referred elements
    2007                 :             :  *         and returns a pointer to it.
    2008                 :             :  *
    2009                 :             :  * This handles both ordinary varlena arrays and fixed-length arrays.
    2010                 :             :  *
    2011                 :             :  * Inputs:
    2012                 :             :  *  arraydatum: the array object (mustn't be NULL)
    2013                 :             :  *  nSubscripts: number of subscripts supplied (must be same for upper/lower)
    2014                 :             :  *  upperIndx[]: the upper subscript values
    2015                 :             :  *  lowerIndx[]: the lower subscript values
    2016                 :             :  *  upperProvided[]: true for provided upper subscript values
    2017                 :             :  *  lowerProvided[]: true for provided lower subscript values
    2018                 :             :  *  arraytyplen: pg_type.typlen for the array type
    2019                 :             :  *  elmlen: pg_type.typlen for the array's element type
    2020                 :             :  *  elmbyval: pg_type.typbyval for the array's element type
    2021                 :             :  *  elmalign: pg_type.typalign for the array's element type
    2022                 :             :  *
    2023                 :             :  * Outputs:
    2024                 :             :  *  The return value is the new array Datum (it's never NULL)
    2025                 :             :  *
    2026                 :             :  * Omitted upper and lower subscript values are replaced by the corresponding
    2027                 :             :  * array bound.
    2028                 :             :  *
    2029                 :             :  * NOTE: we assume it is OK to scribble on the provided subscript arrays
    2030                 :             :  * lowerIndx[] and upperIndx[]; also, these arrays must be of size MAXDIM
    2031                 :             :  * even when nSubscripts is less.  These are generally just temporaries.
    2032                 :             :  */
    2033                 :             : Datum
    2034                 :         276 : array_get_slice(Datum arraydatum,
    2035                 :             :                 int nSubscripts,
    2036                 :             :                 int *upperIndx,
    2037                 :             :                 int *lowerIndx,
    2038                 :             :                 bool *upperProvided,
    2039                 :             :                 bool *lowerProvided,
    2040                 :             :                 int arraytyplen,
    2041                 :             :                 int elmlen,
    2042                 :             :                 bool elmbyval,
    2043                 :             :                 char elmalign)
    2044                 :             : {
    2045                 :             :     ArrayType  *array;
    2046                 :             :     ArrayType  *newarray;
    2047                 :             :     int         i,
    2048                 :             :                 ndim,
    2049                 :             :                *dim,
    2050                 :             :                *lb,
    2051                 :             :                *newlb;
    2052                 :             :     int         fixedDim[1],
    2053                 :             :                 fixedLb[1];
    2054                 :             :     Oid         elemtype;
    2055                 :             :     char       *arraydataptr;
    2056                 :             :     uint8      *arraynullsptr;
    2057                 :             :     int32       dataoffset;
    2058                 :             :     int         bytes,
    2059                 :             :                 span[MAXDIM];
    2060                 :             : 
    2061         [ +  + ]:         276 :     if (arraytyplen > 0)
    2062                 :             :     {
    2063                 :             :         /*
    2064                 :             :          * fixed-length arrays -- currently, cannot slice these because parser
    2065                 :             :          * labels output as being of the fixed-length array type! Code below
    2066                 :             :          * shows how we could support it if the parser were changed to label
    2067                 :             :          * output as a suitable varlena array type.
    2068                 :             :          */
    2069         [ +  - ]:          16 :         ereport(ERROR,
    2070                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2071                 :             :                  errmsg("slices of fixed-length arrays not implemented")));
    2072                 :             : 
    2073                 :             :         /*
    2074                 :             :          * fixed-length arrays -- these are assumed to be 1-d, 0-based
    2075                 :             :          *
    2076                 :             :          * XXX where would we get the correct ELEMTYPE from?
    2077                 :             :          */
    2078                 :             :         ndim = 1;
    2079                 :             :         fixedDim[0] = arraytyplen / elmlen;
    2080                 :             :         fixedLb[0] = 0;
    2081                 :             :         dim = fixedDim;
    2082                 :             :         lb = fixedLb;
    2083                 :             :         elemtype = InvalidOid;  /* XXX */
    2084                 :             :         arraydataptr = (char *) DatumGetPointer(arraydatum);
    2085                 :             :         arraynullsptr = NULL;
    2086                 :             :     }
    2087                 :             :     else
    2088                 :             :     {
    2089                 :             :         /* detoast input array if necessary */
    2090                 :         260 :         array = DatumGetArrayTypeP(arraydatum);
    2091                 :             : 
    2092                 :         260 :         ndim = ARR_NDIM(array);
    2093                 :         260 :         dim = ARR_DIMS(array);
    2094                 :         260 :         lb = ARR_LBOUND(array);
    2095                 :         260 :         elemtype = ARR_ELEMTYPE(array);
    2096         [ +  + ]:         260 :         arraydataptr = ARR_DATA_PTR(array);
    2097         [ +  + ]:         260 :         arraynullsptr = ARR_NULLBITMAP(array);
    2098                 :             :     }
    2099                 :             : 
    2100                 :             :     /*
    2101                 :             :      * Check provided subscripts.  A slice exceeding the current array limits
    2102                 :             :      * is silently truncated to the array limits.  If we end up with an empty
    2103                 :             :      * slice, return an empty array.
    2104                 :             :      */
    2105   [ +  +  +  -  :         260 :     if (ndim < nSubscripts || ndim <= 0 || ndim > MAXDIM)
                   -  + ]
    2106                 :          64 :         return PointerGetDatum(construct_empty_array(elemtype));
    2107                 :             : 
    2108         [ +  + ]:         451 :     for (i = 0; i < nSubscripts; i++)
    2109                 :             :     {
    2110   [ +  +  +  + ]:         263 :         if (!lowerProvided[i] || lowerIndx[i] < lb[i])
    2111                 :          84 :             lowerIndx[i] = lb[i];
    2112   [ +  +  +  + ]:         263 :         if (!upperProvided[i] || upperIndx[i] >= (dim[i] + lb[i]))
    2113                 :          48 :             upperIndx[i] = dim[i] + lb[i] - 1;
    2114         [ +  + ]:         263 :         if (lowerIndx[i] > upperIndx[i])
    2115                 :           8 :             return PointerGetDatum(construct_empty_array(elemtype));
    2116                 :             :     }
    2117                 :             :     /* fill any missing subscript positions with full array range */
    2118         [ +  + ]:         221 :     for (; i < ndim; i++)
    2119                 :             :     {
    2120                 :          33 :         lowerIndx[i] = lb[i];
    2121                 :          33 :         upperIndx[i] = dim[i] + lb[i] - 1;
    2122         [ -  + ]:          33 :         if (lowerIndx[i] > upperIndx[i])
    2123                 :           0 :             return PointerGetDatum(construct_empty_array(elemtype));
    2124                 :             :     }
    2125                 :             : 
    2126                 :         188 :     mda_get_range(ndim, span, lowerIndx, upperIndx);
    2127                 :             : 
    2128                 :         188 :     bytes = array_slice_size(arraydataptr, arraynullsptr,
    2129                 :             :                              ndim, dim, lb,
    2130                 :             :                              lowerIndx, upperIndx,
    2131                 :             :                              elmlen, elmbyval, elmalign);
    2132                 :             : 
    2133                 :             :     /*
    2134                 :             :      * Currently, we put a null bitmap in the result if the source has one;
    2135                 :             :      * could be smarter ...
    2136                 :             :      */
    2137         [ +  + ]:         188 :     if (arraynullsptr)
    2138                 :             :     {
    2139                 :          24 :         dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, ArrayGetNItems(ndim, span));
    2140                 :          24 :         bytes += dataoffset;
    2141                 :             :     }
    2142                 :             :     else
    2143                 :             :     {
    2144                 :         164 :         dataoffset = 0;         /* marker for no null bitmap */
    2145                 :         164 :         bytes += ARR_OVERHEAD_NONULLS(ndim);
    2146                 :             :     }
    2147                 :             : 
    2148                 :         188 :     newarray = (ArrayType *) palloc0(bytes);
    2149                 :         188 :     SET_VARSIZE(newarray, bytes);
    2150                 :         188 :     newarray->ndim = ndim;
    2151                 :         188 :     newarray->dataoffset = dataoffset;
    2152                 :         188 :     newarray->elemtype = elemtype;
    2153                 :         188 :     memcpy(ARR_DIMS(newarray), span, ndim * sizeof(int));
    2154                 :             : 
    2155                 :             :     /*
    2156                 :             :      * Lower bounds of the new array are set to 1.  Formerly (before 7.3) we
    2157                 :             :      * copied the given lowerIndx values ... but that seems confusing.
    2158                 :             :      */
    2159                 :         188 :     newlb = ARR_LBOUND(newarray);
    2160         [ +  + ]:         476 :     for (i = 0; i < ndim; i++)
    2161                 :         288 :         newlb[i] = 1;
    2162                 :             : 
    2163                 :         188 :     array_extract_slice(newarray,
    2164                 :             :                         ndim, dim, lb,
    2165                 :             :                         arraydataptr, arraynullsptr,
    2166                 :             :                         lowerIndx, upperIndx,
    2167                 :             :                         elmlen, elmbyval, elmalign);
    2168                 :             : 
    2169                 :         188 :     return PointerGetDatum(newarray);
    2170                 :             : }
    2171                 :             : 
    2172                 :             : /*
    2173                 :             :  * array_set_element :
    2174                 :             :  *        This routine sets the value of one array element (specified by
    2175                 :             :  *        a subscript array) to a new value specified by "dataValue".
    2176                 :             :  *
    2177                 :             :  * This handles both ordinary varlena arrays and fixed-length arrays.
    2178                 :             :  *
    2179                 :             :  * Inputs:
    2180                 :             :  *  arraydatum: the initial array object (mustn't be NULL)
    2181                 :             :  *  nSubscripts: number of subscripts supplied
    2182                 :             :  *  indx[]: the subscript values
    2183                 :             :  *  dataValue: the datum to be inserted at the given position
    2184                 :             :  *  isNull: whether dataValue is NULL
    2185                 :             :  *  arraytyplen: pg_type.typlen for the array type
    2186                 :             :  *  elmlen: pg_type.typlen for the array's element type
    2187                 :             :  *  elmbyval: pg_type.typbyval for the array's element type
    2188                 :             :  *  elmalign: pg_type.typalign for the array's element type
    2189                 :             :  *
    2190                 :             :  * Result:
    2191                 :             :  *        A new array is returned, just like the old except for the one
    2192                 :             :  *        modified entry.  The original array object is not changed,
    2193                 :             :  *        unless what is passed is a read-write reference to an expanded
    2194                 :             :  *        array object; in that case the expanded array is updated in-place.
    2195                 :             :  *
    2196                 :             :  * For one-dimensional arrays only, we allow the array to be extended
    2197                 :             :  * by assigning to a position outside the existing subscript range; any
    2198                 :             :  * positions between the existing elements and the new one are set to NULLs.
    2199                 :             :  * (XXX TODO: allow a corresponding behavior for multidimensional arrays)
    2200                 :             :  *
    2201                 :             :  * NOTE: For assignments, we throw an error for invalid subscripts etc,
    2202                 :             :  * rather than returning a NULL as the fetch operations do.
    2203                 :             :  */
    2204                 :             : Datum
    2205                 :        2668 : array_set_element(Datum arraydatum,
    2206                 :             :                   int nSubscripts,
    2207                 :             :                   int *indx,
    2208                 :             :                   Datum dataValue,
    2209                 :             :                   bool isNull,
    2210                 :             :                   int arraytyplen,
    2211                 :             :                   int elmlen,
    2212                 :             :                   bool elmbyval,
    2213                 :             :                   char elmalign)
    2214                 :             : {
    2215                 :             :     ArrayType  *array;
    2216                 :             :     ArrayType  *newarray;
    2217                 :             :     int         i,
    2218                 :             :                 ndim,
    2219                 :             :                 dim[MAXDIM],
    2220                 :             :                 lb[MAXDIM],
    2221                 :             :                 offset;
    2222                 :             :     char       *elt_ptr;
    2223                 :             :     bool        newhasnulls;
    2224                 :             :     uint8      *oldnullbitmap;
    2225                 :             :     int         oldnitems,
    2226                 :             :                 newnitems,
    2227                 :             :                 olddatasize,
    2228                 :             :                 newsize,
    2229                 :             :                 olditemlen,
    2230                 :             :                 newitemlen,
    2231                 :             :                 overheadlen,
    2232                 :             :                 oldoverheadlen,
    2233                 :             :                 addedbefore,
    2234                 :             :                 addedafter,
    2235                 :             :                 lenbefore,
    2236                 :             :                 lenafter;
    2237                 :        2668 :     uint8       elmalignby = typalign_to_alignby(elmalign);
    2238                 :             : 
    2239         [ +  + ]:        2668 :     if (arraytyplen > 0)
    2240                 :             :     {
    2241                 :             :         /*
    2242                 :             :          * fixed-length arrays -- these are assumed to be 1-d, 0-based. We
    2243                 :             :          * cannot extend them, either.
    2244                 :             :          */
    2245                 :             :         char       *resultarray;
    2246                 :             : 
    2247         [ -  + ]:          12 :         if (nSubscripts != 1)
    2248         [ #  # ]:           0 :             ereport(ERROR,
    2249                 :             :                     (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    2250                 :             :                      errmsg("wrong number of array subscripts")));
    2251                 :             : 
    2252   [ +  -  +  + ]:          12 :         if (indx[0] < 0 || indx[0] >= arraytyplen / elmlen)
    2253         [ +  - ]:           4 :             ereport(ERROR,
    2254                 :             :                     (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    2255                 :             :                      errmsg("array subscript out of range")));
    2256                 :             : 
    2257         [ -  + ]:           8 :         if (isNull)
    2258         [ #  # ]:           0 :             ereport(ERROR,
    2259                 :             :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    2260                 :             :                      errmsg("cannot assign null value to an element of a fixed-length array")));
    2261                 :             : 
    2262                 :           8 :         resultarray = (char *) palloc(arraytyplen);
    2263                 :           8 :         memcpy(resultarray, DatumGetPointer(arraydatum), arraytyplen);
    2264                 :           8 :         elt_ptr = resultarray + indx[0] * elmlen;
    2265                 :           8 :         ArrayCastAndSet(dataValue, elmlen, elmbyval, elmalignby, elt_ptr);
    2266                 :           8 :         return PointerGetDatum(resultarray);
    2267                 :             :     }
    2268                 :             : 
    2269   [ +  -  -  + ]:        2656 :     if (nSubscripts <= 0 || nSubscripts > MAXDIM)
    2270         [ #  # ]:           0 :         ereport(ERROR,
    2271                 :             :                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    2272                 :             :                  errmsg("wrong number of array subscripts")));
    2273                 :             : 
    2274                 :             :     /* make sure item to be inserted is not toasted */
    2275   [ +  +  +  + ]:        2656 :     if (elmlen == -1 && !isNull)
    2276                 :        1590 :         dataValue = PointerGetDatum(PG_DETOAST_DATUM(dataValue));
    2277                 :             : 
    2278         [ +  + ]:        2656 :     if (VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(arraydatum)))
    2279                 :             :     {
    2280                 :             :         /* expanded array: let's do this in a separate function */
    2281                 :        1361 :         return array_set_element_expanded(arraydatum,
    2282                 :             :                                           nSubscripts,
    2283                 :             :                                           indx,
    2284                 :             :                                           dataValue,
    2285                 :             :                                           isNull,
    2286                 :             :                                           arraytyplen,
    2287                 :             :                                           elmlen,
    2288                 :             :                                           elmbyval,
    2289                 :             :                                           elmalign);
    2290                 :             :     }
    2291                 :             : 
    2292                 :             :     /* detoast input array if necessary */
    2293                 :        1295 :     array = DatumGetArrayTypeP(arraydatum);
    2294                 :             : 
    2295                 :        1295 :     ndim = ARR_NDIM(array);
    2296                 :             : 
    2297                 :             :     /*
    2298                 :             :      * if number of dims is zero, i.e. an empty array, create an array with
    2299                 :             :      * nSubscripts dimensions, and set the lower bounds to the supplied
    2300                 :             :      * subscripts
    2301                 :             :      */
    2302         [ +  + ]:        1295 :     if (ndim == 0)
    2303                 :             :     {
    2304                 :         240 :         Oid         elmtype = ARR_ELEMTYPE(array);
    2305                 :             : 
    2306         [ +  + ]:         481 :         for (i = 0; i < nSubscripts; i++)
    2307                 :             :         {
    2308                 :         241 :             dim[i] = 1;
    2309                 :         241 :             lb[i] = indx[i];
    2310                 :             :         }
    2311                 :             : 
    2312                 :         240 :         return PointerGetDatum(construct_md_array(&dataValue, &isNull,
    2313                 :             :                                                   nSubscripts, dim, lb,
    2314                 :             :                                                   elmtype,
    2315                 :             :                                                   elmlen, elmbyval, elmalign));
    2316                 :             :     }
    2317                 :             : 
    2318         [ +  + ]:        1055 :     if (ndim != nSubscripts)
    2319         [ +  - ]:           4 :         ereport(ERROR,
    2320                 :             :                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    2321                 :             :                  errmsg("wrong number of array subscripts")));
    2322                 :             : 
    2323                 :             :     /* copy dim/lb since we may modify them */
    2324                 :        1051 :     memcpy(dim, ARR_DIMS(array), ndim * sizeof(int));
    2325                 :        1051 :     memcpy(lb, ARR_LBOUND(array), ndim * sizeof(int));
    2326                 :             : 
    2327   [ +  +  +  + ]:        1051 :     newhasnulls = (ARR_HASNULL(array) || isNull);
    2328                 :        1051 :     addedbefore = addedafter = 0;
    2329                 :             : 
    2330                 :             :     /*
    2331                 :             :      * Check subscripts.  We assume the existing subscripts passed
    2332                 :             :      * ArrayCheckBounds, so that dim[i] + lb[i] can be computed without
    2333                 :             :      * overflow.  But we must beware of other overflows in our calculations of
    2334                 :             :      * new dim[] values.
    2335                 :             :      */
    2336         [ +  + ]:        1051 :     if (ndim == 1)
    2337                 :             :     {
    2338         [ +  + ]:        1047 :         if (indx[0] < lb[0])
    2339                 :             :         {
    2340                 :             :             /* addedbefore = lb[0] - indx[0]; */
    2341                 :             :             /* dim[0] += addedbefore; */
    2342   [ +  -  -  + ]:          32 :             if (pg_sub_s32_overflow(lb[0], indx[0], &addedbefore) ||
    2343                 :          16 :                 pg_add_s32_overflow(dim[0], addedbefore, &dim[0]))
    2344         [ #  # ]:           0 :                 ereport(ERROR,
    2345                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2346                 :             :                          errmsg("array size exceeds the maximum allowed (%zu)",
    2347                 :             :                                 MaxArraySize)));
    2348                 :          16 :             lb[0] = indx[0];
    2349         [ +  + ]:          16 :             if (addedbefore > 1)
    2350                 :           8 :                 newhasnulls = true; /* will insert nulls */
    2351                 :             :         }
    2352         [ +  + ]:        1047 :         if (indx[0] >= (dim[0] + lb[0]))
    2353                 :             :         {
    2354                 :             :             /* addedafter = indx[0] - (dim[0] + lb[0]) + 1; */
    2355                 :             :             /* dim[0] += addedafter; */
    2356   [ +  +  +  - ]:        1606 :             if (pg_sub_s32_overflow(indx[0], dim[0] + lb[0], &addedafter) ||
    2357         [ -  + ]:        1602 :                 pg_add_s32_overflow(addedafter, 1, &addedafter) ||
    2358                 :         801 :                 pg_add_s32_overflow(dim[0], addedafter, &dim[0]))
    2359         [ +  - ]:           4 :                 ereport(ERROR,
    2360                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2361                 :             :                          errmsg("array size exceeds the maximum allowed (%zu)",
    2362                 :             :                                 MaxArraySize)));
    2363         [ +  + ]:         801 :             if (addedafter > 1)
    2364                 :          25 :                 newhasnulls = true; /* will insert nulls */
    2365                 :             :         }
    2366                 :             :     }
    2367                 :             :     else
    2368                 :             :     {
    2369                 :             :         /*
    2370                 :             :          * XXX currently we do not support extending multi-dimensional arrays
    2371                 :             :          * during assignment
    2372                 :             :          */
    2373         [ +  + ]:          12 :         for (i = 0; i < ndim; i++)
    2374                 :             :         {
    2375         [ +  - ]:           8 :             if (indx[i] < lb[i] ||
    2376         [ -  + ]:           8 :                 indx[i] >= (dim[i] + lb[i]))
    2377         [ #  # ]:           0 :                 ereport(ERROR,
    2378                 :             :                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    2379                 :             :                          errmsg("array subscript out of range")));
    2380                 :             :         }
    2381                 :             :     }
    2382                 :             : 
    2383                 :             :     /* This checks for overflow of the array dimensions */
    2384                 :        1047 :     newnitems = ArrayGetNItems(ndim, dim);
    2385                 :        1047 :     ArrayCheckBounds(ndim, dim, lb);
    2386                 :             : 
    2387                 :             :     /*
    2388                 :             :      * Compute sizes of items and areas to copy
    2389                 :             :      */
    2390         [ +  + ]:        1047 :     if (newhasnulls)
    2391                 :          90 :         overheadlen = ARR_OVERHEAD_WITHNULLS(ndim, newnitems);
    2392                 :             :     else
    2393                 :         957 :         overheadlen = ARR_OVERHEAD_NONULLS(ndim);
    2394                 :        1047 :     oldnitems = ArrayGetNItems(ndim, ARR_DIMS(array));
    2395         [ +  + ]:        1047 :     oldnullbitmap = ARR_NULLBITMAP(array);
    2396         [ +  + ]:        1047 :     oldoverheadlen = ARR_DATA_OFFSET(array);
    2397                 :        1047 :     olddatasize = ARR_SIZE(array) - oldoverheadlen;
    2398         [ +  + ]:        1047 :     if (addedbefore)
    2399                 :             :     {
    2400                 :          16 :         offset = 0;
    2401                 :          16 :         lenbefore = 0;
    2402                 :          16 :         olditemlen = 0;
    2403                 :          16 :         lenafter = olddatasize;
    2404                 :             :     }
    2405         [ +  + ]:        1031 :     else if (addedafter)
    2406                 :             :     {
    2407                 :         801 :         offset = oldnitems;
    2408                 :         801 :         lenbefore = olddatasize;
    2409                 :         801 :         olditemlen = 0;
    2410                 :         801 :         lenafter = 0;
    2411                 :             :     }
    2412                 :             :     else
    2413                 :             :     {
    2414                 :         230 :         offset = ArrayGetOffset(nSubscripts, dim, lb, indx);
    2415         [ +  + ]:         230 :         elt_ptr = array_seek(ARR_DATA_PTR(array), 0, oldnullbitmap, offset,
    2416                 :             :                              elmlen, elmbyval, elmalign);
    2417         [ +  + ]:         230 :         lenbefore = (int) (elt_ptr - ARR_DATA_PTR(array));
    2418         [ +  + ]:         230 :         if (array_get_isnull(oldnullbitmap, offset))
    2419                 :          16 :             olditemlen = 0;
    2420                 :             :         else
    2421                 :             :         {
    2422   [ +  +  +  - ]:         214 :             olditemlen = att_addlength_pointer(0, elmlen, elt_ptr);
    2423                 :         214 :             olditemlen = att_nominal_alignby(olditemlen, elmalignby);
    2424                 :             :         }
    2425                 :         230 :         lenafter = olddatasize - lenbefore - olditemlen;
    2426                 :             :     }
    2427                 :             : 
    2428         [ +  + ]:        1047 :     if (isNull)
    2429                 :          13 :         newitemlen = 0;
    2430                 :             :     else
    2431                 :             :     {
    2432   [ +  +  +  - ]:        1034 :         newitemlen = att_addlength_datum(0, elmlen, dataValue);
    2433                 :        1034 :         newitemlen = att_nominal_alignby(newitemlen, elmalignby);
    2434                 :             :     }
    2435                 :             : 
    2436                 :        1047 :     newsize = overheadlen + lenbefore + newitemlen + lenafter;
    2437                 :             : 
    2438                 :             :     /*
    2439                 :             :      * OK, create the new array and fill in header/dimensions
    2440                 :             :      */
    2441                 :        1047 :     newarray = (ArrayType *) palloc0(newsize);
    2442                 :        1047 :     SET_VARSIZE(newarray, newsize);
    2443                 :        1047 :     newarray->ndim = ndim;
    2444         [ +  + ]:        1047 :     newarray->dataoffset = newhasnulls ? overheadlen : 0;
    2445                 :        1047 :     newarray->elemtype = ARR_ELEMTYPE(array);
    2446                 :        1047 :     memcpy(ARR_DIMS(newarray), dim, ndim * sizeof(int));
    2447                 :        1047 :     memcpy(ARR_LBOUND(newarray), lb, ndim * sizeof(int));
    2448                 :             : 
    2449                 :             :     /*
    2450                 :             :      * Fill in data
    2451                 :             :      */
    2452                 :        1047 :     memcpy((char *) newarray + overheadlen,
    2453                 :             :            (char *) array + oldoverheadlen,
    2454                 :             :            lenbefore);
    2455         [ +  + ]:        1047 :     if (!isNull)
    2456                 :        1034 :         ArrayCastAndSet(dataValue, elmlen, elmbyval, elmalignby,
    2457                 :        1034 :                         (char *) newarray + overheadlen + lenbefore);
    2458                 :        1047 :     memcpy((char *) newarray + overheadlen + lenbefore + newitemlen,
    2459                 :        1047 :            (char *) array + oldoverheadlen + lenbefore + olditemlen,
    2460                 :             :            lenafter);
    2461                 :             : 
    2462                 :             :     /*
    2463                 :             :      * Fill in nulls bitmap if needed
    2464                 :             :      *
    2465                 :             :      * Note: it's possible we just replaced the last NULL with a non-NULL, and
    2466                 :             :      * could get rid of the bitmap.  Seems not worth testing for though.
    2467                 :             :      */
    2468         [ +  + ]:        1047 :     if (newhasnulls)
    2469                 :             :     {
    2470         [ +  - ]:          90 :         uint8      *newnullbitmap = ARR_NULLBITMAP(newarray);
    2471                 :             : 
    2472                 :             :         /* palloc0 above already marked any inserted positions as nulls */
    2473                 :             :         /* Fix the inserted value */
    2474         [ +  + ]:          90 :         if (addedafter)
    2475                 :          38 :             array_set_isnull(newnullbitmap, newnitems - 1, isNull);
    2476                 :             :         else
    2477                 :          52 :             array_set_isnull(newnullbitmap, offset, isNull);
    2478                 :             :         /* Fix the copied range(s) */
    2479         [ +  + ]:          90 :         if (addedbefore)
    2480                 :          16 :             array_bitmap_copy(newnullbitmap, addedbefore,
    2481                 :             :                               oldnullbitmap, 0,
    2482                 :             :                               oldnitems);
    2483                 :             :         else
    2484                 :             :         {
    2485                 :          74 :             array_bitmap_copy(newnullbitmap, 0,
    2486                 :             :                               oldnullbitmap, 0,
    2487                 :             :                               offset);
    2488         [ +  + ]:          74 :             if (addedafter == 0)
    2489                 :          36 :                 array_bitmap_copy(newnullbitmap, offset + 1,
    2490                 :             :                                   oldnullbitmap, offset + 1,
    2491                 :          36 :                                   oldnitems - offset - 1);
    2492                 :             :         }
    2493                 :             :     }
    2494                 :             : 
    2495                 :        1047 :     return PointerGetDatum(newarray);
    2496                 :             : }
    2497                 :             : 
    2498                 :             : /*
    2499                 :             :  * Implementation of array_set_element() for an expanded array
    2500                 :             :  *
    2501                 :             :  * Note: as with any operation on a read/write expanded object, we must
    2502                 :             :  * take pains not to leave the object in a corrupt state if we fail partway
    2503                 :             :  * through.
    2504                 :             :  */
    2505                 :             : static Datum
    2506                 :        1361 : array_set_element_expanded(Datum arraydatum,
    2507                 :             :                            int nSubscripts, int *indx,
    2508                 :             :                            Datum dataValue, bool isNull,
    2509                 :             :                            int arraytyplen,
    2510                 :             :                            int elmlen, bool elmbyval, char elmalign)
    2511                 :             : {
    2512                 :             :     ExpandedArrayHeader *eah;
    2513                 :             :     Datum      *dvalues;
    2514                 :             :     bool       *dnulls;
    2515                 :             :     int         i,
    2516                 :             :                 ndim,
    2517                 :             :                 dim[MAXDIM],
    2518                 :             :                 lb[MAXDIM],
    2519                 :             :                 offset;
    2520                 :             :     bool        dimschanged,
    2521                 :             :                 newhasnulls;
    2522                 :             :     int         addedbefore,
    2523                 :             :                 addedafter;
    2524                 :             :     char       *oldValue;
    2525                 :             : 
    2526                 :             :     /* Convert to R/W object if not so already */
    2527                 :        1361 :     eah = DatumGetExpandedArray(arraydatum);
    2528                 :             : 
    2529                 :             :     /* Sanity-check caller's info against object; we don't use it otherwise */
    2530                 :             :     Assert(arraytyplen == -1);
    2531                 :             :     Assert(elmlen == eah->typlen);
    2532                 :             :     Assert(elmbyval == eah->typbyval);
    2533                 :             :     Assert(elmalign == eah->typalign);
    2534                 :             : 
    2535                 :             :     /*
    2536                 :             :      * Copy dimension info into local storage.  This allows us to modify the
    2537                 :             :      * dimensions if needed, while not messing up the expanded value if we
    2538                 :             :      * fail partway through.
    2539                 :             :      */
    2540                 :        1361 :     ndim = eah->ndims;
    2541                 :             :     Assert(ndim >= 0 && ndim <= MAXDIM);
    2542                 :        1361 :     memcpy(dim, eah->dims, ndim * sizeof(int));
    2543                 :        1361 :     memcpy(lb, eah->lbound, ndim * sizeof(int));
    2544                 :        1361 :     dimschanged = false;
    2545                 :             : 
    2546                 :             :     /*
    2547                 :             :      * if number of dims is zero, i.e. an empty array, create an array with
    2548                 :             :      * nSubscripts dimensions, and set the lower bounds to the supplied
    2549                 :             :      * subscripts.
    2550                 :             :      */
    2551         [ +  + ]:        1361 :     if (ndim == 0)
    2552                 :             :     {
    2553                 :             :         /*
    2554                 :             :          * Allocate adequate space for new dimension info.  This is harmless
    2555                 :             :          * if we fail later.
    2556                 :             :          */
    2557                 :             :         Assert(nSubscripts > 0 && nSubscripts <= MAXDIM);
    2558                 :         271 :         eah->dims = (int *) MemoryContextAllocZero(eah->hdr.eoh_context,
    2559                 :             :                                                    nSubscripts * sizeof(int));
    2560                 :         271 :         eah->lbound = (int *) MemoryContextAllocZero(eah->hdr.eoh_context,
    2561                 :             :                                                      nSubscripts * sizeof(int));
    2562                 :             : 
    2563                 :             :         /* Update local copies of dimension info */
    2564                 :         271 :         ndim = nSubscripts;
    2565         [ +  + ]:         542 :         for (i = 0; i < nSubscripts; i++)
    2566                 :             :         {
    2567                 :         271 :             dim[i] = 0;
    2568                 :         271 :             lb[i] = indx[i];
    2569                 :             :         }
    2570                 :         271 :         dimschanged = true;
    2571                 :             :     }
    2572         [ -  + ]:        1090 :     else if (ndim != nSubscripts)
    2573         [ #  # ]:           0 :         ereport(ERROR,
    2574                 :             :                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    2575                 :             :                  errmsg("wrong number of array subscripts")));
    2576                 :             : 
    2577                 :             :     /*
    2578                 :             :      * Deconstruct array if we didn't already.  (Someday maybe add a special
    2579                 :             :      * case path for fixed-length, no-nulls cases, where we can overwrite an
    2580                 :             :      * element in place without ever deconstructing.  But today is not that
    2581                 :             :      * day.)
    2582                 :             :      */
    2583                 :        1361 :     deconstruct_expanded_array(eah);
    2584                 :             : 
    2585                 :             :     /*
    2586                 :             :      * Copy new element into array's context, if needed (we assume it's
    2587                 :             :      * already detoasted, so no junk should be created).  Doing this before
    2588                 :             :      * we've made any significant changes ensures that our behavior is sane
    2589                 :             :      * even when the source is a reference to some element of this same array.
    2590                 :             :      * If we fail further down, this memory is leaked, but that's reasonably
    2591                 :             :      * harmless.
    2592                 :             :      */
    2593   [ +  +  +  - ]:        1361 :     if (!eah->typbyval && !isNull)
    2594                 :             :     {
    2595                 :         587 :         MemoryContext oldcxt = MemoryContextSwitchTo(eah->hdr.eoh_context);
    2596                 :             : 
    2597                 :         587 :         dataValue = datumCopy(dataValue, false, eah->typlen);
    2598                 :         587 :         MemoryContextSwitchTo(oldcxt);
    2599                 :             :     }
    2600                 :             : 
    2601                 :        1361 :     dvalues = eah->dvalues;
    2602                 :        1361 :     dnulls = eah->dnulls;
    2603                 :             : 
    2604   [ +  -  -  + ]:        1361 :     newhasnulls = ((dnulls != NULL) || isNull);
    2605                 :        1361 :     addedbefore = addedafter = 0;
    2606                 :             : 
    2607                 :             :     /*
    2608                 :             :      * Check subscripts (this logic must match array_set_element).  We assume
    2609                 :             :      * the existing subscripts passed ArrayCheckBounds, so that dim[i] + lb[i]
    2610                 :             :      * can be computed without overflow.  But we must beware of other
    2611                 :             :      * overflows in our calculations of new dim[] values.
    2612                 :             :      */
    2613         [ +  - ]:        1361 :     if (ndim == 1)
    2614                 :             :     {
    2615         [ +  + ]:        1361 :         if (indx[0] < lb[0])
    2616                 :             :         {
    2617                 :             :             /* addedbefore = lb[0] - indx[0]; */
    2618                 :             :             /* dim[0] += addedbefore; */
    2619   [ +  -  -  + ]:         126 :             if (pg_sub_s32_overflow(lb[0], indx[0], &addedbefore) ||
    2620                 :          63 :                 pg_add_s32_overflow(dim[0], addedbefore, &dim[0]))
    2621         [ #  # ]:           0 :                 ereport(ERROR,
    2622                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2623                 :             :                          errmsg("array size exceeds the maximum allowed (%zu)",
    2624                 :             :                                 MaxArraySize)));
    2625                 :          63 :             lb[0] = indx[0];
    2626                 :          63 :             dimschanged = true;
    2627         [ -  + ]:          63 :             if (addedbefore > 1)
    2628                 :           0 :                 newhasnulls = true; /* will insert nulls */
    2629                 :             :         }
    2630         [ +  + ]:        1361 :         if (indx[0] >= (dim[0] + lb[0]))
    2631                 :             :         {
    2632                 :             :             /* addedafter = indx[0] - (dim[0] + lb[0]) + 1; */
    2633                 :             :             /* dim[0] += addedafter; */
    2634   [ +  +  +  - ]:        2528 :             if (pg_sub_s32_overflow(indx[0], dim[0] + lb[0], &addedafter) ||
    2635         [ -  + ]:        2524 :                 pg_add_s32_overflow(addedafter, 1, &addedafter) ||
    2636                 :        1262 :                 pg_add_s32_overflow(dim[0], addedafter, &dim[0]))
    2637         [ +  - ]:           4 :                 ereport(ERROR,
    2638                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2639                 :             :                          errmsg("array size exceeds the maximum allowed (%zu)",
    2640                 :             :                                 MaxArraySize)));
    2641                 :        1262 :             dimschanged = true;
    2642         [ -  + ]:        1262 :             if (addedafter > 1)
    2643                 :           0 :                 newhasnulls = true; /* will insert nulls */
    2644                 :             :         }
    2645                 :             :     }
    2646                 :             :     else
    2647                 :             :     {
    2648                 :             :         /*
    2649                 :             :          * XXX currently we do not support extending multi-dimensional arrays
    2650                 :             :          * during assignment
    2651                 :             :          */
    2652         [ #  # ]:           0 :         for (i = 0; i < ndim; i++)
    2653                 :             :         {
    2654         [ #  # ]:           0 :             if (indx[i] < lb[i] ||
    2655         [ #  # ]:           0 :                 indx[i] >= (dim[i] + lb[i]))
    2656         [ #  # ]:           0 :                 ereport(ERROR,
    2657                 :             :                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    2658                 :             :                          errmsg("array subscript out of range")));
    2659                 :             :         }
    2660                 :             :     }
    2661                 :             : 
    2662                 :             :     /* Check for overflow of the array dimensions */
    2663         [ +  + ]:        1357 :     if (dimschanged)
    2664                 :             :     {
    2665                 :        1325 :         (void) ArrayGetNItems(ndim, dim);
    2666                 :        1325 :         ArrayCheckBounds(ndim, dim, lb);
    2667                 :             :     }
    2668                 :             : 
    2669                 :             :     /* Now we can calculate linear offset of target item in array */
    2670                 :        1357 :     offset = ArrayGetOffset(nSubscripts, dim, lb, indx);
    2671                 :             : 
    2672                 :             :     /* Physically enlarge existing dvalues/dnulls arrays if needed */
    2673         [ +  + ]:        1357 :     if (dim[0] > eah->dvalueslen)
    2674                 :             :     {
    2675                 :             :         /* We want some extra space if we're enlarging */
    2676                 :        1317 :         int         newlen = dim[0] + dim[0] / 8;
    2677                 :             : 
    2678                 :        1317 :         newlen = Max(newlen, dim[0]);   /* integer overflow guard */
    2679                 :        1317 :         eah->dvalues = dvalues = repalloc_array(dvalues, Datum, newlen);
    2680         [ -  + ]:        1317 :         if (dnulls)
    2681                 :           0 :             eah->dnulls = dnulls = repalloc_array(dnulls, bool, newlen);
    2682                 :        1317 :         eah->dvalueslen = newlen;
    2683                 :             :     }
    2684                 :             : 
    2685                 :             :     /*
    2686                 :             :      * If we need a nulls bitmap and don't already have one, create it, being
    2687                 :             :      * sure to mark all existing entries as not null.
    2688                 :             :      */
    2689   [ -  +  -  - ]:        1357 :     if (newhasnulls && dnulls == NULL)
    2690                 :           0 :         eah->dnulls = dnulls = (bool *)
    2691                 :           0 :             MemoryContextAllocZero(eah->hdr.eoh_context,
    2692                 :           0 :                                    eah->dvalueslen * sizeof(bool));
    2693                 :             : 
    2694                 :             :     /*
    2695                 :             :      * We now have all the needed space allocated, so we're ready to make
    2696                 :             :      * irreversible changes.  Be very wary of allowing failure below here.
    2697                 :             :      */
    2698                 :             : 
    2699                 :             :     /* Flattened value will no longer represent array accurately */
    2700                 :        1357 :     eah->fvalue = NULL;
    2701                 :             :     /* And we don't know the flattened size either */
    2702                 :        1357 :     eah->flat_size = 0;
    2703                 :             : 
    2704                 :             :     /* Update dimensionality info if needed */
    2705         [ +  + ]:        1357 :     if (dimschanged)
    2706                 :             :     {
    2707                 :        1325 :         eah->ndims = ndim;
    2708                 :        1325 :         memcpy(eah->dims, dim, ndim * sizeof(int));
    2709                 :        1325 :         memcpy(eah->lbound, lb, ndim * sizeof(int));
    2710                 :             :     }
    2711                 :             : 
    2712                 :             :     /* Reposition items if needed, and fill addedbefore items with nulls */
    2713         [ +  + ]:        1357 :     if (addedbefore > 0)
    2714                 :             :     {
    2715                 :          63 :         memmove(dvalues + addedbefore, dvalues, eah->nelems * sizeof(Datum));
    2716         [ +  + ]:         126 :         for (i = 0; i < addedbefore; i++)
    2717                 :          63 :             dvalues[i] = (Datum) 0;
    2718         [ -  + ]:          63 :         if (dnulls)
    2719                 :             :         {
    2720                 :           0 :             memmove(dnulls + addedbefore, dnulls, eah->nelems * sizeof(bool));
    2721         [ #  # ]:           0 :             for (i = 0; i < addedbefore; i++)
    2722                 :           0 :                 dnulls[i] = true;
    2723                 :             :         }
    2724                 :          63 :         eah->nelems += addedbefore;
    2725                 :             :     }
    2726                 :             : 
    2727                 :             :     /* fill addedafter items with nulls */
    2728         [ +  + ]:        1357 :     if (addedafter > 0)
    2729                 :             :     {
    2730         [ +  + ]:        2524 :         for (i = 0; i < addedafter; i++)
    2731                 :        1262 :             dvalues[eah->nelems + i] = (Datum) 0;
    2732         [ -  + ]:        1262 :         if (dnulls)
    2733                 :             :         {
    2734         [ #  # ]:           0 :             for (i = 0; i < addedafter; i++)
    2735                 :           0 :                 dnulls[eah->nelems + i] = true;
    2736                 :             :         }
    2737                 :        1262 :         eah->nelems += addedafter;
    2738                 :             :     }
    2739                 :             : 
    2740                 :             :     /* Grab old element value for pfree'ing, if needed. */
    2741   [ +  +  -  +  :        1357 :     if (!eah->typbyval && (dnulls == NULL || !dnulls[offset]))
                   -  - ]
    2742                 :         587 :         oldValue = (char *) DatumGetPointer(dvalues[offset]);
    2743                 :             :     else
    2744                 :         770 :         oldValue = NULL;
    2745                 :             : 
    2746                 :             :     /* And finally we can insert the new element. */
    2747                 :        1357 :     dvalues[offset] = dataValue;
    2748         [ -  + ]:        1357 :     if (dnulls)
    2749                 :           0 :         dnulls[offset] = isNull;
    2750                 :             : 
    2751                 :             :     /*
    2752                 :             :      * Free old element if needed; this keeps repeated element replacements
    2753                 :             :      * from bloating the array's storage.  If the pfree somehow fails, it
    2754                 :             :      * won't corrupt the array.
    2755                 :             :      */
    2756         [ +  + ]:        1357 :     if (oldValue)
    2757                 :             :     {
    2758                 :             :         /* Don't try to pfree a part of the original flat array */
    2759   [ +  -  -  + ]:           1 :         if (oldValue < eah->fstartptr || oldValue >= eah->fendptr)
    2760                 :           0 :             pfree(oldValue);
    2761                 :             :     }
    2762                 :             : 
    2763                 :             :     /* Done, return standard TOAST pointer for object */
    2764                 :        1357 :     return EOHPGetRWDatum(&eah->hdr);
    2765                 :             : }
    2766                 :             : 
    2767                 :             : /*
    2768                 :             :  * array_set_slice :
    2769                 :             :  *        This routine sets the value of a range of array locations (specified
    2770                 :             :  *        by upper and lower subscript values) to new values passed as
    2771                 :             :  *        another array.
    2772                 :             :  *
    2773                 :             :  * This handles both ordinary varlena arrays and fixed-length arrays.
    2774                 :             :  *
    2775                 :             :  * Inputs:
    2776                 :             :  *  arraydatum: the initial array object (mustn't be NULL)
    2777                 :             :  *  nSubscripts: number of subscripts supplied (must be same for upper/lower)
    2778                 :             :  *  upperIndx[]: the upper subscript values
    2779                 :             :  *  lowerIndx[]: the lower subscript values
    2780                 :             :  *  upperProvided[]: true for provided upper subscript values
    2781                 :             :  *  lowerProvided[]: true for provided lower subscript values
    2782                 :             :  *  srcArrayDatum: the source for the inserted values
    2783                 :             :  *  isNull: indicates whether srcArrayDatum is NULL
    2784                 :             :  *  arraytyplen: pg_type.typlen for the array type
    2785                 :             :  *  elmlen: pg_type.typlen for the array's element type
    2786                 :             :  *  elmbyval: pg_type.typbyval for the array's element type
    2787                 :             :  *  elmalign: pg_type.typalign for the array's element type
    2788                 :             :  *
    2789                 :             :  * Result:
    2790                 :             :  *        A new array is returned, just like the old except for the
    2791                 :             :  *        modified range.  The original array object is not changed.
    2792                 :             :  *
    2793                 :             :  * Omitted upper and lower subscript values are replaced by the corresponding
    2794                 :             :  * array bound.
    2795                 :             :  *
    2796                 :             :  * For one-dimensional arrays only, we allow the array to be extended
    2797                 :             :  * by assigning to positions outside the existing subscript range; any
    2798                 :             :  * positions between the existing elements and the new ones are set to NULLs.
    2799                 :             :  * (XXX TODO: allow a corresponding behavior for multidimensional arrays)
    2800                 :             :  *
    2801                 :             :  * NOTE: we assume it is OK to scribble on the provided index arrays
    2802                 :             :  * lowerIndx[] and upperIndx[]; also, these arrays must be of size MAXDIM
    2803                 :             :  * even when nSubscripts is less.  These are generally just temporaries.
    2804                 :             :  *
    2805                 :             :  * NOTE: For assignments, we throw an error for silly subscripts etc,
    2806                 :             :  * rather than returning a NULL or empty array as the fetch operations do.
    2807                 :             :  */
    2808                 :             : Datum
    2809                 :         180 : array_set_slice(Datum arraydatum,
    2810                 :             :                 int nSubscripts,
    2811                 :             :                 int *upperIndx,
    2812                 :             :                 int *lowerIndx,
    2813                 :             :                 bool *upperProvided,
    2814                 :             :                 bool *lowerProvided,
    2815                 :             :                 Datum srcArrayDatum,
    2816                 :             :                 bool isNull,
    2817                 :             :                 int arraytyplen,
    2818                 :             :                 int elmlen,
    2819                 :             :                 bool elmbyval,
    2820                 :             :                 char elmalign)
    2821                 :             : {
    2822                 :             :     ArrayType  *array;
    2823                 :             :     ArrayType  *srcArray;
    2824                 :             :     ArrayType  *newarray;
    2825                 :             :     int         i,
    2826                 :             :                 ndim,
    2827                 :             :                 dim[MAXDIM],
    2828                 :             :                 lb[MAXDIM],
    2829                 :             :                 span[MAXDIM];
    2830                 :             :     bool        newhasnulls;
    2831                 :             :     int         nitems,
    2832                 :             :                 nsrcitems,
    2833                 :             :                 olddatasize,
    2834                 :             :                 newsize,
    2835                 :             :                 olditemsize,
    2836                 :             :                 newitemsize,
    2837                 :             :                 overheadlen,
    2838                 :             :                 oldoverheadlen,
    2839                 :             :                 addedbefore,
    2840                 :             :                 addedafter,
    2841                 :             :                 lenbefore,
    2842                 :             :                 lenafter,
    2843                 :             :                 itemsbefore,
    2844                 :             :                 itemsafter,
    2845                 :             :                 nolditems;
    2846                 :             : 
    2847                 :             :     /* Currently, assignment from a NULL source array is a no-op */
    2848         [ -  + ]:         180 :     if (isNull)
    2849                 :           0 :         return arraydatum;
    2850                 :             : 
    2851         [ -  + ]:         180 :     if (arraytyplen > 0)
    2852                 :             :     {
    2853                 :             :         /*
    2854                 :             :          * fixed-length arrays -- not got round to doing this...
    2855                 :             :          */
    2856         [ #  # ]:           0 :         ereport(ERROR,
    2857                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2858                 :             :                  errmsg("updates on slices of fixed-length arrays not implemented")));
    2859                 :             :     }
    2860                 :             : 
    2861                 :             :     /* detoast arrays if necessary */
    2862                 :         180 :     array = DatumGetArrayTypeP(arraydatum);
    2863                 :         180 :     srcArray = DatumGetArrayTypeP(srcArrayDatum);
    2864                 :             : 
    2865                 :             :     /* note: we assume srcArray contains no toasted elements */
    2866                 :             : 
    2867                 :         180 :     ndim = ARR_NDIM(array);
    2868                 :             : 
    2869                 :             :     /*
    2870                 :             :      * if number of dims is zero, i.e. an empty array, create an array with
    2871                 :             :      * nSubscripts dimensions, and set the upper and lower bounds to the
    2872                 :             :      * supplied subscripts
    2873                 :             :      */
    2874         [ +  + ]:         180 :     if (ndim == 0)
    2875                 :             :     {
    2876                 :             :         Datum      *dvalues;
    2877                 :             :         bool       *dnulls;
    2878                 :             :         int         nelems;
    2879                 :          43 :         Oid         elmtype = ARR_ELEMTYPE(array);
    2880                 :             : 
    2881                 :          43 :         deconstruct_array(srcArray, elmtype, elmlen, elmbyval, elmalign,
    2882                 :             :                           &dvalues, &dnulls, &nelems);
    2883                 :             : 
    2884         [ +  + ]:          89 :         for (i = 0; i < nSubscripts; i++)
    2885                 :             :         {
    2886   [ +  +  -  + ]:          58 :             if (!upperProvided[i] || !lowerProvided[i])
    2887         [ +  - ]:           4 :                 ereport(ERROR,
    2888                 :             :                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    2889                 :             :                          errmsg("array slice subscript must provide both boundaries"),
    2890                 :             :                          errdetail("When assigning to a slice of an empty array value,"
    2891                 :             :                                    " slice boundaries must be fully specified.")));
    2892                 :             : 
    2893                 :             :             /* compute "upperIndx[i] - lowerIndx[i] + 1", detecting overflow */
    2894   [ +  +  +  + ]:         104 :             if (pg_sub_s32_overflow(upperIndx[i], lowerIndx[i], &dim[i]) ||
    2895                 :          50 :                 pg_add_s32_overflow(dim[i], 1, &dim[i]))
    2896         [ +  - ]:           8 :                 ereport(ERROR,
    2897                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2898                 :             :                          errmsg("array size exceeds the maximum allowed (%zu)",
    2899                 :             :                                 MaxArraySize)));
    2900                 :             : 
    2901                 :          46 :             lb[i] = lowerIndx[i];
    2902                 :             :         }
    2903                 :             : 
    2904                 :             :         /* complain if too few source items; we ignore extras, however */
    2905         [ -  + ]:          31 :         if (nelems < ArrayGetNItems(nSubscripts, dim))
    2906         [ #  # ]:           0 :             ereport(ERROR,
    2907                 :             :                     (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    2908                 :             :                      errmsg("source array too small")));
    2909                 :             : 
    2910                 :          31 :         return PointerGetDatum(construct_md_array(dvalues, dnulls, nSubscripts,
    2911                 :             :                                                   dim, lb, elmtype,
    2912                 :             :                                                   elmlen, elmbyval, elmalign));
    2913                 :             :     }
    2914                 :             : 
    2915   [ +  -  +  -  :         137 :     if (ndim < nSubscripts || ndim <= 0 || ndim > MAXDIM)
                   -  + ]
    2916         [ #  # ]:           0 :         ereport(ERROR,
    2917                 :             :                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    2918                 :             :                  errmsg("wrong number of array subscripts")));
    2919                 :             : 
    2920                 :             :     /* copy dim/lb since we may modify them */
    2921                 :         137 :     memcpy(dim, ARR_DIMS(array), ndim * sizeof(int));
    2922                 :         137 :     memcpy(lb, ARR_LBOUND(array), ndim * sizeof(int));
    2923                 :             : 
    2924   [ +  +  -  + ]:         137 :     newhasnulls = (ARR_HASNULL(array) || ARR_HASNULL(srcArray));
    2925                 :         137 :     addedbefore = addedafter = 0;
    2926                 :             : 
    2927                 :             :     /*
    2928                 :             :      * Check subscripts.  We assume the existing subscripts passed
    2929                 :             :      * ArrayCheckBounds, so that dim[i] + lb[i] can be computed without
    2930                 :             :      * overflow.  But we must beware of other overflows in our calculations of
    2931                 :             :      * new dim[] values.
    2932                 :             :      */
    2933         [ +  + ]:         137 :     if (ndim == 1)
    2934                 :             :     {
    2935                 :             :         Assert(nSubscripts == 1);
    2936         [ +  + ]:         117 :         if (!lowerProvided[0])
    2937                 :          24 :             lowerIndx[0] = lb[0];
    2938         [ +  + ]:         117 :         if (!upperProvided[0])
    2939                 :          28 :             upperIndx[0] = dim[0] + lb[0] - 1;
    2940         [ -  + ]:         117 :         if (lowerIndx[0] > upperIndx[0])
    2941         [ #  # ]:           0 :             ereport(ERROR,
    2942                 :             :                     (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    2943                 :             :                      errmsg("upper bound cannot be less than lower bound")));
    2944         [ +  + ]:         117 :         if (lowerIndx[0] < lb[0])
    2945                 :             :         {
    2946                 :             :             /* addedbefore = lb[0] - lowerIndx[0]; */
    2947                 :             :             /* dim[0] += addedbefore; */
    2948   [ +  -  -  + ]:          64 :             if (pg_sub_s32_overflow(lb[0], lowerIndx[0], &addedbefore) ||
    2949                 :          32 :                 pg_add_s32_overflow(dim[0], addedbefore, &dim[0]))
    2950         [ #  # ]:           0 :                 ereport(ERROR,
    2951                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2952                 :             :                          errmsg("array size exceeds the maximum allowed (%zu)",
    2953                 :             :                                 MaxArraySize)));
    2954                 :          32 :             lb[0] = lowerIndx[0];
    2955         [ +  + ]:          32 :             if (addedbefore > 1)
    2956                 :          24 :                 newhasnulls = true; /* will insert nulls */
    2957                 :             :         }
    2958         [ +  + ]:         117 :         if (upperIndx[0] >= (dim[0] + lb[0]))
    2959                 :             :         {
    2960                 :             :             /* addedafter = upperIndx[0] - (dim[0] + lb[0]) + 1; */
    2961                 :             :             /* dim[0] += addedafter; */
    2962   [ +  +  +  - ]:          78 :             if (pg_sub_s32_overflow(upperIndx[0], dim[0] + lb[0], &addedafter) ||
    2963         [ -  + ]:          74 :                 pg_add_s32_overflow(addedafter, 1, &addedafter) ||
    2964                 :          37 :                 pg_add_s32_overflow(dim[0], addedafter, &dim[0]))
    2965         [ +  - ]:           4 :                 ereport(ERROR,
    2966                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2967                 :             :                          errmsg("array size exceeds the maximum allowed (%zu)",
    2968                 :             :                                 MaxArraySize)));
    2969         [ +  + ]:          37 :             if (addedafter > 1)
    2970                 :          24 :                 newhasnulls = true; /* will insert nulls */
    2971                 :             :         }
    2972                 :             :     }
    2973                 :             :     else
    2974                 :             :     {
    2975                 :             :         /*
    2976                 :             :          * XXX currently we do not support extending multi-dimensional arrays
    2977                 :             :          * during assignment
    2978                 :             :          */
    2979         [ +  + ]:          68 :         for (i = 0; i < nSubscripts; i++)
    2980                 :             :         {
    2981         [ +  + ]:          48 :             if (!lowerProvided[i])
    2982                 :           8 :                 lowerIndx[i] = lb[i];
    2983         [ +  + ]:          48 :             if (!upperProvided[i])
    2984                 :          16 :                 upperIndx[i] = dim[i] + lb[i] - 1;
    2985         [ -  + ]:          48 :             if (lowerIndx[i] > upperIndx[i])
    2986         [ #  # ]:           0 :                 ereport(ERROR,
    2987                 :             :                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    2988                 :             :                          errmsg("upper bound cannot be less than lower bound")));
    2989         [ +  - ]:          48 :             if (lowerIndx[i] < lb[i] ||
    2990         [ -  + ]:          48 :                 upperIndx[i] >= (dim[i] + lb[i]))
    2991         [ #  # ]:           0 :                 ereport(ERROR,
    2992                 :             :                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    2993                 :             :                          errmsg("array subscript out of range")));
    2994                 :             :         }
    2995                 :             :         /* fill any missing subscript positions with full array range */
    2996         [ -  + ]:          20 :         for (; i < ndim; i++)
    2997                 :             :         {
    2998                 :           0 :             lowerIndx[i] = lb[i];
    2999                 :           0 :             upperIndx[i] = dim[i] + lb[i] - 1;
    3000         [ #  # ]:           0 :             if (lowerIndx[i] > upperIndx[i])
    3001         [ #  # ]:           0 :                 ereport(ERROR,
    3002                 :             :                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    3003                 :             :                          errmsg("upper bound cannot be less than lower bound")));
    3004                 :             :         }
    3005                 :             :     }
    3006                 :             : 
    3007                 :             :     /* Do this mainly to check for overflow */
    3008                 :         133 :     nitems = ArrayGetNItems(ndim, dim);
    3009                 :         133 :     ArrayCheckBounds(ndim, dim, lb);
    3010                 :             : 
    3011                 :             :     /*
    3012                 :             :      * Make sure source array has enough entries.  Note we ignore the shape of
    3013                 :             :      * the source array and just read entries serially.
    3014                 :             :      */
    3015                 :         133 :     mda_get_range(ndim, span, lowerIndx, upperIndx);
    3016                 :         133 :     nsrcitems = ArrayGetNItems(ndim, span);
    3017         [ +  + ]:         133 :     if (nsrcitems > ArrayGetNItems(ARR_NDIM(srcArray), ARR_DIMS(srcArray)))
    3018         [ +  - ]:           4 :         ereport(ERROR,
    3019                 :             :                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    3020                 :             :                  errmsg("source array too small")));
    3021                 :             : 
    3022                 :             :     /*
    3023                 :             :      * Compute space occupied by new entries, space occupied by replaced
    3024                 :             :      * entries, and required space for new array.
    3025                 :             :      */
    3026         [ +  + ]:         129 :     if (newhasnulls)
    3027                 :          64 :         overheadlen = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
    3028                 :             :     else
    3029                 :          65 :         overheadlen = ARR_OVERHEAD_NONULLS(ndim);
    3030         [ +  + ]:         129 :     newitemsize = array_nelems_size(ARR_DATA_PTR(srcArray), 0,
    3031         [ +  + ]:         129 :                                     ARR_NULLBITMAP(srcArray), nsrcitems,
    3032                 :             :                                     elmlen, elmbyval, elmalign);
    3033         [ +  + ]:         129 :     oldoverheadlen = ARR_DATA_OFFSET(array);
    3034                 :         129 :     olddatasize = ARR_SIZE(array) - oldoverheadlen;
    3035         [ +  + ]:         129 :     if (ndim > 1)
    3036                 :             :     {
    3037                 :             :         /*
    3038                 :             :          * here we do not need to cope with extension of the array; it would
    3039                 :             :          * be a lot more complicated if we had to do so...
    3040                 :             :          */
    3041         [ -  + ]:          20 :         olditemsize = array_slice_size(ARR_DATA_PTR(array),
    3042         [ -  + ]:          20 :                                        ARR_NULLBITMAP(array),
    3043                 :             :                                        ndim, dim, lb,
    3044                 :             :                                        lowerIndx, upperIndx,
    3045                 :             :                                        elmlen, elmbyval, elmalign);
    3046                 :          20 :         lenbefore = lenafter = 0;   /* keep compiler quiet */
    3047                 :          20 :         itemsbefore = itemsafter = nolditems = 0;
    3048                 :             :     }
    3049                 :             :     else
    3050                 :             :     {
    3051                 :             :         /*
    3052                 :             :          * here we must allow for possibility of slice larger than orig array
    3053                 :             :          * and/or not adjacent to orig array subscripts
    3054                 :             :          */
    3055                 :         109 :         int         oldlb = ARR_LBOUND(array)[0];
    3056                 :         109 :         int         oldub = oldlb + ARR_DIMS(array)[0] - 1;
    3057                 :         109 :         int         slicelb = Max(oldlb, lowerIndx[0]);
    3058                 :         109 :         int         sliceub = Min(oldub, upperIndx[0]);
    3059         [ +  + ]:         109 :         char       *oldarraydata = ARR_DATA_PTR(array);
    3060         [ +  + ]:         109 :         uint8      *oldarraybitmap = ARR_NULLBITMAP(array);
    3061                 :             : 
    3062                 :             :         /* count/size of old array entries that will go before the slice */
    3063                 :         109 :         itemsbefore = Min(slicelb, oldub + 1) - oldlb;
    3064                 :         109 :         lenbefore = array_nelems_size(oldarraydata, 0, oldarraybitmap,
    3065                 :             :                                       itemsbefore,
    3066                 :             :                                       elmlen, elmbyval, elmalign);
    3067                 :             :         /* count/size of old array entries that will be replaced by slice */
    3068         [ +  + ]:         109 :         if (slicelb > sliceub)
    3069                 :             :         {
    3070                 :          36 :             nolditems = 0;
    3071                 :          36 :             olditemsize = 0;
    3072                 :             :         }
    3073                 :             :         else
    3074                 :             :         {
    3075                 :          73 :             nolditems = sliceub - slicelb + 1;
    3076                 :          73 :             olditemsize = array_nelems_size(oldarraydata + lenbefore,
    3077                 :             :                                             itemsbefore, oldarraybitmap,
    3078                 :             :                                             nolditems,
    3079                 :             :                                             elmlen, elmbyval, elmalign);
    3080                 :             :         }
    3081                 :             :         /* count/size of old array entries that will go after the slice */
    3082                 :         109 :         itemsafter = oldub + 1 - Max(sliceub + 1, oldlb);
    3083                 :         109 :         lenafter = olddatasize - lenbefore - olditemsize;
    3084                 :             :     }
    3085                 :             : 
    3086                 :         129 :     newsize = overheadlen + olddatasize - olditemsize + newitemsize;
    3087                 :             : 
    3088                 :         129 :     newarray = (ArrayType *) palloc0(newsize);
    3089                 :         129 :     SET_VARSIZE(newarray, newsize);
    3090                 :         129 :     newarray->ndim = ndim;
    3091         [ +  + ]:         129 :     newarray->dataoffset = newhasnulls ? overheadlen : 0;
    3092                 :         129 :     newarray->elemtype = ARR_ELEMTYPE(array);
    3093                 :         129 :     memcpy(ARR_DIMS(newarray), dim, ndim * sizeof(int));
    3094                 :         129 :     memcpy(ARR_LBOUND(newarray), lb, ndim * sizeof(int));
    3095                 :             : 
    3096         [ +  + ]:         129 :     if (ndim > 1)
    3097                 :             :     {
    3098                 :             :         /*
    3099                 :             :          * here we do not need to cope with extension of the array; it would
    3100                 :             :          * be a lot more complicated if we had to do so...
    3101                 :             :          */
    3102                 :          20 :         array_insert_slice(newarray, array, srcArray,
    3103                 :             :                            ndim, dim, lb,
    3104                 :             :                            lowerIndx, upperIndx,
    3105                 :             :                            elmlen, elmbyval, elmalign);
    3106                 :             :     }
    3107                 :             :     else
    3108                 :             :     {
    3109                 :             :         /* fill in data */
    3110                 :         109 :         memcpy((char *) newarray + overheadlen,
    3111                 :             :                (char *) array + oldoverheadlen,
    3112                 :             :                lenbefore);
    3113                 :         218 :         memcpy((char *) newarray + overheadlen + lenbefore,
    3114         [ +  + ]:         109 :                ARR_DATA_PTR(srcArray),
    3115                 :             :                newitemsize);
    3116                 :         109 :         memcpy((char *) newarray + overheadlen + lenbefore + newitemsize,
    3117                 :         109 :                (char *) array + oldoverheadlen + lenbefore + olditemsize,
    3118                 :             :                lenafter);
    3119                 :             :         /* fill in nulls bitmap if needed */
    3120         [ +  + ]:         109 :         if (newhasnulls)
    3121                 :             :         {
    3122         [ +  - ]:          64 :             uint8      *newnullbitmap = ARR_NULLBITMAP(newarray);
    3123         [ +  - ]:          64 :             uint8      *oldnullbitmap = ARR_NULLBITMAP(array);
    3124                 :             : 
    3125                 :             :             /* palloc0 above already marked any inserted positions as nulls */
    3126                 :          64 :             array_bitmap_copy(newnullbitmap, addedbefore,
    3127                 :             :                               oldnullbitmap, 0,
    3128                 :             :                               itemsbefore);
    3129                 :          64 :             array_bitmap_copy(newnullbitmap, lowerIndx[0] - lb[0],
    3130         [ +  + ]:          64 :                               ARR_NULLBITMAP(srcArray), 0,
    3131                 :             :                               nsrcitems);
    3132                 :          64 :             array_bitmap_copy(newnullbitmap, addedbefore + itemsbefore + nolditems,
    3133                 :             :                               oldnullbitmap, itemsbefore + nolditems,
    3134                 :             :                               itemsafter);
    3135                 :             :         }
    3136                 :             :     }
    3137                 :             : 
    3138                 :         129 :     return PointerGetDatum(newarray);
    3139                 :             : }
    3140                 :             : 
    3141                 :             : /*
    3142                 :             :  * array_ref : backwards compatibility wrapper for array_get_element
    3143                 :             :  *
    3144                 :             :  * This only works for detoasted/flattened varlena arrays, since the array
    3145                 :             :  * argument is declared as "ArrayType *".  However there's enough code like
    3146                 :             :  * that to justify preserving this API.
    3147                 :             :  */
    3148                 :             : Datum
    3149                 :       29002 : array_ref(ArrayType *array, int nSubscripts, int *indx,
    3150                 :             :           int arraytyplen, int elmlen, bool elmbyval, char elmalign,
    3151                 :             :           bool *isNull)
    3152                 :             : {
    3153                 :       29002 :     return array_get_element(PointerGetDatum(array), nSubscripts, indx,
    3154                 :             :                              arraytyplen, elmlen, elmbyval, elmalign,
    3155                 :             :                              isNull);
    3156                 :             : }
    3157                 :             : 
    3158                 :             : /*
    3159                 :             :  * array_set : backwards compatibility wrapper for array_set_element
    3160                 :             :  *
    3161                 :             :  * This only works for detoasted/flattened varlena arrays, since the array
    3162                 :             :  * argument and result are declared as "ArrayType *".  However there's enough
    3163                 :             :  * code like that to justify preserving this API.
    3164                 :             :  */
    3165                 :             : ArrayType *
    3166                 :         616 : array_set(ArrayType *array, int nSubscripts, int *indx,
    3167                 :             :           Datum dataValue, bool isNull,
    3168                 :             :           int arraytyplen, int elmlen, bool elmbyval, char elmalign)
    3169                 :             : {
    3170                 :         616 :     return DatumGetArrayTypeP(array_set_element(PointerGetDatum(array),
    3171                 :             :                                                 nSubscripts, indx,
    3172                 :             :                                                 dataValue, isNull,
    3173                 :             :                                                 arraytyplen,
    3174                 :             :                                                 elmlen, elmbyval, elmalign));
    3175                 :             : }
    3176                 :             : 
    3177                 :             : /*
    3178                 :             :  * array_map()
    3179                 :             :  *
    3180                 :             :  * Map an array through an arbitrary expression.  Return a new array with
    3181                 :             :  * the same dimensions and each source element transformed by the given,
    3182                 :             :  * already-compiled expression.  Each source element is placed in the
    3183                 :             :  * innermost_caseval/innermost_casenull fields of the ExprState.
    3184                 :             :  *
    3185                 :             :  * Parameters are:
    3186                 :             :  * * arrayd: Datum representing array argument.
    3187                 :             :  * * exprstate: ExprState representing the per-element transformation.
    3188                 :             :  * * econtext: context for expression evaluation.
    3189                 :             :  * * retType: OID of element type of output array.  This must be the same as,
    3190                 :             :  *   or binary-compatible with, the result type of the expression.  It might
    3191                 :             :  *   be different from the input array's element type.
    3192                 :             :  * * amstate: workspace for array_map.  Must be zeroed by caller before
    3193                 :             :  *   first call, and not touched after that.
    3194                 :             :  *
    3195                 :             :  * It is legitimate to pass a freshly-zeroed ArrayMapState on each call,
    3196                 :             :  * but better performance can be had if the state can be preserved across
    3197                 :             :  * a series of calls.
    3198                 :             :  *
    3199                 :             :  * NB: caller must assure that input array is not NULL.  NULL elements in
    3200                 :             :  * the array are OK however.
    3201                 :             :  * NB: caller should be running in econtext's per-tuple memory context.
    3202                 :             :  */
    3203                 :             : Datum
    3204                 :       20620 : array_map(Datum arrayd,
    3205                 :             :           ExprState *exprstate, ExprContext *econtext,
    3206                 :             :           Oid retType, ArrayMapState *amstate)
    3207                 :             : {
    3208                 :       20620 :     AnyArrayType *v = DatumGetAnyArrayP(arrayd);
    3209                 :             :     ArrayType  *result;
    3210                 :             :     Datum      *values;
    3211                 :             :     bool       *nulls;
    3212                 :             :     int        *dim;
    3213                 :             :     int         ndim;
    3214                 :             :     int         nitems;
    3215                 :             :     int         i;
    3216                 :       20620 :     int32       nbytes = 0;
    3217                 :             :     int32       dataoffset;
    3218                 :             :     bool        hasnulls;
    3219                 :             :     Oid         inpType;
    3220                 :             :     int         inp_typlen;
    3221                 :             :     bool        inp_typbyval;
    3222                 :             :     char        inp_typalign;
    3223                 :             :     int         typlen;
    3224                 :             :     bool        typbyval;
    3225                 :             :     char        typalign;
    3226                 :             :     uint8       typalignby;
    3227                 :             :     array_iter  iter;
    3228                 :             :     ArrayMetaState *inp_extra;
    3229                 :             :     ArrayMetaState *ret_extra;
    3230                 :       20620 :     Datum      *transform_source = exprstate->innermost_caseval;
    3231                 :       20620 :     bool       *transform_source_isnull = exprstate->innermost_casenull;
    3232                 :             : 
    3233         [ -  + ]:       20620 :     inpType = AARR_ELEMTYPE(v);
    3234         [ -  + ]:       20620 :     ndim = AARR_NDIM(v);
    3235         [ -  + ]:       20620 :     dim = AARR_DIMS(v);
    3236                 :       20620 :     nitems = ArrayGetNItems(ndim, dim);
    3237                 :             : 
    3238                 :             :     /* Check for empty array */
    3239         [ +  + ]:       20620 :     if (nitems <= 0)
    3240                 :             :     {
    3241                 :             :         /* Return empty array */
    3242                 :          10 :         return PointerGetDatum(construct_empty_array(retType));
    3243                 :             :     }
    3244                 :             : 
    3245                 :             :     /*
    3246                 :             :      * We arrange to look up info about input and return element types only
    3247                 :             :      * once per series of calls, assuming the element type doesn't change
    3248                 :             :      * underneath us.
    3249                 :             :      */
    3250                 :       20610 :     inp_extra = &amstate->inp_extra;
    3251                 :       20610 :     ret_extra = &amstate->ret_extra;
    3252                 :             : 
    3253         [ +  + ]:       20610 :     if (inp_extra->element_type != inpType)
    3254                 :             :     {
    3255                 :         310 :         get_typlenbyvalalign(inpType,
    3256                 :             :                              &inp_extra->typlen,
    3257                 :             :                              &inp_extra->typbyval,
    3258                 :             :                              &inp_extra->typalign);
    3259                 :         310 :         inp_extra->element_type = inpType;
    3260                 :             :     }
    3261                 :       20610 :     inp_typlen = inp_extra->typlen;
    3262                 :       20610 :     inp_typbyval = inp_extra->typbyval;
    3263                 :       20610 :     inp_typalign = inp_extra->typalign;
    3264                 :             : 
    3265         [ +  + ]:       20610 :     if (ret_extra->element_type != retType)
    3266                 :             :     {
    3267                 :         310 :         get_typlenbyvalalign(retType,
    3268                 :             :                              &ret_extra->typlen,
    3269                 :             :                              &ret_extra->typbyval,
    3270                 :             :                              &ret_extra->typalign);
    3271                 :         310 :         ret_extra->element_type = retType;
    3272                 :             :     }
    3273                 :       20610 :     typlen = ret_extra->typlen;
    3274                 :       20610 :     typbyval = ret_extra->typbyval;
    3275                 :       20610 :     typalign = ret_extra->typalign;
    3276                 :       20610 :     typalignby = typalign_to_alignby(typalign);
    3277                 :             : 
    3278                 :             :     /* Allocate temporary arrays for new values */
    3279                 :       20610 :     values = palloc_array(Datum, nitems);
    3280                 :       20610 :     nulls = palloc_array(bool, nitems);
    3281                 :             : 
    3282                 :             :     /* Loop over source data */
    3283                 :       20610 :     array_iter_setup(&iter, v, inp_typlen, inp_typbyval, inp_typalign);
    3284                 :       20610 :     hasnulls = false;
    3285                 :             : 
    3286         [ +  + ]:      231677 :     for (i = 0; i < nitems; i++)
    3287                 :             :     {
    3288                 :             :         /* Get source element, checking for NULL */
    3289                 :      211087 :         *transform_source =
    3290                 :      211087 :             array_iter_next(&iter, transform_source_isnull, i);
    3291                 :             : 
    3292                 :             :         /* Apply the given expression to source element */
    3293                 :      211087 :         values[i] = ExecEvalExpr(exprstate, econtext, &nulls[i]);
    3294                 :             : 
    3295         [ +  + ]:      211067 :         if (nulls[i])
    3296                 :          10 :             hasnulls = true;
    3297                 :             :         else
    3298                 :             :         {
    3299                 :             :             /* Ensure data is not toasted */
    3300         [ +  + ]:      211057 :             if (typlen == -1)
    3301                 :         342 :                 values[i] = PointerGetDatum(PG_DETOAST_DATUM(values[i]));
    3302                 :             :             /* Update total result size */
    3303   [ +  +  +  - ]:      211057 :             nbytes = att_addlength_datum(nbytes, typlen, values[i]);
    3304                 :      211057 :             nbytes = att_nominal_alignby(nbytes, typalignby);
    3305                 :             :             /* check for overflow of total request */
    3306         [ -  + ]:      211057 :             if (!AllocSizeIsValid(nbytes))
    3307         [ #  # ]:           0 :                 ereport(ERROR,
    3308                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    3309                 :             :                          errmsg("array size exceeds the maximum allowed (%zu)",
    3310                 :             :                                 MaxAllocSize)));
    3311                 :             :         }
    3312                 :             :     }
    3313                 :             : 
    3314                 :             :     /* Allocate and fill the result array */
    3315         [ +  + ]:       20590 :     if (hasnulls)
    3316                 :             :     {
    3317                 :           5 :         dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nitems);
    3318                 :           5 :         nbytes += dataoffset;
    3319                 :             :     }
    3320                 :             :     else
    3321                 :             :     {
    3322                 :       20585 :         dataoffset = 0;         /* marker for no null bitmap */
    3323                 :       20585 :         nbytes += ARR_OVERHEAD_NONULLS(ndim);
    3324                 :             :     }
    3325                 :       20590 :     result = (ArrayType *) palloc0(nbytes);
    3326                 :       20590 :     SET_VARSIZE(result, nbytes);
    3327                 :       20590 :     result->ndim = ndim;
    3328                 :       20590 :     result->dataoffset = dataoffset;
    3329                 :       20590 :     result->elemtype = retType;
    3330         [ -  + ]:       20590 :     memcpy(ARR_DIMS(result), AARR_DIMS(v), ndim * sizeof(int));
    3331         [ -  + ]:       20590 :     memcpy(ARR_LBOUND(result), AARR_LBOUND(v), ndim * sizeof(int));
    3332                 :             : 
    3333                 :       20590 :     CopyArrayEls(result,
    3334                 :             :                  values, nulls, nitems,
    3335                 :             :                  typlen, typbyval, typalign,
    3336                 :             :                  false);
    3337                 :             : 
    3338                 :             :     /*
    3339                 :             :      * Note: do not risk trying to pfree the results of the called expression
    3340                 :             :      */
    3341                 :       20590 :     pfree(values);
    3342                 :       20590 :     pfree(nulls);
    3343                 :             : 
    3344                 :       20590 :     return PointerGetDatum(result);
    3345                 :             : }
    3346                 :             : 
    3347                 :             : /*
    3348                 :             :  * construct_array  --- simple method for constructing an array object
    3349                 :             :  *
    3350                 :             :  * elems: array of Datum items to become the array contents
    3351                 :             :  *        (NULL element values are not supported).
    3352                 :             :  * nelems: number of items
    3353                 :             :  * elmtype, elmlen, elmbyval, elmalign: info for the datatype of the items
    3354                 :             :  *
    3355                 :             :  * A palloc'd 1-D array object is constructed and returned.  Note that
    3356                 :             :  * elem values will be copied into the object even if pass-by-ref type.
    3357                 :             :  * Also note the result will be 0-D not 1-D if nelems = 0.
    3358                 :             :  *
    3359                 :             :  * NOTE: it would be cleaner to look up the elmlen/elmbval/elmalign info
    3360                 :             :  * from the system catalogs, given the elmtype.  However, the caller is
    3361                 :             :  * in a better position to cache this info across multiple uses, or even
    3362                 :             :  * to hard-wire values if the element type is hard-wired.
    3363                 :             :  */
    3364                 :             : ArrayType *
    3365                 :      224875 : construct_array(Datum *elems, int nelems,
    3366                 :             :                 Oid elmtype,
    3367                 :             :                 int elmlen, bool elmbyval, char elmalign)
    3368                 :             : {
    3369                 :             :     int         dims[1];
    3370                 :             :     int         lbs[1];
    3371                 :             : 
    3372                 :      224875 :     dims[0] = nelems;
    3373                 :      224875 :     lbs[0] = 1;
    3374                 :             : 
    3375                 :      224875 :     return construct_md_array(elems, NULL, 1, dims, lbs,
    3376                 :             :                               elmtype, elmlen, elmbyval, elmalign);
    3377                 :             : }
    3378                 :             : 
    3379                 :             : /*
    3380                 :             :  * Like construct_array(), where elmtype must be a built-in type, and
    3381                 :             :  * elmlen/elmbyval/elmalign is looked up from hardcoded data.  This is often
    3382                 :             :  * useful when manipulating arrays from/for system catalogs.
    3383                 :             :  */
    3384                 :             : ArrayType *
    3385                 :      155422 : construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
    3386                 :             : {
    3387                 :             :     int         elmlen;
    3388                 :             :     bool        elmbyval;
    3389                 :             :     char        elmalign;
    3390                 :             : 
    3391   [ +  +  +  +  :      155422 :     switch (elmtype)
          +  +  +  +  +  
             +  +  +  - ]
    3392                 :             :     {
    3393                 :        1934 :         case CHAROID:
    3394                 :        1934 :             elmlen = 1;
    3395                 :        1934 :             elmbyval = true;
    3396                 :        1934 :             elmalign = TYPALIGN_CHAR;
    3397                 :        1934 :             break;
    3398                 :             : 
    3399                 :        5367 :         case CSTRINGOID:
    3400                 :        5367 :             elmlen = -2;
    3401                 :        5367 :             elmbyval = false;
    3402                 :        5367 :             elmalign = TYPALIGN_CHAR;
    3403                 :        5367 :             break;
    3404                 :             : 
    3405                 :       84983 :         case FLOAT4OID:
    3406                 :       84983 :             elmlen = sizeof(float4);
    3407                 :       84983 :             elmbyval = true;
    3408                 :       84983 :             elmalign = TYPALIGN_INT;
    3409                 :       84983 :             break;
    3410                 :             : 
    3411                 :          40 :         case FLOAT8OID:
    3412                 :          40 :             elmlen = sizeof(float8);
    3413                 :          40 :             elmbyval = true;
    3414                 :          40 :             elmalign = TYPALIGN_DOUBLE;
    3415                 :          40 :             break;
    3416                 :             : 
    3417                 :       39342 :         case INT2OID:
    3418                 :       39342 :             elmlen = sizeof(int16);
    3419                 :       39342 :             elmbyval = true;
    3420                 :       39342 :             elmalign = TYPALIGN_SHORT;
    3421                 :       39342 :             break;
    3422                 :             : 
    3423                 :        4279 :         case INT4OID:
    3424                 :        4279 :             elmlen = sizeof(int32);
    3425                 :        4279 :             elmbyval = true;
    3426                 :        4279 :             elmalign = TYPALIGN_INT;
    3427                 :        4279 :             break;
    3428                 :             : 
    3429                 :           2 :         case INT8OID:
    3430                 :           2 :             elmlen = sizeof(int64);
    3431                 :           2 :             elmbyval = true;
    3432                 :           2 :             elmalign = TYPALIGN_DOUBLE;
    3433                 :           2 :             break;
    3434                 :             : 
    3435                 :         406 :         case NAMEOID:
    3436                 :         406 :             elmlen = NAMEDATALEN;
    3437                 :         406 :             elmbyval = false;
    3438                 :         406 :             elmalign = TYPALIGN_CHAR;
    3439                 :         406 :             break;
    3440                 :             : 
    3441                 :       12280 :         case OIDOID:
    3442                 :             :         case REGTYPEOID:
    3443                 :       12280 :             elmlen = sizeof(Oid);
    3444                 :       12280 :             elmbyval = true;
    3445                 :       12280 :             elmalign = TYPALIGN_INT;
    3446                 :       12280 :             break;
    3447                 :             : 
    3448                 :        6766 :         case TEXTOID:
    3449                 :        6766 :             elmlen = -1;
    3450                 :        6766 :             elmbyval = false;
    3451                 :        6766 :             elmalign = TYPALIGN_INT;
    3452                 :        6766 :             break;
    3453                 :             : 
    3454                 :          21 :         case TIDOID:
    3455                 :          21 :             elmlen = sizeof(ItemPointerData);
    3456                 :          21 :             elmbyval = false;
    3457                 :          21 :             elmalign = TYPALIGN_SHORT;
    3458                 :          21 :             break;
    3459                 :             : 
    3460                 :           2 :         case XIDOID:
    3461                 :           2 :             elmlen = sizeof(TransactionId);
    3462                 :           2 :             elmbyval = true;
    3463                 :           2 :             elmalign = TYPALIGN_INT;
    3464                 :           2 :             break;
    3465                 :             : 
    3466                 :           0 :         default:
    3467         [ #  # ]:           0 :             elog(ERROR, "type %u not supported by construct_array_builtin()", elmtype);
    3468                 :             :             /* keep compiler quiet */
    3469                 :             :             elmlen = 0;
    3470                 :             :             elmbyval = false;
    3471                 :             :             elmalign = 0;
    3472                 :             :     }
    3473                 :             : 
    3474                 :      155422 :     return construct_array(elems, nelems, elmtype, elmlen, elmbyval, elmalign);
    3475                 :             : }
    3476                 :             : 
    3477                 :             : /*
    3478                 :             :  * construct_md_array   --- simple method for constructing an array object
    3479                 :             :  *                          with arbitrary dimensions and possible NULLs
    3480                 :             :  *
    3481                 :             :  * elems: array of Datum items to become the array contents
    3482                 :             :  * nulls: array of is-null flags (can be NULL if no nulls)
    3483                 :             :  * ndims: number of dimensions
    3484                 :             :  * dims: integer array with size of each dimension
    3485                 :             :  * lbs: integer array with lower bound of each dimension
    3486                 :             :  * elmtype, elmlen, elmbyval, elmalign: info for the datatype of the items
    3487                 :             :  *
    3488                 :             :  * A palloc'd ndims-D array object is constructed and returned.  Note that
    3489                 :             :  * elem values will be copied into the object even if pass-by-ref type.
    3490                 :             :  * Also note the result will be 0-D not ndims-D if any dims[i] = 0.
    3491                 :             :  *
    3492                 :             :  * NOTE: it would be cleaner to look up the elmlen/elmbval/elmalign info
    3493                 :             :  * from the system catalogs, given the elmtype.  However, the caller is
    3494                 :             :  * in a better position to cache this info across multiple uses, or even
    3495                 :             :  * to hard-wire values if the element type is hard-wired.
    3496                 :             :  */
    3497                 :             : ArrayType *
    3498                 :     1029243 : construct_md_array(Datum *elems,
    3499                 :             :                    bool *nulls,
    3500                 :             :                    int ndims,
    3501                 :             :                    int *dims,
    3502                 :             :                    int *lbs,
    3503                 :             :                    Oid elmtype, int elmlen, bool elmbyval, char elmalign)
    3504                 :             : {
    3505                 :             :     ArrayType  *result;
    3506                 :             :     bool        hasnulls;
    3507                 :             :     int32       nbytes;
    3508                 :             :     int32       dataoffset;
    3509                 :             :     int         i;
    3510                 :             :     int         nelems;
    3511                 :     1029243 :     uint8       elmalignby = typalign_to_alignby(elmalign);
    3512                 :             : 
    3513         [ -  + ]:     1029243 :     if (ndims < 0)               /* we do allow zero-dimension arrays */
    3514         [ #  # ]:           0 :         ereport(ERROR,
    3515                 :             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    3516                 :             :                  errmsg("invalid number of dimensions: %d", ndims)));
    3517         [ -  + ]:     1029243 :     if (ndims > MAXDIM)
    3518         [ #  # ]:           0 :         ereport(ERROR,
    3519                 :             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    3520                 :             :                  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
    3521                 :             :                         ndims, MAXDIM)));
    3522                 :             : 
    3523                 :             :     /* This checks for overflow of the array dimensions */
    3524                 :     1029243 :     nelems = ArrayGetNItems(ndims, dims);
    3525                 :     1029243 :     ArrayCheckBounds(ndims, dims, lbs);
    3526                 :             : 
    3527                 :             :     /* if ndims <= 0 or any dims[i] == 0, return empty array */
    3528         [ +  + ]:     1029243 :     if (nelems <= 0)
    3529                 :       31456 :         return construct_empty_array(elmtype);
    3530                 :             : 
    3531                 :             :     /* compute required space */
    3532                 :      997787 :     nbytes = 0;
    3533                 :      997787 :     hasnulls = false;
    3534         [ +  + ]:     7719071 :     for (i = 0; i < nelems; i++)
    3535                 :             :     {
    3536   [ +  +  +  + ]:     6721284 :         if (nulls && nulls[i])
    3537                 :             :         {
    3538                 :       22189 :             hasnulls = true;
    3539                 :       22189 :             continue;
    3540                 :             :         }
    3541                 :             :         /* make sure data is not toasted */
    3542         [ +  + ]:     6699095 :         if (elmlen == -1)
    3543                 :     1577557 :             elems[i] = PointerGetDatum(PG_DETOAST_DATUM(elems[i]));
    3544   [ +  +  +  + ]:     6699095 :         nbytes = att_addlength_datum(nbytes, elmlen, elems[i]);
    3545                 :     6699095 :         nbytes = att_nominal_alignby(nbytes, elmalignby);
    3546                 :             :         /* check for overflow of total request */
    3547         [ -  + ]:     6699095 :         if (!AllocSizeIsValid(nbytes))
    3548         [ #  # ]:           0 :             ereport(ERROR,
    3549                 :             :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    3550                 :             :                      errmsg("array size exceeds the maximum allowed (%zu)",
    3551                 :             :                             MaxAllocSize)));
    3552                 :             :     }
    3553                 :             : 
    3554                 :             :     /* Allocate and initialize result array */
    3555         [ +  + ]:      997787 :     if (hasnulls)
    3556                 :             :     {
    3557                 :       11990 :         dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nelems);
    3558                 :       11990 :         nbytes += dataoffset;
    3559                 :             :     }
    3560                 :             :     else
    3561                 :             :     {
    3562                 :      985797 :         dataoffset = 0;         /* marker for no null bitmap */
    3563                 :      985797 :         nbytes += ARR_OVERHEAD_NONULLS(ndims);
    3564                 :             :     }
    3565                 :      997787 :     result = (ArrayType *) palloc0(nbytes);
    3566                 :      997787 :     SET_VARSIZE(result, nbytes);
    3567                 :      997787 :     result->ndim = ndims;
    3568                 :      997787 :     result->dataoffset = dataoffset;
    3569                 :      997787 :     result->elemtype = elmtype;
    3570                 :      997787 :     memcpy(ARR_DIMS(result), dims, ndims * sizeof(int));
    3571                 :      997787 :     memcpy(ARR_LBOUND(result), lbs, ndims * sizeof(int));
    3572                 :             : 
    3573                 :      997787 :     CopyArrayEls(result,
    3574                 :             :                  elems, nulls, nelems,
    3575                 :             :                  elmlen, elmbyval, elmalign,
    3576                 :             :                  false);
    3577                 :             : 
    3578                 :      997787 :     return result;
    3579                 :             : }
    3580                 :             : 
    3581                 :             : /*
    3582                 :             :  * construct_empty_array    --- make a zero-dimensional array of given type
    3583                 :             :  */
    3584                 :             : ArrayType *
    3585                 :     1438504 : construct_empty_array(Oid elmtype)
    3586                 :             : {
    3587                 :             :     ArrayType  *result;
    3588                 :             : 
    3589                 :     1438504 :     result = palloc0_object(ArrayType);
    3590                 :     1438504 :     SET_VARSIZE(result, sizeof(ArrayType));
    3591                 :     1438504 :     result->ndim = 0;
    3592                 :     1438504 :     result->dataoffset = 0;
    3593                 :     1438504 :     result->elemtype = elmtype;
    3594                 :     1438504 :     return result;
    3595                 :             : }
    3596                 :             : 
    3597                 :             : /*
    3598                 :             :  * construct_empty_expanded_array: make an empty expanded array
    3599                 :             :  * given only type information.  (metacache can be NULL if not needed.)
    3600                 :             :  */
    3601                 :             : ExpandedArrayHeader *
    3602                 :          17 : construct_empty_expanded_array(Oid element_type,
    3603                 :             :                                MemoryContext parentcontext,
    3604                 :             :                                ArrayMetaState *metacache)
    3605                 :             : {
    3606                 :          17 :     ArrayType  *array = construct_empty_array(element_type);
    3607                 :             :     Datum       d;
    3608                 :             : 
    3609                 :          17 :     d = expand_array(PointerGetDatum(array), parentcontext, metacache);
    3610                 :          17 :     pfree(array);
    3611                 :          17 :     return (ExpandedArrayHeader *) DatumGetEOHP(d);
    3612                 :             : }
    3613                 :             : 
    3614                 :             : /*
    3615                 :             :  * deconstruct_array  --- simple method for extracting data from an array
    3616                 :             :  *
    3617                 :             :  * array: array object to examine (must not be NULL)
    3618                 :             :  * elmtype, elmlen, elmbyval, elmalign: info for the datatype of the items
    3619                 :             :  * elemsp: return value, set to point to palloc'd array of Datum values
    3620                 :             :  * nullsp: return value, set to point to palloc'd array of isnull markers
    3621                 :             :  * nelemsp: return value, set to number of extracted values
    3622                 :             :  *
    3623                 :             :  * The caller may pass nullsp == NULL if it does not support NULLs in the
    3624                 :             :  * array.  Note that this produces a very uninformative error message,
    3625                 :             :  * so do it only in cases where a NULL is really not expected.
    3626                 :             :  *
    3627                 :             :  * If array elements are pass-by-ref data type, the returned Datums will
    3628                 :             :  * be pointers into the array object.
    3629                 :             :  *
    3630                 :             :  * NOTE: it would be cleaner to look up the elmlen/elmbval/elmalign info
    3631                 :             :  * from the system catalogs, given the elmtype.  However, the caller is
    3632                 :             :  * in a better position to cache this info across multiple uses, or even
    3633                 :             :  * to hard-wire values if the element type is hard-wired.
    3634                 :             :  */
    3635                 :             : void
    3636                 :     2056615 : deconstruct_array(const ArrayType *array,
    3637                 :             :                   Oid elmtype,
    3638                 :             :                   int elmlen, bool elmbyval, char elmalign,
    3639                 :             :                   Datum **elemsp, bool **nullsp, int *nelemsp)
    3640                 :             : {
    3641                 :             :     Datum      *elems;
    3642                 :             :     bool       *nulls;
    3643                 :             :     int         nelems;
    3644                 :             :     char       *p;
    3645                 :             :     uint8      *bitmap;
    3646                 :             :     int         bitmask;
    3647                 :             :     int         i;
    3648                 :     2056615 :     uint8       elmalignby = typalign_to_alignby(elmalign);
    3649                 :             : 
    3650                 :             :     Assert(ARR_ELEMTYPE(array) == elmtype);
    3651                 :             : 
    3652                 :     2056615 :     nelems = ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array));
    3653                 :     2056615 :     *elemsp = elems = palloc_array(Datum, nelems);
    3654         [ +  + ]:     2056615 :     if (nullsp)
    3655                 :     1144626 :         *nullsp = nulls = palloc0_array(bool, nelems);
    3656                 :             :     else
    3657                 :      911989 :         nulls = NULL;
    3658                 :     2056615 :     *nelemsp = nelems;
    3659                 :             : 
    3660         [ +  + ]:     2056615 :     p = ARR_DATA_PTR(array);
    3661         [ +  + ]:     2056615 :     bitmap = ARR_NULLBITMAP(array);
    3662                 :     2056615 :     bitmask = 1;
    3663                 :             : 
    3664         [ +  + ]:    36751843 :     for (i = 0; i < nelems; i++)
    3665                 :             :     {
    3666                 :             :         /* Get source element, checking for NULL */
    3667   [ +  +  +  + ]:    34695228 :         if (bitmap && (*bitmap & bitmask) == 0)
    3668                 :             :         {
    3669                 :        2396 :             elems[i] = (Datum) 0;
    3670         [ +  - ]:        2396 :             if (nulls)
    3671                 :        2396 :                 nulls[i] = true;
    3672                 :             :             else
    3673         [ #  # ]:           0 :                 ereport(ERROR,
    3674                 :             :                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    3675                 :             :                          errmsg("null array element not allowed in this context")));
    3676                 :             :         }
    3677                 :             :         else
    3678                 :             :         {
    3679                 :    34692832 :             elems[i] = fetch_att(p, elmbyval, elmlen);
    3680   [ +  +  +  + ]:    34692832 :             p = att_addlength_pointer(p, elmlen, p);
    3681                 :    34692832 :             p = (char *) att_nominal_alignby(p, elmalignby);
    3682                 :             :         }
    3683                 :             : 
    3684                 :             :         /* advance bitmap pointer if any */
    3685         [ +  + ]:    34695228 :         if (bitmap)
    3686                 :             :         {
    3687                 :        3781 :             bitmask <<= 1;
    3688         [ +  + ]:        3781 :             if (bitmask == 0x100)
    3689                 :             :             {
    3690                 :          52 :                 bitmap++;
    3691                 :          52 :                 bitmask = 1;
    3692                 :             :             }
    3693                 :             :         }
    3694                 :             :     }
    3695                 :     2056615 : }
    3696                 :             : 
    3697                 :             : /*
    3698                 :             :  * Like deconstruct_array(), where elmtype must be a built-in type, and
    3699                 :             :  * elmlen/elmbyval/elmalign is looked up from hardcoded data.  This is often
    3700                 :             :  * useful when manipulating arrays from/for system catalogs.
    3701                 :             :  */
    3702                 :             : void
    3703                 :      342002 : deconstruct_array_builtin(const ArrayType *array,
    3704                 :             :                           Oid elmtype,
    3705                 :             :                           Datum **elemsp, bool **nullsp, int *nelemsp)
    3706                 :             : {
    3707                 :             :     int         elmlen;
    3708                 :             :     bool        elmbyval;
    3709                 :             :     char        elmalign;
    3710                 :             : 
    3711   [ +  +  +  +  :      342002 :     switch (elmtype)
             +  +  +  +  
                      - ]
    3712                 :             :     {
    3713                 :          14 :         case CHAROID:
    3714                 :          14 :             elmlen = 1;
    3715                 :          14 :             elmbyval = true;
    3716                 :          14 :             elmalign = TYPALIGN_CHAR;
    3717                 :          14 :             break;
    3718                 :             : 
    3719                 :        7719 :         case CSTRINGOID:
    3720                 :        7719 :             elmlen = -2;
    3721                 :        7719 :             elmbyval = false;
    3722                 :        7719 :             elmalign = TYPALIGN_CHAR;
    3723                 :        7719 :             break;
    3724                 :             : 
    3725                 :          20 :         case FLOAT8OID:
    3726                 :          20 :             elmlen = sizeof(float8);
    3727                 :          20 :             elmbyval = true;
    3728                 :          20 :             elmalign = TYPALIGN_DOUBLE;
    3729                 :          20 :             break;
    3730                 :             : 
    3731                 :       10897 :         case INT2OID:
    3732                 :       10897 :             elmlen = sizeof(int16);
    3733                 :       10897 :             elmbyval = true;
    3734                 :       10897 :             elmalign = TYPALIGN_SHORT;
    3735                 :       10897 :             break;
    3736                 :             : 
    3737                 :         200 :         case INT4OID:
    3738                 :         200 :             elmlen = sizeof(int32);
    3739                 :         200 :             elmbyval = true;
    3740                 :         200 :             elmalign = TYPALIGN_INT;
    3741                 :         200 :             break;
    3742                 :             : 
    3743                 :        3132 :         case OIDOID:
    3744                 :        3132 :             elmlen = sizeof(Oid);
    3745                 :        3132 :             elmbyval = true;
    3746                 :        3132 :             elmalign = TYPALIGN_INT;
    3747                 :        3132 :             break;
    3748                 :             : 
    3749                 :      319991 :         case TEXTOID:
    3750                 :      319991 :             elmlen = -1;
    3751                 :      319991 :             elmbyval = false;
    3752                 :      319991 :             elmalign = TYPALIGN_INT;
    3753                 :      319991 :             break;
    3754                 :             : 
    3755                 :          29 :         case TIDOID:
    3756                 :          29 :             elmlen = sizeof(ItemPointerData);
    3757                 :          29 :             elmbyval = false;
    3758                 :          29 :             elmalign = TYPALIGN_SHORT;
    3759                 :          29 :             break;
    3760                 :             : 
    3761                 :           0 :         default:
    3762         [ #  # ]:           0 :             elog(ERROR, "type %u not supported by deconstruct_array_builtin()", elmtype);
    3763                 :             :             /* keep compiler quiet */
    3764                 :             :             elmlen = 0;
    3765                 :             :             elmbyval = false;
    3766                 :             :             elmalign = 0;
    3767                 :             :     }
    3768                 :             : 
    3769                 :      342002 :     deconstruct_array(array, elmtype, elmlen, elmbyval, elmalign, elemsp, nullsp, nelemsp);
    3770                 :      342002 : }
    3771                 :             : 
    3772                 :             : /*
    3773                 :             :  * array_contains_nulls --- detect whether an array has any null elements
    3774                 :             :  *
    3775                 :             :  * This gives an accurate answer, whereas testing ARR_HASNULL only tells
    3776                 :             :  * if the array *might* contain a null.
    3777                 :             :  */
    3778                 :             : bool
    3779                 :       40664 : array_contains_nulls(const ArrayType *array)
    3780                 :             : {
    3781                 :             :     int         nelems;
    3782                 :             :     uint8      *bitmap;
    3783                 :             :     int         bitmask;
    3784                 :             : 
    3785                 :             :     /* Easy answer if there's no null bitmap */
    3786         [ +  + ]:       40664 :     if (!ARR_HASNULL(array))
    3787                 :       40612 :         return false;
    3788                 :             : 
    3789                 :          52 :     nelems = ArrayGetNItems(ARR_NDIM(array), ARR_DIMS(array));
    3790                 :             : 
    3791         [ +  - ]:          52 :     bitmap = ARR_NULLBITMAP(array);
    3792                 :             : 
    3793                 :             :     /* check whole bytes of the bitmap byte-at-a-time */
    3794         [ +  + ]:          52 :     while (nelems >= 8)
    3795                 :             :     {
    3796         [ +  - ]:          14 :         if (*bitmap != 0xFF)
    3797                 :          14 :             return true;
    3798                 :           0 :         bitmap++;
    3799                 :           0 :         nelems -= 8;
    3800                 :             :     }
    3801                 :             : 
    3802                 :             :     /* check last partial byte */
    3803                 :          38 :     bitmask = 1;
    3804         [ +  - ]:          93 :     while (nelems > 0)
    3805                 :             :     {
    3806         [ +  + ]:          93 :         if ((*bitmap & bitmask) == 0)
    3807                 :          38 :             return true;
    3808                 :          55 :         bitmask <<= 1;
    3809                 :          55 :         nelems--;
    3810                 :             :     }
    3811                 :             : 
    3812                 :           0 :     return false;
    3813                 :             : }
    3814                 :             : 
    3815                 :             : 
    3816                 :             : /*
    3817                 :             :  * array_eq :
    3818                 :             :  *        compares two arrays for equality
    3819                 :             :  * result :
    3820                 :             :  *        returns true if the arrays are equal, false otherwise.
    3821                 :             :  *
    3822                 :             :  * Note: we do not use array_cmp here, since equality may be meaningful in
    3823                 :             :  * datatypes that don't have a total ordering (and hence no btree support).
    3824                 :             :  */
    3825                 :             : Datum
    3826                 :      154288 : array_eq(PG_FUNCTION_ARGS)
    3827                 :             : {
    3828                 :      154288 :     LOCAL_FCINFO(locfcinfo, 2);
    3829                 :      154288 :     AnyArrayType *array1 = PG_GETARG_ANY_ARRAY_P(0);
    3830                 :      154288 :     AnyArrayType *array2 = PG_GETARG_ANY_ARRAY_P(1);
    3831                 :      154288 :     Oid         collation = PG_GET_COLLATION();
    3832         [ +  + ]:      154288 :     int         ndims1 = AARR_NDIM(array1);
    3833         [ +  + ]:      154288 :     int         ndims2 = AARR_NDIM(array2);
    3834         [ +  + ]:      154288 :     int        *dims1 = AARR_DIMS(array1);
    3835         [ +  + ]:      154288 :     int        *dims2 = AARR_DIMS(array2);
    3836         [ +  + ]:      154288 :     int        *lbs1 = AARR_LBOUND(array1);
    3837         [ +  + ]:      154288 :     int        *lbs2 = AARR_LBOUND(array2);
    3838         [ +  + ]:      154288 :     Oid         element_type = AARR_ELEMTYPE(array1);
    3839                 :      154288 :     bool        result = true;
    3840                 :             :     int         nitems;
    3841                 :             :     TypeCacheEntry *typentry;
    3842                 :             :     int         typlen;
    3843                 :             :     bool        typbyval;
    3844                 :             :     char        typalign;
    3845                 :             :     array_iter  it1;
    3846                 :             :     array_iter  it2;
    3847                 :             :     int         i;
    3848                 :             : 
    3849   [ +  +  -  + ]:      154288 :     if (element_type != AARR_ELEMTYPE(array2))
    3850         [ #  # ]:           0 :         ereport(ERROR,
    3851                 :             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3852                 :             :                  errmsg("cannot compare arrays of different element types")));
    3853                 :             : 
    3854                 :             :     /* fast path if the arrays do not have the same dimensionality */
    3855         [ +  + ]:      154288 :     if (ndims1 != ndims2 ||
    3856         [ +  + ]:      146689 :         memcmp(dims1, dims2, ndims1 * sizeof(int)) != 0 ||
    3857         [ -  + ]:      111101 :         memcmp(lbs1, lbs2, ndims1 * sizeof(int)) != 0)
    3858                 :       43187 :         result = false;
    3859                 :             :     else
    3860                 :             :     {
    3861                 :             :         /*
    3862                 :             :          * We arrange to look up the equality function only once per series of
    3863                 :             :          * calls, assuming the element type doesn't change underneath us.  The
    3864                 :             :          * typcache is used so that we have no memory leakage when being used
    3865                 :             :          * as an index support function.
    3866                 :             :          */
    3867                 :      111101 :         typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
    3868         [ +  + ]:      111101 :         if (typentry == NULL ||
    3869         [ -  + ]:      109441 :             typentry->type_id != element_type)
    3870                 :             :         {
    3871                 :        1660 :             typentry = lookup_type_cache(element_type,
    3872                 :             :                                          TYPECACHE_EQ_OPR_FINFO);
    3873         [ -  + ]:        1660 :             if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
    3874         [ #  # ]:           0 :                 ereport(ERROR,
    3875                 :             :                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
    3876                 :             :                          errmsg("could not identify an equality operator for type %s",
    3877                 :             :                                 format_type_be(element_type))));
    3878                 :        1660 :             fcinfo->flinfo->fn_extra = typentry;
    3879                 :             :         }
    3880                 :      111101 :         typlen = typentry->typlen;
    3881                 :      111101 :         typbyval = typentry->typbyval;
    3882                 :      111101 :         typalign = typentry->typalign;
    3883                 :             : 
    3884                 :             :         /*
    3885                 :             :          * apply the operator to each pair of array elements.
    3886                 :             :          */
    3887                 :      111101 :         InitFunctionCallInfoData(*locfcinfo, &typentry->eq_opr_finfo, 2,
    3888                 :             :                                  collation, NULL, NULL);
    3889                 :             : 
    3890                 :             :         /* Loop over source data */
    3891                 :      111101 :         nitems = ArrayGetNItems(ndims1, dims1);
    3892                 :      111101 :         array_iter_setup(&it1, array1, typlen, typbyval, typalign);
    3893                 :      111101 :         array_iter_setup(&it2, array2, typlen, typbyval, typalign);
    3894                 :             : 
    3895         [ +  + ]:      263778 :         for (i = 0; i < nitems; i++)
    3896                 :             :         {
    3897                 :             :             Datum       elt1;
    3898                 :             :             Datum       elt2;
    3899                 :             :             bool        isnull1;
    3900                 :             :             bool        isnull2;
    3901                 :             :             bool        oprresult;
    3902                 :             : 
    3903                 :             :             /* Get elements, checking for NULL */
    3904                 :      173309 :             elt1 = array_iter_next(&it1, &isnull1, i);
    3905                 :      173309 :             elt2 = array_iter_next(&it2, &isnull2, i);
    3906                 :             : 
    3907                 :             :             /*
    3908                 :             :              * We consider two NULLs equal; NULL and not-NULL are unequal.
    3909                 :             :              */
    3910   [ +  +  +  - ]:      173309 :             if (isnull1 && isnull2)
    3911                 :          29 :                 continue;
    3912   [ +  -  +  + ]:      173280 :             if (isnull1 || isnull2)
    3913                 :             :             {
    3914                 :          72 :                 result = false;
    3915                 :       20632 :                 break;
    3916                 :             :             }
    3917                 :             : 
    3918                 :             :             /*
    3919                 :             :              * Apply the operator to the element pair; treat NULL as false
    3920                 :             :              */
    3921                 :      173208 :             locfcinfo->args[0].value = elt1;
    3922                 :      173208 :             locfcinfo->args[0].isnull = false;
    3923                 :      173208 :             locfcinfo->args[1].value = elt2;
    3924                 :      173208 :             locfcinfo->args[1].isnull = false;
    3925                 :      173208 :             locfcinfo->isnull = false;
    3926                 :      173208 :             oprresult = DatumGetBool(FunctionCallInvoke(locfcinfo));
    3927   [ +  -  +  + ]:      173208 :             if (locfcinfo->isnull || !oprresult)
    3928                 :             :             {
    3929                 :       20560 :                 result = false;
    3930                 :       20560 :                 break;
    3931                 :             :             }
    3932                 :             :         }
    3933                 :             :     }
    3934                 :             : 
    3935                 :             :     /* Avoid leaking memory when handed toasted input. */
    3936   [ +  +  +  + ]:      154288 :     AARR_FREE_IF_COPY(array1, 0);
    3937   [ +  +  +  + ]:      154288 :     AARR_FREE_IF_COPY(array2, 1);
    3938                 :             : 
    3939                 :      154288 :     PG_RETURN_BOOL(result);
    3940                 :             : }
    3941                 :             : 
    3942                 :             : 
    3943                 :             : /*-----------------------------------------------------------------------------
    3944                 :             :  * array-array bool operators:
    3945                 :             :  *      Given two arrays, iterate comparison operators
    3946                 :             :  *      over the array. Uses logic similar to text comparison
    3947                 :             :  *      functions, except element-by-element instead of
    3948                 :             :  *      character-by-character.
    3949                 :             :  *----------------------------------------------------------------------------
    3950                 :             :  */
    3951                 :             : 
    3952                 :             : Datum
    3953                 :         700 : array_ne(PG_FUNCTION_ARGS)
    3954                 :             : {
    3955                 :         700 :     PG_RETURN_BOOL(!DatumGetBool(array_eq(fcinfo)));
    3956                 :             : }
    3957                 :             : 
    3958                 :             : Datum
    3959                 :        3942 : array_lt(PG_FUNCTION_ARGS)
    3960                 :             : {
    3961                 :        3942 :     PG_RETURN_BOOL(array_cmp(fcinfo) < 0);
    3962                 :             : }
    3963                 :             : 
    3964                 :             : Datum
    3965                 :          12 : array_gt(PG_FUNCTION_ARGS)
    3966                 :             : {
    3967                 :          12 :     PG_RETURN_BOOL(array_cmp(fcinfo) > 0);
    3968                 :             : }
    3969                 :             : 
    3970                 :             : Datum
    3971                 :          12 : array_le(PG_FUNCTION_ARGS)
    3972                 :             : {
    3973                 :          12 :     PG_RETURN_BOOL(array_cmp(fcinfo) <= 0);
    3974                 :             : }
    3975                 :             : 
    3976                 :             : Datum
    3977                 :          12 : array_ge(PG_FUNCTION_ARGS)
    3978                 :             : {
    3979                 :          12 :     PG_RETURN_BOOL(array_cmp(fcinfo) >= 0);
    3980                 :             : }
    3981                 :             : 
    3982                 :             : Datum
    3983                 :     5533988 : btarraycmp(PG_FUNCTION_ARGS)
    3984                 :             : {
    3985                 :     5533988 :     PG_RETURN_INT32(array_cmp(fcinfo));
    3986                 :             : }
    3987                 :             : 
    3988                 :             : /*
    3989                 :             :  * array_cmp()
    3990                 :             :  * Internal comparison function for arrays.
    3991                 :             :  *
    3992                 :             :  * Returns -1, 0 or 1
    3993                 :             :  */
    3994                 :             : static int
    3995                 :     5538330 : array_cmp(FunctionCallInfo fcinfo)
    3996                 :             : {
    3997                 :     5538330 :     LOCAL_FCINFO(locfcinfo, 2);
    3998                 :     5538330 :     AnyArrayType *array1 = PG_GETARG_ANY_ARRAY_P(0);
    3999                 :     5538330 :     AnyArrayType *array2 = PG_GETARG_ANY_ARRAY_P(1);
    4000                 :     5538330 :     Oid         collation = PG_GET_COLLATION();
    4001         [ -  + ]:     5538330 :     int         ndims1 = AARR_NDIM(array1);
    4002         [ -  + ]:     5538330 :     int         ndims2 = AARR_NDIM(array2);
    4003         [ -  + ]:     5538330 :     int        *dims1 = AARR_DIMS(array1);
    4004         [ -  + ]:     5538330 :     int        *dims2 = AARR_DIMS(array2);
    4005                 :     5538330 :     int         nitems1 = ArrayGetNItems(ndims1, dims1);
    4006                 :     5538330 :     int         nitems2 = ArrayGetNItems(ndims2, dims2);
    4007         [ -  + ]:     5538330 :     Oid         element_type = AARR_ELEMTYPE(array1);
    4008                 :     5538330 :     int         result = 0;
    4009                 :             :     TypeCacheEntry *typentry;
    4010                 :             :     int         typlen;
    4011                 :             :     bool        typbyval;
    4012                 :             :     char        typalign;
    4013                 :             :     int         min_nitems;
    4014                 :             :     array_iter  it1;
    4015                 :             :     array_iter  it2;
    4016                 :             :     int         i;
    4017                 :             : 
    4018   [ -  +  +  + ]:     5538330 :     if (element_type != AARR_ELEMTYPE(array2))
    4019         [ +  - ]:           4 :         ereport(ERROR,
    4020                 :             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    4021                 :             :                  errmsg("cannot compare arrays of different element types")));
    4022                 :             : 
    4023                 :             :     /*
    4024                 :             :      * We arrange to look up the comparison function only once per series of
    4025                 :             :      * calls, assuming the element type doesn't change underneath us. The
    4026                 :             :      * typcache is used so that we have no memory leakage when being used as
    4027                 :             :      * an index support function.
    4028                 :             :      */
    4029                 :     5538326 :     typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
    4030         [ +  + ]:     5538326 :     if (typentry == NULL ||
    4031         [ -  + ]:     5536688 :         typentry->type_id != element_type)
    4032                 :             :     {
    4033                 :        1638 :         typentry = lookup_type_cache(element_type,
    4034                 :             :                                      TYPECACHE_CMP_PROC_FINFO);
    4035         [ +  + ]:        1638 :         if (!OidIsValid(typentry->cmp_proc_finfo.fn_oid))
    4036         [ +  - ]:           4 :             ereport(ERROR,
    4037                 :             :                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
    4038                 :             :                      errmsg("could not identify a comparison function for type %s",
    4039                 :             :                             format_type_be(element_type))));
    4040                 :        1634 :         fcinfo->flinfo->fn_extra = typentry;
    4041                 :             :     }
    4042                 :     5538322 :     typlen = typentry->typlen;
    4043                 :     5538322 :     typbyval = typentry->typbyval;
    4044                 :     5538322 :     typalign = typentry->typalign;
    4045                 :             : 
    4046                 :             :     /*
    4047                 :             :      * apply the operator to each pair of array elements.
    4048                 :             :      */
    4049                 :     5538322 :     InitFunctionCallInfoData(*locfcinfo, &typentry->cmp_proc_finfo, 2,
    4050                 :             :                              collation, NULL, NULL);
    4051                 :             : 
    4052                 :             :     /* Loop over source data */
    4053                 :     5538322 :     min_nitems = Min(nitems1, nitems2);
    4054                 :     5538322 :     array_iter_setup(&it1, array1, typlen, typbyval, typalign);
    4055                 :     5538322 :     array_iter_setup(&it2, array2, typlen, typbyval, typalign);
    4056                 :             : 
    4057         [ +  + ]:    11541541 :     for (i = 0; i < min_nitems; i++)
    4058                 :             :     {
    4059                 :             :         Datum       elt1;
    4060                 :             :         Datum       elt2;
    4061                 :             :         bool        isnull1;
    4062                 :             :         bool        isnull2;
    4063                 :             :         int32       cmpresult;
    4064                 :             : 
    4065                 :             :         /* Get elements, checking for NULL */
    4066                 :     9864049 :         elt1 = array_iter_next(&it1, &isnull1, i);
    4067                 :     9864049 :         elt2 = array_iter_next(&it2, &isnull2, i);
    4068                 :             : 
    4069                 :             :         /*
    4070                 :             :          * We consider two NULLs equal; NULL > not-NULL.
    4071                 :             :          */
    4072   [ +  +  +  + ]:     9864049 :         if (isnull1 && isnull2)
    4073                 :     6003219 :             continue;
    4074         [ +  + ]:     9864036 :         if (isnull1)
    4075                 :             :         {
    4076                 :             :             /* arg1 is greater than arg2 */
    4077                 :         160 :             result = 1;
    4078                 :     3860830 :             break;
    4079                 :             :         }
    4080         [ +  + ]:     9863876 :         if (isnull2)
    4081                 :             :         {
    4082                 :             :             /* arg1 is less than arg2 */
    4083                 :         260 :             result = -1;
    4084                 :         260 :             break;
    4085                 :             :         }
    4086                 :             : 
    4087                 :             :         /* Compare the pair of elements */
    4088                 :     9863616 :         locfcinfo->args[0].value = elt1;
    4089                 :     9863616 :         locfcinfo->args[0].isnull = false;
    4090                 :     9863616 :         locfcinfo->args[1].value = elt2;
    4091                 :     9863616 :         locfcinfo->args[1].isnull = false;
    4092                 :     9863616 :         cmpresult = DatumGetInt32(FunctionCallInvoke(locfcinfo));
    4093                 :             : 
    4094                 :             :         /* We don't expect comparison support functions to return null */
    4095                 :             :         Assert(!locfcinfo->isnull);
    4096                 :             : 
    4097         [ +  + ]:     9863616 :         if (cmpresult == 0)
    4098                 :     6003206 :             continue;           /* equal */
    4099                 :             : 
    4100         [ +  + ]:     3860410 :         if (cmpresult < 0)
    4101                 :             :         {
    4102                 :             :             /* arg1 is less than arg2 */
    4103                 :     2201185 :             result = -1;
    4104                 :     2201185 :             break;
    4105                 :             :         }
    4106                 :             :         else
    4107                 :             :         {
    4108                 :             :             /* arg1 is greater than arg2 */
    4109                 :     1659225 :             result = 1;
    4110                 :     1659225 :             break;
    4111                 :             :         }
    4112                 :             :     }
    4113                 :             : 
    4114                 :             :     /*
    4115                 :             :      * If arrays contain same data (up to end of shorter one), apply
    4116                 :             :      * additional rules to sort by dimensionality.  The relative significance
    4117                 :             :      * of the different bits of information is historical; mainly we just care
    4118                 :             :      * that we don't say "equal" for arrays of different dimensionality.
    4119                 :             :      */
    4120         [ +  + ]:     5538322 :     if (result == 0)
    4121                 :             :     {
    4122         [ +  + ]:     1677492 :         if (nitems1 != nitems2)
    4123         [ +  + ]:      155906 :             result = (nitems1 < nitems2) ? -1 : 1;
    4124         [ -  + ]:     1521586 :         else if (ndims1 != ndims2)
    4125         [ #  # ]:           0 :             result = (ndims1 < ndims2) ? -1 : 1;
    4126                 :             :         else
    4127                 :             :         {
    4128         [ +  + ]:     3043145 :             for (i = 0; i < ndims1; i++)
    4129                 :             :             {
    4130         [ -  + ]:     1521559 :                 if (dims1[i] != dims2[i])
    4131                 :             :                 {
    4132         [ #  # ]:           0 :                     result = (dims1[i] < dims2[i]) ? -1 : 1;
    4133                 :           0 :                     break;
    4134                 :             :                 }
    4135                 :             :             }
    4136         [ +  - ]:     1521586 :             if (result == 0)
    4137                 :             :             {
    4138         [ -  + ]:     1521586 :                 int        *lbound1 = AARR_LBOUND(array1);
    4139         [ -  + ]:     1521586 :                 int        *lbound2 = AARR_LBOUND(array2);
    4140                 :             : 
    4141         [ +  + ]:     3043145 :                 for (i = 0; i < ndims1; i++)
    4142                 :             :                 {
    4143         [ -  + ]:     1521559 :                     if (lbound1[i] != lbound2[i])
    4144                 :             :                     {
    4145         [ #  # ]:           0 :                         result = (lbound1[i] < lbound2[i]) ? -1 : 1;
    4146                 :           0 :                         break;
    4147                 :             :                     }
    4148                 :             :                 }
    4149                 :             :             }
    4150                 :             :         }
    4151                 :             :     }
    4152                 :             : 
    4153                 :             :     /* Avoid leaking memory when handed toasted input. */
    4154   [ +  -  +  + ]:     5538322 :     AARR_FREE_IF_COPY(array1, 0);
    4155   [ +  -  +  + ]:     5538322 :     AARR_FREE_IF_COPY(array2, 1);
    4156                 :             : 
    4157                 :     5538322 :     return result;
    4158                 :             : }
    4159                 :             : 
    4160                 :             : 
    4161                 :             : /*-----------------------------------------------------------------------------
    4162                 :             :  * array hashing
    4163                 :             :  *      Hash the elements and combine the results.
    4164                 :             :  *----------------------------------------------------------------------------
    4165                 :             :  */
    4166                 :             : 
    4167                 :             : Datum
    4168                 :       39891 : hash_array(PG_FUNCTION_ARGS)
    4169                 :             : {
    4170                 :       39891 :     LOCAL_FCINFO(locfcinfo, 1);
    4171                 :       39891 :     AnyArrayType *array = PG_GETARG_ANY_ARRAY_P(0);
    4172         [ +  + ]:       39891 :     int         ndims = AARR_NDIM(array);
    4173         [ +  + ]:       39891 :     int        *dims = AARR_DIMS(array);
    4174         [ +  + ]:       39891 :     Oid         element_type = AARR_ELEMTYPE(array);
    4175                 :       39891 :     uint32      result = 1;
    4176                 :             :     int         nitems;
    4177                 :             :     TypeCacheEntry *typentry;
    4178                 :             :     int         typlen;
    4179                 :             :     bool        typbyval;
    4180                 :             :     char        typalign;
    4181                 :             :     int         i;
    4182                 :             :     array_iter  iter;
    4183                 :             : 
    4184                 :             :     /*
    4185                 :             :      * We arrange to look up the hash function only once per series of calls,
    4186                 :             :      * assuming the element type doesn't change underneath us.  The typcache
    4187                 :             :      * is used so that we have no memory leakage when being used as an index
    4188                 :             :      * support function.
    4189                 :             :      */
    4190                 :       39891 :     typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
    4191         [ +  + ]:       39891 :     if (typentry == NULL ||
    4192         [ -  + ]:       39478 :         typentry->type_id != element_type)
    4193                 :             :     {
    4194                 :         413 :         typentry = lookup_type_cache(element_type,
    4195                 :             :                                      TYPECACHE_HASH_PROC_FINFO);
    4196   [ +  +  +  + ]:         413 :         if (!OidIsValid(typentry->hash_proc_finfo.fn_oid) && element_type != RECORDOID)
    4197         [ +  - ]:           4 :             ereport(ERROR,
    4198                 :             :                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
    4199                 :             :                      errmsg("could not identify a hash function for type %s",
    4200                 :             :                             format_type_be(element_type))));
    4201                 :             : 
    4202                 :             :         /*
    4203                 :             :          * The type cache doesn't believe that record is hashable (see
    4204                 :             :          * cache_record_field_properties()), but since we're here, we're
    4205                 :             :          * committed to hashing, so we can assume it does.  Worst case, if any
    4206                 :             :          * components of the record don't support hashing, we will fail at
    4207                 :             :          * execution.
    4208                 :             :          */
    4209         [ +  + ]:         409 :         if (element_type == RECORDOID)
    4210                 :             :         {
    4211                 :             :             MemoryContext oldcontext;
    4212                 :             :             TypeCacheEntry *record_typentry;
    4213                 :             : 
    4214                 :          12 :             oldcontext = MemoryContextSwitchTo(fcinfo->flinfo->fn_mcxt);
    4215                 :             : 
    4216                 :             :             /*
    4217                 :             :              * Make fake type cache entry structure.  Note that we can't just
    4218                 :             :              * modify typentry, since that points directly into the type
    4219                 :             :              * cache.
    4220                 :             :              */
    4221                 :          12 :             record_typentry = palloc0_object(TypeCacheEntry);
    4222                 :          12 :             record_typentry->type_id = element_type;
    4223                 :             : 
    4224                 :             :             /* fill in what we need below */
    4225                 :          12 :             record_typentry->typlen = typentry->typlen;
    4226                 :          12 :             record_typentry->typbyval = typentry->typbyval;
    4227                 :          12 :             record_typentry->typalign = typentry->typalign;
    4228                 :          12 :             fmgr_info(F_HASH_RECORD, &record_typentry->hash_proc_finfo);
    4229                 :             : 
    4230                 :          12 :             MemoryContextSwitchTo(oldcontext);
    4231                 :             : 
    4232                 :          12 :             typentry = record_typentry;
    4233                 :             :         }
    4234                 :             : 
    4235                 :         409 :         fcinfo->flinfo->fn_extra = typentry;
    4236                 :             :     }
    4237                 :             : 
    4238                 :       39887 :     typlen = typentry->typlen;
    4239                 :       39887 :     typbyval = typentry->typbyval;
    4240                 :       39887 :     typalign = typentry->typalign;
    4241                 :             : 
    4242                 :             :     /*
    4243                 :             :      * apply the hash function to each array element.
    4244                 :             :      */
    4245                 :       39887 :     InitFunctionCallInfoData(*locfcinfo, &typentry->hash_proc_finfo, 1,
    4246                 :             :                              PG_GET_COLLATION(), NULL, NULL);
    4247                 :             : 
    4248                 :             :     /* Loop over source data */
    4249                 :       39887 :     nitems = ArrayGetNItems(ndims, dims);
    4250                 :       39887 :     array_iter_setup(&iter, array, typlen, typbyval, typalign);
    4251                 :             : 
    4252         [ +  + ]:      105955 :     for (i = 0; i < nitems; i++)
    4253                 :             :     {
    4254                 :             :         Datum       elt;
    4255                 :             :         bool        isnull;
    4256                 :             :         uint32      elthash;
    4257                 :             : 
    4258                 :             :         /* Get element, checking for NULL */
    4259                 :       66068 :         elt = array_iter_next(&iter, &isnull, i);
    4260                 :             : 
    4261         [ +  + ]:       66068 :         if (isnull)
    4262                 :             :         {
    4263                 :             :             /* Treat nulls as having hashvalue 0 */
    4264                 :          32 :             elthash = 0;
    4265                 :             :         }
    4266                 :             :         else
    4267                 :             :         {
    4268                 :             :             /* Apply the hash function */
    4269                 :       66036 :             locfcinfo->args[0].value = elt;
    4270                 :       66036 :             locfcinfo->args[0].isnull = false;
    4271                 :       66036 :             elthash = DatumGetUInt32(FunctionCallInvoke(locfcinfo));
    4272                 :             :             /* We don't expect hash functions to return null */
    4273                 :             :             Assert(!locfcinfo->isnull);
    4274                 :             :         }
    4275                 :             : 
    4276                 :             :         /*
    4277                 :             :          * Combine hash values of successive elements by multiplying the
    4278                 :             :          * current value by 31 and adding on the new element's hash value.
    4279                 :             :          *
    4280                 :             :          * The result is a sum in which each element's hash value is
    4281                 :             :          * multiplied by a different power of 31. This is modulo 2^32
    4282                 :             :          * arithmetic, and the powers of 31 modulo 2^32 form a cyclic group of
    4283                 :             :          * order 2^27. So for arrays of up to 2^27 elements, each element's
    4284                 :             :          * hash value is multiplied by a different (odd) number, resulting in
    4285                 :             :          * a good mixing of all the elements' hash values.
    4286                 :             :          */
    4287                 :       66068 :         result = (result << 5) - result + elthash;
    4288                 :             :     }
    4289                 :             : 
    4290                 :             :     /* Avoid leaking memory when handed toasted input. */
    4291   [ +  +  +  + ]:       39887 :     AARR_FREE_IF_COPY(array, 0);
    4292                 :             : 
    4293                 :       39887 :     PG_RETURN_UINT32(result);
    4294                 :             : }
    4295                 :             : 
    4296                 :             : /*
    4297                 :             :  * Returns 64-bit value by hashing a value to a 64-bit value, with a seed.
    4298                 :             :  * Otherwise, similar to hash_array.
    4299                 :             :  */
    4300                 :             : Datum
    4301                 :         100 : hash_array_extended(PG_FUNCTION_ARGS)
    4302                 :             : {
    4303                 :         100 :     LOCAL_FCINFO(locfcinfo, 2);
    4304                 :         100 :     AnyArrayType *array = PG_GETARG_ANY_ARRAY_P(0);
    4305                 :         100 :     uint64      seed = PG_GETARG_INT64(1);
    4306         [ -  + ]:         100 :     int         ndims = AARR_NDIM(array);
    4307         [ -  + ]:         100 :     int        *dims = AARR_DIMS(array);
    4308         [ -  + ]:         100 :     Oid         element_type = AARR_ELEMTYPE(array);
    4309                 :         100 :     uint64      result = 1;
    4310                 :             :     int         nitems;
    4311                 :             :     TypeCacheEntry *typentry;
    4312                 :             :     int         typlen;
    4313                 :             :     bool        typbyval;
    4314                 :             :     char        typalign;
    4315                 :             :     int         i;
    4316                 :             :     array_iter  iter;
    4317                 :             : 
    4318                 :         100 :     typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
    4319         [ +  + ]:         100 :     if (typentry == NULL ||
    4320         [ -  + ]:          56 :         typentry->type_id != element_type)
    4321                 :             :     {
    4322                 :          44 :         typentry = lookup_type_cache(element_type,
    4323                 :             :                                      TYPECACHE_HASH_EXTENDED_PROC_FINFO);
    4324         [ +  + ]:          44 :         if (!OidIsValid(typentry->hash_extended_proc_finfo.fn_oid))
    4325         [ +  - ]:           4 :             ereport(ERROR,
    4326                 :             :                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
    4327                 :             :                      errmsg("could not identify an extended hash function for type %s",
    4328                 :             :                             format_type_be(element_type))));
    4329                 :          40 :         fcinfo->flinfo->fn_extra = typentry;
    4330                 :             :     }
    4331                 :          96 :     typlen = typentry->typlen;
    4332                 :          96 :     typbyval = typentry->typbyval;
    4333                 :          96 :     typalign = typentry->typalign;
    4334                 :             : 
    4335                 :          96 :     InitFunctionCallInfoData(*locfcinfo, &typentry->hash_extended_proc_finfo, 2,
    4336                 :             :                              PG_GET_COLLATION(), NULL, NULL);
    4337                 :             : 
    4338                 :             :     /* Loop over source data */
    4339                 :          96 :     nitems = ArrayGetNItems(ndims, dims);
    4340                 :          96 :     array_iter_setup(&iter, array, typlen, typbyval, typalign);
    4341                 :             : 
    4342         [ +  + ]:         314 :     for (i = 0; i < nitems; i++)
    4343                 :             :     {
    4344                 :             :         Datum       elt;
    4345                 :             :         bool        isnull;
    4346                 :             :         uint64      elthash;
    4347                 :             : 
    4348                 :             :         /* Get element, checking for NULL */
    4349                 :         218 :         elt = array_iter_next(&iter, &isnull, i);
    4350                 :             : 
    4351         [ -  + ]:         218 :         if (isnull)
    4352                 :             :         {
    4353                 :           0 :             elthash = 0;
    4354                 :             :         }
    4355                 :             :         else
    4356                 :             :         {
    4357                 :             :             /* Apply the hash function */
    4358                 :         218 :             locfcinfo->args[0].value = elt;
    4359                 :         218 :             locfcinfo->args[0].isnull = false;
    4360                 :         218 :             locfcinfo->args[1].value = Int64GetDatum(seed);
    4361                 :         218 :             locfcinfo->args[1].isnull = false;
    4362                 :         218 :             elthash = DatumGetUInt64(FunctionCallInvoke(locfcinfo));
    4363                 :             :             /* We don't expect hash functions to return null */
    4364                 :             :             Assert(!locfcinfo->isnull);
    4365                 :             :         }
    4366                 :             : 
    4367                 :         218 :         result = (result << 5) - result + elthash;
    4368                 :             :     }
    4369                 :             : 
    4370   [ +  -  -  + ]:          96 :     AARR_FREE_IF_COPY(array, 0);
    4371                 :             : 
    4372                 :          96 :     PG_RETURN_UINT64(result);
    4373                 :             : }
    4374                 :             : 
    4375                 :             : 
    4376                 :             : /*-----------------------------------------------------------------------------
    4377                 :             :  * array overlap/containment comparisons
    4378                 :             :  *      These use the same methods of comparing array elements as array_eq.
    4379                 :             :  *      We consider only the elements of the arrays, ignoring dimensionality.
    4380                 :             :  *----------------------------------------------------------------------------
    4381                 :             :  */
    4382                 :             : 
    4383                 :             : /*
    4384                 :             :  * array_contain_compare :
    4385                 :             :  *        compares two arrays for overlap/containment
    4386                 :             :  *
    4387                 :             :  * When matchall is true, return true if all members of array1 are in array2.
    4388                 :             :  * When matchall is false, return true if any members of array1 are in array2.
    4389                 :             :  */
    4390                 :             : static bool
    4391                 :       14883 : array_contain_compare(AnyArrayType *array1, AnyArrayType *array2, Oid collation,
    4392                 :             :                       bool matchall, void **fn_extra)
    4393                 :             : {
    4394                 :       14883 :     LOCAL_FCINFO(locfcinfo, 2);
    4395                 :       14883 :     bool        result = matchall;
    4396         [ +  + ]:       14883 :     Oid         element_type = AARR_ELEMTYPE(array1);
    4397                 :             :     TypeCacheEntry *typentry;
    4398                 :             :     int         nelems1;
    4399                 :             :     Datum      *values2;
    4400                 :             :     bool       *nulls2;
    4401                 :             :     int         nelems2;
    4402                 :             :     int         typlen;
    4403                 :             :     bool        typbyval;
    4404                 :             :     char        typalign;
    4405                 :             :     int         i;
    4406                 :             :     int         j;
    4407                 :             :     array_iter  it1;
    4408                 :             : 
    4409   [ +  +  -  + ]:       14883 :     if (element_type != AARR_ELEMTYPE(array2))
    4410         [ #  # ]:           0 :         ereport(ERROR,
    4411                 :             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    4412                 :             :                  errmsg("cannot compare arrays of different element types")));
    4413                 :             : 
    4414                 :             :     /*
    4415                 :             :      * We arrange to look up the equality function only once per series of
    4416                 :             :      * calls, assuming the element type doesn't change underneath us.  The
    4417                 :             :      * typcache is used so that we have no memory leakage when being used as
    4418                 :             :      * an index support function.
    4419                 :             :      */
    4420                 :       14883 :     typentry = (TypeCacheEntry *) *fn_extra;
    4421         [ +  + ]:       14883 :     if (typentry == NULL ||
    4422         [ -  + ]:       14507 :         typentry->type_id != element_type)
    4423                 :             :     {
    4424                 :         376 :         typentry = lookup_type_cache(element_type,
    4425                 :             :                                      TYPECACHE_EQ_OPR_FINFO);
    4426         [ -  + ]:         376 :         if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
    4427         [ #  # ]:           0 :             ereport(ERROR,
    4428                 :             :                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
    4429                 :             :                      errmsg("could not identify an equality operator for type %s",
    4430                 :             :                             format_type_be(element_type))));
    4431                 :         376 :         *fn_extra = typentry;
    4432                 :             :     }
    4433                 :       14883 :     typlen = typentry->typlen;
    4434                 :       14883 :     typbyval = typentry->typbyval;
    4435                 :       14883 :     typalign = typentry->typalign;
    4436                 :             : 
    4437                 :             :     /*
    4438                 :             :      * Since we probably will need to scan array2 multiple times, it's
    4439                 :             :      * worthwhile to use deconstruct_array on it.  We scan array1 the hard way
    4440                 :             :      * however, since we very likely won't need to look at all of it.
    4441                 :             :      */
    4442         [ +  + ]:       14883 :     if (VARATT_IS_EXPANDED_HEADER(array2))
    4443                 :             :     {
    4444                 :             :         /* This should be safe even if input is read-only */
    4445                 :        3408 :         deconstruct_expanded_array(&(array2->xpn));
    4446                 :        3408 :         values2 = array2->xpn.dvalues;
    4447                 :        3408 :         nulls2 = array2->xpn.dnulls;
    4448                 :        3408 :         nelems2 = array2->xpn.nelems;
    4449                 :             :     }
    4450                 :             :     else
    4451                 :       11475 :         deconstruct_array((ArrayType *) array2,
    4452                 :             :                           element_type, typlen, typbyval, typalign,
    4453                 :             :                           &values2, &nulls2, &nelems2);
    4454                 :             : 
    4455                 :             :     /*
    4456                 :             :      * Apply the comparison operator to each pair of array elements.
    4457                 :             :      */
    4458                 :       14883 :     InitFunctionCallInfoData(*locfcinfo, &typentry->eq_opr_finfo, 2,
    4459                 :             :                              collation, NULL, NULL);
    4460                 :             : 
    4461                 :             :     /* Loop over source data */
    4462   [ +  +  +  + ]:       14883 :     nelems1 = ArrayGetNItems(AARR_NDIM(array1), AARR_DIMS(array1));
    4463                 :       14883 :     array_iter_setup(&it1, array1, typlen, typbyval, typalign);
    4464                 :             : 
    4465         [ +  + ]:      280131 :     for (i = 0; i < nelems1; i++)
    4466                 :             :     {
    4467                 :             :         Datum       elt1;
    4468                 :             :         bool        isnull1;
    4469                 :             : 
    4470                 :             :         /* Get element, checking for NULL */
    4471                 :      271459 :         elt1 = array_iter_next(&it1, &isnull1, i);
    4472                 :             : 
    4473                 :             :         /*
    4474                 :             :          * We assume that the comparison operator is strict, so a NULL can't
    4475                 :             :          * match anything.  XXX this diverges from the "NULL=NULL" behavior of
    4476                 :             :          * array_eq, should we act like that?
    4477                 :             :          */
    4478         [ +  + ]:      271459 :         if (isnull1)
    4479                 :             :         {
    4480         [ +  + ]:         880 :             if (matchall)
    4481                 :             :             {
    4482                 :         840 :                 result = false;
    4483                 :        6211 :                 break;
    4484                 :             :             }
    4485                 :          40 :             continue;
    4486                 :             :         }
    4487                 :             : 
    4488         [ +  + ]:    12277282 :         for (j = 0; j < nelems2; j++)
    4489                 :             :         {
    4490                 :    12251099 :             Datum       elt2 = values2[j];
    4491         [ +  + ]:    12251099 :             bool        isnull2 = nulls2 ? nulls2[j] : false;
    4492                 :             :             bool        oprresult;
    4493                 :             : 
    4494         [ +  + ]:    12251099 :             if (isnull2)
    4495                 :        4808 :                 continue;       /* can't match */
    4496                 :             : 
    4497                 :             :             /*
    4498                 :             :              * Apply the operator to the element pair; treat NULL as false
    4499                 :             :              */
    4500                 :    12246291 :             locfcinfo->args[0].value = elt1;
    4501                 :    12246291 :             locfcinfo->args[0].isnull = false;
    4502                 :    12246291 :             locfcinfo->args[1].value = elt2;
    4503                 :    12246291 :             locfcinfo->args[1].isnull = false;
    4504                 :    12246291 :             locfcinfo->isnull = false;
    4505                 :    12246291 :             oprresult = DatumGetBool(FunctionCallInvoke(locfcinfo));
    4506   [ +  -  +  + ]:    12246291 :             if (!locfcinfo->isnull && oprresult)
    4507                 :      244396 :                 break;
    4508                 :             :         }
    4509                 :             : 
    4510         [ +  + ]:      270579 :         if (j < nelems2)
    4511                 :             :         {
    4512                 :             :             /* found a match for elt1 */
    4513         [ +  + ]:      244396 :             if (!matchall)
    4514                 :             :             {
    4515                 :         152 :                 result = true;
    4516                 :         152 :                 break;
    4517                 :             :             }
    4518                 :             :         }
    4519                 :             :         else
    4520                 :             :         {
    4521                 :             :             /* no match for elt1 */
    4522         [ +  + ]:       26183 :             if (matchall)
    4523                 :             :             {
    4524                 :        5219 :                 result = false;
    4525                 :        5219 :                 break;
    4526                 :             :             }
    4527                 :             :         }
    4528                 :             :     }
    4529                 :             : 
    4530                 :       14883 :     return result;
    4531                 :             : }
    4532                 :             : 
    4533                 :             : Datum
    4534                 :        4080 : arrayoverlap(PG_FUNCTION_ARGS)
    4535                 :             : {
    4536                 :        4080 :     AnyArrayType *array1 = PG_GETARG_ANY_ARRAY_P(0);
    4537                 :        4080 :     AnyArrayType *array2 = PG_GETARG_ANY_ARRAY_P(1);
    4538                 :        4080 :     Oid         collation = PG_GET_COLLATION();
    4539                 :             :     bool        result;
    4540                 :             : 
    4541                 :        4080 :     result = array_contain_compare(array1, array2, collation, false,
    4542                 :        4080 :                                    &fcinfo->flinfo->fn_extra);
    4543                 :             : 
    4544                 :             :     /* Avoid leaking memory when handed toasted input. */
    4545   [ +  -  +  + ]:        4080 :     AARR_FREE_IF_COPY(array1, 0);
    4546   [ +  -  -  + ]:        4080 :     AARR_FREE_IF_COPY(array2, 1);
    4547                 :             : 
    4548                 :        4080 :     PG_RETURN_BOOL(result);
    4549                 :             : }
    4550                 :             : 
    4551                 :             : Datum
    4552                 :        6459 : arraycontains(PG_FUNCTION_ARGS)
    4553                 :             : {
    4554                 :        6459 :     AnyArrayType *array1 = PG_GETARG_ANY_ARRAY_P(0);
    4555                 :        6459 :     AnyArrayType *array2 = PG_GETARG_ANY_ARRAY_P(1);
    4556                 :        6459 :     Oid         collation = PG_GET_COLLATION();
    4557                 :             :     bool        result;
    4558                 :             : 
    4559                 :        6459 :     result = array_contain_compare(array2, array1, collation, true,
    4560                 :        6459 :                                    &fcinfo->flinfo->fn_extra);
    4561                 :             : 
    4562                 :             :     /* Avoid leaking memory when handed toasted input. */
    4563   [ +  +  +  + ]:        6459 :     AARR_FREE_IF_COPY(array1, 0);
    4564   [ +  +  -  + ]:        6459 :     AARR_FREE_IF_COPY(array2, 1);
    4565                 :             : 
    4566                 :        6459 :     PG_RETURN_BOOL(result);
    4567                 :             : }
    4568                 :             : 
    4569                 :             : Datum
    4570                 :        4344 : arraycontained(PG_FUNCTION_ARGS)
    4571                 :             : {
    4572                 :        4344 :     AnyArrayType *array1 = PG_GETARG_ANY_ARRAY_P(0);
    4573                 :        4344 :     AnyArrayType *array2 = PG_GETARG_ANY_ARRAY_P(1);
    4574                 :        4344 :     Oid         collation = PG_GET_COLLATION();
    4575                 :             :     bool        result;
    4576                 :             : 
    4577                 :        4344 :     result = array_contain_compare(array1, array2, collation, true,
    4578                 :        4344 :                                    &fcinfo->flinfo->fn_extra);
    4579                 :             : 
    4580                 :             :     /* Avoid leaking memory when handed toasted input. */
    4581   [ +  +  +  + ]:        4344 :     AARR_FREE_IF_COPY(array1, 0);
    4582   [ +  +  -  + ]:        4344 :     AARR_FREE_IF_COPY(array2, 1);
    4583                 :             : 
    4584                 :        4344 :     PG_RETURN_BOOL(result);
    4585                 :             : }
    4586                 :             : 
    4587                 :             : 
    4588                 :             : /*-----------------------------------------------------------------------------
    4589                 :             :  * Array iteration functions
    4590                 :             :  *      These functions are used to iterate efficiently through arrays
    4591                 :             :  *-----------------------------------------------------------------------------
    4592                 :             :  */
    4593                 :             : 
    4594                 :             : /*
    4595                 :             :  * array_create_iterator --- set up to iterate through an array
    4596                 :             :  *
    4597                 :             :  * If slice_ndim is zero, we will iterate element-by-element; the returned
    4598                 :             :  * datums are of the array's element type.
    4599                 :             :  *
    4600                 :             :  * If slice_ndim is 1..ARR_NDIM(arr), we will iterate by slices: the
    4601                 :             :  * returned datums are of the same array type as 'arr', but of size
    4602                 :             :  * equal to the rightmost N dimensions of 'arr'.
    4603                 :             :  *
    4604                 :             :  * The passed-in array must remain valid for the lifetime of the iterator.
    4605                 :             :  */
    4606                 :             : ArrayIterator
    4607                 :         370 : array_create_iterator(ArrayType *arr, int slice_ndim, ArrayMetaState *mstate)
    4608                 :             : {
    4609                 :         370 :     ArrayIterator iterator = palloc0_object(ArrayIteratorData);
    4610                 :             : 
    4611                 :             :     /*
    4612                 :             :      * Sanity-check inputs --- caller should have got this right already
    4613                 :             :      */
    4614                 :             :     Assert(arr);
    4615   [ +  -  -  + ]:         370 :     if (slice_ndim < 0 || slice_ndim > ARR_NDIM(arr))
    4616         [ #  # ]:           0 :         elog(ERROR, "invalid arguments to array_create_iterator");
    4617                 :             : 
    4618                 :             :     /*
    4619                 :             :      * Remember basic info about the array and its element type
    4620                 :             :      */
    4621                 :         370 :     iterator->arr = arr;
    4622         [ +  + ]:         370 :     iterator->nullbitmap = ARR_NULLBITMAP(arr);
    4623                 :         370 :     iterator->nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
    4624                 :             : 
    4625         [ +  + ]:         370 :     if (mstate != NULL)
    4626                 :             :     {
    4627                 :             :         Assert(mstate->element_type == ARR_ELEMTYPE(arr));
    4628                 :             : 
    4629                 :         261 :         iterator->typlen = mstate->typlen;
    4630                 :         261 :         iterator->typbyval = mstate->typbyval;
    4631                 :         261 :         iterator->typalign = mstate->typalign;
    4632                 :             :     }
    4633                 :             :     else
    4634                 :         109 :         get_typlenbyvalalign(ARR_ELEMTYPE(arr),
    4635                 :             :                              &iterator->typlen,
    4636                 :             :                              &iterator->typbyval,
    4637                 :             :                              &iterator->typalign);
    4638                 :         370 :     iterator->typalignby = typalign_to_alignby(iterator->typalign);
    4639                 :             : 
    4640                 :             :     /*
    4641                 :             :      * Remember the slicing parameters.
    4642                 :             :      */
    4643                 :         370 :     iterator->slice_ndim = slice_ndim;
    4644                 :             : 
    4645         [ +  + ]:         370 :     if (slice_ndim > 0)
    4646                 :             :     {
    4647                 :             :         /*
    4648                 :             :          * Get pointers into the array's dims and lbound arrays to represent
    4649                 :             :          * the dims/lbound arrays of a slice.  These are the same as the
    4650                 :             :          * rightmost N dimensions of the array.
    4651                 :             :          */
    4652                 :          58 :         iterator->slice_dims = ARR_DIMS(arr) + ARR_NDIM(arr) - slice_ndim;
    4653                 :          58 :         iterator->slice_lbound = ARR_LBOUND(arr) + ARR_NDIM(arr) - slice_ndim;
    4654                 :             : 
    4655                 :             :         /*
    4656                 :             :          * Compute number of elements in a slice.
    4657                 :             :          */
    4658                 :         116 :         iterator->slice_len = ArrayGetNItems(slice_ndim,
    4659                 :          58 :                                              iterator->slice_dims);
    4660                 :             : 
    4661                 :             :         /*
    4662                 :             :          * Create workspace for building sub-arrays.
    4663                 :             :          */
    4664                 :          58 :         iterator->slice_values = palloc_array(Datum, iterator->slice_len);
    4665                 :          58 :         iterator->slice_nulls = palloc_array(bool, iterator->slice_len);
    4666                 :             :     }
    4667                 :             : 
    4668                 :             :     /*
    4669                 :             :      * Initialize our data pointer and linear element number.  These will
    4670                 :             :      * advance through the array during array_iterate().
    4671                 :             :      */
    4672         [ +  + ]:         370 :     iterator->data_ptr = ARR_DATA_PTR(arr);
    4673                 :         370 :     iterator->current_item = 0;
    4674                 :             : 
    4675                 :         370 :     return iterator;
    4676                 :             : }
    4677                 :             : 
    4678                 :             : /*
    4679                 :             :  * Iterate through the array referenced by 'iterator'.
    4680                 :             :  *
    4681                 :             :  * As long as there is another element (or slice), return it into
    4682                 :             :  * *value / *isnull, and return true.  Return false when no more data.
    4683                 :             :  */
    4684                 :             : bool
    4685                 :        5223 : array_iterate(ArrayIterator iterator, Datum *value, bool *isnull)
    4686                 :             : {
    4687                 :             :     /* Done if we have reached the end of the array */
    4688         [ +  + ]:        5223 :     if (iterator->current_item >= iterator->nitems)
    4689                 :         261 :         return false;
    4690                 :             : 
    4691         [ +  + ]:        4962 :     if (iterator->slice_ndim == 0)
    4692                 :             :     {
    4693                 :             :         /*
    4694                 :             :          * Scalar case: return one element.
    4695                 :             :          */
    4696         [ +  + ]:        4843 :         if (array_get_isnull(iterator->nullbitmap, iterator->current_item++))
    4697                 :             :         {
    4698                 :          55 :             *isnull = true;
    4699                 :          55 :             *value = (Datum) 0;
    4700                 :             :         }
    4701                 :             :         else
    4702                 :             :         {
    4703                 :             :             /* non-NULL, so fetch the individual Datum to return */
    4704                 :        4788 :             char       *p = iterator->data_ptr;
    4705                 :             : 
    4706                 :        4788 :             *isnull = false;
    4707                 :        4788 :             *value = fetch_att(p, iterator->typbyval, iterator->typlen);
    4708                 :             : 
    4709                 :             :             /* Move our data pointer forward to the next element */
    4710   [ +  +  +  - ]:        4788 :             p = att_addlength_pointer(p, iterator->typlen, p);
    4711                 :        4788 :             p = (char *) att_nominal_alignby(p, iterator->typalignby);
    4712                 :        4788 :             iterator->data_ptr = p;
    4713                 :             :         }
    4714                 :             :     }
    4715                 :             :     else
    4716                 :             :     {
    4717                 :             :         /*
    4718                 :             :          * Slice case: build and return an array of the requested size.
    4719                 :             :          */
    4720                 :             :         ArrayType  *result;
    4721                 :         119 :         Datum      *values = iterator->slice_values;
    4722                 :         119 :         bool       *nulls = iterator->slice_nulls;
    4723                 :         119 :         char       *p = iterator->data_ptr;
    4724                 :             :         int         i;
    4725                 :             : 
    4726         [ +  + ]:         375 :         for (i = 0; i < iterator->slice_len; i++)
    4727                 :             :         {
    4728         [ -  + ]:         256 :             if (array_get_isnull(iterator->nullbitmap,
    4729                 :         256 :                                  iterator->current_item++))
    4730                 :             :             {
    4731                 :           0 :                 nulls[i] = true;
    4732                 :           0 :                 values[i] = (Datum) 0;
    4733                 :             :             }
    4734                 :             :             else
    4735                 :             :             {
    4736                 :         256 :                 nulls[i] = false;
    4737                 :         256 :                 values[i] = fetch_att(p, iterator->typbyval, iterator->typlen);
    4738                 :             : 
    4739                 :             :                 /* Move our data pointer forward to the next element */
    4740   [ +  +  +  - ]:         256 :                 p = att_addlength_pointer(p, iterator->typlen, p);
    4741                 :         256 :                 p = (char *) att_nominal_alignby(p, iterator->typalignby);
    4742                 :             :             }
    4743                 :             :         }
    4744                 :             : 
    4745                 :         119 :         iterator->data_ptr = p;
    4746                 :             : 
    4747                 :         119 :         result = construct_md_array(values,
    4748                 :             :                                     nulls,
    4749                 :             :                                     iterator->slice_ndim,
    4750                 :             :                                     iterator->slice_dims,
    4751                 :             :                                     iterator->slice_lbound,
    4752                 :         119 :                                     ARR_ELEMTYPE(iterator->arr),
    4753                 :         119 :                                     iterator->typlen,
    4754                 :         119 :                                     iterator->typbyval,
    4755                 :         119 :                                     iterator->typalign);
    4756                 :             : 
    4757                 :         119 :         *isnull = false;
    4758                 :         119 :         *value = PointerGetDatum(result);
    4759                 :             :     }
    4760                 :             : 
    4761                 :        4962 :     return true;
    4762                 :             : }
    4763                 :             : 
    4764                 :             : /*
    4765                 :             :  * Release an ArrayIterator data structure
    4766                 :             :  */
    4767                 :             : void
    4768                 :         261 : array_free_iterator(ArrayIterator iterator)
    4769                 :             : {
    4770         [ +  + ]:         261 :     if (iterator->slice_ndim > 0)
    4771                 :             :     {
    4772                 :          34 :         pfree(iterator->slice_values);
    4773                 :          34 :         pfree(iterator->slice_nulls);
    4774                 :             :     }
    4775                 :         261 :     pfree(iterator);
    4776                 :         261 : }
    4777                 :             : 
    4778                 :             : 
    4779                 :             : /***************************************************************************/
    4780                 :             : /******************|          Support  Routines           |*****************/
    4781                 :             : /***************************************************************************/
    4782                 :             : 
    4783                 :             : /*
    4784                 :             :  * Check whether a specific array element is NULL
    4785                 :             :  *
    4786                 :             :  * nullbitmap: pointer to array's null bitmap (NULL if none)
    4787                 :             :  * offset: 0-based linear element number of array element
    4788                 :             :  */
    4789                 :             : static bool
    4790                 :      518700 : array_get_isnull(const uint8 *nullbitmap, int offset)
    4791                 :             : {
    4792         [ +  + ]:      518700 :     if (nullbitmap == NULL)
    4793                 :      518072 :         return false;           /* assume not null */
    4794         [ +  + ]:         628 :     if (nullbitmap[offset / 8] & (1 << (offset % 8)))
    4795                 :         501 :         return false;           /* not null */
    4796                 :         127 :     return true;
    4797                 :             : }
    4798                 :             : 
    4799                 :             : /*
    4800                 :             :  * Set a specific array element's null-bitmap entry
    4801                 :             :  *
    4802                 :             :  * nullbitmap: pointer to array's null bitmap (mustn't be NULL)
    4803                 :             :  * offset: 0-based linear element number of array element
    4804                 :             :  * isNull: null status to set
    4805                 :             :  */
    4806                 :             : static void
    4807                 :          90 : array_set_isnull(uint8 *nullbitmap, int offset, bool isNull)
    4808                 :             : {
    4809                 :             :     int         bitmask;
    4810                 :             : 
    4811                 :          90 :     nullbitmap += offset / 8;
    4812                 :          90 :     bitmask = 1 << (offset % 8);
    4813         [ +  + ]:          90 :     if (isNull)
    4814                 :          13 :         *nullbitmap &= ~bitmask;
    4815                 :             :     else
    4816                 :          77 :         *nullbitmap |= bitmask;
    4817                 :          90 : }
    4818                 :             : 
    4819                 :             : /*
    4820                 :             :  * Fetch array element at pointer, converted correctly to a Datum
    4821                 :             :  *
    4822                 :             :  * Caller must have handled case of NULL element
    4823                 :             :  */
    4824                 :             : static Datum
    4825                 :      513151 : ArrayCast(char *value, bool byval, int len)
    4826                 :             : {
    4827                 :      513151 :     return fetch_att(value, byval, len);
    4828                 :             : }
    4829                 :             : 
    4830                 :             : /*
    4831                 :             :  * Copy datum to *dest and return total space used (including align padding)
    4832                 :             :  *
    4833                 :             :  * Caller must have handled case of NULL element
    4834                 :             :  */
    4835                 :             : static int
    4836                 :    10132974 : ArrayCastAndSet(Datum src,
    4837                 :             :                 int typlen,
    4838                 :             :                 bool typbyval,
    4839                 :             :                 uint8 typalignby,
    4840                 :             :                 char *dest)
    4841                 :             : {
    4842                 :             :     int         inc;
    4843                 :             : 
    4844         [ +  + ]:    10132974 :     if (typlen > 0)
    4845                 :             :     {
    4846         [ +  + ]:     8133903 :         if (typbyval)
    4847                 :     4981663 :             store_att_byval(dest, src, typlen);
    4848                 :             :         else
    4849                 :     3152240 :             memmove(dest, DatumGetPointer(src), typlen);
    4850                 :     8133903 :         inc = att_nominal_alignby(typlen, typalignby);
    4851                 :             :     }
    4852                 :             :     else
    4853                 :             :     {
    4854                 :             :         Assert(!typbyval);
    4855   [ +  -  +  + ]:     1999071 :         inc = att_addlength_datum(0, typlen, src);
    4856                 :     1999071 :         memmove(dest, DatumGetPointer(src), inc);
    4857                 :     1999071 :         inc = att_nominal_alignby(inc, typalignby);
    4858                 :             :     }
    4859                 :             : 
    4860                 :    10132974 :     return inc;
    4861                 :             : }
    4862                 :             : 
    4863                 :             : /*
    4864                 :             :  * Advance ptr over nitems array elements
    4865                 :             :  *
    4866                 :             :  * ptr: starting location in array
    4867                 :             :  * offset: 0-based linear element number of first element (the one at *ptr)
    4868                 :             :  * nullbitmap: start of array's null bitmap, or NULL if none
    4869                 :             :  * nitems: number of array elements to advance over (>= 0)
    4870                 :             :  * typlen, typbyval, typalign: storage parameters of array element datatype
    4871                 :             :  *
    4872                 :             :  * It is caller's responsibility to ensure that nitems is within range
    4873                 :             :  */
    4874                 :             : static char *
    4875                 :      514801 : array_seek(char *ptr, int offset, uint8 *nullbitmap, int nitems,
    4876                 :             :            int typlen, bool typbyval, char typalign)
    4877                 :             : {
    4878                 :      514801 :     uint8       typalignby = typalign_to_alignby(typalign);
    4879                 :             :     int         bitmask;
    4880                 :             :     int         i;
    4881                 :             : 
    4882                 :             :     /* easy if fixed-size elements and no NULLs */
    4883   [ +  +  +  + ]:      514801 :     if (typlen > 0 && !nullbitmap)
    4884                 :      375275 :         return ptr + nitems * ((Size) att_nominal_alignby(typlen, typalignby));
    4885                 :             : 
    4886                 :             :     /* seems worth having separate loops for NULL and no-NULLs cases */
    4887         [ +  + ]:      139526 :     if (nullbitmap)
    4888                 :             :     {
    4889                 :         402 :         nullbitmap += offset / 8;
    4890                 :         402 :         bitmask = 1 << (offset % 8);
    4891                 :             : 
    4892         [ +  + ]:        1234 :         for (i = 0; i < nitems; i++)
    4893                 :             :         {
    4894         [ +  + ]:         832 :             if (*nullbitmap & bitmask)
    4895                 :             :             {
    4896   [ +  +  +  - ]:         592 :                 ptr = att_addlength_pointer(ptr, typlen, ptr);
    4897                 :         592 :                 ptr = (char *) att_nominal_alignby(ptr, typalignby);
    4898                 :             :             }
    4899                 :         832 :             bitmask <<= 1;
    4900         [ +  + ]:         832 :             if (bitmask == 0x100)
    4901                 :             :             {
    4902                 :          32 :                 nullbitmap++;
    4903                 :          32 :                 bitmask = 1;
    4904                 :             :             }
    4905                 :             :         }
    4906                 :             :     }
    4907                 :             :     else
    4908                 :             :     {
    4909         [ +  + ]:      613794 :         for (i = 0; i < nitems; i++)
    4910                 :             :         {
    4911   [ -  +  +  - ]:      474670 :             ptr = att_addlength_pointer(ptr, typlen, ptr);
    4912                 :      474670 :             ptr = (char *) att_nominal_alignby(ptr, typalignby);
    4913                 :             :         }
    4914                 :             :     }
    4915                 :      139526 :     return ptr;
    4916                 :             : }
    4917                 :             : 
    4918                 :             : /*
    4919                 :             :  * Compute total size of the nitems array elements starting at *ptr
    4920                 :             :  *
    4921                 :             :  * Parameters same as for array_seek
    4922                 :             :  */
    4923                 :             : static int
    4924                 :        1105 : array_nelems_size(char *ptr, int offset, uint8 *nullbitmap, int nitems,
    4925                 :             :                   int typlen, bool typbyval, char typalign)
    4926                 :             : {
    4927                 :        1105 :     return array_seek(ptr, offset, nullbitmap, nitems,
    4928                 :        1105 :                       typlen, typbyval, typalign) - ptr;
    4929                 :             : }
    4930                 :             : 
    4931                 :             : /*
    4932                 :             :  * Copy nitems array elements from srcptr to destptr
    4933                 :             :  *
    4934                 :             :  * destptr: starting destination location (must be enough room!)
    4935                 :             :  * nitems: number of array elements to copy (>= 0)
    4936                 :             :  * srcptr: starting location in source array
    4937                 :             :  * offset: 0-based linear element number of first element (the one at *srcptr)
    4938                 :             :  * nullbitmap: start of source array's null bitmap, or NULL if none
    4939                 :             :  * typlen, typbyval, typalign: storage parameters of array element datatype
    4940                 :             :  *
    4941                 :             :  * Returns number of bytes copied
    4942                 :             :  *
    4943                 :             :  * NB: this does not take care of setting up the destination's null bitmap!
    4944                 :             :  */
    4945                 :             : static int
    4946                 :         794 : array_copy(char *destptr, int nitems,
    4947                 :             :            char *srcptr, int offset, uint8 *nullbitmap,
    4948                 :             :            int typlen, bool typbyval, char typalign)
    4949                 :             : {
    4950                 :             :     int         numbytes;
    4951                 :             : 
    4952                 :         794 :     numbytes = array_nelems_size(srcptr, offset, nullbitmap, nitems,
    4953                 :             :                                  typlen, typbyval, typalign);
    4954                 :         794 :     memcpy(destptr, srcptr, numbytes);
    4955                 :         794 :     return numbytes;
    4956                 :             : }
    4957                 :             : 
    4958                 :             : /*
    4959                 :             :  * Copy nitems null-bitmap bits from source to destination
    4960                 :             :  *
    4961                 :             :  * destbitmap: start of destination array's null bitmap (mustn't be NULL)
    4962                 :             :  * destoffset: 0-based linear element number of first dest element
    4963                 :             :  * srcbitmap: start of source array's null bitmap, or NULL if none
    4964                 :             :  * srcoffset: 0-based linear element number of first source element
    4965                 :             :  * nitems: number of bits to copy (>= 0)
    4966                 :             :  *
    4967                 :             :  * If srcbitmap is NULL then we assume the source is all-non-NULL and
    4968                 :             :  * fill 1's into the destination bitmap.  Note that only the specified
    4969                 :             :  * bits in the destination map are changed, not any before or after.
    4970                 :             :  *
    4971                 :             :  * Note: this could certainly be optimized using standard bitblt methods.
    4972                 :             :  * However, it's not clear that the typical Postgres array has enough elements
    4973                 :             :  * to make it worth worrying too much.  For the moment, KISS.
    4974                 :             :  */
    4975                 :             : void
    4976                 :       20700 : array_bitmap_copy(uint8 *destbitmap, int destoffset,
    4977                 :             :                   const uint8 *srcbitmap, int srcoffset,
    4978                 :             :                   int nitems)
    4979                 :             : {
    4980                 :             :     int         destbitmask,
    4981                 :             :                 destbitval,
    4982                 :             :                 srcbitmask,
    4983                 :             :                 srcbitval;
    4984                 :             : 
    4985                 :             :     Assert(destbitmap);
    4986         [ +  + ]:       20700 :     if (nitems <= 0)
    4987                 :         125 :         return;                 /* don't risk fetch off end of memory */
    4988                 :       20575 :     destbitmap += destoffset / 8;
    4989                 :       20575 :     destbitmask = 1 << (destoffset % 8);
    4990                 :       20575 :     destbitval = *destbitmap;
    4991         [ +  + ]:       20575 :     if (srcbitmap)
    4992                 :             :     {
    4993                 :       10473 :         srcbitmap += srcoffset / 8;
    4994                 :       10473 :         srcbitmask = 1 << (srcoffset % 8);
    4995                 :       10473 :         srcbitval = *srcbitmap;
    4996         [ +  + ]:       49806 :         while (nitems-- > 0)
    4997                 :             :         {
    4998         [ +  + ]:       39333 :             if (srcbitval & srcbitmask)
    4999                 :       14973 :                 destbitval |= destbitmask;
    5000                 :             :             else
    5001                 :       24360 :                 destbitval &= ~destbitmask;
    5002                 :       39333 :             destbitmask <<= 1;
    5003         [ +  + ]:       39333 :             if (destbitmask == 0x100)
    5004                 :             :             {
    5005                 :        4641 :                 *destbitmap++ = destbitval;
    5006                 :        4641 :                 destbitmask = 1;
    5007         [ +  + ]:        4641 :                 if (nitems > 0)
    5008                 :        3523 :                     destbitval = *destbitmap;
    5009                 :             :             }
    5010                 :       39333 :             srcbitmask <<= 1;
    5011         [ +  + ]:       39333 :             if (srcbitmask == 0x100)
    5012                 :             :             {
    5013                 :        3531 :                 srcbitmap++;
    5014                 :        3531 :                 srcbitmask = 1;
    5015         [ +  + ]:        3531 :                 if (nitems > 0)
    5016                 :        3482 :                     srcbitval = *srcbitmap;
    5017                 :             :             }
    5018                 :             :         }
    5019         [ +  + ]:       10473 :         if (destbitmask != 1)
    5020                 :        9355 :             *destbitmap = destbitval;
    5021                 :             :     }
    5022                 :             :     else
    5023                 :             :     {
    5024         [ +  + ]:       20412 :         while (nitems-- > 0)
    5025                 :             :         {
    5026                 :       10310 :             destbitval |= destbitmask;
    5027                 :       10310 :             destbitmask <<= 1;
    5028         [ +  + ]:       10310 :             if (destbitmask == 0x100)
    5029                 :             :             {
    5030                 :        1426 :                 *destbitmap++ = destbitval;
    5031                 :        1426 :                 destbitmask = 1;
    5032         [ -  + ]:        1426 :                 if (nitems > 0)
    5033                 :           0 :                     destbitval = *destbitmap;
    5034                 :             :             }
    5035                 :             :         }
    5036         [ +  + ]:       10102 :         if (destbitmask != 1)
    5037                 :        8676 :             *destbitmap = destbitval;
    5038                 :             :     }
    5039                 :             : }
    5040                 :             : 
    5041                 :             : /*
    5042                 :             :  * Compute space needed for a slice of an array
    5043                 :             :  *
    5044                 :             :  * We assume the caller has verified that the slice coordinates are valid.
    5045                 :             :  */
    5046                 :             : static int
    5047                 :         208 : array_slice_size(char *arraydataptr, uint8 *arraynullsptr,
    5048                 :             :                  int ndim, int *dim, int *lb,
    5049                 :             :                  int *st, int *endp,
    5050                 :             :                  int typlen, bool typbyval, char typalign)
    5051                 :             : {
    5052                 :             :     int         src_offset,
    5053                 :             :                 span[MAXDIM],
    5054                 :             :                 prod[MAXDIM],
    5055                 :             :                 dist[MAXDIM],
    5056                 :             :                 indx[MAXDIM];
    5057                 :             :     char       *ptr;
    5058                 :             :     int         i,
    5059                 :             :                 j,
    5060                 :             :                 inc;
    5061                 :         208 :     int         count = 0;
    5062                 :         208 :     uint8       typalignby = typalign_to_alignby(typalign);
    5063                 :             : 
    5064                 :         208 :     mda_get_range(ndim, span, st, endp);
    5065                 :             : 
    5066                 :             :     /* Pretty easy for fixed element length without nulls ... */
    5067   [ +  +  +  + ]:         208 :     if (typlen > 0 && !arraynullsptr)
    5068                 :         156 :         return ArrayGetNItems(ndim, span) * att_nominal_alignby(typlen, typalignby);
    5069                 :             : 
    5070                 :             :     /* Else gotta do it the hard way */
    5071                 :          52 :     src_offset = ArrayGetOffset(ndim, dim, lb, st);
    5072                 :          52 :     ptr = array_seek(arraydataptr, 0, arraynullsptr, src_offset,
    5073                 :             :                      typlen, typbyval, typalign);
    5074                 :          52 :     mda_get_prod(ndim, dim, prod);
    5075                 :          52 :     mda_get_offset_values(ndim, dist, prod, span);
    5076         [ +  + ]:         132 :     for (i = 0; i < ndim; i++)
    5077                 :          80 :         indx[i] = 0;
    5078                 :          52 :     j = ndim - 1;
    5079                 :             :     do
    5080                 :             :     {
    5081         [ -  + ]:         172 :         if (dist[j])
    5082                 :             :         {
    5083                 :           0 :             ptr = array_seek(ptr, src_offset, arraynullsptr, dist[j],
    5084                 :             :                              typlen, typbyval, typalign);
    5085                 :           0 :             src_offset += dist[j];
    5086                 :             :         }
    5087         [ +  + ]:         172 :         if (!array_get_isnull(arraynullsptr, src_offset))
    5088                 :             :         {
    5089   [ +  +  +  - ]:         164 :             inc = att_addlength_pointer(0, typlen, ptr);
    5090                 :         164 :             inc = att_nominal_alignby(inc, typalignby);
    5091                 :         164 :             ptr += inc;
    5092                 :         164 :             count += inc;
    5093                 :             :         }
    5094                 :         172 :         src_offset++;
    5095         [ +  + ]:         172 :     } while ((j = mda_next_tuple(ndim, indx, span)) != -1);
    5096                 :          52 :     return count;
    5097                 :             : }
    5098                 :             : 
    5099                 :             : /*
    5100                 :             :  * Extract a slice of an array into consecutive elements in the destination
    5101                 :             :  * array.
    5102                 :             :  *
    5103                 :             :  * We assume the caller has verified that the slice coordinates are valid,
    5104                 :             :  * allocated enough storage for the result, and initialized the header
    5105                 :             :  * of the new array.
    5106                 :             :  */
    5107                 :             : static void
    5108                 :         188 : array_extract_slice(ArrayType *newarray,
    5109                 :             :                     int ndim,
    5110                 :             :                     int *dim,
    5111                 :             :                     int *lb,
    5112                 :             :                     char *arraydataptr,
    5113                 :             :                     uint8 *arraynullsptr,
    5114                 :             :                     int *st,
    5115                 :             :                     int *endp,
    5116                 :             :                     int typlen,
    5117                 :             :                     bool typbyval,
    5118                 :             :                     char typalign)
    5119                 :             : {
    5120         [ +  + ]:         188 :     char       *destdataptr = ARR_DATA_PTR(newarray);
    5121         [ +  + ]:         188 :     uint8      *destnullsptr = ARR_NULLBITMAP(newarray);
    5122                 :             :     char       *srcdataptr;
    5123                 :             :     int         src_offset,
    5124                 :             :                 dest_offset,
    5125                 :             :                 prod[MAXDIM],
    5126                 :             :                 span[MAXDIM],
    5127                 :             :                 dist[MAXDIM],
    5128                 :             :                 indx[MAXDIM];
    5129                 :             :     int         i,
    5130                 :             :                 j,
    5131                 :             :                 inc;
    5132                 :             : 
    5133                 :         188 :     src_offset = ArrayGetOffset(ndim, dim, lb, st);
    5134                 :         188 :     srcdataptr = array_seek(arraydataptr, 0, arraynullsptr, src_offset,
    5135                 :             :                             typlen, typbyval, typalign);
    5136                 :         188 :     mda_get_prod(ndim, dim, prod);
    5137                 :         188 :     mda_get_range(ndim, span, st, endp);
    5138                 :         188 :     mda_get_offset_values(ndim, dist, prod, span);
    5139         [ +  + ]:         476 :     for (i = 0; i < ndim; i++)
    5140                 :         288 :         indx[i] = 0;
    5141                 :         188 :     dest_offset = 0;
    5142                 :         188 :     j = ndim - 1;
    5143                 :             :     do
    5144                 :             :     {
    5145         [ +  + ]:         690 :         if (dist[j])
    5146                 :             :         {
    5147                 :             :             /* skip unwanted elements */
    5148                 :          23 :             srcdataptr = array_seek(srcdataptr, src_offset, arraynullsptr,
    5149                 :             :                                     dist[j],
    5150                 :             :                                     typlen, typbyval, typalign);
    5151                 :          23 :             src_offset += dist[j];
    5152                 :             :         }
    5153                 :         690 :         inc = array_copy(destdataptr, 1,
    5154                 :             :                          srcdataptr, src_offset, arraynullsptr,
    5155                 :             :                          typlen, typbyval, typalign);
    5156         [ +  + ]:         690 :         if (destnullsptr)
    5157                 :         120 :             array_bitmap_copy(destnullsptr, dest_offset,
    5158                 :             :                               arraynullsptr, src_offset,
    5159                 :             :                               1);
    5160                 :         690 :         destdataptr += inc;
    5161                 :         690 :         srcdataptr += inc;
    5162                 :         690 :         src_offset++;
    5163                 :         690 :         dest_offset++;
    5164         [ +  + ]:         690 :     } while ((j = mda_next_tuple(ndim, indx, span)) != -1);
    5165                 :         188 : }
    5166                 :             : 
    5167                 :             : /*
    5168                 :             :  * Insert a slice into an array.
    5169                 :             :  *
    5170                 :             :  * ndim/dim[]/lb[] are dimensions of the original array.  A new array with
    5171                 :             :  * those same dimensions is to be constructed.  destArray must already
    5172                 :             :  * have been allocated and its header initialized.
    5173                 :             :  *
    5174                 :             :  * st[]/endp[] identify the slice to be replaced.  Elements within the slice
    5175                 :             :  * volume are taken from consecutive elements of the srcArray; elements
    5176                 :             :  * outside it are copied from origArray.
    5177                 :             :  *
    5178                 :             :  * We assume the caller has verified that the slice coordinates are valid.
    5179                 :             :  */
    5180                 :             : static void
    5181                 :          20 : array_insert_slice(ArrayType *destArray,
    5182                 :             :                    ArrayType *origArray,
    5183                 :             :                    ArrayType *srcArray,
    5184                 :             :                    int ndim,
    5185                 :             :                    int *dim,
    5186                 :             :                    int *lb,
    5187                 :             :                    int *st,
    5188                 :             :                    int *endp,
    5189                 :             :                    int typlen,
    5190                 :             :                    bool typbyval,
    5191                 :             :                    char typalign)
    5192                 :             : {
    5193         [ -  + ]:          20 :     char       *destPtr = ARR_DATA_PTR(destArray);
    5194         [ -  + ]:          20 :     char       *origPtr = ARR_DATA_PTR(origArray);
    5195         [ -  + ]:          20 :     char       *srcPtr = ARR_DATA_PTR(srcArray);
    5196         [ -  + ]:          20 :     uint8      *destBitmap = ARR_NULLBITMAP(destArray);
    5197         [ -  + ]:          20 :     uint8      *origBitmap = ARR_NULLBITMAP(origArray);
    5198         [ -  + ]:          20 :     uint8      *srcBitmap = ARR_NULLBITMAP(srcArray);
    5199                 :          20 :     int         orignitems = ArrayGetNItems(ARR_NDIM(origArray),
    5200                 :             :                                             ARR_DIMS(origArray));
    5201                 :             :     int         dest_offset,
    5202                 :             :                 orig_offset,
    5203                 :             :                 src_offset,
    5204                 :             :                 prod[MAXDIM],
    5205                 :             :                 span[MAXDIM],
    5206                 :             :                 dist[MAXDIM],
    5207                 :             :                 indx[MAXDIM];
    5208                 :             :     int         i,
    5209                 :             :                 j,
    5210                 :             :                 inc;
    5211                 :             : 
    5212                 :          20 :     dest_offset = ArrayGetOffset(ndim, dim, lb, st);
    5213                 :             :     /* copy items before the slice start */
    5214                 :          20 :     inc = array_copy(destPtr, dest_offset,
    5215                 :             :                      origPtr, 0, origBitmap,
    5216                 :             :                      typlen, typbyval, typalign);
    5217                 :          20 :     destPtr += inc;
    5218                 :          20 :     origPtr += inc;
    5219         [ -  + ]:          20 :     if (destBitmap)
    5220                 :           0 :         array_bitmap_copy(destBitmap, 0, origBitmap, 0, dest_offset);
    5221                 :          20 :     orig_offset = dest_offset;
    5222                 :          20 :     mda_get_prod(ndim, dim, prod);
    5223                 :          20 :     mda_get_range(ndim, span, st, endp);
    5224                 :          20 :     mda_get_offset_values(ndim, dist, prod, span);
    5225         [ +  + ]:          68 :     for (i = 0; i < ndim; i++)
    5226                 :          48 :         indx[i] = 0;
    5227                 :          20 :     src_offset = 0;
    5228                 :          20 :     j = ndim - 1;
    5229                 :             :     do
    5230                 :             :     {
    5231                 :             :         /* Copy/advance over elements between here and next part of slice */
    5232         [ +  + ]:          52 :         if (dist[j])
    5233                 :             :         {
    5234                 :          12 :             inc = array_copy(destPtr, dist[j],
    5235                 :             :                              origPtr, orig_offset, origBitmap,
    5236                 :             :                              typlen, typbyval, typalign);
    5237                 :          12 :             destPtr += inc;
    5238                 :          12 :             origPtr += inc;
    5239         [ -  + ]:          12 :             if (destBitmap)
    5240                 :           0 :                 array_bitmap_copy(destBitmap, dest_offset,
    5241                 :             :                                   origBitmap, orig_offset,
    5242                 :             :                                   dist[j]);
    5243                 :          12 :             dest_offset += dist[j];
    5244                 :          12 :             orig_offset += dist[j];
    5245                 :             :         }
    5246                 :             :         /* Copy new element at this slice position */
    5247                 :          52 :         inc = array_copy(destPtr, 1,
    5248                 :             :                          srcPtr, src_offset, srcBitmap,
    5249                 :             :                          typlen, typbyval, typalign);
    5250         [ -  + ]:          52 :         if (destBitmap)
    5251                 :           0 :             array_bitmap_copy(destBitmap, dest_offset,
    5252                 :             :                               srcBitmap, src_offset,
    5253                 :             :                               1);
    5254                 :          52 :         destPtr += inc;
    5255                 :          52 :         srcPtr += inc;
    5256                 :          52 :         dest_offset++;
    5257                 :          52 :         src_offset++;
    5258                 :             :         /* Advance over old element at this slice position */
    5259                 :          52 :         origPtr = array_seek(origPtr, orig_offset, origBitmap, 1,
    5260                 :             :                              typlen, typbyval, typalign);
    5261                 :          52 :         orig_offset++;
    5262         [ +  + ]:          52 :     } while ((j = mda_next_tuple(ndim, indx, span)) != -1);
    5263                 :             : 
    5264                 :             :     /* don't miss any data at the end */
    5265                 :          20 :     array_copy(destPtr, orignitems - orig_offset,
    5266                 :             :                origPtr, orig_offset, origBitmap,
    5267                 :             :                typlen, typbyval, typalign);
    5268         [ -  + ]:          20 :     if (destBitmap)
    5269                 :           0 :         array_bitmap_copy(destBitmap, dest_offset,
    5270                 :             :                           origBitmap, orig_offset,
    5271                 :             :                           orignitems - orig_offset);
    5272                 :          20 : }
    5273                 :             : 
    5274                 :             : /*
    5275                 :             :  * initArrayResult - initialize an empty ArrayBuildState
    5276                 :             :  *
    5277                 :             :  *  element_type is the array element type (must be a valid array element type)
    5278                 :             :  *  rcontext is where to keep working state
    5279                 :             :  *  subcontext is a flag determining whether to use a separate memory context
    5280                 :             :  *
    5281                 :             :  * Note: there are two common schemes for using accumArrayResult().
    5282                 :             :  * In the older scheme, you start with a NULL ArrayBuildState pointer, and
    5283                 :             :  * call accumArrayResult once per element.  In this scheme you end up with
    5284                 :             :  * a NULL pointer if there were no elements, which you need to special-case.
    5285                 :             :  * In the newer scheme, call initArrayResult and then call accumArrayResult
    5286                 :             :  * once per element.  In this scheme you always end with a non-NULL pointer
    5287                 :             :  * that you can pass to makeArrayResult; you get an empty array if there
    5288                 :             :  * were no elements.  This is preferred if an empty array is what you want.
    5289                 :             :  *
    5290                 :             :  * It's possible to choose whether to create a separate memory context for the
    5291                 :             :  * array build state, or whether to allocate it directly within rcontext.
    5292                 :             :  *
    5293                 :             :  * When there are many concurrent small states (e.g. array_agg() using hash
    5294                 :             :  * aggregation of many small groups), using a separate memory context for each
    5295                 :             :  * one may result in severe memory bloat. In such cases, use the same memory
    5296                 :             :  * context to initialize all such array build states, and pass
    5297                 :             :  * subcontext=false.
    5298                 :             :  *
    5299                 :             :  * In cases when the array build states have different lifetimes, using a
    5300                 :             :  * single memory context is impractical. Instead, pass subcontext=true so that
    5301                 :             :  * the array build states can be freed individually.
    5302                 :             :  */
    5303                 :             : ArrayBuildState *
    5304                 :      219747 : initArrayResult(Oid element_type, MemoryContext rcontext, bool subcontext)
    5305                 :             : {
    5306                 :             :     /*
    5307                 :             :      * When using a subcontext, we can afford to start with a somewhat larger
    5308                 :             :      * initial array size.  Without subcontexts, we'd better hope that most of
    5309                 :             :      * the states stay small ...
    5310                 :             :      */
    5311         [ +  + ]:      219747 :     return initArrayResultWithSize(element_type, rcontext, subcontext,
    5312                 :             :                                    subcontext ? 64 : 8);
    5313                 :             : }
    5314                 :             : 
    5315                 :             : /*
    5316                 :             :  * initArrayResultWithSize
    5317                 :             :  *      As initArrayResult, but allow the initial size of the allocated arrays
    5318                 :             :  *      to be specified.
    5319                 :             :  */
    5320                 :             : ArrayBuildState *
    5321                 :      219867 : initArrayResultWithSize(Oid element_type, MemoryContext rcontext,
    5322                 :             :                         bool subcontext, int initsize)
    5323                 :             : {
    5324                 :             :     ArrayBuildState *astate;
    5325                 :      219867 :     MemoryContext arr_context = rcontext;
    5326                 :             : 
    5327                 :             :     /* Make a temporary context to hold all the junk */
    5328         [ +  + ]:      219867 :     if (subcontext)
    5329                 :      143160 :         arr_context = AllocSetContextCreate(rcontext,
    5330                 :             :                                             "accumArrayResult",
    5331                 :             :                                             ALLOCSET_DEFAULT_SIZES);
    5332                 :             : 
    5333                 :             :     astate = (ArrayBuildState *)
    5334                 :      219867 :         MemoryContextAlloc(arr_context, sizeof(ArrayBuildState));
    5335                 :      219867 :     astate->mcontext = arr_context;
    5336                 :      219867 :     astate->private_cxt = subcontext;
    5337                 :      219867 :     astate->alen = initsize;
    5338                 :      219867 :     astate->dvalues = (Datum *)
    5339                 :      219867 :         MemoryContextAlloc(arr_context, astate->alen * sizeof(Datum));
    5340                 :      219867 :     astate->dnulls = (bool *)
    5341                 :      219867 :         MemoryContextAlloc(arr_context, astate->alen * sizeof(bool));
    5342                 :      219867 :     astate->nelems = 0;
    5343                 :      219867 :     astate->element_type = element_type;
    5344                 :      219867 :     get_typlenbyvalalign(element_type,
    5345                 :             :                          &astate->typlen,
    5346                 :             :                          &astate->typbyval,
    5347                 :             :                          &astate->typalign);
    5348                 :             : 
    5349                 :      219867 :     return astate;
    5350                 :             : }
    5351                 :             : 
    5352                 :             : /*
    5353                 :             :  * accumArrayResult - accumulate one (more) Datum for an array result
    5354                 :             :  *
    5355                 :             :  *  astate is working state (can be NULL on first call)
    5356                 :             :  *  dvalue/disnull represent the new Datum to append to the array
    5357                 :             :  *  element_type is the Datum's type (must be a valid array element type)
    5358                 :             :  *  rcontext is where to keep working state
    5359                 :             :  */
    5360                 :             : ArrayBuildState *
    5361                 :     2227303 : accumArrayResult(ArrayBuildState *astate,
    5362                 :             :                  Datum dvalue, bool disnull,
    5363                 :             :                  Oid element_type,
    5364                 :             :                  MemoryContext rcontext)
    5365                 :             : {
    5366                 :             :     MemoryContext oldcontext;
    5367                 :             : 
    5368         [ +  + ]:     2227303 :     if (astate == NULL)
    5369                 :             :     {
    5370                 :             :         /* First time through --- initialize */
    5371                 :      110933 :         astate = initArrayResult(element_type, rcontext, true);
    5372                 :             :     }
    5373                 :             :     else
    5374                 :             :     {
    5375                 :             :         Assert(astate->element_type == element_type);
    5376                 :             :     }
    5377                 :             : 
    5378                 :     2227303 :     oldcontext = MemoryContextSwitchTo(astate->mcontext);
    5379                 :             : 
    5380                 :             :     /* enlarge dvalues[]/dnulls[] if needed */
    5381         [ +  + ]:     2227303 :     if (astate->nelems >= astate->alen)
    5382                 :             :     {
    5383                 :       46780 :         astate->alen *= 2;
    5384                 :             :         /* give an array-related error if we go past MaxAllocSize */
    5385         [ -  + ]:       46780 :         if (!AllocSizeIsValid(astate->alen * sizeof(Datum)))
    5386         [ #  # ]:           0 :             ereport(ERROR,
    5387                 :             :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    5388                 :             :                      errmsg("array size exceeds the maximum allowed (%zu)",
    5389                 :             :                             MaxAllocSize)));
    5390                 :       46780 :         astate->dvalues = repalloc_array(astate->dvalues, Datum, astate->alen);
    5391                 :       46780 :         astate->dnulls = repalloc_array(astate->dnulls, bool, astate->alen);
    5392                 :             :     }
    5393                 :             : 
    5394                 :             :     /*
    5395                 :             :      * Ensure pass-by-ref stuff is copied into mcontext; and detoast it too if
    5396                 :             :      * it's varlena.  (You might think that detoasting is not needed here
    5397                 :             :      * because construct_md_array can detoast the array elements later.
    5398                 :             :      * However, we must not let construct_md_array modify the ArrayBuildState
    5399                 :             :      * because that would mean array_agg_finalfn damages its input, which is
    5400                 :             :      * verboten.  Also, this way frequently saves one copying step.)
    5401                 :             :      */
    5402   [ +  +  +  + ]:     2227303 :     if (!disnull && !astate->typbyval)
    5403                 :             :     {
    5404         [ +  + ]:     1490437 :         if (astate->typlen == -1)
    5405                 :     1005273 :             dvalue = PointerGetDatum(PG_DETOAST_DATUM_COPY(dvalue));
    5406                 :             :         else
    5407                 :      485164 :             dvalue = datumCopy(dvalue, astate->typbyval, astate->typlen);
    5408                 :             :     }
    5409                 :             : 
    5410                 :     2227303 :     astate->dvalues[astate->nelems] = dvalue;
    5411                 :     2227303 :     astate->dnulls[astate->nelems] = disnull;
    5412                 :     2227303 :     astate->nelems++;
    5413                 :             : 
    5414                 :     2227303 :     MemoryContextSwitchTo(oldcontext);
    5415                 :             : 
    5416                 :     2227303 :     return astate;
    5417                 :             : }
    5418                 :             : 
    5419                 :             : /*
    5420                 :             :  * makeArrayResult - produce 1-D final result of accumArrayResult
    5421                 :             :  *
    5422                 :             :  * Note: only releases astate if it was initialized within a separate memory
    5423                 :             :  * context (i.e. using subcontext=true when calling initArrayResult).
    5424                 :             :  *
    5425                 :             :  *  astate is working state (must not be NULL)
    5426                 :             :  *  rcontext is where to construct result
    5427                 :             :  */
    5428                 :             : Datum
    5429                 :      111071 : makeArrayResult(ArrayBuildState *astate,
    5430                 :             :                 MemoryContext rcontext)
    5431                 :             : {
    5432                 :             :     int         ndims;
    5433                 :             :     int         dims[1];
    5434                 :             :     int         lbs[1];
    5435                 :             : 
    5436                 :             :     /* If no elements were presented, we want to create an empty array */
    5437                 :      111071 :     ndims = (astate->nelems > 0) ? 1 : 0;
    5438                 :      111071 :     dims[0] = astate->nelems;
    5439                 :      111071 :     lbs[0] = 1;
    5440                 :             : 
    5441                 :      222142 :     return makeMdArrayResult(astate, ndims, dims, lbs, rcontext,
    5442                 :      111071 :                              astate->private_cxt);
    5443                 :             : }
    5444                 :             : 
    5445                 :             : /*
    5446                 :             :  * makeMdArrayResult - produce multi-D final result of accumArrayResult
    5447                 :             :  *
    5448                 :             :  * beware: no check that specified dimensions match the number of values
    5449                 :             :  * accumulated.
    5450                 :             :  *
    5451                 :             :  * Note: if the astate was not initialized within a separate memory context
    5452                 :             :  * (that is, initArrayResult was called with subcontext=false), then using
    5453                 :             :  * release=true is illegal. Instead, release astate along with the rest of its
    5454                 :             :  * context when appropriate.
    5455                 :             :  *
    5456                 :             :  *  astate is working state (must not be NULL)
    5457                 :             :  *  rcontext is where to construct result
    5458                 :             :  *  release is true if okay to release working state
    5459                 :             :  */
    5460                 :             : Datum
    5461                 :      218963 : makeMdArrayResult(ArrayBuildState *astate,
    5462                 :             :                   int ndims,
    5463                 :             :                   int *dims,
    5464                 :             :                   int *lbs,
    5465                 :             :                   MemoryContext rcontext,
    5466                 :             :                   bool release)
    5467                 :             : {
    5468                 :             :     ArrayType  *result;
    5469                 :             :     MemoryContext oldcontext;
    5470                 :             : 
    5471                 :             :     /* Build the final array result in rcontext */
    5472                 :      218963 :     oldcontext = MemoryContextSwitchTo(rcontext);
    5473                 :             : 
    5474                 :      218963 :     result = construct_md_array(astate->dvalues,
    5475                 :             :                                 astate->dnulls,
    5476                 :             :                                 ndims,
    5477                 :             :                                 dims,
    5478                 :             :                                 lbs,
    5479                 :             :                                 astate->element_type,
    5480                 :      218963 :                                 astate->typlen,
    5481                 :      218963 :                                 astate->typbyval,
    5482                 :      218963 :                                 astate->typalign);
    5483                 :             : 
    5484                 :      218963 :     MemoryContextSwitchTo(oldcontext);
    5485                 :             : 
    5486                 :             :     /* Clean up all the junk */
    5487         [ +  + ]:      218963 :     if (release)
    5488                 :             :     {
    5489                 :             :         Assert(astate->private_cxt);
    5490                 :      142760 :         MemoryContextDelete(astate->mcontext);
    5491                 :             :     }
    5492                 :             : 
    5493                 :      218963 :     return PointerGetDatum(result);
    5494                 :             : }
    5495                 :             : 
    5496                 :             : /*
    5497                 :             :  * The following three functions provide essentially the same API as
    5498                 :             :  * initArrayResult/accumArrayResult/makeArrayResult, but instead of accepting
    5499                 :             :  * inputs that are array elements, they accept inputs that are arrays and
    5500                 :             :  * produce an output array having N+1 dimensions.  The inputs must all have
    5501                 :             :  * identical dimensionality as well as element type.
    5502                 :             :  */
    5503                 :             : 
    5504                 :             : /*
    5505                 :             :  * initArrayResultArr - initialize an empty ArrayBuildStateArr
    5506                 :             :  *
    5507                 :             :  *  array_type is the array type (must be a valid varlena array type)
    5508                 :             :  *  element_type is the type of the array's elements (lookup if InvalidOid)
    5509                 :             :  *  rcontext is where to keep working state
    5510                 :             :  *  subcontext is a flag determining whether to use a separate memory context
    5511                 :             :  */
    5512                 :             : ArrayBuildStateArr *
    5513                 :         428 : initArrayResultArr(Oid array_type, Oid element_type, MemoryContext rcontext,
    5514                 :             :                    bool subcontext)
    5515                 :             : {
    5516                 :             :     ArrayBuildStateArr *astate;
    5517                 :         428 :     MemoryContext arr_context = rcontext;   /* by default use the parent ctx */
    5518                 :             : 
    5519                 :             :     /* Lookup element type, unless element_type already provided */
    5520         [ +  + ]:         428 :     if (!OidIsValid(element_type))
    5521                 :             :     {
    5522                 :         348 :         element_type = get_element_type(array_type);
    5523                 :             : 
    5524         [ -  + ]:         348 :         if (!OidIsValid(element_type))
    5525         [ #  # ]:           0 :             ereport(ERROR,
    5526                 :             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    5527                 :             :                      errmsg("data type %s is not an array type",
    5528                 :             :                             format_type_be(array_type))));
    5529                 :             :     }
    5530                 :             : 
    5531                 :             :     /* Make a temporary context to hold all the junk */
    5532         [ +  + ]:         428 :     if (subcontext)
    5533                 :          38 :         arr_context = AllocSetContextCreate(rcontext,
    5534                 :             :                                             "accumArrayResultArr",
    5535                 :             :                                             ALLOCSET_DEFAULT_SIZES);
    5536                 :             : 
    5537                 :             :     /* Note we initialize all fields to zero */
    5538                 :             :     astate = (ArrayBuildStateArr *)
    5539                 :         428 :         MemoryContextAllocZero(arr_context, sizeof(ArrayBuildStateArr));
    5540                 :         428 :     astate->mcontext = arr_context;
    5541                 :         428 :     astate->private_cxt = subcontext;
    5542                 :             : 
    5543                 :             :     /* Save relevant datatype information */
    5544                 :         428 :     astate->array_type = array_type;
    5545                 :         428 :     astate->element_type = element_type;
    5546                 :             : 
    5547                 :         428 :     return astate;
    5548                 :             : }
    5549                 :             : 
    5550                 :             : /*
    5551                 :             :  * accumArrayResultArr - accumulate one (more) sub-array for an array result
    5552                 :             :  *
    5553                 :             :  *  astate is working state (can be NULL on first call)
    5554                 :             :  *  dvalue/disnull represent the new sub-array to append to the array
    5555                 :             :  *  array_type is the array type (must be a valid varlena array type)
    5556                 :             :  *  rcontext is where to keep working state
    5557                 :             :  */
    5558                 :             : ArrayBuildStateArr *
    5559                 :       84000 : accumArrayResultArr(ArrayBuildStateArr *astate,
    5560                 :             :                     Datum dvalue, bool disnull,
    5561                 :             :                     Oid array_type,
    5562                 :             :                     MemoryContext rcontext)
    5563                 :             : {
    5564                 :             :     ArrayType  *arg;
    5565                 :             :     MemoryContext oldcontext;
    5566                 :             :     int        *dims,
    5567                 :             :                *lbs,
    5568                 :             :                 ndims,
    5569                 :             :                 nitems,
    5570                 :             :                 ndatabytes;
    5571                 :             :     char       *data;
    5572                 :             :     int         i;
    5573                 :             :     int         newnitems;
    5574                 :             : 
    5575                 :             :     /*
    5576                 :             :      * We disallow accumulating null subarrays.  Another plausible definition
    5577                 :             :      * is to ignore them, but callers that want that can just skip calling
    5578                 :             :      * this function.
    5579                 :             :      */
    5580         [ +  + ]:       84000 :     if (disnull)
    5581         [ +  - ]:           4 :         ereport(ERROR,
    5582                 :             :                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    5583                 :             :                  errmsg("cannot accumulate null arrays")));
    5584                 :             : 
    5585                 :             :     /* Detoast input array in caller's context */
    5586                 :       83996 :     arg = DatumGetArrayTypeP(dvalue);
    5587                 :             : 
    5588         [ -  + ]:       83996 :     if (astate == NULL)
    5589                 :           0 :         astate = initArrayResultArr(array_type, InvalidOid, rcontext, true);
    5590                 :             :     else
    5591                 :             :         Assert(astate->array_type == array_type);
    5592                 :             : 
    5593                 :       83996 :     oldcontext = MemoryContextSwitchTo(astate->mcontext);
    5594                 :             : 
    5595                 :             :     /* Collect this input's dimensions */
    5596                 :       83996 :     ndims = ARR_NDIM(arg);
    5597                 :       83996 :     dims = ARR_DIMS(arg);
    5598                 :       83996 :     lbs = ARR_LBOUND(arg);
    5599         [ +  + ]:       83996 :     data = ARR_DATA_PTR(arg);
    5600                 :       83996 :     nitems = ArrayGetNItems(ndims, dims);
    5601         [ +  + ]:       83996 :     ndatabytes = ARR_SIZE(arg) - ARR_DATA_OFFSET(arg);
    5602                 :             : 
    5603                 :             :     /* Check that the array doesn't grow too large */
    5604                 :       83996 :     newnitems = astate->nitems + nitems;
    5605         [ -  + ]:       83996 :     if (newnitems > MaxArraySize)
    5606         [ #  # ]:           0 :         ereport(ERROR,
    5607                 :             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    5608                 :             :                  errmsg("array size exceeds the maximum allowed (%zu)",
    5609                 :             :                         MaxArraySize)));
    5610                 :             : 
    5611         [ +  + ]:       83996 :     if (astate->ndims == 0)
    5612                 :             :     {
    5613                 :             :         /* First input; check/save the dimensionality info */
    5614                 :             : 
    5615                 :             :         /* Should we allow empty inputs and just produce an empty output? */
    5616         [ +  + ]:         304 :         if (ndims == 0)
    5617         [ +  - ]:           4 :             ereport(ERROR,
    5618                 :             :                     (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    5619                 :             :                      errmsg("cannot accumulate empty arrays")));
    5620         [ -  + ]:         300 :         if (ndims + 1 > MAXDIM)
    5621         [ #  # ]:           0 :             ereport(ERROR,
    5622                 :             :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    5623                 :             :                      errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
    5624                 :             :                             ndims + 1, MAXDIM)));
    5625                 :             : 
    5626                 :             :         /*
    5627                 :             :          * The output array will have n+1 dimensions, with the ones after the
    5628                 :             :          * first matching the input's dimensions.
    5629                 :             :          */
    5630                 :         300 :         astate->ndims = ndims + 1;
    5631                 :         300 :         astate->dims[0] = 0;
    5632                 :         300 :         memcpy(&astate->dims[1], dims, ndims * sizeof(int));
    5633                 :         300 :         astate->lbs[0] = 1;
    5634                 :         300 :         memcpy(&astate->lbs[1], lbs, ndims * sizeof(int));
    5635                 :             : 
    5636                 :             :         /* Allocate at least enough data space for this item */
    5637                 :         300 :         astate->abytes = pg_nextpower2_32(Max(1024, ndatabytes + 1));
    5638                 :         300 :         astate->data = (char *) palloc(astate->abytes);
    5639                 :             :     }
    5640                 :             :     else
    5641                 :             :     {
    5642                 :             :         /* Second or later input: must match first input's dimensionality */
    5643         [ -  + ]:       83692 :         if (astate->ndims != ndims + 1)
    5644         [ #  # ]:           0 :             ereport(ERROR,
    5645                 :             :                     (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    5646                 :             :                      errmsg("cannot accumulate arrays of different dimensionality")));
    5647         [ +  + ]:      167380 :         for (i = 0; i < ndims; i++)
    5648                 :             :         {
    5649   [ +  +  -  + ]:       83692 :             if (astate->dims[i + 1] != dims[i] || astate->lbs[i + 1] != lbs[i])
    5650         [ +  - ]:           4 :                 ereport(ERROR,
    5651                 :             :                         (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    5652                 :             :                          errmsg("cannot accumulate arrays of different dimensionality")));
    5653                 :             :         }
    5654                 :             : 
    5655                 :             :         /* Enlarge data space if needed */
    5656         [ +  + ]:       83688 :         if (astate->nbytes + ndatabytes > astate->abytes)
    5657                 :             :         {
    5658                 :         111 :             astate->abytes = Max(astate->abytes * 2,
    5659                 :             :                                  astate->nbytes + ndatabytes);
    5660                 :         111 :             astate->data = (char *) repalloc(astate->data, astate->abytes);
    5661                 :             :         }
    5662                 :             :     }
    5663                 :             : 
    5664                 :             :     /*
    5665                 :             :      * Copy the data portion of the sub-array.  Note we assume that the
    5666                 :             :      * advertised data length of the sub-array is properly aligned.  We do not
    5667                 :             :      * have to worry about detoasting elements since whatever's in the
    5668                 :             :      * sub-array should be OK already.
    5669                 :             :      */
    5670                 :       83988 :     memcpy(astate->data + astate->nbytes, data, ndatabytes);
    5671                 :       83988 :     astate->nbytes += ndatabytes;
    5672                 :             : 
    5673                 :             :     /* Deal with null bitmap if needed */
    5674   [ +  +  +  + ]:       83988 :     if (astate->nullbitmap || ARR_HASNULL(arg))
    5675                 :             :     {
    5676         [ +  + ]:       20058 :         if (astate->nullbitmap == NULL)
    5677                 :             :         {
    5678                 :             :             /*
    5679                 :             :              * First input with nulls; we must retrospectively handle any
    5680                 :             :              * previous inputs by marking all their items non-null.
    5681                 :             :              */
    5682                 :          85 :             astate->aitems = pg_nextpower2_32(Max(256, newnitems + 1));
    5683                 :          85 :             astate->nullbitmap = palloc_array(uint8, (astate->aitems + 7) / 8);
    5684                 :          85 :             array_bitmap_copy(astate->nullbitmap, 0,
    5685                 :             :                               NULL, 0,
    5686                 :             :                               astate->nitems);
    5687                 :             :         }
    5688         [ +  + ]:       19973 :         else if (newnitems > astate->aitems)
    5689                 :             :         {
    5690                 :          40 :             astate->aitems = Max(astate->aitems * 2, newnitems);
    5691                 :          40 :             astate->nullbitmap = repalloc_array(astate->nullbitmap,
    5692                 :             :                                                 uint8, (astate->aitems + 7) / 8);
    5693                 :             :         }
    5694                 :       20058 :         array_bitmap_copy(astate->nullbitmap, astate->nitems,
    5695         [ +  + ]:       20058 :                           ARR_NULLBITMAP(arg), 0,
    5696                 :             :                           nitems);
    5697                 :             :     }
    5698                 :             : 
    5699                 :       83988 :     astate->nitems = newnitems;
    5700                 :       83988 :     astate->dims[0] += 1;
    5701                 :             : 
    5702                 :       83988 :     MemoryContextSwitchTo(oldcontext);
    5703                 :             : 
    5704                 :             :     /* Release detoasted copy if any */
    5705         [ +  + ]:       83988 :     if (arg != DatumGetPointer(dvalue))
    5706                 :        3774 :         pfree(arg);
    5707                 :             : 
    5708                 :       83988 :     return astate;
    5709                 :             : }
    5710                 :             : 
    5711                 :             : /*
    5712                 :             :  * makeArrayResultArr - produce N+1-D final result of accumArrayResultArr
    5713                 :             :  *
    5714                 :             :  *  astate is working state (must not be NULL)
    5715                 :             :  *  rcontext is where to construct result
    5716                 :             :  *  release is true if okay to release working state
    5717                 :             :  */
    5718                 :             : Datum
    5719                 :         256 : makeArrayResultArr(ArrayBuildStateArr *astate,
    5720                 :             :                    MemoryContext rcontext,
    5721                 :             :                    bool release)
    5722                 :             : {
    5723                 :             :     ArrayType  *result;
    5724                 :             :     MemoryContext oldcontext;
    5725                 :             : 
    5726                 :             :     /* Build the final array result in rcontext */
    5727                 :         256 :     oldcontext = MemoryContextSwitchTo(rcontext);
    5728                 :             : 
    5729         [ -  + ]:         256 :     if (astate->ndims == 0)
    5730                 :             :     {
    5731                 :             :         /* No inputs, return empty array */
    5732                 :           0 :         result = construct_empty_array(astate->element_type);
    5733                 :             :     }
    5734                 :             :     else
    5735                 :             :     {
    5736                 :             :         int         dataoffset,
    5737                 :             :                     nbytes;
    5738                 :             : 
    5739                 :             :         /* Check for overflow of the array dimensions */
    5740                 :         256 :         (void) ArrayGetNItems(astate->ndims, astate->dims);
    5741                 :         256 :         ArrayCheckBounds(astate->ndims, astate->dims, astate->lbs);
    5742                 :             : 
    5743                 :             :         /* Compute required space */
    5744                 :         256 :         nbytes = astate->nbytes;
    5745         [ +  + ]:         256 :         if (astate->nullbitmap != NULL)
    5746                 :             :         {
    5747                 :          65 :             dataoffset = ARR_OVERHEAD_WITHNULLS(astate->ndims, astate->nitems);
    5748                 :          65 :             nbytes += dataoffset;
    5749                 :             :         }
    5750                 :             :         else
    5751                 :             :         {
    5752                 :         191 :             dataoffset = 0;
    5753                 :         191 :             nbytes += ARR_OVERHEAD_NONULLS(astate->ndims);
    5754                 :             :         }
    5755                 :             : 
    5756                 :         256 :         result = (ArrayType *) palloc0(nbytes);
    5757                 :         256 :         SET_VARSIZE(result, nbytes);
    5758                 :         256 :         result->ndim = astate->ndims;
    5759                 :         256 :         result->dataoffset = dataoffset;
    5760                 :         256 :         result->elemtype = astate->element_type;
    5761                 :             : 
    5762                 :         256 :         memcpy(ARR_DIMS(result), astate->dims, astate->ndims * sizeof(int));
    5763                 :         256 :         memcpy(ARR_LBOUND(result), astate->lbs, astate->ndims * sizeof(int));
    5764         [ +  + ]:         256 :         memcpy(ARR_DATA_PTR(result), astate->data, astate->nbytes);
    5765                 :             : 
    5766         [ +  + ]:         256 :         if (astate->nullbitmap != NULL)
    5767                 :          65 :             array_bitmap_copy(ARR_NULLBITMAP(result), 0,
    5768         [ +  - ]:          65 :                               astate->nullbitmap, 0,
    5769                 :             :                               astate->nitems);
    5770                 :             :     }
    5771                 :             : 
    5772                 :         256 :     MemoryContextSwitchTo(oldcontext);
    5773                 :             : 
    5774                 :             :     /* Clean up all the junk */
    5775         [ +  + ]:         256 :     if (release)
    5776                 :             :     {
    5777                 :             :         Assert(astate->private_cxt);
    5778                 :          38 :         MemoryContextDelete(astate->mcontext);
    5779                 :             :     }
    5780                 :             : 
    5781                 :         256 :     return PointerGetDatum(result);
    5782                 :             : }
    5783                 :             : 
    5784                 :             : /*
    5785                 :             :  * The following three functions provide essentially the same API as
    5786                 :             :  * initArrayResult/accumArrayResult/makeArrayResult, but can accept either
    5787                 :             :  * scalar or array inputs, invoking the appropriate set of functions above.
    5788                 :             :  */
    5789                 :             : 
    5790                 :             : /*
    5791                 :             :  * initArrayResultAny - initialize an empty ArrayBuildStateAny
    5792                 :             :  *
    5793                 :             :  *  input_type is the input datatype (either element or array type)
    5794                 :             :  *  rcontext is where to keep working state
    5795                 :             :  *  subcontext is a flag determining whether to use a separate memory context
    5796                 :             :  */
    5797                 :             : ArrayBuildStateAny *
    5798                 :       30645 : initArrayResultAny(Oid input_type, MemoryContext rcontext, bool subcontext)
    5799                 :             : {
    5800                 :             :     ArrayBuildStateAny *astate;
    5801                 :             : 
    5802                 :             :     /*
    5803                 :             :      * int2vector and oidvector will satisfy both get_element_type and
    5804                 :             :      * get_array_type.  We prefer to treat them as scalars, to be consistent
    5805                 :             :      * with get_promoted_array_type.  Hence, check get_array_type not
    5806                 :             :      * get_element_type.
    5807                 :             :      */
    5808         [ +  + ]:       30645 :     if (!OidIsValid(get_array_type(input_type)))
    5809                 :             :     {
    5810                 :             :         /* Array case */
    5811                 :             :         ArrayBuildStateArr *arraystate;
    5812                 :             : 
    5813                 :          38 :         arraystate = initArrayResultArr(input_type, InvalidOid, rcontext, subcontext);
    5814                 :             :         astate = (ArrayBuildStateAny *)
    5815                 :          38 :             MemoryContextAlloc(arraystate->mcontext,
    5816                 :             :                                sizeof(ArrayBuildStateAny));
    5817                 :          38 :         astate->scalarstate = NULL;
    5818                 :          38 :         astate->arraystate = arraystate;
    5819                 :             :     }
    5820                 :             :     else
    5821                 :             :     {
    5822                 :             :         /* Scalar case */
    5823                 :             :         ArrayBuildState *scalarstate;
    5824                 :             : 
    5825                 :       30607 :         scalarstate = initArrayResult(input_type, rcontext, subcontext);
    5826                 :             :         astate = (ArrayBuildStateAny *)
    5827                 :       30607 :             MemoryContextAlloc(scalarstate->mcontext,
    5828                 :             :                                sizeof(ArrayBuildStateAny));
    5829                 :       30607 :         astate->scalarstate = scalarstate;
    5830                 :       30607 :         astate->arraystate = NULL;
    5831                 :             :     }
    5832                 :             : 
    5833                 :       30645 :     return astate;
    5834                 :             : }
    5835                 :             : 
    5836                 :             : /*
    5837                 :             :  * accumArrayResultAny - accumulate one (more) input for an array result
    5838                 :             :  *
    5839                 :             :  *  astate is working state (can be NULL on first call)
    5840                 :             :  *  dvalue/disnull represent the new input to append to the array
    5841                 :             :  *  input_type is the input datatype (either element or array type)
    5842                 :             :  *  rcontext is where to keep working state
    5843                 :             :  */
    5844                 :             : ArrayBuildStateAny *
    5845                 :       76664 : accumArrayResultAny(ArrayBuildStateAny *astate,
    5846                 :             :                     Datum dvalue, bool disnull,
    5847                 :             :                     Oid input_type,
    5848                 :             :                     MemoryContext rcontext)
    5849                 :             : {
    5850         [ +  + ]:       76664 :     if (astate == NULL)
    5851                 :          99 :         astate = initArrayResultAny(input_type, rcontext, true);
    5852                 :             : 
    5853         [ +  + ]:       76664 :     if (astate->scalarstate)
    5854                 :       76557 :         (void) accumArrayResult(astate->scalarstate,
    5855                 :             :                                 dvalue, disnull,
    5856                 :             :                                 input_type, rcontext);
    5857                 :             :     else
    5858                 :         107 :         (void) accumArrayResultArr(astate->arraystate,
    5859                 :             :                                    dvalue, disnull,
    5860                 :             :                                    input_type, rcontext);
    5861                 :             : 
    5862                 :       76664 :     return astate;
    5863                 :             : }
    5864                 :             : 
    5865                 :             : /*
    5866                 :             :  * makeArrayResultAny - produce final result of accumArrayResultAny
    5867                 :             :  *
    5868                 :             :  *  astate is working state (must not be NULL)
    5869                 :             :  *  rcontext is where to construct result
    5870                 :             :  *  release is true if okay to release working state
    5871                 :             :  */
    5872                 :             : Datum
    5873                 :       30645 : makeArrayResultAny(ArrayBuildStateAny *astate,
    5874                 :             :                    MemoryContext rcontext, bool release)
    5875                 :             : {
    5876                 :             :     Datum       result;
    5877                 :             : 
    5878         [ +  + ]:       30645 :     if (astate->scalarstate)
    5879                 :             :     {
    5880                 :             :         /* Must use makeMdArrayResult to support "release" parameter */
    5881                 :             :         int         ndims;
    5882                 :             :         int         dims[1];
    5883                 :             :         int         lbs[1];
    5884                 :             : 
    5885                 :             :         /* If no elements were presented, we want to create an empty array */
    5886                 :       30607 :         ndims = (astate->scalarstate->nelems > 0) ? 1 : 0;
    5887                 :       30607 :         dims[0] = astate->scalarstate->nelems;
    5888                 :       30607 :         lbs[0] = 1;
    5889                 :             : 
    5890                 :       30607 :         result = makeMdArrayResult(astate->scalarstate, ndims, dims, lbs,
    5891                 :             :                                    rcontext, release);
    5892                 :             :     }
    5893                 :             :     else
    5894                 :             :     {
    5895                 :          38 :         result = makeArrayResultArr(astate->arraystate,
    5896                 :             :                                     rcontext, release);
    5897                 :             :     }
    5898                 :       30645 :     return result;
    5899                 :             : }
    5900                 :             : 
    5901                 :             : 
    5902                 :             : Datum
    5903                 :         192 : array_larger(PG_FUNCTION_ARGS)
    5904                 :             : {
    5905         [ +  + ]:         192 :     if (array_cmp(fcinfo) > 0)
    5906                 :          96 :         PG_RETURN_DATUM(PG_GETARG_DATUM(0));
    5907                 :             :     else
    5908                 :          92 :         PG_RETURN_DATUM(PG_GETARG_DATUM(1));
    5909                 :             : }
    5910                 :             : 
    5911                 :             : Datum
    5912                 :         172 : array_smaller(PG_FUNCTION_ARGS)
    5913                 :             : {
    5914         [ +  + ]:         172 :     if (array_cmp(fcinfo) < 0)
    5915                 :         116 :         PG_RETURN_DATUM(PG_GETARG_DATUM(0));
    5916                 :             :     else
    5917                 :          56 :         PG_RETURN_DATUM(PG_GETARG_DATUM(1));
    5918                 :             : }
    5919                 :             : 
    5920                 :             : 
    5921                 :             : typedef struct generate_subscripts_fctx
    5922                 :             : {
    5923                 :             :     int32       lower;
    5924                 :             :     int32       upper;
    5925                 :             :     bool        reverse;
    5926                 :             : } generate_subscripts_fctx;
    5927                 :             : 
    5928                 :             : /*
    5929                 :             :  * generate_subscripts(array anyarray, dim int [, reverse bool])
    5930                 :             :  *      Returns all subscripts of the array for any dimension
    5931                 :             :  */
    5932                 :             : Datum
    5933                 :        2630 : generate_subscripts(PG_FUNCTION_ARGS)
    5934                 :             : {
    5935                 :             :     FuncCallContext *funcctx;
    5936                 :             :     MemoryContext oldcontext;
    5937                 :             :     generate_subscripts_fctx *fctx;
    5938                 :             : 
    5939                 :             :     /* stuff done only on the first call of the function */
    5940         [ +  + ]:        2630 :     if (SRF_IS_FIRSTCALL())
    5941                 :             :     {
    5942                 :        1199 :         AnyArrayType *v = PG_GETARG_ANY_ARRAY_P(0);
    5943                 :        1199 :         int         reqdim = PG_GETARG_INT32(1);
    5944                 :             :         int        *lb,
    5945                 :             :                    *dimv;
    5946                 :             : 
    5947                 :             :         /* create a function context for cross-call persistence */
    5948                 :        1199 :         funcctx = SRF_FIRSTCALL_INIT();
    5949                 :             : 
    5950                 :             :         /* Sanity check: does it look like an array at all? */
    5951   [ -  +  -  -  :        1199 :         if (AARR_NDIM(v) <= 0 || AARR_NDIM(v) > MAXDIM)
          +  +  -  +  -  
                -  -  + ]
    5952                 :           5 :             SRF_RETURN_DONE(funcctx);
    5953                 :             : 
    5954                 :             :         /* Sanity check: was the requested dim valid */
    5955   [ +  -  -  +  :        1194 :         if (reqdim <= 0 || reqdim > AARR_NDIM(v))
                   -  + ]
    5956                 :           0 :             SRF_RETURN_DONE(funcctx);
    5957                 :             : 
    5958                 :             :         /*
    5959                 :             :          * switch to memory context appropriate for multiple function calls
    5960                 :             :          */
    5961                 :        1194 :         oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
    5962                 :        1194 :         fctx = palloc_object(generate_subscripts_fctx);
    5963                 :             : 
    5964         [ -  + ]:        1194 :         lb = AARR_LBOUND(v);
    5965         [ -  + ]:        1194 :         dimv = AARR_DIMS(v);
    5966                 :             : 
    5967                 :        1194 :         fctx->lower = lb[reqdim - 1];
    5968                 :        1194 :         fctx->upper = dimv[reqdim - 1] + lb[reqdim - 1] - 1;
    5969   [ -  +  -  - ]:        1194 :         fctx->reverse = (PG_NARGS() < 3) ? false : PG_GETARG_BOOL(2);
    5970                 :             : 
    5971                 :        1194 :         funcctx->user_fctx = fctx;
    5972                 :             : 
    5973                 :        1194 :         MemoryContextSwitchTo(oldcontext);
    5974                 :             :     }
    5975                 :             : 
    5976                 :        2625 :     funcctx = SRF_PERCALL_SETUP();
    5977                 :             : 
    5978                 :        2625 :     fctx = funcctx->user_fctx;
    5979                 :             : 
    5980         [ +  + ]:        2625 :     if (fctx->lower <= fctx->upper)
    5981                 :             :     {
    5982         [ +  - ]:        1431 :         if (!fctx->reverse)
    5983                 :        1431 :             SRF_RETURN_NEXT(funcctx, Int32GetDatum(fctx->lower++));
    5984                 :             :         else
    5985                 :           0 :             SRF_RETURN_NEXT(funcctx, Int32GetDatum(fctx->upper--));
    5986                 :             :     }
    5987                 :             :     else
    5988                 :             :         /* done when there are no more elements left */
    5989                 :        1194 :         SRF_RETURN_DONE(funcctx);
    5990                 :             : }
    5991                 :             : 
    5992                 :             : /*
    5993                 :             :  * generate_subscripts_nodir
    5994                 :             :  *      Implements the 2-argument version of generate_subscripts
    5995                 :             :  */
    5996                 :             : Datum
    5997                 :        2630 : generate_subscripts_nodir(PG_FUNCTION_ARGS)
    5998                 :             : {
    5999                 :             :     /* just call the other one -- it can handle both cases */
    6000                 :        2630 :     return generate_subscripts(fcinfo);
    6001                 :             : }
    6002                 :             : 
    6003                 :             : /*
    6004                 :             :  * array_fill_with_lower_bounds
    6005                 :             :  *      Create and fill array with defined lower bounds.
    6006                 :             :  */
    6007                 :             : Datum
    6008                 :          51 : array_fill_with_lower_bounds(PG_FUNCTION_ARGS)
    6009                 :             : {
    6010                 :             :     ArrayType  *dims;
    6011                 :             :     ArrayType  *lbs;
    6012                 :             :     ArrayType  *result;
    6013                 :             :     Oid         elmtype;
    6014                 :             :     Datum       value;
    6015                 :             :     bool        isnull;
    6016                 :             : 
    6017   [ +  +  +  + ]:          51 :     if (PG_ARGISNULL(1) || PG_ARGISNULL(2))
    6018         [ +  - ]:           8 :         ereport(ERROR,
    6019                 :             :                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    6020                 :             :                  errmsg("dimension array or low bound array cannot be null")));
    6021                 :             : 
    6022                 :          43 :     dims = PG_GETARG_ARRAYTYPE_P(1);
    6023                 :          43 :     lbs = PG_GETARG_ARRAYTYPE_P(2);
    6024                 :             : 
    6025         [ +  + ]:          43 :     if (!PG_ARGISNULL(0))
    6026                 :             :     {
    6027                 :          33 :         value = PG_GETARG_DATUM(0);
    6028                 :          33 :         isnull = false;
    6029                 :             :     }
    6030                 :             :     else
    6031                 :             :     {
    6032                 :          10 :         value = 0;
    6033                 :          10 :         isnull = true;
    6034                 :             :     }
    6035                 :             : 
    6036                 :          43 :     elmtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
    6037         [ -  + ]:          43 :     if (!OidIsValid(elmtype))
    6038         [ #  # ]:           0 :         elog(ERROR, "could not determine data type of input");
    6039                 :             : 
    6040                 :          43 :     result = array_fill_internal(dims, lbs, value, isnull, elmtype, fcinfo);
    6041                 :          35 :     PG_RETURN_ARRAYTYPE_P(result);
    6042                 :             : }
    6043                 :             : 
    6044                 :             : /*
    6045                 :             :  * array_fill
    6046                 :             :  *      Create and fill array with default lower bounds.
    6047                 :             :  */
    6048                 :             : Datum
    6049                 :          71 : array_fill(PG_FUNCTION_ARGS)
    6050                 :             : {
    6051                 :             :     ArrayType  *dims;
    6052                 :             :     ArrayType  *result;
    6053                 :             :     Oid         elmtype;
    6054                 :             :     Datum       value;
    6055                 :             :     bool        isnull;
    6056                 :             : 
    6057         [ -  + ]:          71 :     if (PG_ARGISNULL(1))
    6058         [ #  # ]:           0 :         ereport(ERROR,
    6059                 :             :                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    6060                 :             :                  errmsg("dimension array or low bound array cannot be null")));
    6061                 :             : 
    6062                 :          71 :     dims = PG_GETARG_ARRAYTYPE_P(1);
    6063                 :             : 
    6064         [ +  + ]:          71 :     if (!PG_ARGISNULL(0))
    6065                 :             :     {
    6066                 :          61 :         value = PG_GETARG_DATUM(0);
    6067                 :          61 :         isnull = false;
    6068                 :             :     }
    6069                 :             :     else
    6070                 :             :     {
    6071                 :          10 :         value = 0;
    6072                 :          10 :         isnull = true;
    6073                 :             :     }
    6074                 :             : 
    6075                 :          71 :     elmtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
    6076         [ -  + ]:          71 :     if (!OidIsValid(elmtype))
    6077         [ #  # ]:           0 :         elog(ERROR, "could not determine data type of input");
    6078                 :             : 
    6079                 :          71 :     result = array_fill_internal(dims, NULL, value, isnull, elmtype, fcinfo);
    6080                 :          63 :     PG_RETURN_ARRAYTYPE_P(result);
    6081                 :             : }
    6082                 :             : 
    6083                 :             : static ArrayType *
    6084                 :          53 : create_array_envelope(int ndims, int *dimv, int *lbsv, int nbytes,
    6085                 :             :                       Oid elmtype, int dataoffset)
    6086                 :             : {
    6087                 :             :     ArrayType  *result;
    6088                 :             : 
    6089                 :          53 :     result = (ArrayType *) palloc0(nbytes);
    6090                 :          53 :     SET_VARSIZE(result, nbytes);
    6091                 :          53 :     result->ndim = ndims;
    6092                 :          53 :     result->dataoffset = dataoffset;
    6093                 :          53 :     result->elemtype = elmtype;
    6094                 :          53 :     memcpy(ARR_DIMS(result), dimv, ndims * sizeof(int));
    6095                 :          53 :     memcpy(ARR_LBOUND(result), lbsv, ndims * sizeof(int));
    6096                 :             : 
    6097                 :          53 :     return result;
    6098                 :             : }
    6099                 :             : 
    6100                 :             : static ArrayType *
    6101                 :         114 : array_fill_internal(ArrayType *dims, ArrayType *lbs,
    6102                 :             :                     Datum value, bool isnull, Oid elmtype,
    6103                 :             :                     FunctionCallInfo fcinfo)
    6104                 :             : {
    6105                 :             :     ArrayType  *result;
    6106                 :             :     int        *dimv;
    6107                 :             :     int        *lbsv;
    6108                 :             :     int         ndims;
    6109                 :             :     int         nitems;
    6110                 :             :     int         deflbs[MAXDIM];
    6111                 :             :     int16       elmlen;
    6112                 :             :     bool        elmbyval;
    6113                 :             :     char        elmalign;
    6114                 :             :     uint8       elmalignby;
    6115                 :             :     ArrayMetaState *my_extra;
    6116                 :             : 
    6117                 :             :     /*
    6118                 :             :      * Params checks
    6119                 :             :      */
    6120         [ +  + ]:         114 :     if (ARR_NDIM(dims) > 1)
    6121         [ +  - ]:           4 :         ereport(ERROR,
    6122                 :             :                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    6123                 :             :                  errmsg("wrong number of array subscripts"),
    6124                 :             :                  errdetail("Dimension array must be one dimensional.")));
    6125                 :             : 
    6126         [ +  + ]:         110 :     if (array_contains_nulls(dims))
    6127         [ +  - ]:           4 :         ereport(ERROR,
    6128                 :             :                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    6129                 :             :                  errmsg("dimension values cannot be null")));
    6130                 :             : 
    6131         [ -  + ]:         106 :     dimv = (int *) ARR_DATA_PTR(dims);
    6132         [ +  + ]:         106 :     ndims = (ARR_NDIM(dims) > 0) ? ARR_DIMS(dims)[0] : 0;
    6133                 :             : 
    6134         [ -  + ]:         106 :     if (ndims < 0)               /* we do allow zero-dimension arrays */
    6135         [ #  # ]:           0 :         ereport(ERROR,
    6136                 :             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    6137                 :             :                  errmsg("invalid number of dimensions: %d", ndims)));
    6138         [ -  + ]:         106 :     if (ndims > MAXDIM)
    6139         [ #  # ]:           0 :         ereport(ERROR,
    6140                 :             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    6141                 :             :                  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
    6142                 :             :                         ndims, MAXDIM)));
    6143                 :             : 
    6144         [ +  + ]:         106 :     if (lbs != NULL)
    6145                 :             :     {
    6146         [ -  + ]:          43 :         if (ARR_NDIM(lbs) > 1)
    6147         [ #  # ]:           0 :             ereport(ERROR,
    6148                 :             :                     (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    6149                 :             :                      errmsg("wrong number of array subscripts"),
    6150                 :             :                      errdetail("Dimension array must be one dimensional.")));
    6151                 :             : 
    6152         [ -  + ]:          43 :         if (array_contains_nulls(lbs))
    6153         [ #  # ]:           0 :             ereport(ERROR,
    6154                 :             :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    6155                 :             :                      errmsg("dimension values cannot be null")));
    6156                 :             : 
    6157   [ +  +  +  + ]:          43 :         if (ndims != ((ARR_NDIM(lbs) > 0) ? ARR_DIMS(lbs)[0] : 0))
    6158         [ +  - ]:           8 :             ereport(ERROR,
    6159                 :             :                     (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    6160                 :             :                      errmsg("wrong number of array subscripts"),
    6161                 :             :                      errdetail("Low bound array has different size than dimensions array.")));
    6162                 :             : 
    6163         [ -  + ]:          35 :         lbsv = (int *) ARR_DATA_PTR(lbs);
    6164                 :             :     }
    6165                 :             :     else
    6166                 :             :     {
    6167                 :             :         int         i;
    6168                 :             : 
    6169         [ +  + ]:         441 :         for (i = 0; i < MAXDIM; i++)
    6170                 :         378 :             deflbs[i] = 1;
    6171                 :             : 
    6172                 :          63 :         lbsv = deflbs;
    6173                 :             :     }
    6174                 :             : 
    6175                 :             :     /* This checks for overflow of the array dimensions */
    6176                 :          98 :     nitems = ArrayGetNItems(ndims, dimv);
    6177                 :          98 :     ArrayCheckBounds(ndims, dimv, lbsv);
    6178                 :             : 
    6179                 :             :     /* fast track for empty array */
    6180         [ +  + ]:          98 :     if (nitems <= 0)
    6181                 :          45 :         return construct_empty_array(elmtype);
    6182                 :             : 
    6183                 :             :     /*
    6184                 :             :      * We arrange to look up info about element type only once per series of
    6185                 :             :      * calls, assuming the element type doesn't change underneath us.
    6186                 :             :      */
    6187                 :          53 :     my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
    6188         [ +  - ]:          53 :     if (my_extra == NULL)
    6189                 :             :     {
    6190                 :          53 :         fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
    6191                 :             :                                                       sizeof(ArrayMetaState));
    6192                 :          53 :         my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
    6193                 :          53 :         my_extra->element_type = InvalidOid;
    6194                 :             :     }
    6195                 :             : 
    6196         [ +  - ]:          53 :     if (my_extra->element_type != elmtype)
    6197                 :             :     {
    6198                 :             :         /* Get info about element type */
    6199                 :          53 :         get_typlenbyvalalign(elmtype,
    6200                 :             :                              &my_extra->typlen,
    6201                 :             :                              &my_extra->typbyval,
    6202                 :             :                              &my_extra->typalign);
    6203                 :          53 :         my_extra->element_type = elmtype;
    6204                 :             :     }
    6205                 :             : 
    6206                 :          53 :     elmlen = my_extra->typlen;
    6207                 :          53 :     elmbyval = my_extra->typbyval;
    6208                 :          53 :     elmalign = my_extra->typalign;
    6209                 :          53 :     elmalignby = typalign_to_alignby(elmalign);
    6210                 :             : 
    6211                 :             :     /* compute required space */
    6212         [ +  + ]:          53 :     if (!isnull)
    6213                 :             :     {
    6214                 :             :         int         i;
    6215                 :             :         char       *p;
    6216                 :             :         int         nbytes;
    6217                 :             :         int         totbytes;
    6218                 :             : 
    6219                 :             :         /* make sure data is not toasted */
    6220         [ +  + ]:          33 :         if (elmlen == -1)
    6221                 :          10 :             value = PointerGetDatum(PG_DETOAST_DATUM(value));
    6222                 :             : 
    6223   [ +  +  +  - ]:          33 :         nbytes = att_addlength_datum(0, elmlen, value);
    6224                 :          33 :         nbytes = att_nominal_alignby(nbytes, elmalignby);
    6225                 :             :         Assert(nbytes > 0);
    6226                 :             : 
    6227                 :          33 :         totbytes = nbytes * nitems;
    6228                 :             : 
    6229                 :             :         /* check for overflow of multiplication or total request */
    6230         [ +  - ]:          33 :         if (totbytes / nbytes != nitems ||
    6231         [ -  + ]:          33 :             !AllocSizeIsValid(totbytes))
    6232         [ #  # ]:           0 :             ereport(ERROR,
    6233                 :             :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    6234                 :             :                      errmsg("array size exceeds the maximum allowed (%zu)",
    6235                 :             :                             MaxAllocSize)));
    6236                 :             : 
    6237                 :             :         /*
    6238                 :             :          * This addition can't overflow, but it might cause us to go past
    6239                 :             :          * MaxAllocSize.  We leave it to palloc to complain in that case.
    6240                 :             :          */
    6241                 :          33 :         totbytes += ARR_OVERHEAD_NONULLS(ndims);
    6242                 :             : 
    6243                 :          33 :         result = create_array_envelope(ndims, dimv, lbsv, totbytes,
    6244                 :             :                                        elmtype, 0);
    6245                 :             : 
    6246         [ -  + ]:          33 :         p = ARR_DATA_PTR(result);
    6247         [ +  + ]:     2500245 :         for (i = 0; i < nitems; i++)
    6248                 :     2500212 :             p += ArrayCastAndSet(value, elmlen, elmbyval, elmalignby, p);
    6249                 :             :     }
    6250                 :             :     else
    6251                 :             :     {
    6252                 :             :         int         nbytes;
    6253                 :             :         int         dataoffset;
    6254                 :             : 
    6255                 :          20 :         dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);
    6256                 :          20 :         nbytes = dataoffset;
    6257                 :             : 
    6258                 :          20 :         result = create_array_envelope(ndims, dimv, lbsv, nbytes,
    6259                 :             :                                        elmtype, dataoffset);
    6260                 :             : 
    6261                 :             :         /* create_array_envelope already zeroed the bitmap, so we're done */
    6262                 :             :     }
    6263                 :             : 
    6264                 :          53 :     return result;
    6265                 :             : }
    6266                 :             : 
    6267                 :             : 
    6268                 :             : /*
    6269                 :             :  * UNNEST
    6270                 :             :  */
    6271                 :             : Datum
    6272                 :      339385 : array_unnest(PG_FUNCTION_ARGS)
    6273                 :             : {
    6274                 :             :     typedef struct
    6275                 :             :     {
    6276                 :             :         array_iter  iter;
    6277                 :             :         int         nextelem;
    6278                 :             :         int         numelems;
    6279                 :             :     } array_unnest_fctx;
    6280                 :             : 
    6281                 :             :     FuncCallContext *funcctx;
    6282                 :             :     array_unnest_fctx *fctx;
    6283                 :             :     MemoryContext oldcontext;
    6284                 :             : 
    6285                 :             :     /* stuff done only on the first call of the function */
    6286         [ +  + ]:      339385 :     if (SRF_IS_FIRSTCALL())
    6287                 :             :     {
    6288                 :             :         AnyArrayType *arr;
    6289                 :             :         int16       elmlen;
    6290                 :             :         bool        elmbyval;
    6291                 :             :         char        elmalign;
    6292                 :             : 
    6293                 :             :         /* create a function context for cross-call persistence */
    6294                 :       57937 :         funcctx = SRF_FIRSTCALL_INIT();
    6295                 :             : 
    6296                 :             :         /*
    6297                 :             :          * switch to memory context appropriate for multiple function calls
    6298                 :             :          */
    6299                 :       57937 :         oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
    6300                 :             : 
    6301                 :             :         /*
    6302                 :             :          * Get the array value and detoast if needed.  We can't do this
    6303                 :             :          * earlier because if we have to detoast, we want the detoasted copy
    6304                 :             :          * to be in multi_call_memory_ctx, so it will go away when we're done
    6305                 :             :          * and not before.  (If no detoast happens, we assume the originally
    6306                 :             :          * passed array will stick around till then.)
    6307                 :             :          */
    6308                 :       57937 :         arr = PG_GETARG_ANY_ARRAY_P(0);
    6309                 :             : 
    6310                 :             :         /* allocate memory for user context */
    6311                 :       57937 :         fctx = palloc_object(array_unnest_fctx);
    6312                 :             : 
    6313                 :             :         /* get element-type data */
    6314         [ +  + ]:       57937 :         if (VARATT_IS_EXPANDED_HEADER(arr))
    6315                 :             :         {
    6316                 :             :             /* we can just grab the type data from expanded array */
    6317                 :           1 :             elmlen = arr->xpn.typlen;
    6318                 :           1 :             elmbyval = arr->xpn.typbyval;
    6319                 :           1 :             elmalign = arr->xpn.typalign;
    6320                 :             :         }
    6321                 :             :         else
    6322         [ -  + ]:       57936 :             get_typlenbyvalalign(AARR_ELEMTYPE(arr),
    6323                 :             :                                  &elmlen,
    6324                 :             :                                  &elmbyval,
    6325                 :             :                                  &elmalign);
    6326                 :             : 
    6327                 :             :         /* initialize state */
    6328                 :       57937 :         array_iter_setup(&fctx->iter, arr, elmlen, elmbyval, elmalign);
    6329                 :       57937 :         fctx->nextelem = 0;
    6330   [ +  +  +  + ]:       57937 :         fctx->numelems = ArrayGetNItems(AARR_NDIM(arr), AARR_DIMS(arr));
    6331                 :             : 
    6332                 :       57937 :         funcctx->user_fctx = fctx;
    6333                 :       57937 :         MemoryContextSwitchTo(oldcontext);
    6334                 :             :     }
    6335                 :             : 
    6336                 :             :     /* stuff done on every call of the function */
    6337                 :      339385 :     funcctx = SRF_PERCALL_SETUP();
    6338                 :      339385 :     fctx = funcctx->user_fctx;
    6339                 :             : 
    6340         [ +  + ]:      339385 :     if (fctx->nextelem < fctx->numelems)
    6341                 :             :     {
    6342                 :      281448 :         int         offset = fctx->nextelem++;
    6343                 :             :         Datum       elem;
    6344                 :             : 
    6345                 :      281448 :         elem = array_iter_next(&fctx->iter, &fcinfo->isnull, offset);
    6346                 :             : 
    6347                 :      281448 :         SRF_RETURN_NEXT(funcctx, elem);
    6348                 :             :     }
    6349                 :             :     else
    6350                 :             :     {
    6351                 :             :         /* do when there is no more left */
    6352                 :       57937 :         SRF_RETURN_DONE(funcctx);
    6353                 :             :     }
    6354                 :             : }
    6355                 :             : 
    6356                 :             : /*
    6357                 :             :  * Planner support function for array_unnest(anyarray)
    6358                 :             :  *
    6359                 :             :  * Note: this is now also used for information_schema._pg_expandarray(),
    6360                 :             :  * which is simply a wrapper around array_unnest().
    6361                 :             :  */
    6362                 :             : Datum
    6363                 :       17383 : array_unnest_support(PG_FUNCTION_ARGS)
    6364                 :             : {
    6365                 :       17383 :     Node       *rawreq = (Node *) PG_GETARG_POINTER(0);
    6366                 :       17383 :     Node       *ret = NULL;
    6367                 :             : 
    6368         [ +  + ]:       17383 :     if (IsA(rawreq, SupportRequestRows))
    6369                 :             :     {
    6370                 :             :         /* Try to estimate the number of rows returned */
    6371                 :        4790 :         SupportRequestRows *req = (SupportRequestRows *) rawreq;
    6372                 :             : 
    6373         [ +  + ]:        4790 :         if (is_funcclause(req->node))    /* be paranoid */
    6374                 :             :         {
    6375                 :        4785 :             List       *args = ((FuncExpr *) req->node)->args;
    6376                 :             :             Node       *arg1;
    6377                 :             : 
    6378                 :             :             /* We can use estimated argument values here */
    6379                 :        4785 :             arg1 = estimate_expression_value(req->root, linitial(args));
    6380                 :             : 
    6381                 :        4785 :             req->rows = estimate_array_length(req->root, arg1);
    6382                 :        4785 :             ret = (Node *) req;
    6383                 :             :         }
    6384                 :             :     }
    6385                 :             : 
    6386                 :       17383 :     PG_RETURN_POINTER(ret);
    6387                 :             : }
    6388                 :             : 
    6389                 :             : 
    6390                 :             : /*
    6391                 :             :  * array_replace/array_remove support
    6392                 :             :  *
    6393                 :             :  * Find all array entries matching (not distinct from) search/search_isnull,
    6394                 :             :  * and delete them if remove is true, else replace them with
    6395                 :             :  * replace/replace_isnull.  Comparisons are done using the specified
    6396                 :             :  * collation.  fcinfo is passed only for caching purposes.
    6397                 :             :  */
    6398                 :             : static ArrayType *
    6399                 :        1812 : array_replace_internal(ArrayType *array,
    6400                 :             :                        Datum search, bool search_isnull,
    6401                 :             :                        Datum replace, bool replace_isnull,
    6402                 :             :                        bool remove, Oid collation,
    6403                 :             :                        FunctionCallInfo fcinfo)
    6404                 :             : {
    6405                 :        1812 :     LOCAL_FCINFO(locfcinfo, 2);
    6406                 :             :     ArrayType  *result;
    6407                 :             :     Oid         element_type;
    6408                 :             :     Datum      *values;
    6409                 :             :     bool       *nulls;
    6410                 :             :     int        *dim;
    6411                 :             :     int         ndim;
    6412                 :             :     int         nitems,
    6413                 :             :                 nresult;
    6414                 :             :     int         i;
    6415                 :        1812 :     int32       nbytes = 0;
    6416                 :             :     int32       dataoffset;
    6417                 :             :     bool        hasnulls;
    6418                 :             :     int         typlen;
    6419                 :             :     bool        typbyval;
    6420                 :             :     char        typalign;
    6421                 :             :     uint8       typalignby;
    6422                 :             :     char       *arraydataptr;
    6423                 :             :     uint8      *bitmap;
    6424                 :             :     int         bitmask;
    6425                 :        1812 :     bool        changed = false;
    6426                 :             :     TypeCacheEntry *typentry;
    6427                 :             : 
    6428                 :        1812 :     element_type = ARR_ELEMTYPE(array);
    6429                 :        1812 :     ndim = ARR_NDIM(array);
    6430                 :        1812 :     dim = ARR_DIMS(array);
    6431                 :        1812 :     nitems = ArrayGetNItems(ndim, dim);
    6432                 :             : 
    6433                 :             :     /* Return input array unmodified if it is empty */
    6434         [ -  + ]:        1812 :     if (nitems <= 0)
    6435                 :           0 :         return array;
    6436                 :             : 
    6437                 :             :     /*
    6438                 :             :      * We can't remove elements from multi-dimensional arrays, since the
    6439                 :             :      * result might not be rectangular.
    6440                 :             :      */
    6441   [ +  +  +  + ]:        1812 :     if (remove && ndim > 1)
    6442         [ +  - ]:           4 :         ereport(ERROR,
    6443                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    6444                 :             :                  errmsg("removing elements from multidimensional arrays is not supported")));
    6445                 :             : 
    6446                 :             :     /*
    6447                 :             :      * We arrange to look up the equality function only once per series of
    6448                 :             :      * calls, assuming the element type doesn't change underneath us.
    6449                 :             :      */
    6450                 :        1808 :     typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
    6451         [ +  + ]:        1808 :     if (typentry == NULL ||
    6452         [ -  + ]:        1362 :         typentry->type_id != element_type)
    6453                 :             :     {
    6454                 :         446 :         typentry = lookup_type_cache(element_type,
    6455                 :             :                                      TYPECACHE_EQ_OPR_FINFO);
    6456         [ -  + ]:         446 :         if (!OidIsValid(typentry->eq_opr_finfo.fn_oid))
    6457         [ #  # ]:           0 :             ereport(ERROR,
    6458                 :             :                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
    6459                 :             :                      errmsg("could not identify an equality operator for type %s",
    6460                 :             :                             format_type_be(element_type))));
    6461                 :         446 :         fcinfo->flinfo->fn_extra = typentry;
    6462                 :             :     }
    6463                 :        1808 :     typlen = typentry->typlen;
    6464                 :        1808 :     typbyval = typentry->typbyval;
    6465                 :        1808 :     typalign = typentry->typalign;
    6466                 :        1808 :     typalignby = typalign_to_alignby(typalign);
    6467                 :             : 
    6468                 :             :     /*
    6469                 :             :      * Detoast values if they are toasted.  The replacement value must be
    6470                 :             :      * detoasted for insertion into the result array, while detoasting the
    6471                 :             :      * search value only once saves cycles.
    6472                 :             :      */
    6473         [ +  + ]:        1808 :     if (typlen == -1)
    6474                 :             :     {
    6475         [ +  + ]:        1773 :         if (!search_isnull)
    6476                 :        1768 :             search = PointerGetDatum(PG_DETOAST_DATUM(search));
    6477         [ +  + ]:        1773 :         if (!replace_isnull)
    6478                 :          10 :             replace = PointerGetDatum(PG_DETOAST_DATUM(replace));
    6479                 :             :     }
    6480                 :             : 
    6481                 :             :     /* Prepare to apply the comparison operator */
    6482                 :        1808 :     InitFunctionCallInfoData(*locfcinfo, &typentry->eq_opr_finfo, 2,
    6483                 :             :                              collation, NULL, NULL);
    6484                 :             : 
    6485                 :             :     /* Allocate temporary arrays for new values */
    6486                 :        1808 :     values = palloc_array(Datum, nitems);
    6487                 :        1808 :     nulls = palloc_array(bool, nitems);
    6488                 :             : 
    6489                 :             :     /* Loop over source data */
    6490         [ +  + ]:        1808 :     arraydataptr = ARR_DATA_PTR(array);
    6491         [ +  + ]:        1808 :     bitmap = ARR_NULLBITMAP(array);
    6492                 :        1808 :     bitmask = 1;
    6493                 :        1808 :     hasnulls = false;
    6494                 :        1808 :     nresult = 0;
    6495                 :             : 
    6496         [ +  + ]:        4003 :     for (i = 0; i < nitems; i++)
    6497                 :             :     {
    6498                 :             :         Datum       elt;
    6499                 :             :         bool        isNull;
    6500                 :             :         bool        oprresult;
    6501                 :        2195 :         bool        skip = false;
    6502                 :             : 
    6503                 :             :         /* Get source element, checking for NULL */
    6504   [ +  +  +  + ]:        2195 :         if (bitmap && (*bitmap & bitmask) == 0)
    6505                 :             :         {
    6506                 :          30 :             isNull = true;
    6507                 :             :             /* If searching for NULL, we have a match */
    6508         [ +  - ]:          30 :             if (search_isnull)
    6509                 :             :             {
    6510         [ +  + ]:          30 :                 if (remove)
    6511                 :             :                 {
    6512                 :          10 :                     skip = true;
    6513                 :          10 :                     changed = true;
    6514                 :             :                 }
    6515         [ +  + ]:          20 :                 else if (!replace_isnull)
    6516                 :             :                 {
    6517                 :          15 :                     values[nresult] = replace;
    6518                 :          15 :                     isNull = false;
    6519                 :          15 :                     changed = true;
    6520                 :             :                 }
    6521                 :             :             }
    6522                 :             :         }
    6523                 :             :         else
    6524                 :             :         {
    6525                 :        2165 :             isNull = false;
    6526                 :        2165 :             elt = fetch_att(arraydataptr, typbyval, typlen);
    6527   [ +  +  +  - ]:        2165 :             arraydataptr = att_addlength_datum(arraydataptr, typlen, elt);
    6528                 :        2165 :             arraydataptr = (char *) att_nominal_alignby(arraydataptr, typalignby);
    6529                 :             : 
    6530         [ +  + ]:        2165 :             if (search_isnull)
    6531                 :             :             {
    6532                 :             :                 /* no match possible, keep element */
    6533                 :          45 :                 values[nresult] = elt;
    6534                 :             :             }
    6535                 :             :             else
    6536                 :             :             {
    6537                 :             :                 /*
    6538                 :             :                  * Apply the operator to the element pair; treat NULL as false
    6539                 :             :                  */
    6540                 :        2120 :                 locfcinfo->args[0].value = elt;
    6541                 :        2120 :                 locfcinfo->args[0].isnull = false;
    6542                 :        2120 :                 locfcinfo->args[1].value = search;
    6543                 :        2120 :                 locfcinfo->args[1].isnull = false;
    6544                 :        2120 :                 locfcinfo->isnull = false;
    6545                 :        2120 :                 oprresult = DatumGetBool(FunctionCallInvoke(locfcinfo));
    6546   [ +  -  +  + ]:        2120 :                 if (locfcinfo->isnull || !oprresult)
    6547                 :             :                 {
    6548                 :             :                     /* no match, keep element */
    6549                 :        2016 :                     values[nresult] = elt;
    6550                 :             :                 }
    6551                 :             :                 else
    6552                 :             :                 {
    6553                 :             :                     /* match, so replace or delete */
    6554                 :         104 :                     changed = true;
    6555         [ +  + ]:         104 :                     if (remove)
    6556                 :          84 :                         skip = true;
    6557                 :             :                     else
    6558                 :             :                     {
    6559                 :          20 :                         values[nresult] = replace;
    6560                 :          20 :                         isNull = replace_isnull;
    6561                 :             :                     }
    6562                 :             :                 }
    6563                 :             :             }
    6564                 :             :         }
    6565                 :             : 
    6566         [ +  + ]:        2195 :         if (!skip)
    6567                 :             :         {
    6568                 :        2101 :             nulls[nresult] = isNull;
    6569         [ +  + ]:        2101 :             if (isNull)
    6570                 :          10 :                 hasnulls = true;
    6571                 :             :             else
    6572                 :             :             {
    6573                 :             :                 /* Update total result size */
    6574   [ +  +  +  - ]:        2091 :                 nbytes = att_addlength_datum(nbytes, typlen, values[nresult]);
    6575                 :        2091 :                 nbytes = att_nominal_alignby(nbytes, typalignby);
    6576                 :             :                 /* check for overflow of total request */
    6577         [ -  + ]:        2091 :                 if (!AllocSizeIsValid(nbytes))
    6578         [ #  # ]:           0 :                     ereport(ERROR,
    6579                 :             :                             (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    6580                 :             :                              errmsg("array size exceeds the maximum allowed (%zu)",
    6581                 :             :                                     MaxAllocSize)));
    6582                 :             :             }
    6583                 :        2101 :             nresult++;
    6584                 :             :         }
    6585                 :             : 
    6586                 :             :         /* advance bitmap pointer if any */
    6587         [ +  + ]:        2195 :         if (bitmap)
    6588                 :             :         {
    6589                 :          75 :             bitmask <<= 1;
    6590         [ -  + ]:          75 :             if (bitmask == 0x100)
    6591                 :             :             {
    6592                 :           0 :                 bitmap++;
    6593                 :           0 :                 bitmask = 1;
    6594                 :             :             }
    6595                 :             :         }
    6596                 :             :     }
    6597                 :             : 
    6598                 :             :     /*
    6599                 :             :      * If not changed just return the original array
    6600                 :             :      */
    6601         [ +  + ]:        1808 :     if (!changed)
    6602                 :             :     {
    6603                 :        1709 :         pfree(values);
    6604                 :        1709 :         pfree(nulls);
    6605                 :        1709 :         return array;
    6606                 :             :     }
    6607                 :             : 
    6608                 :             :     /* If all elements were removed return an empty array */
    6609         [ +  + ]:          99 :     if (nresult == 0)
    6610                 :             :     {
    6611                 :           5 :         pfree(values);
    6612                 :           5 :         pfree(nulls);
    6613                 :           5 :         return construct_empty_array(element_type);
    6614                 :             :     }
    6615                 :             : 
    6616                 :             :     /* Allocate and initialize the result array */
    6617         [ +  + ]:          94 :     if (hasnulls)
    6618                 :             :     {
    6619                 :           5 :         dataoffset = ARR_OVERHEAD_WITHNULLS(ndim, nresult);
    6620                 :           5 :         nbytes += dataoffset;
    6621                 :             :     }
    6622                 :             :     else
    6623                 :             :     {
    6624                 :          89 :         dataoffset = 0;         /* marker for no null bitmap */
    6625                 :          89 :         nbytes += ARR_OVERHEAD_NONULLS(ndim);
    6626                 :             :     }
    6627                 :          94 :     result = (ArrayType *) palloc0(nbytes);
    6628                 :          94 :     SET_VARSIZE(result, nbytes);
    6629                 :          94 :     result->ndim = ndim;
    6630                 :          94 :     result->dataoffset = dataoffset;
    6631                 :          94 :     result->elemtype = element_type;
    6632                 :          94 :     memcpy(ARR_DIMS(result), ARR_DIMS(array), ndim * sizeof(int));
    6633                 :          94 :     memcpy(ARR_LBOUND(result), ARR_LBOUND(array), ndim * sizeof(int));
    6634                 :             : 
    6635         [ +  + ]:          94 :     if (remove)
    6636                 :             :     {
    6637                 :             :         /* Adjust the result length */
    6638                 :          69 :         ARR_DIMS(result)[0] = nresult;
    6639                 :             :     }
    6640                 :             : 
    6641                 :             :     /* Insert data into result array */
    6642                 :          94 :     CopyArrayEls(result,
    6643                 :             :                  values, nulls, nresult,
    6644                 :             :                  typlen, typbyval, typalign,
    6645                 :             :                  false);
    6646                 :             : 
    6647                 :          94 :     pfree(values);
    6648                 :          94 :     pfree(nulls);
    6649                 :             : 
    6650                 :          94 :     return result;
    6651                 :             : }
    6652                 :             : 
    6653                 :             : /*
    6654                 :             :  * Remove any occurrences of an element from an array
    6655                 :             :  *
    6656                 :             :  * If used on a multi-dimensional array this will raise an error.
    6657                 :             :  */
    6658                 :             : Datum
    6659                 :      111330 : array_remove(PG_FUNCTION_ARGS)
    6660                 :             : {
    6661                 :             :     ArrayType  *array;
    6662                 :      111330 :     Datum       search = PG_GETARG_DATUM(1);
    6663                 :      111330 :     bool        search_isnull = PG_ARGISNULL(1);
    6664                 :             : 
    6665         [ +  + ]:      111330 :     if (PG_ARGISNULL(0))
    6666                 :      109548 :         PG_RETURN_NULL();
    6667                 :        1782 :     array = PG_GETARG_ARRAYTYPE_P(0);
    6668                 :             : 
    6669                 :        1782 :     array = array_replace_internal(array,
    6670                 :             :                                    search, search_isnull,
    6671                 :             :                                    (Datum) 0, true,
    6672                 :             :                                    true, PG_GET_COLLATION(),
    6673                 :             :                                    fcinfo);
    6674                 :        1778 :     PG_RETURN_ARRAYTYPE_P(array);
    6675                 :             : }
    6676                 :             : 
    6677                 :             : /*
    6678                 :             :  * Replace any occurrences of an element in an array
    6679                 :             :  */
    6680                 :             : Datum
    6681                 :          30 : array_replace(PG_FUNCTION_ARGS)
    6682                 :             : {
    6683                 :             :     ArrayType  *array;
    6684                 :          30 :     Datum       search = PG_GETARG_DATUM(1);
    6685                 :          30 :     bool        search_isnull = PG_ARGISNULL(1);
    6686                 :          30 :     Datum       replace = PG_GETARG_DATUM(2);
    6687                 :          30 :     bool        replace_isnull = PG_ARGISNULL(2);
    6688                 :             : 
    6689         [ -  + ]:          30 :     if (PG_ARGISNULL(0))
    6690                 :           0 :         PG_RETURN_NULL();
    6691                 :          30 :     array = PG_GETARG_ARRAYTYPE_P(0);
    6692                 :             : 
    6693                 :          30 :     array = array_replace_internal(array,
    6694                 :             :                                    search, search_isnull,
    6695                 :             :                                    replace, replace_isnull,
    6696                 :             :                                    false, PG_GET_COLLATION(),
    6697                 :             :                                    fcinfo);
    6698                 :          30 :     PG_RETURN_ARRAYTYPE_P(array);
    6699                 :             : }
    6700                 :             : 
    6701                 :             : /*
    6702                 :             :  * Implements width_bucket(anyelement, anyarray).
    6703                 :             :  *
    6704                 :             :  * 'thresholds' is an array containing lower bound values for each bucket;
    6705                 :             :  * these must be sorted from smallest to largest, or bogus results will be
    6706                 :             :  * produced.  If N thresholds are supplied, the output is from 0 to N:
    6707                 :             :  * 0 is for inputs < first threshold, N is for inputs >= last threshold.
    6708                 :             :  */
    6709                 :             : Datum
    6710                 :         542 : width_bucket_array(PG_FUNCTION_ARGS)
    6711                 :             : {
    6712                 :         542 :     Datum       operand = PG_GETARG_DATUM(0);
    6713                 :         542 :     ArrayType  *thresholds = PG_GETARG_ARRAYTYPE_P(1);
    6714                 :         542 :     Oid         collation = PG_GET_COLLATION();
    6715                 :         542 :     Oid         element_type = ARR_ELEMTYPE(thresholds);
    6716                 :             :     int         result;
    6717                 :             : 
    6718                 :             :     /* Check input */
    6719         [ +  + ]:         542 :     if (ARR_NDIM(thresholds) > 1)
    6720         [ +  - ]:           4 :         ereport(ERROR,
    6721                 :             :                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    6722                 :             :                  errmsg("thresholds must be one-dimensional array")));
    6723                 :             : 
    6724         [ +  + ]:         538 :     if (array_contains_nulls(thresholds))
    6725         [ +  - ]:           4 :         ereport(ERROR,
    6726                 :             :                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    6727                 :             :                  errmsg("thresholds array must not contain NULLs")));
    6728                 :             : 
    6729                 :             :     /* We have a dedicated implementation for float8 data */
    6730         [ +  + ]:         534 :     if (element_type == FLOAT8OID)
    6731                 :         244 :         result = width_bucket_array_float8(operand, thresholds);
    6732                 :             :     else
    6733                 :             :     {
    6734                 :             :         TypeCacheEntry *typentry;
    6735                 :             : 
    6736                 :             :         /* Cache information about the input type */
    6737                 :         290 :         typentry = (TypeCacheEntry *) fcinfo->flinfo->fn_extra;
    6738         [ +  + ]:         290 :         if (typentry == NULL ||
    6739         [ -  + ]:         260 :             typentry->type_id != element_type)
    6740                 :             :         {
    6741                 :          30 :             typentry = lookup_type_cache(element_type,
    6742                 :             :                                          TYPECACHE_CMP_PROC_FINFO);
    6743         [ -  + ]:          30 :             if (!OidIsValid(typentry->cmp_proc_finfo.fn_oid))
    6744         [ #  # ]:           0 :                 ereport(ERROR,
    6745                 :             :                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
    6746                 :             :                          errmsg("could not identify a comparison function for type %s",
    6747                 :             :                                 format_type_be(element_type))));
    6748                 :          30 :             fcinfo->flinfo->fn_extra = typentry;
    6749                 :             :         }
    6750                 :             : 
    6751                 :             :         /*
    6752                 :             :          * We have separate implementation paths for fixed- and variable-width
    6753                 :             :          * types, since indexing the array is a lot cheaper in the first case.
    6754                 :             :          */
    6755         [ +  + ]:         290 :         if (typentry->typlen > 0)
    6756                 :          62 :             result = width_bucket_array_fixed(operand, thresholds,
    6757                 :             :                                               collation, typentry);
    6758                 :             :         else
    6759                 :         228 :             result = width_bucket_array_variable(operand, thresholds,
    6760                 :             :                                                  collation, typentry);
    6761                 :             :     }
    6762                 :             : 
    6763                 :             :     /* Avoid leaking memory when handed toasted input. */
    6764         [ -  + ]:         534 :     PG_FREE_IF_COPY(thresholds, 1);
    6765                 :             : 
    6766                 :         534 :     PG_RETURN_INT32(result);
    6767                 :             : }
    6768                 :             : 
    6769                 :             : /*
    6770                 :             :  * width_bucket_array for float8 data.
    6771                 :             :  */
    6772                 :             : static int
    6773                 :         244 : width_bucket_array_float8(Datum operand, ArrayType *thresholds)
    6774                 :             : {
    6775                 :         244 :     float8      op = DatumGetFloat8(operand);
    6776                 :             :     float8     *thresholds_data;
    6777                 :             :     int         left;
    6778                 :             :     int         right;
    6779                 :             : 
    6780                 :             :     /*
    6781                 :             :      * Since we know the array contains no NULLs, we can just index it
    6782                 :             :      * directly.
    6783                 :             :      */
    6784         [ -  + ]:         244 :     thresholds_data = (float8 *) ARR_DATA_PTR(thresholds);
    6785                 :             : 
    6786                 :         244 :     left = 0;
    6787                 :         244 :     right = ArrayGetNItems(ARR_NDIM(thresholds), ARR_DIMS(thresholds));
    6788                 :             : 
    6789                 :             :     /*
    6790                 :             :      * If the probe value is a NaN, it's greater than or equal to all possible
    6791                 :             :      * threshold values (including other NaNs), so we need not search.  Note
    6792                 :             :      * that this would give the same result as searching even if the array
    6793                 :             :      * contains multiple NaNs (as long as they're correctly sorted), since the
    6794                 :             :      * loop logic will find the rightmost of multiple equal threshold values.
    6795                 :             :      */
    6796         [ +  + ]:         244 :     if (isnan(op))
    6797                 :           4 :         return right;
    6798                 :             : 
    6799                 :             :     /* Find the bucket */
    6800         [ +  + ]:         756 :     while (left < right)
    6801                 :             :     {
    6802                 :         516 :         int         mid = (left + right) / 2;
    6803                 :             : 
    6804   [ +  +  +  + ]:         516 :         if (isnan(thresholds_data[mid]) || op < thresholds_data[mid])
    6805                 :         224 :             right = mid;
    6806                 :             :         else
    6807                 :         292 :             left = mid + 1;
    6808                 :             :     }
    6809                 :             : 
    6810                 :         240 :     return left;
    6811                 :             : }
    6812                 :             : 
    6813                 :             : /*
    6814                 :             :  * width_bucket_array for generic fixed-width data types.
    6815                 :             :  */
    6816                 :             : static int
    6817                 :          62 : width_bucket_array_fixed(Datum operand,
    6818                 :             :                          ArrayType *thresholds,
    6819                 :             :                          Oid collation,
    6820                 :             :                          TypeCacheEntry *typentry)
    6821                 :             : {
    6822                 :          62 :     LOCAL_FCINFO(locfcinfo, 2);
    6823                 :             :     char       *thresholds_data;
    6824                 :          62 :     int         typlen = typentry->typlen;
    6825                 :          62 :     bool        typbyval = typentry->typbyval;
    6826                 :             :     int         left;
    6827                 :             :     int         right;
    6828                 :             : 
    6829                 :             :     /*
    6830                 :             :      * Since we know the array contains no NULLs, we can just index it
    6831                 :             :      * directly.
    6832                 :             :      */
    6833         [ -  + ]:          62 :     thresholds_data = (char *) ARR_DATA_PTR(thresholds);
    6834                 :             : 
    6835                 :          62 :     InitFunctionCallInfoData(*locfcinfo, &typentry->cmp_proc_finfo, 2,
    6836                 :             :                              collation, NULL, NULL);
    6837                 :             : 
    6838                 :             :     /* Find the bucket */
    6839                 :          62 :     left = 0;
    6840                 :          62 :     right = ArrayGetNItems(ARR_NDIM(thresholds), ARR_DIMS(thresholds));
    6841         [ +  + ]:         183 :     while (left < right)
    6842                 :             :     {
    6843                 :         121 :         int         mid = (left + right) / 2;
    6844                 :             :         char       *ptr;
    6845                 :             :         int32       cmpresult;
    6846                 :             : 
    6847                 :         121 :         ptr = thresholds_data + mid * typlen;
    6848                 :             : 
    6849                 :         121 :         locfcinfo->args[0].value = operand;
    6850                 :         121 :         locfcinfo->args[0].isnull = false;
    6851                 :         121 :         locfcinfo->args[1].value = fetch_att(ptr, typbyval, typlen);
    6852                 :         121 :         locfcinfo->args[1].isnull = false;
    6853                 :             : 
    6854                 :         121 :         cmpresult = DatumGetInt32(FunctionCallInvoke(locfcinfo));
    6855                 :             : 
    6856                 :             :         /* We don't expect comparison support functions to return null */
    6857                 :             :         Assert(!locfcinfo->isnull);
    6858                 :             : 
    6859         [ +  + ]:         121 :         if (cmpresult < 0)
    6860                 :          60 :             right = mid;
    6861                 :             :         else
    6862                 :          61 :             left = mid + 1;
    6863                 :             :     }
    6864                 :             : 
    6865                 :          62 :     return left;
    6866                 :             : }
    6867                 :             : 
    6868                 :             : /*
    6869                 :             :  * width_bucket_array for generic variable-width data types.
    6870                 :             :  */
    6871                 :             : static int
    6872                 :         228 : width_bucket_array_variable(Datum operand,
    6873                 :             :                             ArrayType *thresholds,
    6874                 :             :                             Oid collation,
    6875                 :             :                             TypeCacheEntry *typentry)
    6876                 :             : {
    6877                 :         228 :     LOCAL_FCINFO(locfcinfo, 2);
    6878                 :             :     char       *thresholds_data;
    6879                 :         228 :     int         typlen = typentry->typlen;
    6880                 :         228 :     bool        typbyval = typentry->typbyval;
    6881                 :         228 :     char        typalign = typentry->typalign;
    6882                 :         228 :     uint8       typalignby = typalign_to_alignby(typalign);
    6883                 :             :     int         left;
    6884                 :             :     int         right;
    6885                 :             : 
    6886         [ -  + ]:         228 :     thresholds_data = (char *) ARR_DATA_PTR(thresholds);
    6887                 :             : 
    6888                 :         228 :     InitFunctionCallInfoData(*locfcinfo, &typentry->cmp_proc_finfo, 2,
    6889                 :             :                              collation, NULL, NULL);
    6890                 :             : 
    6891                 :             :     /* Find the bucket */
    6892                 :         228 :     left = 0;
    6893                 :         228 :     right = ArrayGetNItems(ARR_NDIM(thresholds), ARR_DIMS(thresholds));
    6894         [ +  + ]:         712 :     while (left < right)
    6895                 :             :     {
    6896                 :         484 :         int         mid = (left + right) / 2;
    6897                 :             :         char       *ptr;
    6898                 :             :         int         i;
    6899                 :             :         int32       cmpresult;
    6900                 :             : 
    6901                 :             :         /* Locate mid'th array element by advancing from left element */
    6902                 :         484 :         ptr = thresholds_data;
    6903         [ +  + ]:         828 :         for (i = left; i < mid; i++)
    6904                 :             :         {
    6905   [ -  +  +  - ]:         344 :             ptr = att_addlength_pointer(ptr, typlen, ptr);
    6906                 :         344 :             ptr = (char *) att_nominal_alignby(ptr, typalignby);
    6907                 :             :         }
    6908                 :             : 
    6909                 :         484 :         locfcinfo->args[0].value = operand;
    6910                 :         484 :         locfcinfo->args[0].isnull = false;
    6911                 :         484 :         locfcinfo->args[1].value = fetch_att(ptr, typbyval, typlen);
    6912                 :         484 :         locfcinfo->args[1].isnull = false;
    6913                 :             : 
    6914                 :         484 :         cmpresult = DatumGetInt32(FunctionCallInvoke(locfcinfo));
    6915                 :             : 
    6916                 :             :         /* We don't expect comparison support functions to return null */
    6917                 :             :         Assert(!locfcinfo->isnull);
    6918                 :             : 
    6919         [ +  + ]:         484 :         if (cmpresult < 0)
    6920                 :         200 :             right = mid;
    6921                 :             :         else
    6922                 :             :         {
    6923                 :         284 :             left = mid + 1;
    6924                 :             : 
    6925                 :             :             /*
    6926                 :             :              * Move the thresholds pointer to match new "left" index, so we
    6927                 :             :              * don't have to seek over those elements again.  This trick
    6928                 :             :              * ensures we do only O(N) array indexing work, not O(N^2).
    6929                 :             :              */
    6930   [ -  +  +  - ]:         284 :             ptr = att_addlength_pointer(ptr, typlen, ptr);
    6931                 :         284 :             thresholds_data = (char *) att_nominal_alignby(ptr, typalignby);
    6932                 :             :         }
    6933                 :             :     }
    6934                 :             : 
    6935                 :         228 :     return left;
    6936                 :             : }
    6937                 :             : 
    6938                 :             : /*
    6939                 :             :  * Trim the last N elements from an array by building an appropriate slice.
    6940                 :             :  * Only the first dimension is trimmed.
    6941                 :             :  */
    6942                 :             : Datum
    6943                 :          32 : trim_array(PG_FUNCTION_ARGS)
    6944                 :             : {
    6945                 :          32 :     ArrayType  *v = PG_GETARG_ARRAYTYPE_P(0);
    6946                 :          32 :     int         n = PG_GETARG_INT32(1);
    6947         [ +  + ]:          32 :     int         array_length = (ARR_NDIM(v) > 0) ? ARR_DIMS(v)[0] : 0;
    6948                 :             :     int16       elmlen;
    6949                 :             :     bool        elmbyval;
    6950                 :             :     char        elmalign;
    6951                 :             :     int         lower[MAXDIM];
    6952                 :             :     int         upper[MAXDIM];
    6953                 :             :     bool        lowerProvided[MAXDIM];
    6954                 :             :     bool        upperProvided[MAXDIM];
    6955                 :             :     Datum       result;
    6956                 :             : 
    6957                 :             :     /* Per spec, throw an error if out of bounds */
    6958   [ +  +  +  + ]:          32 :     if (n < 0 || n > array_length)
    6959         [ +  - ]:          12 :         ereport(ERROR,
    6960                 :             :                 (errcode(ERRCODE_ARRAY_ELEMENT_ERROR),
    6961                 :             :                  errmsg("number of elements to trim must be between 0 and %d",
    6962                 :             :                         array_length)));
    6963                 :             : 
    6964                 :             :     /* Set all the bounds as unprovided except the first upper bound */
    6965                 :          20 :     memset(lowerProvided, false, sizeof(lowerProvided));
    6966                 :          20 :     memset(upperProvided, false, sizeof(upperProvided));
    6967         [ +  - ]:          20 :     if (ARR_NDIM(v) > 0)
    6968                 :             :     {
    6969                 :          20 :         upper[0] = ARR_LBOUND(v)[0] + array_length - n - 1;
    6970                 :          20 :         upperProvided[0] = true;
    6971                 :             :     }
    6972                 :             : 
    6973                 :             :     /* Fetch the needed information about the element type */
    6974                 :          20 :     get_typlenbyvalalign(ARR_ELEMTYPE(v), &elmlen, &elmbyval, &elmalign);
    6975                 :             : 
    6976                 :             :     /* Get the slice */
    6977                 :          20 :     result = array_get_slice(PointerGetDatum(v), 1,
    6978                 :             :                              upper, lower, upperProvided, lowerProvided,
    6979                 :             :                              -1, elmlen, elmbyval, elmalign);
    6980                 :             : 
    6981                 :          20 :     PG_RETURN_DATUM(result);
    6982                 :             : }
        

Generated by: LCOV version 2.0-1