LCOV - code coverage report
Current view: top level - src/backend/utils/adt - varlena.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 91.3 % 1932 1763
Test Date: 2026-12-03 09:16:00 Functions: 92.6 % 148 137
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 74.5 % 1163 867

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * varlena.c
       4                 :             :  *    Functions for the variable-length built-in types.
       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/varlena.c
      12                 :             :  *
      13                 :             :  *-------------------------------------------------------------------------
      14                 :             :  */
      15                 :             : #include "postgres.h"
      16                 :             : 
      17                 :             : #include <ctype.h>
      18                 :             : #include <limits.h>
      19                 :             : 
      20                 :             : #include "access/detoast.h"
      21                 :             : #include "access/toast_compression.h"
      22                 :             : #include "access/tupmacs.h"
      23                 :             : #include "catalog/pg_collation.h"
      24                 :             : #include "catalog/pg_type.h"
      25                 :             : #include "common/hashfn.h"
      26                 :             : #include "common/int.h"
      27                 :             : #include "common/unicode_category.h"
      28                 :             : #include "common/unicode_norm.h"
      29                 :             : #include "common/unicode_version.h"
      30                 :             : #include "funcapi.h"
      31                 :             : #include "lib/hyperloglog.h"
      32                 :             : #include "libpq/pqformat.h"
      33                 :             : #include "miscadmin.h"
      34                 :             : #include "nodes/execnodes.h"
      35                 :             : #include "parser/scansup.h"
      36                 :             : #include "port/pg_bswap.h"
      37                 :             : #include "regex/regex.h"
      38                 :             : #include "utils/ascii.h"
      39                 :             : #include "utils/builtins.h"
      40                 :             : #include "utils/guc.h"
      41                 :             : #include "utils/lsyscache.h"
      42                 :             : #include "utils/memutils.h"
      43                 :             : #include "utils/pg_locale.h"
      44                 :             : #include "utils/sortsupport.h"
      45                 :             : #include "utils/tuplestore.h"
      46                 :             : #include "utils/varlena.h"
      47                 :             : 
      48                 :             : typedef varlena VarString;
      49                 :             : 
      50                 :             : /*
      51                 :             :  * State for text_position_* functions.
      52                 :             :  */
      53                 :             : typedef struct
      54                 :             : {
      55                 :             :     pg_locale_t locale;         /* collation used for substring matching */
      56                 :             :     bool        is_multibyte_char_in_char;  /* need to check char boundaries? */
      57                 :             :     bool        greedy;         /* find longest possible substring? */
      58                 :             : 
      59                 :             :     char       *str1;           /* haystack string */
      60                 :             :     char       *str2;           /* needle string */
      61                 :             :     int         len1;           /* string lengths in bytes */
      62                 :             :     int         len2;
      63                 :             : 
      64                 :             :     /* Skip table for Boyer-Moore-Horspool search algorithm: */
      65                 :             :     int         skiptablemask;  /* mask for ANDing with skiptable subscripts */
      66                 :             :     int         skiptable[256]; /* skip distance for given mismatched char */
      67                 :             : 
      68                 :             :     /*
      69                 :             :      * Note that with nondeterministic collations, the length of the last
      70                 :             :      * match is not necessarily equal to the length of the "needle" passed in.
      71                 :             :      */
      72                 :             :     char       *last_match;     /* pointer to last match in 'str1' */
      73                 :             :     int         last_match_len; /* length of last match */
      74                 :             :     int         last_match_len_tmp; /* same but for internal use */
      75                 :             : 
      76                 :             :     /*
      77                 :             :      * Sometimes we need to convert the byte position of a match to a
      78                 :             :      * character position.  These store the last position that was converted,
      79                 :             :      * so that on the next call, we can continue from that point, rather than
      80                 :             :      * count characters from the very beginning.
      81                 :             :      */
      82                 :             :     char       *refpoint;       /* pointer within original haystack string */
      83                 :             :     int         refpos;         /* 0-based character offset of the same point */
      84                 :             : } TextPositionState;
      85                 :             : 
      86                 :             : typedef struct
      87                 :             : {
      88                 :             :     char       *buf1;           /* 1st string, or abbreviation original string
      89                 :             :                                  * buf */
      90                 :             :     char       *buf2;           /* 2nd string, or abbreviation strxfrm() buf */
      91                 :             :     int         buflen1;        /* Allocated length of buf1 */
      92                 :             :     int         buflen2;        /* Allocated length of buf2 */
      93                 :             :     int         last_len1;      /* Length of last buf1 string/strxfrm() input */
      94                 :             :     int         last_len2;      /* Length of last buf2 string/strxfrm() blob */
      95                 :             :     int         last_returned;  /* Last comparison result (cache) */
      96                 :             :     bool        cache_blob;     /* Does buf2 contain strxfrm() blob, etc? */
      97                 :             :     bool        collate_c;
      98                 :             :     Oid         typid;          /* Actual datatype (text/bpchar/name) */
      99                 :             :     hyperLogLogState abbr_card; /* Abbreviated key cardinality state */
     100                 :             :     hyperLogLogState full_card; /* Full key cardinality state */
     101                 :             :     double      prop_card;      /* Required cardinality proportion */
     102                 :             :     pg_locale_t locale;
     103                 :             : } VarStringSortSupport;
     104                 :             : 
     105                 :             : /*
     106                 :             :  * Output data for split_text(): we output either to an array or a table.
     107                 :             :  * tupstore and tupdesc must be set up in advance to output to a table.
     108                 :             :  */
     109                 :             : typedef struct
     110                 :             : {
     111                 :             :     ArrayBuildState *astate;
     112                 :             :     Tuplestorestate *tupstore;
     113                 :             :     TupleDesc   tupdesc;
     114                 :             : } SplitTextOutputData;
     115                 :             : 
     116                 :             : /*
     117                 :             :  * This should be large enough that most strings will fit, but small enough
     118                 :             :  * that we feel comfortable putting it on the stack
     119                 :             :  */
     120                 :             : #define TEXTBUFLEN      1024
     121                 :             : 
     122                 :             : #define DatumGetVarStringP(X)       ((VarString *) PG_DETOAST_DATUM(X))
     123                 :             : #define DatumGetVarStringPP(X)      ((VarString *) PG_DETOAST_DATUM_PACKED(X))
     124                 :             : 
     125                 :             : static int  varstrfastcmp_c(Datum x, Datum y, SortSupport ssup);
     126                 :             : static int  bpcharfastcmp_c(Datum x, Datum y, SortSupport ssup);
     127                 :             : static int  namefastcmp_c(Datum x, Datum y, SortSupport ssup);
     128                 :             : static int  varlenafastcmp_locale(Datum x, Datum y, SortSupport ssup);
     129                 :             : static int  namefastcmp_locale(Datum x, Datum y, SortSupport ssup);
     130                 :             : static int  varstrfastcmp_locale(char *a1p, int len1, char *a2p, int len2, SortSupport ssup);
     131                 :             : static Datum varstr_abbrev_convert(Datum original, SortSupport ssup);
     132                 :             : static bool varstr_abbrev_abort(int memtupcount, SortSupport ssup);
     133                 :             : static int32 text_length(Datum str);
     134                 :             : static text *text_catenate(text *t1, text *t2);
     135                 :             : static text *text_substring(Datum str,
     136                 :             :                             int32 start,
     137                 :             :                             int32 length,
     138                 :             :                             bool length_not_specified);
     139                 :             : static int  pg_mbcharcliplen_chars(const char *mbstr, int len, int limit);
     140                 :             : static text *text_overlay(text *t1, text *t2, int sp, int sl);
     141                 :             : static int  text_position(text *t1, text *t2, Oid collid);
     142                 :             : static void text_position_setup(text *t1, text *t2, Oid collid, TextPositionState *state);
     143                 :             : static bool text_position_next(TextPositionState *state);
     144                 :             : static char *text_position_next_internal(char *start_ptr, TextPositionState *state);
     145                 :             : static char *text_position_get_match_ptr(TextPositionState *state);
     146                 :             : static int  text_position_get_match_pos(TextPositionState *state);
     147                 :             : static void text_position_cleanup(TextPositionState *state);
     148                 :             : static void check_collation_set(Oid collid);
     149                 :             : static int  text_cmp(text *arg1, text *arg2, Oid collid);
     150                 :             : static void appendStringInfoText(StringInfo str, const text *t);
     151                 :             : static bool split_text(FunctionCallInfo fcinfo, SplitTextOutputData *tstate);
     152                 :             : static void split_text_accum_result(SplitTextOutputData *tstate,
     153                 :             :                                     text *field_value,
     154                 :             :                                     text *null_string,
     155                 :             :                                     Oid collation);
     156                 :             : static text *array_to_text_internal(FunctionCallInfo fcinfo, ArrayType *v,
     157                 :             :                                     const char *fldsep, const char *null_string);
     158                 :             : static StringInfo makeStringAggState(FunctionCallInfo fcinfo);
     159                 :             : static bool text_format_parse_digits(const char **ptr, const char *end_ptr,
     160                 :             :                                      int *value);
     161                 :             : static const char *text_format_parse_format(const char *start_ptr,
     162                 :             :                                             const char *end_ptr,
     163                 :             :                                             int *argpos, int *widthpos,
     164                 :             :                                             int *flags, int *width);
     165                 :             : static void text_format_string_conversion(StringInfo buf, char conversion,
     166                 :             :                                           FmgrInfo *typOutputInfo,
     167                 :             :                                           Datum value, bool isNull,
     168                 :             :                                           int flags, int width);
     169                 :             : static void text_format_append_string(StringInfo buf, const char *str,
     170                 :             :                                       int flags, int width);
     171                 :             : static UnicodeNormalizationForm unicode_norm_form_from_text(text *formtxt);
     172                 :             : static int  valid_ascii_prefix_len(const unsigned char *s, int len);
     173                 :             : 
     174                 :             : 
     175                 :             : /*****************************************************************************
     176                 :             :  *   CONVERSION ROUTINES EXPORTED FOR USE BY C CODE                          *
     177                 :             :  *****************************************************************************/
     178                 :             : 
     179                 :             : /*
     180                 :             :  * cstring_to_text
     181                 :             :  *
     182                 :             :  * Create a text value from a null-terminated C string.
     183                 :             :  *
     184                 :             :  * The new text value is freshly palloc'd with a full-size VARHDR.
     185                 :             :  */
     186                 :             : text *
     187                 :    25587310 : cstring_to_text(const char *s)
     188                 :             : {
     189                 :    25587310 :     return cstring_to_text_with_len(s, strlen(s));
     190                 :             : }
     191                 :             : 
     192                 :             : /*
     193                 :             :  * cstring_to_text_with_len
     194                 :             :  *
     195                 :             :  * Same as cstring_to_text except the caller specifies the string length;
     196                 :             :  * the string need not be null_terminated.
     197                 :             :  */
     198                 :             : text *
     199                 :    27154235 : cstring_to_text_with_len(const char *s, int len)
     200                 :             : {
     201                 :    27154235 :     text       *result = (text *) palloc(len + VARHDRSZ);
     202                 :             : 
     203                 :    27154235 :     SET_VARSIZE(result, len + VARHDRSZ);
     204                 :    27154235 :     memcpy(VARDATA(result), s, len);
     205                 :             : 
     206                 :    27154235 :     return result;
     207                 :             : }
     208                 :             : 
     209                 :             : /*
     210                 :             :  * text_to_cstring
     211                 :             :  *
     212                 :             :  * Create a palloc'd, null-terminated C string from a text value.
     213                 :             :  *
     214                 :             :  * We support being passed a compressed or toasted text value.
     215                 :             :  * This is a bit bogus since such values shouldn't really be referred to as
     216                 :             :  * "text *", but it seems useful for robustness.  If we didn't handle that
     217                 :             :  * case here, we'd need another routine that did, anyway.
     218                 :             :  */
     219                 :             : char *
     220                 :    10900835 : text_to_cstring(const text *t)
     221                 :             : {
     222                 :             :     /* must cast away the const, unfortunately */
     223                 :    10900835 :     text       *tunpacked = pg_detoast_datum_packed(unconstify(text *, t));
     224                 :    10900835 :     int         len = VARSIZE_ANY_EXHDR(tunpacked);
     225                 :             :     char       *result;
     226                 :             : 
     227                 :    10900835 :     result = (char *) palloc(len + 1);
     228                 :    10900835 :     memcpy(result, VARDATA_ANY(tunpacked), len);
     229                 :    10900835 :     result[len] = '\0';
     230                 :             : 
     231         [ +  + ]:    10900835 :     if (tunpacked != t)
     232                 :       29595 :         pfree(tunpacked);
     233                 :             : 
     234                 :    10900835 :     return result;
     235                 :             : }
     236                 :             : 
     237                 :             : /*
     238                 :             :  * text_to_cstring_buffer
     239                 :             :  *
     240                 :             :  * Copy a text value into a caller-supplied buffer of size dst_len.
     241                 :             :  *
     242                 :             :  * The text string is truncated if necessary to fit.  The result is
     243                 :             :  * guaranteed null-terminated (unless dst_len == 0).
     244                 :             :  *
     245                 :             :  * We support being passed a compressed or toasted text value.
     246                 :             :  * This is a bit bogus since such values shouldn't really be referred to as
     247                 :             :  * "text *", but it seems useful for robustness.  If we didn't handle that
     248                 :             :  * case here, we'd need another routine that did, anyway.
     249                 :             :  */
     250                 :             : void
     251                 :         727 : text_to_cstring_buffer(const text *src, char *dst, size_t dst_len)
     252                 :             : {
     253                 :             :     /* must cast away the const, unfortunately */
     254                 :         727 :     text       *srcunpacked = pg_detoast_datum_packed(unconstify(text *, src));
     255                 :         727 :     size_t      src_len = VARSIZE_ANY_EXHDR(srcunpacked);
     256                 :             : 
     257         [ +  - ]:         727 :     if (dst_len > 0)
     258                 :             :     {
     259                 :         727 :         dst_len--;
     260         [ +  - ]:         727 :         if (dst_len >= src_len)
     261                 :         727 :             dst_len = src_len;
     262                 :             :         else                    /* ensure truncation is encoding-safe */
     263                 :           0 :             dst_len = pg_mbcliplen(VARDATA_ANY(srcunpacked), src_len, dst_len);
     264                 :         727 :         memcpy(dst, VARDATA_ANY(srcunpacked), dst_len);
     265                 :         727 :         dst[dst_len] = '\0';
     266                 :             :     }
     267                 :             : 
     268         [ -  + ]:         727 :     if (srcunpacked != src)
     269                 :           0 :         pfree(srcunpacked);
     270                 :         727 : }
     271                 :             : 
     272                 :             : 
     273                 :             : /*****************************************************************************
     274                 :             :  *   USER I/O ROUTINES                                                       *
     275                 :             :  *****************************************************************************/
     276                 :             : 
     277                 :             : /*
     278                 :             :  *      textin          - converts cstring to internal representation
     279                 :             :  */
     280                 :             : Datum
     281                 :    23246413 : textin(PG_FUNCTION_ARGS)
     282                 :             : {
     283                 :    23246413 :     char       *inputText = PG_GETARG_CSTRING(0);
     284                 :             : 
     285                 :    23246413 :     PG_RETURN_TEXT_P(cstring_to_text(inputText));
     286                 :             : }
     287                 :             : 
     288                 :             : /*
     289                 :             :  *      textout         - converts internal representation to cstring
     290                 :             :  */
     291                 :             : Datum
     292                 :     4607512 : textout(PG_FUNCTION_ARGS)
     293                 :             : {
     294                 :     4607512 :     Datum       txt = PG_GETARG_DATUM(0);
     295                 :             : 
     296                 :     4607512 :     PG_RETURN_CSTRING(TextDatumGetCString(txt));
     297                 :             : }
     298                 :             : 
     299                 :             : /*
     300                 :             :  *      textrecv            - converts external binary format to text
     301                 :             :  */
     302                 :             : Datum
     303                 :          27 : textrecv(PG_FUNCTION_ARGS)
     304                 :             : {
     305                 :          27 :     StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
     306                 :             :     text       *result;
     307                 :             :     char       *str;
     308                 :             :     int         nbytes;
     309                 :             : 
     310                 :          27 :     str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
     311                 :             : 
     312                 :          27 :     result = cstring_to_text_with_len(str, nbytes);
     313                 :          27 :     pfree(str);
     314                 :          27 :     PG_RETURN_TEXT_P(result);
     315                 :             : }
     316                 :             : 
     317                 :             : /*
     318                 :             :  *      textsend            - converts text to binary format
     319                 :             :  */
     320                 :             : Datum
     321                 :        2968 : textsend(PG_FUNCTION_ARGS)
     322                 :             : {
     323                 :        2968 :     text       *t = PG_GETARG_TEXT_PP(0);
     324                 :             :     StringInfoData buf;
     325                 :             : 
     326                 :        2968 :     pq_begintypsend(&buf);
     327                 :        2968 :     pq_sendtext(&buf, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
     328                 :        2968 :     PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
     329                 :             : }
     330                 :             : 
     331                 :             : 
     332                 :             : /*
     333                 :             :  *      unknownin           - converts cstring to internal representation
     334                 :             :  */
     335                 :             : Datum
     336                 :           0 : unknownin(PG_FUNCTION_ARGS)
     337                 :             : {
     338                 :           0 :     char       *str = PG_GETARG_CSTRING(0);
     339                 :             : 
     340                 :             :     /* representation is same as cstring */
     341                 :           0 :     PG_RETURN_CSTRING(pstrdup(str));
     342                 :             : }
     343                 :             : 
     344                 :             : /*
     345                 :             :  *      unknownout          - converts internal representation to cstring
     346                 :             :  */
     347                 :             : Datum
     348                 :         692 : unknownout(PG_FUNCTION_ARGS)
     349                 :             : {
     350                 :             :     /* representation is same as cstring */
     351                 :         692 :     char       *str = PG_GETARG_CSTRING(0);
     352                 :             : 
     353                 :         692 :     PG_RETURN_CSTRING(pstrdup(str));
     354                 :             : }
     355                 :             : 
     356                 :             : /*
     357                 :             :  *      unknownrecv         - converts external binary format to unknown
     358                 :             :  */
     359                 :             : Datum
     360                 :           0 : unknownrecv(PG_FUNCTION_ARGS)
     361                 :             : {
     362                 :           0 :     StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
     363                 :             :     char       *str;
     364                 :             :     int         nbytes;
     365                 :             : 
     366                 :           0 :     str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
     367                 :             :     /* representation is same as cstring */
     368                 :           0 :     PG_RETURN_CSTRING(str);
     369                 :             : }
     370                 :             : 
     371                 :             : /*
     372                 :             :  *      unknownsend         - converts unknown to binary format
     373                 :             :  */
     374                 :             : Datum
     375                 :           0 : unknownsend(PG_FUNCTION_ARGS)
     376                 :             : {
     377                 :             :     /* representation is same as cstring */
     378                 :           0 :     char       *str = PG_GETARG_CSTRING(0);
     379                 :             :     StringInfoData buf;
     380                 :             : 
     381                 :           0 :     pq_begintypsend(&buf);
     382                 :           0 :     pq_sendtext(&buf, str, strlen(str));
     383                 :           0 :     PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
     384                 :             : }
     385                 :             : 
     386                 :             : 
     387                 :             : /* ========== PUBLIC ROUTINES ========== */
     388                 :             : 
     389                 :             : /*
     390                 :             :  * textlen -
     391                 :             :  *    returns the logical length of a text*
     392                 :             :  *     (which is less than the VARSIZE of the text*)
     393                 :             :  */
     394                 :             : Datum
     395                 :      286238 : textlen(PG_FUNCTION_ARGS)
     396                 :             : {
     397                 :      286238 :     Datum       str = PG_GETARG_DATUM(0);
     398                 :             : 
     399                 :             :     /* try to avoid decompressing argument */
     400                 :      286238 :     PG_RETURN_INT32(text_length(str));
     401                 :             : }
     402                 :             : 
     403                 :             : /*
     404                 :             :  * text_length -
     405                 :             :  *  Does the real work for textlen()
     406                 :             :  *
     407                 :             :  *  This is broken out so it can be called directly by other string processing
     408                 :             :  *  functions.  Note that the argument is passed as a Datum, to indicate that
     409                 :             :  *  it may still be in compressed form.  We can avoid decompressing it at all
     410                 :             :  *  in some cases.
     411                 :             :  */
     412                 :             : static int32
     413                 :      286248 : text_length(Datum str)
     414                 :             : {
     415                 :             :     /* fastpath when max encoding length is one */
     416         [ +  + ]:      286248 :     if (pg_database_encoding_max_length() == 1)
     417                 :          10 :         return (toast_raw_datum_size(str) - VARHDRSZ);
     418                 :             :     else
     419                 :             :     {
     420                 :      286238 :         text       *t = DatumGetTextPP(str);
     421                 :             : 
     422                 :      286238 :         return (pg_mbstrlen_with_len(VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t)));
     423                 :             :     }
     424                 :             : }
     425                 :             : 
     426                 :             : /*
     427                 :             :  * textoctetlen -
     428                 :             :  *    returns the physical length of a text*
     429                 :             :  *     (which is less than the VARSIZE of the text*)
     430                 :             :  */
     431                 :             : Datum
     432                 :          45 : textoctetlen(PG_FUNCTION_ARGS)
     433                 :             : {
     434                 :          45 :     Datum       str = PG_GETARG_DATUM(0);
     435                 :             : 
     436                 :             :     /* We need not detoast the input at all */
     437                 :          45 :     PG_RETURN_INT32(toast_raw_datum_size(str) - VARHDRSZ);
     438                 :             : }
     439                 :             : 
     440                 :             : /*
     441                 :             :  * textcat -
     442                 :             :  *    takes two text* and returns a text* that is the concatenation of
     443                 :             :  *    the two.
     444                 :             :  *
     445                 :             :  * Rewritten by Sapa, sapa@hq.icb.chel.su. 8-Jul-96.
     446                 :             :  * Updated by Thomas, Thomas.Lockhart@jpl.nasa.gov 1997-07-10.
     447                 :             :  * Allocate space for output in all cases.
     448                 :             :  * XXX - thomas 1997-07-10
     449                 :             :  */
     450                 :             : Datum
     451                 :     1385505 : textcat(PG_FUNCTION_ARGS)
     452                 :             : {
     453                 :     1385505 :     text       *t1 = PG_GETARG_TEXT_PP(0);
     454                 :     1385505 :     text       *t2 = PG_GETARG_TEXT_PP(1);
     455                 :             : 
     456                 :     1385505 :     PG_RETURN_TEXT_P(text_catenate(t1, t2));
     457                 :             : }
     458                 :             : 
     459                 :             : /*
     460                 :             :  * text_catenate
     461                 :             :  *  Guts of textcat(), broken out so it can be used by other functions
     462                 :             :  *
     463                 :             :  * Arguments can be in short-header form, but not compressed or out-of-line
     464                 :             :  */
     465                 :             : static text *
     466                 :     1385561 : text_catenate(text *t1, text *t2)
     467                 :             : {
     468                 :             :     text       *result;
     469                 :             :     int         len1,
     470                 :             :                 len2,
     471                 :             :                 len;
     472                 :             :     char       *ptr;
     473                 :             : 
     474                 :     1385561 :     len1 = VARSIZE_ANY_EXHDR(t1);
     475                 :     1385561 :     len2 = VARSIZE_ANY_EXHDR(t2);
     476                 :             : 
     477                 :             :     /* paranoia ... probably should throw error instead? */
     478         [ -  + ]:     1385561 :     if (len1 < 0)
     479                 :           0 :         len1 = 0;
     480         [ -  + ]:     1385561 :     if (len2 < 0)
     481                 :           0 :         len2 = 0;
     482                 :             : 
     483                 :     1385561 :     len = len1 + len2 + VARHDRSZ;
     484                 :     1385561 :     result = (text *) palloc(len);
     485                 :             : 
     486                 :             :     /* Set size of result string... */
     487                 :     1385561 :     SET_VARSIZE(result, len);
     488                 :             : 
     489                 :             :     /* Fill data field of result string... */
     490                 :     1385561 :     ptr = VARDATA(result);
     491         [ +  + ]:     1385561 :     if (len1 > 0)
     492                 :     1383410 :         memcpy(ptr, VARDATA_ANY(t1), len1);
     493         [ +  + ]:     1385561 :     if (len2 > 0)
     494                 :     1385394 :         memcpy(ptr + len1, VARDATA_ANY(t2), len2);
     495                 :             : 
     496                 :     1385561 :     return result;
     497                 :             : }
     498                 :             : 
     499                 :             : /*
     500                 :             :  * charlen_to_bytelen()
     501                 :             :  *  Compute the number of bytes occupied by n characters starting at *p
     502                 :             :  *
     503                 :             :  * The caller shall ensure there are n complete characters.  Callers achieve
     504                 :             :  * this by deriving "n" from regmatch_t findings from searching a wchar array.
     505                 :             :  * pg_mb2wchar_with_len() skips any trailing incomplete character, so regex
     506                 :             :  * matches will end no later than the last complete character.  (The string
     507                 :             :  * need not be null-terminated.)
     508                 :             :  */
     509                 :             : static int
     510                 :       12280 : charlen_to_bytelen(const char *p, int n)
     511                 :             : {
     512         [ +  + ]:       12280 :     if (pg_database_encoding_max_length() == 1)
     513                 :             :     {
     514                 :             :         /* Optimization for single-byte encodings */
     515                 :         102 :         return n;
     516                 :             :     }
     517                 :             :     else
     518                 :             :     {
     519                 :             :         const char *s;
     520                 :             : 
     521         [ +  + ]:     3910449 :         for (s = p; n > 0; n--)
     522                 :     3898271 :             s += pg_mblen_unbounded(s); /* caller verified encoding */
     523                 :             : 
     524                 :       12178 :         return s - p;
     525                 :             :     }
     526                 :             : }
     527                 :             : 
     528                 :             : /*
     529                 :             :  * text_substr()
     530                 :             :  * Return a substring starting at the specified position.
     531                 :             :  * - thomas 1997-12-31
     532                 :             :  *
     533                 :             :  * Input:
     534                 :             :  *  - string
     535                 :             :  *  - starting position (is one-based)
     536                 :             :  *  - string length
     537                 :             :  *
     538                 :             :  * If the starting position is zero or less, then return from the start of the string
     539                 :             :  *  adjusting the length to be consistent with the "negative start" per SQL.
     540                 :             :  * If the length is less than zero, return the remaining string.
     541                 :             :  *
     542                 :             :  * Added multibyte support.
     543                 :             :  * - Tatsuo Ishii 1998-4-21
     544                 :             :  * Changed behavior if starting position is less than one to conform to SQL behavior.
     545                 :             :  * Formerly returned the entire string; now returns a portion.
     546                 :             :  * - Thomas Lockhart 1998-12-10
     547                 :             :  * Now uses faster TOAST-slicing interface
     548                 :             :  * - John Gray 2002-02-22
     549                 :             :  * Remove "#ifdef MULTIBYTE" and test for encoding_max_length instead. Change
     550                 :             :  * behaviors conflicting with SQL to meet SQL (if E = S + L < S throw
     551                 :             :  * error; if E < 1, return '', not entire string). Fixed MB related bug when
     552                 :             :  * S > LC and < LC + 4 sometimes garbage characters are returned.
     553                 :             :  * - Joe Conway 2002-08-10
     554                 :             :  */
     555                 :             : Datum
     556                 :      371803 : text_substr(PG_FUNCTION_ARGS)
     557                 :             : {
     558                 :      371803 :     PG_RETURN_TEXT_P(text_substring(PG_GETARG_DATUM(0),
     559                 :             :                                     PG_GETARG_INT32(1),
     560                 :             :                                     PG_GETARG_INT32(2),
     561                 :             :                                     false));
     562                 :             : }
     563                 :             : 
     564                 :             : /*
     565                 :             :  * text_substr_no_len -
     566                 :             :  *    Wrapper to avoid opr_sanity failure due to
     567                 :             :  *    one function accepting a different number of args.
     568                 :             :  */
     569                 :             : Datum
     570                 :          65 : text_substr_no_len(PG_FUNCTION_ARGS)
     571                 :             : {
     572                 :          65 :     PG_RETURN_TEXT_P(text_substring(PG_GETARG_DATUM(0),
     573                 :             :                                     PG_GETARG_INT32(1),
     574                 :             :                                     -1, true));
     575                 :             : }
     576                 :             : 
     577                 :             : /*
     578                 :             :  * text_substring -
     579                 :             :  *  Does the real work for text_substr() and text_substr_no_len()
     580                 :             :  *
     581                 :             :  *  This is broken out so it can be called directly by other string processing
     582                 :             :  *  functions.  Note that the argument is passed as a Datum, to indicate that
     583                 :             :  *  it may still be in compressed/toasted form.  We can avoid detoasting all
     584                 :             :  *  of it in some cases.
     585                 :             :  *
     586                 :             :  *  The result is always a freshly palloc'd datum.
     587                 :             :  */
     588                 :             : static text *
     589                 :      398619 : text_substring(Datum str, int32 start, int32 length, bool length_not_specified)
     590                 :             : {
     591                 :      398619 :     int32       eml = pg_database_encoding_max_length();
     592                 :      398619 :     int32       S = start;      /* start position */
     593                 :             :     int32       S1;             /* adjusted start position */
     594                 :             :     int32       L1;             /* adjusted substring length */
     595                 :             :     int32       E;              /* end position, exclusive */
     596                 :             : 
     597                 :             :     /*
     598                 :             :      * SQL99 says S can be zero or negative (which we don't document), but we
     599                 :             :      * still must fetch from the start of the string.
     600                 :             :      * https://www.postgresql.org/message-id/170905442373.643.11536838320909376197%40wrigleys.postgresql.org
     601                 :             :      */
     602                 :      398619 :     S1 = Max(S, 1);
     603                 :             : 
     604                 :             :     /* life is easy if the encoding max length is 1 */
     605         [ +  + ]:      398619 :     if (eml == 1)
     606                 :             :     {
     607         [ -  + ]:          11 :         if (length_not_specified)   /* special case - get length to end of
     608                 :             :                                      * string */
     609                 :           0 :             L1 = -1;
     610         [ -  + ]:          11 :         else if (length < 0)
     611                 :             :         {
     612                 :             :             /* SQL99 says to throw an error for E < S, i.e., negative length */
     613         [ #  # ]:           0 :             ereport(ERROR,
     614                 :             :                     (errcode(ERRCODE_SUBSTRING_ERROR),
     615                 :             :                      errmsg("negative substring length not allowed")));
     616                 :             :             L1 = -1;            /* silence stupider compilers */
     617                 :             :         }
     618         [ -  + ]:          11 :         else if (pg_add_s32_overflow(S, length, &E))
     619                 :             :         {
     620                 :             :             /*
     621                 :             :              * L could be large enough for S + L to overflow, in which case
     622                 :             :              * the substring must run to end of string.
     623                 :             :              */
     624                 :           0 :             L1 = -1;
     625                 :             :         }
     626                 :             :         else
     627                 :             :         {
     628                 :             :             /*
     629                 :             :              * A zero or negative value for the end position can happen if the
     630                 :             :              * start was negative or one. SQL99 says to return a zero-length
     631                 :             :              * string.
     632                 :             :              */
     633         [ -  + ]:          11 :             if (E < 1)
     634                 :           0 :                 return cstring_to_text("");
     635                 :             : 
     636                 :          11 :             L1 = E - S1;
     637                 :             :         }
     638                 :             : 
     639                 :             :         /*
     640                 :             :          * If the start position is past the end of the string, SQL99 says to
     641                 :             :          * return a zero-length string -- DatumGetTextPSlice() will do that
     642                 :             :          * for us.  We need only convert S1 to zero-based starting position.
     643                 :             :          */
     644                 :          11 :         return DatumGetTextPSlice(str, S1 - 1, L1);
     645                 :             :     }
     646         [ +  - ]:      398608 :     else if (eml > 1)
     647                 :             :     {
     648                 :             :         /*
     649                 :             :          * When encoding max length is > 1, we can't get LC without
     650                 :             :          * detoasting, so we'll grab a conservatively large slice now and go
     651                 :             :          * back later to do the right thing
     652                 :             :          */
     653                 :             :         int32       slice_start;
     654                 :             :         int32       slice_size;
     655                 :             :         int32       slice_strlen;
     656                 :             :         int32       slice_len;
     657                 :             :         text       *slice;
     658                 :             :         int32       E1;
     659                 :             :         int32       i;
     660                 :             :         char       *p;
     661                 :             :         char       *s;
     662                 :             :         text       *ret;
     663                 :             : 
     664                 :             :         /*
     665                 :             :          * We need to start at position zero because there is no way to know
     666                 :             :          * in advance which byte offset corresponds to the supplied start
     667                 :             :          * position.
     668                 :             :          */
     669                 :      398608 :         slice_start = 0;
     670                 :             : 
     671         [ +  + ]:      398608 :         if (length_not_specified)   /* special case - get length to end of
     672                 :             :                                      * string */
     673                 :          93 :             E = slice_size = L1 = -1;
     674         [ +  + ]:      398515 :         else if (length < 0)
     675                 :             :         {
     676                 :             :             /* SQL99 says to throw an error for E < S, i.e., negative length */
     677         [ +  - ]:          12 :             ereport(ERROR,
     678                 :             :                     (errcode(ERRCODE_SUBSTRING_ERROR),
     679                 :             :                      errmsg("negative substring length not allowed")));
     680                 :             :             E = slice_size = L1 = -1;   /* silence stupider compilers */
     681                 :             :         }
     682         [ +  + ]:      398503 :         else if (pg_add_s32_overflow(S, length, &E))
     683                 :             :         {
     684                 :             :             /*
     685                 :             :              * L could be large enough for S + L to overflow, in which case
     686                 :             :              * the substring must run to end of string.
     687                 :             :              */
     688                 :           5 :             slice_size = L1 = -1;
     689                 :             :         }
     690                 :             :         else
     691                 :             :         {
     692                 :             :             /*
     693                 :             :              * Ending at position 1, exclusive, obviously yields an empty
     694                 :             :              * string.  A zero or negative value can happen if the start was
     695                 :             :              * negative or one. SQL99 says to return a zero-length string.
     696                 :             :              */
     697         [ +  + ]:      398498 :             if (E <= 1)
     698                 :           8 :                 return cstring_to_text("");
     699                 :             : 
     700                 :             :             /*
     701                 :             :              * if E is past the end of the string, the tuple toaster will
     702                 :             :              * truncate the length for us
     703                 :             :              */
     704                 :      398490 :             L1 = E - S1;
     705                 :             : 
     706                 :             :             /*
     707                 :             :              * Total slice size in bytes can't be any longer than the
     708                 :             :              * inclusive end position times the encoding max length.  If that
     709                 :             :              * overflows, we can just use -1.
     710                 :             :              */
     711         [ +  + ]:      398490 :             if (pg_mul_s32_overflow(E - 1, eml, &slice_size))
     712                 :           5 :                 slice_size = -1;
     713                 :             :         }
     714                 :             : 
     715                 :             :         /*
     716                 :             :          * If we're working with an untoasted source, no need to do an extra
     717                 :             :          * copying step.
     718                 :             :          */
     719   [ +  +  +  + ]:      797064 :         if (VARATT_IS_COMPRESSED(DatumGetPointer(str)) ||
     720                 :      398476 :             VARATT_IS_EXTERNAL(DatumGetPointer(str)))
     721                 :         315 :             slice = DatumGetTextPSlice(str, slice_start, slice_size);
     722                 :             :         else
     723                 :      398273 :             slice = (text *) DatumGetPointer(str);
     724                 :             : 
     725                 :             :         /* see if we got back an empty string */
     726                 :      398588 :         slice_len = VARSIZE_ANY_EXHDR(slice);
     727         [ -  + ]:      398588 :         if (slice_len == 0)
     728                 :             :         {
     729         [ #  # ]:           0 :             if (slice != (text *) DatumGetPointer(str))
     730                 :           0 :                 pfree(slice);
     731                 :           0 :             return cstring_to_text("");
     732                 :             :         }
     733                 :             : 
     734                 :             :         /*
     735                 :             :          * Now we can get the actual length of the slice in MB characters,
     736                 :             :          * stopping at the end of the substring.  Continuing beyond the
     737                 :             :          * substring end could find an incomplete character attributable
     738                 :             :          * solely to DatumGetTextPSlice() chopping in the middle of a
     739                 :             :          * character, and it would be superfluous work at best.
     740                 :             :          */
     741                 :      398580 :         slice_strlen =
     742                 :      398588 :             (slice_size == -1 ?
     743         [ +  + ]:      398588 :              pg_mbstrlen_with_len(VARDATA_ANY(slice), slice_len) :
     744                 :      398485 :              pg_mbcharcliplen_chars(VARDATA_ANY(slice), slice_len, E - 1));
     745                 :             : 
     746                 :             :         /*
     747                 :             :          * Check that the start position wasn't > slice_strlen. If so, SQL99
     748                 :             :          * says to return a zero-length string.
     749                 :             :          */
     750         [ +  + ]:      398580 :         if (S1 > slice_strlen)
     751                 :             :         {
     752         [ +  + ]:          25 :             if (slice != (text *) DatumGetPointer(str))
     753                 :           4 :                 pfree(slice);
     754                 :          25 :             return cstring_to_text("");
     755                 :             :         }
     756                 :             : 
     757                 :             :         /*
     758                 :             :          * Adjust L1 and E1 now that we know the slice string length. Again
     759                 :             :          * remember that S1 is one based, and slice_start is zero based.
     760                 :             :          */
     761         [ +  + ]:      398555 :         if (L1 > -1)
     762                 :      398470 :             E1 = Min(S1 + L1, slice_start + 1 + slice_strlen);
     763                 :             :         else
     764                 :          85 :             E1 = slice_start + 1 + slice_strlen;
     765                 :             : 
     766                 :             :         /*
     767                 :             :          * Find the start position in the slice; remember S1 is not zero based
     768                 :             :          */
     769                 :      398555 :         p = VARDATA_ANY(slice);
     770         [ +  + ]:     9836914 :         for (i = 0; i < S1 - 1; i++)
     771                 :     9438359 :             p += pg_mblen_unbounded(p);
     772                 :             : 
     773                 :             :         /* hang onto a pointer to our start position */
     774                 :      398555 :         s = p;
     775                 :             : 
     776                 :             :         /*
     777                 :             :          * Count the actual bytes used by the substring of the requested
     778                 :             :          * length.
     779                 :             :          */
     780         [ +  + ]:     6250855 :         for (i = S1; i < E1; i++)
     781                 :     5852300 :             p += pg_mblen_unbounded(p);
     782                 :             : 
     783                 :      398555 :         ret = (text *) palloc(VARHDRSZ + (p - s));
     784                 :      398555 :         SET_VARSIZE(ret, VARHDRSZ + (p - s));
     785                 :      398555 :         memcpy(VARDATA(ret), s, (p - s));
     786                 :             : 
     787         [ +  + ]:      398555 :         if (slice != (text *) DatumGetPointer(str))
     788                 :         307 :             pfree(slice);
     789                 :             : 
     790                 :      398555 :         return ret;
     791                 :             :     }
     792                 :             :     else
     793         [ #  # ]:           0 :         elog(ERROR, "invalid backend encoding: encoding max length < 1");
     794                 :             : 
     795                 :             :     /* not reached: suppress compiler warning */
     796                 :             :     return NULL;
     797                 :             : }
     798                 :             : 
     799                 :             : /*
     800                 :             :  * pg_mbcharcliplen_chars -
     801                 :             :  *  Mirror pg_mbcharcliplen(), except return value unit is chars, not bytes.
     802                 :             :  *
     803                 :             :  *  This mirrors all the dubious historical behavior, so it's static to
     804                 :             :  *  discourage proliferation.  The assertions are specific to the one caller.
     805                 :             :  */
     806                 :             : static int
     807                 :      398485 : pg_mbcharcliplen_chars(const char *mbstr, int len, int limit)
     808                 :             : {
     809                 :      398485 :     int         nch = 0;
     810                 :             :     int         l;
     811                 :             : 
     812                 :             :     Assert(len > 0);
     813                 :             :     Assert(limit > 0);
     814                 :             :     Assert(pg_database_encoding_max_length() > 1);
     815                 :             : 
     816   [ +  +  +  + ]:     9722816 :     while (len > 0 && *mbstr)
     817                 :             :     {
     818                 :     9722460 :         l = pg_mblen_with_len(mbstr, len);
     819                 :     9722452 :         nch++;
     820         [ +  + ]:     9722452 :         if (nch == limit)
     821                 :      398121 :             break;
     822                 :     9324331 :         len -= l;
     823                 :     9324331 :         mbstr += l;
     824                 :             :     }
     825                 :      398477 :     return nch;
     826                 :             : }
     827                 :             : 
     828                 :             : /*
     829                 :             :  * textoverlay
     830                 :             :  *  Replace specified substring of first string with second
     831                 :             :  *
     832                 :             :  * The SQL standard defines OVERLAY() in terms of substring and concatenation.
     833                 :             :  * This code is a direct implementation of what the standard says.
     834                 :             :  */
     835                 :             : Datum
     836                 :          18 : textoverlay(PG_FUNCTION_ARGS)
     837                 :             : {
     838                 :          18 :     text       *t1 = PG_GETARG_TEXT_PP(0);
     839                 :          18 :     text       *t2 = PG_GETARG_TEXT_PP(1);
     840                 :          18 :     int         sp = PG_GETARG_INT32(2);    /* substring start position */
     841                 :          18 :     int         sl = PG_GETARG_INT32(3);    /* substring length */
     842                 :             : 
     843                 :          18 :     PG_RETURN_TEXT_P(text_overlay(t1, t2, sp, sl));
     844                 :             : }
     845                 :             : 
     846                 :             : Datum
     847                 :          10 : textoverlay_no_len(PG_FUNCTION_ARGS)
     848                 :             : {
     849                 :          10 :     text       *t1 = PG_GETARG_TEXT_PP(0);
     850                 :          10 :     text       *t2 = PG_GETARG_TEXT_PP(1);
     851                 :          10 :     int         sp = PG_GETARG_INT32(2);    /* substring start position */
     852                 :             :     int         sl;
     853                 :             : 
     854                 :          10 :     sl = text_length(PointerGetDatum(t2));  /* defaults to length(t2) */
     855                 :          10 :     PG_RETURN_TEXT_P(text_overlay(t1, t2, sp, sl));
     856                 :             : }
     857                 :             : 
     858                 :             : static text *
     859                 :          28 : text_overlay(text *t1, text *t2, int sp, int sl)
     860                 :             : {
     861                 :             :     text       *result;
     862                 :             :     text       *s1;
     863                 :             :     text       *s2;
     864                 :             :     int         sp_pl_sl;
     865                 :             : 
     866                 :             :     /*
     867                 :             :      * Check for possible integer-overflow cases.  For negative sp, throw a
     868                 :             :      * "substring length" error because that's what should be expected
     869                 :             :      * according to the spec's definition of OVERLAY().
     870                 :             :      */
     871         [ -  + ]:          28 :     if (sp <= 0)
     872         [ #  # ]:           0 :         ereport(ERROR,
     873                 :             :                 (errcode(ERRCODE_SUBSTRING_ERROR),
     874                 :             :                  errmsg("negative substring length not allowed")));
     875         [ -  + ]:          28 :     if (pg_add_s32_overflow(sp, sl, &sp_pl_sl))
     876         [ #  # ]:           0 :         ereport(ERROR,
     877                 :             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
     878                 :             :                  errmsg("integer out of range")));
     879                 :             : 
     880                 :          28 :     s1 = text_substring(PointerGetDatum(t1), 1, sp - 1, false);
     881                 :          28 :     s2 = text_substring(PointerGetDatum(t1), sp_pl_sl, -1, true);
     882                 :          28 :     result = text_catenate(s1, t2);
     883                 :          28 :     result = text_catenate(result, s2);
     884                 :             : 
     885                 :          28 :     return result;
     886                 :             : }
     887                 :             : 
     888                 :             : /*
     889                 :             :  * textpos -
     890                 :             :  *    Return the position of the specified substring.
     891                 :             :  *    Implements the SQL POSITION() function.
     892                 :             :  *    Ref: A Guide To The SQL Standard, Date & Darwen, 1997
     893                 :             :  * - thomas 1997-07-27
     894                 :             :  */
     895                 :             : Datum
     896                 :          87 : textpos(PG_FUNCTION_ARGS)
     897                 :             : {
     898                 :          87 :     text       *str = PG_GETARG_TEXT_PP(0);
     899                 :          87 :     text       *search_str = PG_GETARG_TEXT_PP(1);
     900                 :             : 
     901                 :          87 :     PG_RETURN_INT32((int32) text_position(str, search_str, PG_GET_COLLATION()));
     902                 :             : }
     903                 :             : 
     904                 :             : /*
     905                 :             :  * text_position -
     906                 :             :  *  Does the real work for textpos()
     907                 :             :  *
     908                 :             :  * Inputs:
     909                 :             :  *      t1 - string to be searched
     910                 :             :  *      t2 - pattern to match within t1
     911                 :             :  * Result:
     912                 :             :  *      Character index of the first matched char, starting from 1,
     913                 :             :  *      or 0 if no match.
     914                 :             :  *
     915                 :             :  *  This is broken out so it can be called directly by other string processing
     916                 :             :  *  functions.
     917                 :             :  */
     918                 :             : static int
     919                 :          87 : text_position(text *t1, text *t2, Oid collid)
     920                 :             : {
     921                 :             :     TextPositionState state;
     922                 :             :     int         result;
     923                 :             : 
     924                 :          87 :     check_collation_set(collid);
     925                 :             : 
     926                 :             :     /* Empty needle always matches at position 1 */
     927         [ +  + ]:          87 :     if (VARSIZE_ANY_EXHDR(t2) < 1)
     928                 :          10 :         return 1;
     929                 :             : 
     930                 :             :     /* Otherwise, can't match if haystack is shorter than needle */
     931         [ +  + ]:          77 :     if (VARSIZE_ANY_EXHDR(t1) < VARSIZE_ANY_EXHDR(t2) &&
     932         [ +  - ]:          13 :         pg_newlocale_from_collation(collid)->deterministic)
     933                 :          13 :         return 0;
     934                 :             : 
     935                 :          64 :     text_position_setup(t1, t2, collid, &state);
     936                 :             :     /* don't need greedy mode here */
     937                 :          64 :     state.greedy = false;
     938                 :             : 
     939         [ +  + ]:          64 :     if (!text_position_next(&state))
     940                 :          14 :         result = 0;
     941                 :             :     else
     942                 :          50 :         result = text_position_get_match_pos(&state);
     943                 :          64 :     text_position_cleanup(&state);
     944                 :          64 :     return result;
     945                 :             : }
     946                 :             : 
     947                 :             : 
     948                 :             : /*
     949                 :             :  * text_position_setup, text_position_next, text_position_cleanup -
     950                 :             :  *  Component steps of text_position()
     951                 :             :  *
     952                 :             :  * These are broken out so that a string can be efficiently searched for
     953                 :             :  * multiple occurrences of the same pattern.  text_position_next may be
     954                 :             :  * called multiple times, and it advances to the next match on each call.
     955                 :             :  * text_position_get_match_ptr() and text_position_get_match_pos() return
     956                 :             :  * a pointer or 1-based character position of the last match, respectively.
     957                 :             :  *
     958                 :             :  * The "state" variable is normally just a local variable in the caller.
     959                 :             :  *
     960                 :             :  * NOTE: text_position_next skips over the matched portion.  For example,
     961                 :             :  * searching for "xx" in "xxx" returns only one match, not two.
     962                 :             :  */
     963                 :             : 
     964                 :             : static void
     965                 :        1293 : text_position_setup(text *t1, text *t2, Oid collid, TextPositionState *state)
     966                 :             : {
     967                 :        1293 :     int         len1 = VARSIZE_ANY_EXHDR(t1);
     968                 :        1293 :     int         len2 = VARSIZE_ANY_EXHDR(t2);
     969                 :             : 
     970                 :        1293 :     check_collation_set(collid);
     971                 :             : 
     972                 :        1293 :     state->locale = pg_newlocale_from_collation(collid);
     973                 :             : 
     974                 :             :     /*
     975                 :             :      * Most callers need greedy mode, but some might want to unset this to
     976                 :             :      * optimize.
     977                 :             :      */
     978                 :        1293 :     state->greedy = true;
     979                 :             : 
     980                 :             :     Assert(len2 > 0);
     981                 :             : 
     982                 :             :     /*
     983                 :             :      * Even with a multi-byte encoding, we perform the search using the raw
     984                 :             :      * byte sequence, ignoring multibyte issues.  For UTF-8, that works fine,
     985                 :             :      * because in UTF-8 the byte sequence of one character cannot contain
     986                 :             :      * another character.  For other multi-byte encodings, we do the search
     987                 :             :      * initially as a simple byte search, ignoring multibyte issues, but
     988                 :             :      * verify afterwards that the match we found is at a character boundary,
     989                 :             :      * and continue the search if it was a false match.
     990                 :             :      */
     991         [ +  + ]:        1293 :     if (pg_database_encoding_max_length() == 1)
     992                 :          60 :         state->is_multibyte_char_in_char = false;
     993         [ +  - ]:        1233 :     else if (GetDatabaseEncoding() == PG_UTF8)
     994                 :        1233 :         state->is_multibyte_char_in_char = false;
     995                 :             :     else
     996                 :           0 :         state->is_multibyte_char_in_char = true;
     997                 :             : 
     998                 :        1293 :     state->str1 = VARDATA_ANY(t1);
     999                 :        1293 :     state->str2 = VARDATA_ANY(t2);
    1000                 :        1293 :     state->len1 = len1;
    1001                 :        1293 :     state->len2 = len2;
    1002                 :        1293 :     state->last_match = NULL;
    1003                 :        1293 :     state->refpoint = state->str1;
    1004                 :        1293 :     state->refpos = 0;
    1005                 :             : 
    1006                 :             :     /*
    1007                 :             :      * Prepare the skip table for Boyer-Moore-Horspool searching.  In these
    1008                 :             :      * notes we use the terminology that the "haystack" is the string to be
    1009                 :             :      * searched (t1) and the "needle" is the pattern being sought (t2).
    1010                 :             :      *
    1011                 :             :      * If the needle is empty or bigger than the haystack then there is no
    1012                 :             :      * point in wasting cycles initializing the table.  We also choose not to
    1013                 :             :      * use B-M-H for needles of length 1, since the skip table can't possibly
    1014                 :             :      * save anything in that case.
    1015                 :             :      *
    1016                 :             :      * (With nondeterministic collations, the search is already
    1017                 :             :      * multibyte-aware, so we don't need this.)
    1018                 :             :      */
    1019   [ +  -  +  +  :        1293 :     if (len1 >= len2 && len2 > 1 && state->locale->deterministic)
                   +  + ]
    1020                 :             :     {
    1021                 :        1035 :         int         searchlength = len1 - len2;
    1022                 :             :         int         skiptablemask;
    1023                 :             :         int         last;
    1024                 :             :         int         i;
    1025                 :        1035 :         const char *str2 = state->str2;
    1026                 :             : 
    1027                 :             :         /*
    1028                 :             :          * First we must determine how much of the skip table to use.  The
    1029                 :             :          * declaration of TextPositionState allows up to 256 elements, but for
    1030                 :             :          * short search problems we don't really want to have to initialize so
    1031                 :             :          * many elements --- it would take too long in comparison to the
    1032                 :             :          * actual search time.  So we choose a useful skip table size based on
    1033                 :             :          * the haystack length minus the needle length.  The closer the needle
    1034                 :             :          * length is to the haystack length the less useful skipping becomes.
    1035                 :             :          *
    1036                 :             :          * Note: since we use bit-masking to select table elements, the skip
    1037                 :             :          * table size MUST be a power of 2, and so the mask must be 2^N-1.
    1038                 :             :          */
    1039         [ +  + ]:        1035 :         if (searchlength < 16)
    1040                 :         112 :             skiptablemask = 3;
    1041         [ +  + ]:         923 :         else if (searchlength < 64)
    1042                 :          24 :             skiptablemask = 7;
    1043         [ +  + ]:         899 :         else if (searchlength < 128)
    1044                 :          14 :             skiptablemask = 15;
    1045         [ +  + ]:         885 :         else if (searchlength < 512)
    1046                 :         203 :             skiptablemask = 31;
    1047         [ +  + ]:         682 :         else if (searchlength < 2048)
    1048                 :         478 :             skiptablemask = 63;
    1049         [ +  + ]:         204 :         else if (searchlength < 4096)
    1050                 :         159 :             skiptablemask = 127;
    1051                 :             :         else
    1052                 :          45 :             skiptablemask = 255;
    1053                 :        1035 :         state->skiptablemask = skiptablemask;
    1054                 :             : 
    1055                 :             :         /*
    1056                 :             :          * Initialize the skip table.  We set all elements to the needle
    1057                 :             :          * length, since this is the correct skip distance for any character
    1058                 :             :          * not found in the needle.
    1059                 :             :          */
    1060         [ +  + ]:       70859 :         for (i = 0; i <= skiptablemask; i++)
    1061                 :       69824 :             state->skiptable[i] = len2;
    1062                 :             : 
    1063                 :             :         /*
    1064                 :             :          * Now examine the needle.  For each character except the last one,
    1065                 :             :          * set the corresponding table element to the appropriate skip
    1066                 :             :          * distance.  Note that when two characters share the same skip table
    1067                 :             :          * entry, the one later in the needle must determine the skip
    1068                 :             :          * distance.
    1069                 :             :          */
    1070                 :        1035 :         last = len2 - 1;
    1071                 :             : 
    1072         [ +  + ]:       12752 :         for (i = 0; i < last; i++)
    1073                 :       11717 :             state->skiptable[(unsigned char) str2[i] & skiptablemask] = last - i;
    1074                 :             :     }
    1075                 :        1293 : }
    1076                 :             : 
    1077                 :             : /*
    1078                 :             :  * Advance to the next match, starting from the end of the previous match
    1079                 :             :  * (or the beginning of the string, on first call).  Returns true if a match
    1080                 :             :  * is found.
    1081                 :             :  *
    1082                 :             :  * Note that this refuses to match an empty-string needle.  Most callers
    1083                 :             :  * will have handled that case specially and we'll never see it here.
    1084                 :             :  */
    1085                 :             : static bool
    1086                 :        6326 : text_position_next(TextPositionState *state)
    1087                 :             : {
    1088                 :        6326 :     int         needle_len = state->len2;
    1089                 :             :     char       *start_ptr;
    1090                 :             :     char       *matchptr;
    1091                 :             : 
    1092         [ -  + ]:        6326 :     if (needle_len <= 0)
    1093                 :           0 :         return false;           /* result for empty pattern */
    1094                 :             : 
    1095                 :             :     /* Start from the point right after the previous match. */
    1096         [ +  + ]:        6326 :     if (state->last_match)
    1097                 :        5019 :         start_ptr = state->last_match + state->last_match_len;
    1098                 :             :     else
    1099                 :        1307 :         start_ptr = state->str1;
    1100                 :             : 
    1101                 :        6326 : retry:
    1102                 :        6326 :     matchptr = text_position_next_internal(start_ptr, state);
    1103                 :             : 
    1104         [ +  + ]:        6326 :     if (!matchptr)
    1105                 :        1225 :         return false;
    1106                 :             : 
    1107                 :             :     /*
    1108                 :             :      * Found a match for the byte sequence.  If this is a multibyte encoding,
    1109                 :             :      * where one character's byte sequence can appear inside a longer
    1110                 :             :      * multi-byte character, we need to verify that the match was at a
    1111                 :             :      * character boundary, not in the middle of a multi-byte character.
    1112                 :             :      */
    1113   [ -  +  -  - ]:        5101 :     if (state->is_multibyte_char_in_char && state->locale->deterministic)
    1114                 :             :     {
    1115                 :           0 :         const char *haystack_end = state->str1 + state->len1;
    1116                 :             : 
    1117                 :             :         /* Walk one character at a time, until we reach the match. */
    1118                 :             : 
    1119                 :             :         /* the search should never move backwards. */
    1120                 :             :         Assert(state->refpoint <= matchptr);
    1121                 :             : 
    1122         [ #  # ]:           0 :         while (state->refpoint < matchptr)
    1123                 :             :         {
    1124                 :             :             /* step to next character. */
    1125                 :           0 :             state->refpoint += pg_mblen_range(state->refpoint, haystack_end);
    1126                 :           0 :             state->refpos++;
    1127                 :             : 
    1128                 :             :             /*
    1129                 :             :              * If we stepped over the match's start position, then it was a
    1130                 :             :              * false positive, where the byte sequence appeared in the middle
    1131                 :             :              * of a multi-byte character.  Skip it, and continue the search at
    1132                 :             :              * the next character boundary.
    1133                 :             :              */
    1134         [ #  # ]:           0 :             if (state->refpoint > matchptr)
    1135                 :             :             {
    1136                 :           0 :                 start_ptr = state->refpoint;
    1137                 :           0 :                 goto retry;
    1138                 :             :             }
    1139                 :             :         }
    1140                 :             :     }
    1141                 :             : 
    1142                 :        5101 :     state->last_match = matchptr;
    1143                 :        5101 :     state->last_match_len = state->last_match_len_tmp;
    1144                 :        5101 :     return true;
    1145                 :             : }
    1146                 :             : 
    1147                 :             : /*
    1148                 :             :  * Subroutine of text_position_next().  This searches for the raw byte
    1149                 :             :  * sequence, ignoring any multi-byte encoding issues.  Returns the first
    1150                 :             :  * match starting at 'start_ptr', or NULL if no match is found.
    1151                 :             :  */
    1152                 :             : static char *
    1153                 :        6326 : text_position_next_internal(char *start_ptr, TextPositionState *state)
    1154                 :             : {
    1155                 :        6326 :     int         haystack_len = state->len1;
    1156                 :        6326 :     int         needle_len = state->len2;
    1157                 :        6326 :     int         skiptablemask = state->skiptablemask;
    1158                 :        6326 :     const char *haystack = state->str1;
    1159                 :        6326 :     char       *needle = state->str2;
    1160                 :        6326 :     const char *haystack_end = &haystack[haystack_len];
    1161                 :             :     char       *hptr;
    1162                 :             : 
    1163                 :             :     Assert(start_ptr >= haystack && start_ptr <= haystack_end);
    1164                 :             :     Assert(needle_len > 0);
    1165                 :             : 
    1166                 :        6326 :     state->last_match_len_tmp = needle_len;
    1167                 :             : 
    1168         [ +  + ]:        6326 :     if (!state->locale->deterministic)
    1169                 :             :     {
    1170                 :             :         /*
    1171                 :             :          * With a nondeterministic collation, we have to use an unoptimized
    1172                 :             :          * route.  We walk through the haystack and see if at each position
    1173                 :             :          * there is a substring of the remaining string that is equal to the
    1174                 :             :          * needle under the given collation.
    1175                 :             :          *
    1176                 :             :          * Note, the found substring could have a different length than the
    1177                 :             :          * needle.  Callers that want to skip over the found string need to
    1178                 :             :          * read the length of the found substring from last_match_len rather
    1179                 :             :          * than just using the length of their needle.
    1180                 :             :          *
    1181                 :             :          * Most callers will require "greedy" semantics, meaning that we need
    1182                 :             :          * to find the longest such substring, not the shortest.  For callers
    1183                 :             :          * that don't need greedy semantics, we can finish on the first match.
    1184                 :             :          *
    1185                 :             :          * This loop depends on the assumption that the needle is nonempty and
    1186                 :             :          * any matching substring must also be nonempty.  (Even if the
    1187                 :             :          * collation would accept an empty match, returning one would send
    1188                 :             :          * callers that search for successive matches into an infinite loop.)
    1189                 :             :          */
    1190                 :         176 :         char       *result_hptr = NULL;
    1191                 :             : 
    1192                 :         176 :         hptr = start_ptr;
    1193         [ +  + ]:         482 :         while (hptr < haystack_end)
    1194                 :             :         {
    1195                 :             :             const char *test_end;
    1196                 :             : 
    1197                 :             :             /*
    1198                 :             :              * First check the common case that there is a match in the
    1199                 :             :              * haystack of exactly the length of the needle.
    1200                 :             :              */
    1201         [ +  + ]:         403 :             if (!state->greedy &&
    1202   [ +  -  +  + ]:          72 :                 haystack_end - hptr >= needle_len &&
    1203                 :          36 :                 pg_strncoll(hptr, needle_len, needle, needle_len, state->locale) == 0)
    1204                 :           8 :                 return hptr;
    1205                 :             : 
    1206                 :             :             /*
    1207                 :             :              * Else check if any of the non-empty substrings starting at hptr
    1208                 :             :              * compare equal to the needle.
    1209                 :             :              */
    1210                 :         395 :             test_end = hptr;
    1211                 :             :             do
    1212                 :             :             {
    1213                 :        1583 :                 test_end += pg_mblen_range(test_end, haystack_end);
    1214         [ +  + ]:        1583 :                 if (pg_strncoll(hptr, (test_end - hptr), needle, needle_len, state->locale) == 0)
    1215                 :             :                 {
    1216                 :          97 :                     state->last_match_len_tmp = (test_end - hptr);
    1217                 :          97 :                     result_hptr = hptr;
    1218         [ -  + ]:          97 :                     if (!state->greedy)
    1219                 :           0 :                         break;
    1220                 :             :                 }
    1221         [ +  + ]:        1583 :             } while (test_end < haystack_end);
    1222                 :             : 
    1223         [ +  + ]:         395 :             if (result_hptr)
    1224                 :          89 :                 break;
    1225                 :             : 
    1226                 :         306 :             hptr += pg_mblen_range(hptr, haystack_end);
    1227                 :             :         }
    1228                 :             : 
    1229                 :         168 :         return result_hptr;
    1230                 :             :     }
    1231         [ +  + ]:        6150 :     else if (needle_len == 1)
    1232                 :             :     {
    1233                 :             :         /* No point in using B-M-H for a one-character needle */
    1234                 :         605 :         char        nchar = *needle;
    1235                 :             : 
    1236                 :         605 :         hptr = start_ptr;
    1237         [ +  + ]:        4322 :         while (hptr < haystack_end)
    1238                 :             :         {
    1239         [ +  + ]:        4184 :             if (*hptr == nchar)
    1240                 :         467 :                 return hptr;
    1241                 :        3717 :             hptr++;
    1242                 :             :         }
    1243                 :             :     }
    1244                 :             :     else
    1245                 :             :     {
    1246                 :        5545 :         char       *needle_last = &needle[needle_len - 1];
    1247                 :             : 
    1248                 :             :         /* Start at startpos plus the length of the needle */
    1249                 :        5545 :         hptr = start_ptr + needle_len - 1;
    1250         [ +  + ]:      132903 :         while (hptr < haystack_end)
    1251                 :             :         {
    1252                 :             :             /* Match the needle scanning *backward* */
    1253                 :             :             char       *nptr;
    1254                 :             :             char       *p;
    1255                 :             : 
    1256                 :      131895 :             nptr = needle_last;
    1257                 :      131895 :             p = hptr;
    1258         [ +  + ]:      199106 :             while (*nptr == *p)
    1259                 :             :             {
    1260                 :             :                 /* Matched it all?  If so, return 1-based position */
    1261         [ +  + ]:       71748 :                 if (nptr == needle)
    1262                 :        4537 :                     return p;
    1263                 :       67211 :                 nptr--, p--;
    1264                 :             :             }
    1265                 :             : 
    1266                 :             :             /*
    1267                 :             :              * No match, so use the haystack char at hptr to decide how far to
    1268                 :             :              * advance.  If the needle had any occurrence of that character
    1269                 :             :              * (or more precisely, one sharing the same skiptable entry)
    1270                 :             :              * before its last character, then we advance far enough to align
    1271                 :             :              * the last such needle character with that haystack position.
    1272                 :             :              * Otherwise we can advance by the whole needle length.
    1273                 :             :              */
    1274                 :      127358 :             hptr += state->skiptable[(unsigned char) *hptr & skiptablemask];
    1275                 :             :         }
    1276                 :             :     }
    1277                 :             : 
    1278                 :        1146 :     return 0;                   /* not found */
    1279                 :             : }
    1280                 :             : 
    1281                 :             : /*
    1282                 :             :  * Return a pointer to the current match.
    1283                 :             :  *
    1284                 :             :  * The returned pointer points into the original haystack string.
    1285                 :             :  */
    1286                 :             : static char *
    1287                 :        5014 : text_position_get_match_ptr(TextPositionState *state)
    1288                 :             : {
    1289                 :        5014 :     return state->last_match;
    1290                 :             : }
    1291                 :             : 
    1292                 :             : /*
    1293                 :             :  * Return the offset of the current match.
    1294                 :             :  *
    1295                 :             :  * The offset is in characters, 1-based.
    1296                 :             :  */
    1297                 :             : static int
    1298                 :          50 : text_position_get_match_pos(TextPositionState *state)
    1299                 :             : {
    1300                 :             :     /* Convert the byte position to char position. */
    1301                 :         100 :     state->refpos += pg_mbstrlen_with_len(state->refpoint,
    1302                 :          50 :                                           state->last_match - state->refpoint);
    1303                 :          50 :     state->refpoint = state->last_match;
    1304                 :          50 :     return state->refpos + 1;
    1305                 :             : }
    1306                 :             : 
    1307                 :             : /*
    1308                 :             :  * Reset search state to the initial state installed by text_position_setup.
    1309                 :             :  *
    1310                 :             :  * The next call to text_position_next will search from the beginning
    1311                 :             :  * of the string.
    1312                 :             :  */
    1313                 :             : static void
    1314                 :          14 : text_position_reset(TextPositionState *state)
    1315                 :             : {
    1316                 :          14 :     state->last_match = NULL;
    1317                 :          14 :     state->refpoint = state->str1;
    1318                 :          14 :     state->refpos = 0;
    1319                 :          14 : }
    1320                 :             : 
    1321                 :             : static void
    1322                 :        1293 : text_position_cleanup(TextPositionState *state)
    1323                 :             : {
    1324                 :             :     /* no cleanup needed */
    1325                 :        1293 : }
    1326                 :             : 
    1327                 :             : 
    1328                 :             : static void
    1329                 :    13037183 : check_collation_set(Oid collid)
    1330                 :             : {
    1331         [ +  + ]:    13037183 :     if (!OidIsValid(collid))
    1332                 :             :     {
    1333                 :             :         /*
    1334                 :             :          * This typically means that the parser could not resolve a conflict
    1335                 :             :          * of implicit collations, so report it that way.
    1336                 :             :          */
    1337         [ +  - ]:          20 :         ereport(ERROR,
    1338                 :             :                 (errcode(ERRCODE_INDETERMINATE_COLLATION),
    1339                 :             :                  errmsg("could not determine which collation to use for string comparison"),
    1340                 :             :                  errhint("Use the COLLATE clause to set the collation explicitly.")));
    1341                 :             :     }
    1342                 :    13037163 : }
    1343                 :             : 
    1344                 :             : /*
    1345                 :             :  * varstr_cmp()
    1346                 :             :  *
    1347                 :             :  * Comparison function for text strings with given lengths, using the
    1348                 :             :  * appropriate locale. Returns an integer less than, equal to, or greater than
    1349                 :             :  * zero, indicating whether arg1 is less than, equal to, or greater than arg2.
    1350                 :             :  *
    1351                 :             :  * Note: many functions that depend on this are marked leakproof; therefore,
    1352                 :             :  * avoid reporting the actual contents of the input when throwing errors.
    1353                 :             :  * All errors herein should be things that can't happen except on corrupt
    1354                 :             :  * data, anyway; otherwise we will have trouble with indexing strings that
    1355                 :             :  * would cause them.
    1356                 :             :  */
    1357                 :             : int
    1358                 :     6233039 : varstr_cmp(const char *arg1, int len1, const char *arg2, int len2, Oid collid)
    1359                 :             : {
    1360                 :             :     int         result;
    1361                 :             :     pg_locale_t mylocale;
    1362                 :             : 
    1363                 :     6233039 :     check_collation_set(collid);
    1364                 :             : 
    1365                 :     6233027 :     mylocale = pg_newlocale_from_collation(collid);
    1366                 :             : 
    1367         [ +  + ]:     6233027 :     if (mylocale->collate_is_c)
    1368                 :             :     {
    1369                 :     2372752 :         result = memcmp(arg1, arg2, Min(len1, len2));
    1370   [ +  +  +  + ]:     2372752 :         if ((result == 0) && (len1 != len2))
    1371         [ +  + ]:       83161 :             result = (len1 < len2) ? -1 : 1;
    1372                 :             :     }
    1373                 :             :     else
    1374                 :             :     {
    1375                 :             :         /*
    1376                 :             :          * memcmp() can't tell us which of two unequal strings sorts first,
    1377                 :             :          * but it's a cheap way to tell if they're equal.  Testing shows that
    1378                 :             :          * memcmp() followed by strcoll() is only trivially slower than
    1379                 :             :          * strcoll() by itself, so we don't lose much if this doesn't work out
    1380                 :             :          * very often, and if it does - for example, because there are many
    1381                 :             :          * equal strings in the input - then we win big by avoiding expensive
    1382                 :             :          * collation-aware comparisons.
    1383                 :             :          */
    1384   [ +  +  +  + ]:     3860275 :         if (len1 == len2 && memcmp(arg1, arg2, len1) == 0)
    1385                 :     1061058 :             return 0;
    1386                 :             : 
    1387                 :     2799217 :         result = pg_strncoll(arg1, len1, arg2, len2, mylocale);
    1388                 :             : 
    1389                 :             :         /* Break tie if necessary. */
    1390   [ +  +  -  + ]:     2799217 :         if (result == 0 && mylocale->deterministic)
    1391                 :             :         {
    1392                 :           0 :             result = memcmp(arg1, arg2, Min(len1, len2));
    1393   [ #  #  #  # ]:           0 :             if ((result == 0) && (len1 != len2))
    1394         [ #  # ]:           0 :                 result = (len1 < len2) ? -1 : 1;
    1395                 :             :         }
    1396                 :             :     }
    1397                 :             : 
    1398                 :     5171969 :     return result;
    1399                 :             : }
    1400                 :             : 
    1401                 :             : /*
    1402                 :             :  * text_cmp()
    1403                 :             :  * Internal comparison function for text strings.
    1404                 :             :  * Returns -1, 0 or 1
    1405                 :             :  */
    1406                 :             : static int
    1407                 :     4833625 : text_cmp(text *arg1, text *arg2, Oid collid)
    1408                 :             : {
    1409                 :             :     char       *a1p,
    1410                 :             :                *a2p;
    1411                 :             :     int         len1,
    1412                 :             :                 len2;
    1413                 :             : 
    1414                 :     4833625 :     a1p = VARDATA_ANY(arg1);
    1415                 :     4833625 :     a2p = VARDATA_ANY(arg2);
    1416                 :             : 
    1417                 :     4833625 :     len1 = VARSIZE_ANY_EXHDR(arg1);
    1418                 :     4833625 :     len2 = VARSIZE_ANY_EXHDR(arg2);
    1419                 :             : 
    1420                 :     4833625 :     return varstr_cmp(a1p, len1, a2p, len2, collid);
    1421                 :             : }
    1422                 :             : 
    1423                 :             : /*
    1424                 :             :  * Comparison functions for text strings.
    1425                 :             :  *
    1426                 :             :  * Note: btree indexes need these routines not to leak memory; therefore,
    1427                 :             :  * be careful to free working copies of toasted datums.  Most places don't
    1428                 :             :  * need to be so careful.
    1429                 :             :  */
    1430                 :             : 
    1431                 :             : Datum
    1432                 :     6173189 : texteq(PG_FUNCTION_ARGS)
    1433                 :             : {
    1434                 :     6173189 :     Oid         collid = PG_GET_COLLATION();
    1435                 :     6173189 :     pg_locale_t mylocale = 0;
    1436                 :             :     bool        result;
    1437                 :             : 
    1438                 :     6173189 :     check_collation_set(collid);
    1439                 :             : 
    1440                 :     6173189 :     mylocale = pg_newlocale_from_collation(collid);
    1441                 :             : 
    1442         [ +  + ]:     6173189 :     if (mylocale->deterministic)
    1443                 :             :     {
    1444                 :     6166775 :         Datum       arg1 = PG_GETARG_DATUM(0);
    1445                 :     6166775 :         Datum       arg2 = PG_GETARG_DATUM(1);
    1446                 :             :         Size        len1,
    1447                 :             :                     len2;
    1448                 :             : 
    1449                 :             :         /*
    1450                 :             :          * Since we only care about equality or not-equality, we can avoid all
    1451                 :             :          * the expense of strcoll() here, and just do bitwise comparison.  In
    1452                 :             :          * fact, we don't even have to do a bitwise comparison if we can show
    1453                 :             :          * the lengths of the strings are unequal; which might save us from
    1454                 :             :          * having to detoast one or both values.
    1455                 :             :          */
    1456                 :     6166775 :         len1 = toast_raw_datum_size(arg1);
    1457                 :     6166775 :         len2 = toast_raw_datum_size(arg2);
    1458         [ +  + ]:     6166775 :         if (len1 != len2)
    1459                 :     3553349 :             result = false;
    1460                 :             :         else
    1461                 :             :         {
    1462                 :     2613426 :             text       *targ1 = DatumGetTextPP(arg1);
    1463                 :     2613426 :             text       *targ2 = DatumGetTextPP(arg2);
    1464                 :             : 
    1465                 :     2613426 :             result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2),
    1466                 :             :                              len1 - VARHDRSZ) == 0);
    1467                 :             : 
    1468         [ +  + ]:     2613426 :             PG_FREE_IF_COPY(targ1, 0);
    1469         [ +  + ]:     2613426 :             PG_FREE_IF_COPY(targ2, 1);
    1470                 :             :         }
    1471                 :             :     }
    1472                 :             :     else
    1473                 :             :     {
    1474                 :        6414 :         text       *arg1 = PG_GETARG_TEXT_PP(0);
    1475                 :        6414 :         text       *arg2 = PG_GETARG_TEXT_PP(1);
    1476                 :             : 
    1477                 :        6414 :         result = (text_cmp(arg1, arg2, collid) == 0);
    1478                 :             : 
    1479         [ -  + ]:        6414 :         PG_FREE_IF_COPY(arg1, 0);
    1480         [ -  + ]:        6414 :         PG_FREE_IF_COPY(arg2, 1);
    1481                 :             :     }
    1482                 :             : 
    1483                 :     6173189 :     PG_RETURN_BOOL(result);
    1484                 :             : }
    1485                 :             : 
    1486                 :             : Datum
    1487                 :      208488 : textne(PG_FUNCTION_ARGS)
    1488                 :             : {
    1489                 :      208488 :     Oid         collid = PG_GET_COLLATION();
    1490                 :             :     pg_locale_t mylocale;
    1491                 :             :     bool        result;
    1492                 :             : 
    1493                 :      208488 :     check_collation_set(collid);
    1494                 :             : 
    1495                 :      208488 :     mylocale = pg_newlocale_from_collation(collid);
    1496                 :             : 
    1497         [ +  + ]:      208488 :     if (mylocale->deterministic)
    1498                 :             :     {
    1499                 :      208472 :         Datum       arg1 = PG_GETARG_DATUM(0);
    1500                 :      208472 :         Datum       arg2 = PG_GETARG_DATUM(1);
    1501                 :             :         Size        len1,
    1502                 :             :                     len2;
    1503                 :             : 
    1504                 :             :         /* See comment in texteq() */
    1505                 :      208472 :         len1 = toast_raw_datum_size(arg1);
    1506                 :      208472 :         len2 = toast_raw_datum_size(arg2);
    1507         [ +  + ]:      208472 :         if (len1 != len2)
    1508                 :       11690 :             result = true;
    1509                 :             :         else
    1510                 :             :         {
    1511                 :      196782 :             text       *targ1 = DatumGetTextPP(arg1);
    1512                 :      196782 :             text       *targ2 = DatumGetTextPP(arg2);
    1513                 :             : 
    1514                 :      196782 :             result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2),
    1515                 :             :                              len1 - VARHDRSZ) != 0);
    1516                 :             : 
    1517         [ -  + ]:      196782 :             PG_FREE_IF_COPY(targ1, 0);
    1518         [ -  + ]:      196782 :             PG_FREE_IF_COPY(targ2, 1);
    1519                 :             :         }
    1520                 :             :     }
    1521                 :             :     else
    1522                 :             :     {
    1523                 :          16 :         text       *arg1 = PG_GETARG_TEXT_PP(0);
    1524                 :          16 :         text       *arg2 = PG_GETARG_TEXT_PP(1);
    1525                 :             : 
    1526                 :          16 :         result = (text_cmp(arg1, arg2, collid) != 0);
    1527                 :             : 
    1528         [ -  + ]:          16 :         PG_FREE_IF_COPY(arg1, 0);
    1529         [ -  + ]:          16 :         PG_FREE_IF_COPY(arg2, 1);
    1530                 :             :     }
    1531                 :             : 
    1532                 :      208488 :     PG_RETURN_BOOL(result);
    1533                 :             : }
    1534                 :             : 
    1535                 :             : Datum
    1536                 :      236762 : text_lt(PG_FUNCTION_ARGS)
    1537                 :             : {
    1538                 :      236762 :     text       *arg1 = PG_GETARG_TEXT_PP(0);
    1539                 :      236762 :     text       *arg2 = PG_GETARG_TEXT_PP(1);
    1540                 :             :     bool        result;
    1541                 :             : 
    1542                 :      236762 :     result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) < 0);
    1543                 :             : 
    1544         [ +  + ]:      236750 :     PG_FREE_IF_COPY(arg1, 0);
    1545         [ -  + ]:      236750 :     PG_FREE_IF_COPY(arg2, 1);
    1546                 :             : 
    1547                 :      236750 :     PG_RETURN_BOOL(result);
    1548                 :             : }
    1549                 :             : 
    1550                 :             : Datum
    1551                 :      213778 : text_le(PG_FUNCTION_ARGS)
    1552                 :             : {
    1553                 :      213778 :     text       *arg1 = PG_GETARG_TEXT_PP(0);
    1554                 :      213778 :     text       *arg2 = PG_GETARG_TEXT_PP(1);
    1555                 :             :     bool        result;
    1556                 :             : 
    1557                 :      213778 :     result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) <= 0);
    1558                 :             : 
    1559         [ +  + ]:      213778 :     PG_FREE_IF_COPY(arg1, 0);
    1560         [ +  + ]:      213778 :     PG_FREE_IF_COPY(arg2, 1);
    1561                 :             : 
    1562                 :      213778 :     PG_RETURN_BOOL(result);
    1563                 :             : }
    1564                 :             : 
    1565                 :             : Datum
    1566                 :      215858 : text_gt(PG_FUNCTION_ARGS)
    1567                 :             : {
    1568                 :      215858 :     text       *arg1 = PG_GETARG_TEXT_PP(0);
    1569                 :      215858 :     text       *arg2 = PG_GETARG_TEXT_PP(1);
    1570                 :             :     bool        result;
    1571                 :             : 
    1572                 :      215858 :     result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) > 0);
    1573                 :             : 
    1574         [ +  + ]:      215858 :     PG_FREE_IF_COPY(arg1, 0);
    1575         [ -  + ]:      215858 :     PG_FREE_IF_COPY(arg2, 1);
    1576                 :             : 
    1577                 :      215858 :     PG_RETURN_BOOL(result);
    1578                 :             : }
    1579                 :             : 
    1580                 :             : Datum
    1581                 :      116371 : text_ge(PG_FUNCTION_ARGS)
    1582                 :             : {
    1583                 :      116371 :     text       *arg1 = PG_GETARG_TEXT_PP(0);
    1584                 :      116371 :     text       *arg2 = PG_GETARG_TEXT_PP(1);
    1585                 :             :     bool        result;
    1586                 :             : 
    1587                 :      116371 :     result = (text_cmp(arg1, arg2, PG_GET_COLLATION()) >= 0);
    1588                 :             : 
    1589         [ +  + ]:      116371 :     PG_FREE_IF_COPY(arg1, 0);
    1590         [ -  + ]:      116371 :     PG_FREE_IF_COPY(arg2, 1);
    1591                 :             : 
    1592                 :      116371 :     PG_RETURN_BOOL(result);
    1593                 :             : }
    1594                 :             : 
    1595                 :             : Datum
    1596                 :       25280 : text_starts_with(PG_FUNCTION_ARGS)
    1597                 :             : {
    1598                 :       25280 :     Datum       arg1 = PG_GETARG_DATUM(0);
    1599                 :       25280 :     Datum       arg2 = PG_GETARG_DATUM(1);
    1600                 :       25280 :     Oid         collid = PG_GET_COLLATION();
    1601                 :             :     pg_locale_t mylocale;
    1602                 :             :     bool        result;
    1603                 :             :     Size        len1,
    1604                 :             :                 len2;
    1605                 :             : 
    1606                 :       25280 :     check_collation_set(collid);
    1607                 :             : 
    1608                 :       25280 :     mylocale = pg_newlocale_from_collation(collid);
    1609                 :             : 
    1610         [ -  + ]:       25280 :     if (!mylocale->deterministic)
    1611         [ #  # ]:           0 :         ereport(ERROR,
    1612                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1613                 :             :                  errmsg("nondeterministic collations are not supported for substring searches")));
    1614                 :             : 
    1615                 :       25280 :     len1 = toast_raw_datum_size(arg1);
    1616                 :       25280 :     len2 = toast_raw_datum_size(arg2);
    1617         [ -  + ]:       25280 :     if (len2 > len1)
    1618                 :           0 :         result = false;
    1619                 :             :     else
    1620                 :             :     {
    1621                 :       25280 :         text       *targ1 = text_substring(arg1, 1, len2, false);
    1622                 :       25280 :         text       *targ2 = DatumGetTextPP(arg2);
    1623                 :             : 
    1624                 :       25280 :         result = (memcmp(VARDATA_ANY(targ1), VARDATA_ANY(targ2),
    1625                 :             :                          VARSIZE_ANY_EXHDR(targ2)) == 0);
    1626                 :             : 
    1627         [ +  - ]:       25280 :         PG_FREE_IF_COPY(targ1, 0);
    1628         [ -  + ]:       25280 :         PG_FREE_IF_COPY(targ2, 1);
    1629                 :             :     }
    1630                 :             : 
    1631                 :       25280 :     PG_RETURN_BOOL(result);
    1632                 :             : }
    1633                 :             : 
    1634                 :             : Datum
    1635                 :     3847979 : bttextcmp(PG_FUNCTION_ARGS)
    1636                 :             : {
    1637                 :     3847979 :     text       *arg1 = PG_GETARG_TEXT_PP(0);
    1638                 :     3847979 :     text       *arg2 = PG_GETARG_TEXT_PP(1);
    1639                 :             :     int32       result;
    1640                 :             : 
    1641                 :     3847979 :     result = text_cmp(arg1, arg2, PG_GET_COLLATION());
    1642                 :             : 
    1643         [ +  + ]:     3847979 :     PG_FREE_IF_COPY(arg1, 0);
    1644         [ +  + ]:     3847979 :     PG_FREE_IF_COPY(arg2, 1);
    1645                 :             : 
    1646                 :     3847979 :     PG_RETURN_INT32(result);
    1647                 :             : }
    1648                 :             : 
    1649                 :             : Datum
    1650                 :       51140 : bttextsortsupport(PG_FUNCTION_ARGS)
    1651                 :             : {
    1652                 :       51140 :     SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
    1653                 :       51140 :     Oid         collid = ssup->ssup_collation;
    1654                 :             :     MemoryContext oldcontext;
    1655                 :             : 
    1656                 :       51140 :     oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
    1657                 :             : 
    1658                 :             :     /* Use generic string SortSupport */
    1659                 :       51140 :     varstr_sortsupport(ssup, TEXTOID, collid);
    1660                 :             : 
    1661                 :       51132 :     MemoryContextSwitchTo(oldcontext);
    1662                 :             : 
    1663                 :       51132 :     PG_RETURN_VOID();
    1664                 :             : }
    1665                 :             : 
    1666                 :             : /*
    1667                 :             :  * Generic sortsupport interface for character type's operator classes.
    1668                 :             :  * Includes locale support, and support for BpChar semantics (i.e. removing
    1669                 :             :  * trailing spaces before comparison).
    1670                 :             :  *
    1671                 :             :  * Relies on the assumption that text, VarChar, and BpChar all have the
    1672                 :             :  * same representation.
    1673                 :             :  */
    1674                 :             : void
    1675                 :       86437 : varstr_sortsupport(SortSupport ssup, Oid typid, Oid collid)
    1676                 :             : {
    1677                 :       86437 :     bool        abbreviate = ssup->abbreviate;
    1678                 :       86437 :     bool        collate_c = false;
    1679                 :             :     VarStringSortSupport *sss;
    1680                 :             :     pg_locale_t locale;
    1681                 :             : 
    1682                 :       86437 :     check_collation_set(collid);
    1683                 :             : 
    1684                 :       86429 :     locale = pg_newlocale_from_collation(collid);
    1685                 :             : 
    1686                 :             :     /*
    1687                 :             :      * If possible, set ssup->comparator to a function which can be used to
    1688                 :             :      * directly compare two datums.  If we can do this, we'll avoid the
    1689                 :             :      * overhead of a trip through the fmgr layer for every comparison, which
    1690                 :             :      * can be substantial.
    1691                 :             :      *
    1692                 :             :      * Most typically, we'll set the comparator to varlenafastcmp_locale,
    1693                 :             :      * which uses strcoll() to perform comparisons.  We use that for the
    1694                 :             :      * BpChar case too, but type NAME uses namefastcmp_locale. However, if
    1695                 :             :      * LC_COLLATE = C, we can make things quite a bit faster with
    1696                 :             :      * varstrfastcmp_c, bpcharfastcmp_c, or namefastcmp_c, all of which use
    1697                 :             :      * memcmp() rather than strcoll().
    1698                 :             :      */
    1699         [ +  + ]:       86429 :     if (locale->collate_is_c)
    1700                 :             :     {
    1701         [ +  + ]:       58893 :         if (typid == BPCHAROID)
    1702                 :         158 :             ssup->comparator = bpcharfastcmp_c;
    1703         [ +  + ]:       58735 :         else if (typid == NAMEOID)
    1704                 :             :         {
    1705                 :       34631 :             ssup->comparator = namefastcmp_c;
    1706                 :             :             /* Not supporting abbreviation with type NAME, for now */
    1707                 :       34631 :             abbreviate = false;
    1708                 :             :         }
    1709                 :             :         else
    1710                 :       24104 :             ssup->comparator = varstrfastcmp_c;
    1711                 :             : 
    1712                 :       58893 :         collate_c = true;
    1713                 :             :     }
    1714                 :             :     else
    1715                 :             :     {
    1716                 :             :         /*
    1717                 :             :          * We use varlenafastcmp_locale except for type NAME.
    1718                 :             :          */
    1719         [ -  + ]:       27536 :         if (typid == NAMEOID)
    1720                 :             :         {
    1721                 :           0 :             ssup->comparator = namefastcmp_locale;
    1722                 :             :             /* Not supporting abbreviation with type NAME, for now */
    1723                 :           0 :             abbreviate = false;
    1724                 :             :         }
    1725                 :             :         else
    1726                 :       27536 :             ssup->comparator = varlenafastcmp_locale;
    1727                 :             : 
    1728                 :             :         /*
    1729                 :             :          * Unfortunately, it seems that abbreviation for non-C collations is
    1730                 :             :          * broken on many common platforms; see pg_strxfrm_enabled().
    1731                 :             :          *
    1732                 :             :          * Even apart from the risk of broken locales, it's possible that
    1733                 :             :          * there are platforms where the use of abbreviated keys should be
    1734                 :             :          * disabled at compile time.  For example, macOS's strxfrm()
    1735                 :             :          * implementation is known to not effectively concentrate a
    1736                 :             :          * significant amount of entropy from the original string in earlier
    1737                 :             :          * transformed blobs.  It's possible that other supported platforms
    1738                 :             :          * are similarly encumbered.  So, if we ever get past disabling this
    1739                 :             :          * categorically, we may still want or need to disable it for
    1740                 :             :          * particular platforms.
    1741                 :             :          */
    1742         [ +  + ]:       27536 :         if (!pg_strxfrm_enabled(locale))
    1743                 :       26909 :             abbreviate = false;
    1744                 :             :     }
    1745                 :             : 
    1746                 :             :     /*
    1747                 :             :      * If we're using abbreviated keys, or if we're using a locale-aware
    1748                 :             :      * comparison, we need to initialize a VarStringSortSupport object. Both
    1749                 :             :      * cases will make use of the temporary buffers we initialize here for
    1750                 :             :      * scratch space (and to detect requirement for BpChar semantics from
    1751                 :             :      * caller), and the abbreviation case requires additional state.
    1752                 :             :      */
    1753   [ +  +  +  + ]:       86429 :     if (abbreviate || !collate_c)
    1754                 :             :     {
    1755                 :       40297 :         sss = palloc_object(VarStringSortSupport);
    1756                 :       40297 :         sss->buf1 = palloc(TEXTBUFLEN);
    1757                 :       40297 :         sss->buflen1 = TEXTBUFLEN;
    1758                 :       40297 :         sss->buf2 = palloc(TEXTBUFLEN);
    1759                 :       40297 :         sss->buflen2 = TEXTBUFLEN;
    1760                 :             :         /* Start with invalid values */
    1761                 :       40297 :         sss->last_len1 = -1;
    1762                 :       40297 :         sss->last_len2 = -1;
    1763                 :             :         /* Initialize */
    1764                 :       40297 :         sss->last_returned = 0;
    1765         [ +  + ]:       40297 :         if (collate_c)
    1766                 :       12761 :             sss->locale = NULL;
    1767                 :             :         else
    1768                 :       27536 :             sss->locale = locale;
    1769                 :             : 
    1770                 :             :         /*
    1771                 :             :          * To avoid somehow confusing a strxfrm() blob and an original string,
    1772                 :             :          * constantly keep track of the variety of data that buf1 and buf2
    1773                 :             :          * currently contain.
    1774                 :             :          *
    1775                 :             :          * Comparisons may be interleaved with conversion calls.  Frequently,
    1776                 :             :          * conversions and comparisons are batched into two distinct phases,
    1777                 :             :          * but the correctness of caching cannot hinge upon this.  For
    1778                 :             :          * comparison caching, buffer state is only trusted if cache_blob is
    1779                 :             :          * found set to false, whereas strxfrm() caching only trusts the state
    1780                 :             :          * when cache_blob is found set to true.
    1781                 :             :          *
    1782                 :             :          * Arbitrarily initialize cache_blob to true.
    1783                 :             :          */
    1784                 :       40297 :         sss->cache_blob = true;
    1785                 :       40297 :         sss->collate_c = collate_c;
    1786                 :       40297 :         sss->typid = typid;
    1787                 :       40297 :         ssup->ssup_extra = sss;
    1788                 :             : 
    1789                 :             :         /*
    1790                 :             :          * If possible, plan to use the abbreviated keys optimization.  The
    1791                 :             :          * core code may switch back to authoritative comparator should
    1792                 :             :          * abbreviation be aborted.
    1793                 :             :          */
    1794         [ +  + ]:       40297 :         if (abbreviate)
    1795                 :             :         {
    1796                 :       13232 :             sss->prop_card = 0.20;
    1797                 :       13232 :             initHyperLogLog(&sss->abbr_card, 10);
    1798                 :       13232 :             initHyperLogLog(&sss->full_card, 10);
    1799                 :       13232 :             ssup->abbrev_full_comparator = ssup->comparator;
    1800                 :       13232 :             ssup->comparator = ssup_datum_uint64_cmp;
    1801                 :       13232 :             ssup->abbrev_converter = varstr_abbrev_convert;
    1802                 :       13232 :             ssup->abbrev_abort = varstr_abbrev_abort;
    1803                 :             :         }
    1804                 :             :     }
    1805                 :       86429 : }
    1806                 :             : 
    1807                 :             : /*
    1808                 :             :  * sortsupport comparison func (for C locale case)
    1809                 :             :  */
    1810                 :             : static int
    1811                 :    27346746 : varstrfastcmp_c(Datum x, Datum y, SortSupport ssup)
    1812                 :             : {
    1813                 :    27346746 :     VarString  *arg1 = DatumGetVarStringPP(x);
    1814                 :    27346746 :     VarString  *arg2 = DatumGetVarStringPP(y);
    1815                 :             :     char       *a1p,
    1816                 :             :                *a2p;
    1817                 :             :     int         len1,
    1818                 :             :                 len2,
    1819                 :             :                 result;
    1820                 :             : 
    1821                 :    27346746 :     a1p = VARDATA_ANY(arg1);
    1822                 :    27346746 :     a2p = VARDATA_ANY(arg2);
    1823                 :             : 
    1824                 :    27346746 :     len1 = VARSIZE_ANY_EXHDR(arg1);
    1825                 :    27346746 :     len2 = VARSIZE_ANY_EXHDR(arg2);
    1826                 :             : 
    1827                 :    27346746 :     result = memcmp(a1p, a2p, Min(len1, len2));
    1828   [ +  +  +  + ]:    27346746 :     if ((result == 0) && (len1 != len2))
    1829         [ +  + ]:      761633 :         result = (len1 < len2) ? -1 : 1;
    1830                 :             : 
    1831                 :             :     /* We can't afford to leak memory here. */
    1832         [ -  + ]:    27346746 :     if (PointerGetDatum(arg1) != x)
    1833                 :           0 :         pfree(arg1);
    1834         [ -  + ]:    27346746 :     if (PointerGetDatum(arg2) != y)
    1835                 :           0 :         pfree(arg2);
    1836                 :             : 
    1837                 :    27346746 :     return result;
    1838                 :             : }
    1839                 :             : 
    1840                 :             : /*
    1841                 :             :  * sortsupport comparison func (for BpChar C locale case)
    1842                 :             :  *
    1843                 :             :  * BpChar outsources its sortsupport to this module.  Specialization for the
    1844                 :             :  * varstr_sortsupport BpChar case, modeled on
    1845                 :             :  * internal_bpchar_pattern_compare().
    1846                 :             :  */
    1847                 :             : static int
    1848                 :       31838 : bpcharfastcmp_c(Datum x, Datum y, SortSupport ssup)
    1849                 :             : {
    1850                 :       31838 :     BpChar     *arg1 = DatumGetBpCharPP(x);
    1851                 :       31838 :     BpChar     *arg2 = DatumGetBpCharPP(y);
    1852                 :             :     char       *a1p,
    1853                 :             :                *a2p;
    1854                 :             :     int         len1,
    1855                 :             :                 len2,
    1856                 :             :                 result;
    1857                 :             : 
    1858                 :       31838 :     a1p = VARDATA_ANY(arg1);
    1859                 :       31838 :     a2p = VARDATA_ANY(arg2);
    1860                 :             : 
    1861                 :       31838 :     len1 = bpchartruelen(a1p, VARSIZE_ANY_EXHDR(arg1));
    1862                 :       31838 :     len2 = bpchartruelen(a2p, VARSIZE_ANY_EXHDR(arg2));
    1863                 :             : 
    1864                 :       31838 :     result = memcmp(a1p, a2p, Min(len1, len2));
    1865   [ +  +  +  + ]:       31838 :     if ((result == 0) && (len1 != len2))
    1866         [ -  + ]:           2 :         result = (len1 < len2) ? -1 : 1;
    1867                 :             : 
    1868                 :             :     /* We can't afford to leak memory here. */
    1869         [ -  + ]:       31838 :     if (PointerGetDatum(arg1) != x)
    1870                 :           0 :         pfree(arg1);
    1871         [ -  + ]:       31838 :     if (PointerGetDatum(arg2) != y)
    1872                 :           0 :         pfree(arg2);
    1873                 :             : 
    1874                 :       31838 :     return result;
    1875                 :             : }
    1876                 :             : 
    1877                 :             : /*
    1878                 :             :  * sortsupport comparison func (for NAME C locale case)
    1879                 :             :  */
    1880                 :             : static int
    1881                 :    27762971 : namefastcmp_c(Datum x, Datum y, SortSupport ssup)
    1882                 :             : {
    1883                 :    27762971 :     Name        arg1 = DatumGetName(x);
    1884                 :    27762971 :     Name        arg2 = DatumGetName(y);
    1885                 :             : 
    1886                 :    27762971 :     return strncmp(NameStr(*arg1), NameStr(*arg2), NAMEDATALEN);
    1887                 :             : }
    1888                 :             : 
    1889                 :             : /*
    1890                 :             :  * sortsupport comparison func (for locale case with all varlena types)
    1891                 :             :  */
    1892                 :             : static int
    1893                 :    23422321 : varlenafastcmp_locale(Datum x, Datum y, SortSupport ssup)
    1894                 :             : {
    1895                 :    23422321 :     VarString  *arg1 = DatumGetVarStringPP(x);
    1896                 :    23422321 :     VarString  *arg2 = DatumGetVarStringPP(y);
    1897                 :             :     char       *a1p,
    1898                 :             :                *a2p;
    1899                 :             :     int         len1,
    1900                 :             :                 len2,
    1901                 :             :                 result;
    1902                 :             : 
    1903                 :    23422321 :     a1p = VARDATA_ANY(arg1);
    1904                 :    23422321 :     a2p = VARDATA_ANY(arg2);
    1905                 :             : 
    1906                 :    23422321 :     len1 = VARSIZE_ANY_EXHDR(arg1);
    1907                 :    23422321 :     len2 = VARSIZE_ANY_EXHDR(arg2);
    1908                 :             : 
    1909                 :    23422321 :     result = varstrfastcmp_locale(a1p, len1, a2p, len2, ssup);
    1910                 :             : 
    1911                 :             :     /* We can't afford to leak memory here. */
    1912         [ +  + ]:    23422321 :     if (PointerGetDatum(arg1) != x)
    1913                 :          72 :         pfree(arg1);
    1914         [ +  + ]:    23422321 :     if (PointerGetDatum(arg2) != y)
    1915                 :          58 :         pfree(arg2);
    1916                 :             : 
    1917                 :    23422321 :     return result;
    1918                 :             : }
    1919                 :             : 
    1920                 :             : /*
    1921                 :             :  * sortsupport comparison func (for locale case with NAME type)
    1922                 :             :  */
    1923                 :             : static int
    1924                 :           0 : namefastcmp_locale(Datum x, Datum y, SortSupport ssup)
    1925                 :             : {
    1926                 :           0 :     Name        arg1 = DatumGetName(x);
    1927                 :           0 :     Name        arg2 = DatumGetName(y);
    1928                 :             : 
    1929                 :           0 :     return varstrfastcmp_locale(NameStr(*arg1), strlen(NameStr(*arg1)),
    1930                 :           0 :                                 NameStr(*arg2), strlen(NameStr(*arg2)),
    1931                 :             :                                 ssup);
    1932                 :             : }
    1933                 :             : 
    1934                 :             : /*
    1935                 :             :  * sortsupport comparison func for locale cases
    1936                 :             :  */
    1937                 :             : static int
    1938                 :    23422321 : varstrfastcmp_locale(char *a1p, int len1, char *a2p, int len2, SortSupport ssup)
    1939                 :             : {
    1940                 :    23422321 :     VarStringSortSupport *sss = (VarStringSortSupport *) ssup->ssup_extra;
    1941                 :             :     int         result;
    1942                 :             :     bool        arg1_match;
    1943                 :             : 
    1944                 :             :     /* Fast pre-check for equality, as discussed in varstr_cmp() */
    1945   [ +  +  +  + ]:    23422321 :     if (len1 == len2 && memcmp(a1p, a2p, len1) == 0)
    1946                 :             :     {
    1947                 :             :         /*
    1948                 :             :          * No change in buf1 or buf2 contents, so avoid changing last_len1 or
    1949                 :             :          * last_len2.  Existing contents of buffers might still be used by
    1950                 :             :          * next call.
    1951                 :             :          *
    1952                 :             :          * It's fine to allow the comparison of BpChar padding bytes here,
    1953                 :             :          * even though that implies that the memcmp() will usually be
    1954                 :             :          * performed for BpChar callers (though multibyte characters could
    1955                 :             :          * still prevent that from occurring).  The memcmp() is still very
    1956                 :             :          * cheap, and BpChar's funny semantics have us remove trailing spaces
    1957                 :             :          * (not limited to padding), so we need make no distinction between
    1958                 :             :          * padding space characters and "real" space characters.
    1959                 :             :          */
    1960                 :     7037518 :         return 0;
    1961                 :             :     }
    1962                 :             : 
    1963         [ +  + ]:    16384803 :     if (sss->typid == BPCHAROID)
    1964                 :             :     {
    1965                 :             :         /* Get true number of bytes, ignoring trailing spaces */
    1966                 :       23335 :         len1 = bpchartruelen(a1p, len1);
    1967                 :       23335 :         len2 = bpchartruelen(a2p, len2);
    1968                 :             :     }
    1969                 :             : 
    1970         [ +  + ]:    16384803 :     if (len1 >= sss->buflen1)
    1971                 :             :     {
    1972         [ +  - ]:           7 :         sss->buflen1 = Max(len1 + 1, Min(sss->buflen1 * 2, MaxAllocSize));
    1973                 :           7 :         sss->buf1 = repalloc(sss->buf1, sss->buflen1);
    1974                 :             :     }
    1975         [ +  + ]:    16384803 :     if (len2 >= sss->buflen2)
    1976                 :             :     {
    1977         [ +  - ]:           4 :         sss->buflen2 = Max(len2 + 1, Min(sss->buflen2 * 2, MaxAllocSize));
    1978                 :           4 :         sss->buf2 = repalloc(sss->buf2, sss->buflen2);
    1979                 :             :     }
    1980                 :             : 
    1981                 :             :     /*
    1982                 :             :      * We're likely to be asked to compare the same strings repeatedly, and
    1983                 :             :      * memcmp() is so much cheaper than strcoll() that it pays to try to cache
    1984                 :             :      * comparisons, even though in general there is no reason to think that
    1985                 :             :      * that will work out (every string datum may be unique).  Caching does
    1986                 :             :      * not slow things down measurably when it doesn't work out, and can speed
    1987                 :             :      * things up by rather a lot when it does.  In part, this is because the
    1988                 :             :      * memcmp() compares data from cachelines that are needed in L1 cache even
    1989                 :             :      * when the last comparison's result cannot be reused.
    1990                 :             :      */
    1991                 :    16384803 :     arg1_match = true;
    1992   [ +  +  +  + ]:    16384803 :     if (len1 != sss->last_len1 || memcmp(sss->buf1, a1p, len1) != 0)
    1993                 :             :     {
    1994                 :    14881351 :         arg1_match = false;
    1995                 :    14881351 :         memcpy(sss->buf1, a1p, len1);
    1996                 :    14881351 :         sss->buf1[len1] = '\0';
    1997                 :    14881351 :         sss->last_len1 = len1;
    1998                 :             :     }
    1999                 :             : 
    2000                 :             :     /*
    2001                 :             :      * If we're comparing the same two strings as last time, we can return the
    2002                 :             :      * same answer without calling strcoll() again.  This is more likely than
    2003                 :             :      * it seems (at least with moderate to low cardinality sets), because
    2004                 :             :      * quicksort compares the same pivot against many values.
    2005                 :             :      */
    2006   [ +  +  +  + ]:    16384803 :     if (len2 != sss->last_len2 || memcmp(sss->buf2, a2p, len2) != 0)
    2007                 :             :     {
    2008                 :     2536879 :         memcpy(sss->buf2, a2p, len2);
    2009                 :     2536879 :         sss->buf2[len2] = '\0';
    2010                 :     2536879 :         sss->last_len2 = len2;
    2011                 :             :     }
    2012   [ +  +  +  - ]:    13847924 :     else if (arg1_match && !sss->cache_blob)
    2013                 :             :     {
    2014                 :             :         /* Use result cached following last actual strcoll() call */
    2015                 :     1250978 :         return sss->last_returned;
    2016                 :             :     }
    2017                 :             : 
    2018                 :    15133825 :     result = pg_strcoll(sss->buf1, sss->buf2, sss->locale);
    2019                 :             : 
    2020                 :             :     /* Break tie if necessary. */
    2021   [ +  +  -  + ]:    15133825 :     if (result == 0 && sss->locale->deterministic)
    2022                 :           0 :         result = strcmp(sss->buf1, sss->buf2);
    2023                 :             : 
    2024                 :             :     /* Cache result, perhaps saving an expensive strcoll() call next time */
    2025                 :    15133825 :     sss->cache_blob = false;
    2026                 :    15133825 :     sss->last_returned = result;
    2027                 :    15133825 :     return result;
    2028                 :             : }
    2029                 :             : 
    2030                 :             : /*
    2031                 :             :  * Conversion routine for sortsupport.  Converts original to abbreviated key
    2032                 :             :  * representation.  Our encoding strategy is simple -- pack the first 8 bytes
    2033                 :             :  * of a strxfrm() blob into a Datum (on little-endian machines, the 8 bytes are
    2034                 :             :  * stored in reverse order), and treat it as an unsigned integer.  When the "C"
    2035                 :             :  * locale is used just memcpy() from original instead.
    2036                 :             :  */
    2037                 :             : static Datum
    2038                 :      501540 : varstr_abbrev_convert(Datum original, SortSupport ssup)
    2039                 :             : {
    2040                 :      501540 :     const size_t max_prefix_bytes = sizeof(Datum);
    2041                 :      501540 :     VarStringSortSupport *sss = (VarStringSortSupport *) ssup->ssup_extra;
    2042                 :      501540 :     VarString  *authoritative = DatumGetVarStringPP(original);
    2043                 :      501540 :     char       *authoritative_data = VARDATA_ANY(authoritative);
    2044                 :             : 
    2045                 :             :     /* working state */
    2046                 :             :     Datum       res;
    2047                 :             :     char       *pres;
    2048                 :             :     int         len;
    2049                 :             :     uint32      hash;
    2050                 :             : 
    2051                 :      501540 :     pres = (char *) &res;
    2052                 :             :     /* memset(), so any non-overwritten bytes are NUL */
    2053                 :      501540 :     memset(pres, 0, max_prefix_bytes);
    2054                 :      501540 :     len = VARSIZE_ANY_EXHDR(authoritative);
    2055                 :             : 
    2056                 :             :     /* Get number of bytes, ignoring trailing spaces */
    2057         [ +  + ]:      501540 :     if (sss->typid == BPCHAROID)
    2058                 :         524 :         len = bpchartruelen(authoritative_data, len);
    2059                 :             : 
    2060                 :             :     /*
    2061                 :             :      * If we're using the C collation, use memcpy(), rather than strxfrm(), to
    2062                 :             :      * abbreviate keys.  The full comparator for the C locale is also
    2063                 :             :      * memcmp().  This should be faster than strxfrm().
    2064                 :             :      */
    2065         [ +  + ]:      501540 :     if (sss->collate_c)
    2066                 :      500051 :         memcpy(pres, authoritative_data, Min(len, max_prefix_bytes));
    2067                 :             :     else
    2068                 :             :     {
    2069                 :             :         Size        bsize;
    2070                 :             : 
    2071                 :             :         /*
    2072                 :             :          * We're not using the C collation, so fall back on strxfrm or ICU
    2073                 :             :          * analogs.
    2074                 :             :          */
    2075                 :             : 
    2076                 :             :         /* By convention, we use buffer 1 to store and NUL-terminate */
    2077         [ -  + ]:        1489 :         if (len >= sss->buflen1)
    2078                 :             :         {
    2079         [ #  # ]:           0 :             sss->buflen1 = Max(len + 1, Min(sss->buflen1 * 2, MaxAllocSize));
    2080                 :           0 :             sss->buf1 = repalloc(sss->buf1, sss->buflen1);
    2081                 :             :         }
    2082                 :             : 
    2083                 :             :         /* Might be able to reuse strxfrm() blob from last call */
    2084   [ +  +  +  - ]:        1489 :         if (sss->last_len1 == len && sss->cache_blob &&
    2085         [ +  + ]:         824 :             memcmp(sss->buf1, authoritative_data, len) == 0)
    2086                 :             :         {
    2087                 :         152 :             memcpy(pres, sss->buf2, Min(max_prefix_bytes, sss->last_len2));
    2088                 :             :             /* No change affecting cardinality, so no hashing required */
    2089                 :         152 :             goto done;
    2090                 :             :         }
    2091                 :             : 
    2092                 :        1337 :         memcpy(sss->buf1, authoritative_data, len);
    2093                 :             : 
    2094                 :             :         /*
    2095                 :             :          * pg_strxfrm() and pg_strxfrm_prefix expect NUL-terminated strings.
    2096                 :             :          */
    2097                 :        1337 :         sss->buf1[len] = '\0';
    2098                 :        1337 :         sss->last_len1 = len;
    2099                 :             : 
    2100         [ +  - ]:        1337 :         if (pg_strxfrm_prefix_enabled(sss->locale))
    2101                 :             :         {
    2102         [ -  + ]:        1337 :             if (sss->buflen2 < max_prefix_bytes)
    2103                 :             :             {
    2104         [ #  # ]:           0 :                 sss->buflen2 = Max(max_prefix_bytes,
    2105                 :             :                                    Min(sss->buflen2 * 2, MaxAllocSize));
    2106                 :           0 :                 sss->buf2 = repalloc(sss->buf2, sss->buflen2);
    2107                 :             :             }
    2108                 :             : 
    2109                 :        1337 :             bsize = pg_strxfrm_prefix(sss->buf2, sss->buf1,
    2110                 :             :                                       max_prefix_bytes, sss->locale);
    2111                 :        1337 :             sss->last_len2 = bsize;
    2112                 :             :         }
    2113                 :             :         else
    2114                 :             :         {
    2115                 :             :             /*
    2116                 :             :              * Loop: Call pg_strxfrm(), possibly enlarge buffer, and try
    2117                 :             :              * again.  The pg_strxfrm() function leaves the result buffer
    2118                 :             :              * content undefined if the result did not fit, so we need to
    2119                 :             :              * retry until everything fits, even though we only need the first
    2120                 :             :              * few bytes in the end.
    2121                 :             :              */
    2122                 :             :             for (;;)
    2123                 :             :             {
    2124                 :           0 :                 bsize = pg_strxfrm(sss->buf2, sss->buf1, sss->buflen2,
    2125                 :             :                                    sss->locale);
    2126                 :             : 
    2127                 :           0 :                 sss->last_len2 = bsize;
    2128         [ #  # ]:           0 :                 if (bsize < sss->buflen2)
    2129                 :           0 :                     break;
    2130                 :             : 
    2131                 :             :                 /*
    2132                 :             :                  * Grow buffer and retry.
    2133                 :             :                  */
    2134         [ #  # ]:           0 :                 sss->buflen2 = Max(bsize + 1,
    2135                 :             :                                    Min(sss->buflen2 * 2, MaxAllocSize));
    2136                 :           0 :                 sss->buf2 = repalloc(sss->buf2, sss->buflen2);
    2137                 :             :             }
    2138                 :             :         }
    2139                 :             : 
    2140                 :             :         /*
    2141                 :             :          * Every Datum byte is always compared.  This is safe because the
    2142                 :             :          * strxfrm() blob is itself NUL terminated, leaving no danger of
    2143                 :             :          * misinterpreting any NUL bytes not intended to be interpreted as
    2144                 :             :          * logically representing termination.
    2145                 :             :          */
    2146                 :        1337 :         memcpy(pres, sss->buf2, Min(max_prefix_bytes, bsize));
    2147                 :             :     }
    2148                 :             : 
    2149                 :             :     /*
    2150                 :             :      * Maintain approximate cardinality of both abbreviated keys and original,
    2151                 :             :      * authoritative keys using HyperLogLog.  Used as cheap insurance against
    2152                 :             :      * the worst case, where we do many string transformations for no saving
    2153                 :             :      * in full strcoll()-based comparisons.  These statistics are used by
    2154                 :             :      * varstr_abbrev_abort().
    2155                 :             :      *
    2156                 :             :      * First, Hash key proper, or a significant fraction of it.  Mix in length
    2157                 :             :      * in order to compensate for cases where differences are past
    2158                 :             :      * PG_CACHE_LINE_SIZE bytes, so as to limit the overhead of hashing.
    2159                 :             :      */
    2160                 :      501388 :     hash = hash_bytes((unsigned char *) authoritative_data,
    2161                 :             :                       Min(len, PG_CACHE_LINE_SIZE));
    2162                 :             : 
    2163         [ +  + ]:      501388 :     if (len > PG_CACHE_LINE_SIZE)
    2164                 :         100 :         hash ^= murmurhash32((uint32) len);
    2165                 :             : 
    2166                 :      501388 :     addHyperLogLog(&sss->full_card, hash);
    2167                 :             : 
    2168                 :             :     /* Hash abbreviated key */
    2169                 :      501388 :     hash = (uint32) murmurhash64(DatumGetUInt64(res));
    2170                 :             : 
    2171                 :      501388 :     addHyperLogLog(&sss->abbr_card, hash);
    2172                 :             : 
    2173                 :             :     /* Cache result, perhaps saving an expensive strxfrm() call next time */
    2174                 :      501388 :     sss->cache_blob = true;
    2175                 :      501540 : done:
    2176                 :             : 
    2177                 :             :     /*
    2178                 :             :      * Byteswap on little-endian machines.
    2179                 :             :      *
    2180                 :             :      * This is needed so that ssup_datum_uint64_cmp() (an unsigned integer
    2181                 :             :      * 3-way comparator) works correctly on all platforms.  If we didn't do
    2182                 :             :      * this, the comparator would have to call memcmp() with a pair of
    2183                 :             :      * pointers to the first byte of each abbreviated key, which is slower.
    2184                 :             :      */
    2185                 :      501540 :     res = DatumBigEndianToNative(res);
    2186                 :             : 
    2187                 :             :     /* Don't leak memory here */
    2188         [ +  + ]:      501540 :     if (PointerGetDatum(authoritative) != original)
    2189                 :           1 :         pfree(authoritative);
    2190                 :             : 
    2191                 :      501540 :     return res;
    2192                 :             : }
    2193                 :             : 
    2194                 :             : /*
    2195                 :             :  * Callback for estimating effectiveness of abbreviated key optimization, using
    2196                 :             :  * heuristic rules.  Returns value indicating if the abbreviation optimization
    2197                 :             :  * should be aborted, based on its projected effectiveness.
    2198                 :             :  */
    2199                 :             : static bool
    2200                 :        1421 : varstr_abbrev_abort(int memtupcount, SortSupport ssup)
    2201                 :             : {
    2202                 :        1421 :     VarStringSortSupport *sss = (VarStringSortSupport *) ssup->ssup_extra;
    2203                 :             :     double      abbrev_distinct,
    2204                 :             :                 key_distinct;
    2205                 :             : 
    2206                 :             :     Assert(ssup->abbreviate);
    2207                 :             : 
    2208                 :             :     /* Have a little patience */
    2209         [ +  + ]:        1421 :     if (memtupcount < 100)
    2210                 :         813 :         return false;
    2211                 :             : 
    2212                 :         608 :     abbrev_distinct = estimateHyperLogLog(&sss->abbr_card);
    2213                 :         608 :     key_distinct = estimateHyperLogLog(&sss->full_card);
    2214                 :             : 
    2215                 :             :     /*
    2216                 :             :      * Clamp cardinality estimates to at least one distinct value.  While
    2217                 :             :      * NULLs are generally disregarded, if only NULL values were seen so far,
    2218                 :             :      * that might misrepresent costs if we failed to clamp.
    2219                 :             :      */
    2220         [ -  + ]:         608 :     if (abbrev_distinct < 1.0)
    2221                 :           0 :         abbrev_distinct = 1.0;
    2222                 :             : 
    2223         [ -  + ]:         608 :     if (key_distinct < 1.0)
    2224                 :           0 :         key_distinct = 1.0;
    2225                 :             : 
    2226                 :             :     /*
    2227                 :             :      * In the worst case all abbreviated keys are identical, while at the same
    2228                 :             :      * time there are differences within full key strings not captured in
    2229                 :             :      * abbreviations.
    2230                 :             :      */
    2231         [ -  + ]:         608 :     if (trace_sort)
    2232                 :             :     {
    2233                 :           0 :         double      norm_abbrev_card = abbrev_distinct / (double) memtupcount;
    2234                 :             : 
    2235         [ #  # ]:           0 :         elog(LOG, "varstr_abbrev: abbrev_distinct after %d: %f "
    2236                 :             :              "(key_distinct: %f, norm_abbrev_card: %f, prop_card: %f)",
    2237                 :             :              memtupcount, abbrev_distinct, key_distinct, norm_abbrev_card,
    2238                 :             :              sss->prop_card);
    2239                 :             :     }
    2240                 :             : 
    2241                 :             :     /*
    2242                 :             :      * If the number of distinct abbreviated keys approximately matches the
    2243                 :             :      * number of distinct authoritative original keys, that's reason enough to
    2244                 :             :      * proceed.  We can win even with a very low cardinality set if most
    2245                 :             :      * tie-breakers only memcmp().  This is by far the most important
    2246                 :             :      * consideration.
    2247                 :             :      *
    2248                 :             :      * While comparisons that are resolved at the abbreviated key level are
    2249                 :             :      * considerably cheaper than tie-breakers resolved with memcmp(), both of
    2250                 :             :      * those two outcomes are so much cheaper than a full strcoll() once
    2251                 :             :      * sorting is underway that it doesn't seem worth it to weigh abbreviated
    2252                 :             :      * cardinality against the overall size of the set in order to more
    2253                 :             :      * accurately model costs.  Assume that an abbreviated comparison, and an
    2254                 :             :      * abbreviated comparison with a cheap memcmp()-based authoritative
    2255                 :             :      * resolution are equivalent.
    2256                 :             :      */
    2257         [ +  - ]:         608 :     if (abbrev_distinct > key_distinct * sss->prop_card)
    2258                 :             :     {
    2259                 :             :         /*
    2260                 :             :          * When we have exceeded 10,000 tuples, decay required cardinality
    2261                 :             :          * aggressively for next call.
    2262                 :             :          *
    2263                 :             :          * This is useful because the number of comparisons required on
    2264                 :             :          * average increases at a linearithmic rate, and at roughly 10,000
    2265                 :             :          * tuples that factor will start to dominate over the linear costs of
    2266                 :             :          * string transformation (this is a conservative estimate).  The decay
    2267                 :             :          * rate is chosen to be a little less aggressive than halving -- which
    2268                 :             :          * (since we're called at points at which memtupcount has doubled)
    2269                 :             :          * would never see the cost model actually abort past the first call
    2270                 :             :          * following a decay.  This decay rate is mostly a precaution against
    2271                 :             :          * a sudden, violent swing in how well abbreviated cardinality tracks
    2272                 :             :          * full key cardinality.  The decay also serves to prevent a marginal
    2273                 :             :          * case from being aborted too late, when too much has already been
    2274                 :             :          * invested in string transformation.
    2275                 :             :          *
    2276                 :             :          * It's possible for sets of several million distinct strings with
    2277                 :             :          * mere tens of thousands of distinct abbreviated keys to still
    2278                 :             :          * benefit very significantly.  This will generally occur provided
    2279                 :             :          * each abbreviated key is a proxy for a roughly uniform number of the
    2280                 :             :          * set's full keys. If it isn't so, we hope to catch that early and
    2281                 :             :          * abort.  If it isn't caught early, by the time the problem is
    2282                 :             :          * apparent it's probably not worth aborting.
    2283                 :             :          */
    2284         [ +  + ]:         608 :         if (memtupcount > 10000)
    2285                 :           2 :             sss->prop_card *= 0.65;
    2286                 :             : 
    2287                 :         608 :         return false;
    2288                 :             :     }
    2289                 :             : 
    2290                 :             :     /*
    2291                 :             :      * Abort abbreviation strategy.
    2292                 :             :      *
    2293                 :             :      * The worst case, where all abbreviated keys are identical while all
    2294                 :             :      * original strings differ will typically only see a regression of about
    2295                 :             :      * 10% in execution time for small to medium sized lists of strings.
    2296                 :             :      * Whereas on modern CPUs where cache stalls are the dominant cost, we can
    2297                 :             :      * often expect very large improvements, particularly with sets of strings
    2298                 :             :      * of moderately high to high abbreviated cardinality.  There is little to
    2299                 :             :      * lose but much to gain, which our strategy reflects.
    2300                 :             :      */
    2301         [ #  # ]:           0 :     if (trace_sort)
    2302         [ #  # ]:           0 :         elog(LOG, "varstr_abbrev: aborted abbreviation at %d "
    2303                 :             :              "(abbrev_distinct: %f, key_distinct: %f, prop_card: %f)",
    2304                 :             :              memtupcount, abbrev_distinct, key_distinct, sss->prop_card);
    2305                 :             : 
    2306                 :           0 :     return true;
    2307                 :             : }
    2308                 :             : 
    2309                 :             : /*
    2310                 :             :  * Generic equalimage support function for character type's operator classes.
    2311                 :             :  * Disables the use of deduplication with nondeterministic collations.
    2312                 :             :  */
    2313                 :             : Datum
    2314                 :        5398 : btvarstrequalimage(PG_FUNCTION_ARGS)
    2315                 :             : {
    2316                 :             : #ifdef NOT_USED
    2317                 :             :     Oid         opcintype = PG_GETARG_OID(0);
    2318                 :             : #endif
    2319                 :        5398 :     Oid         collid = PG_GET_COLLATION();
    2320                 :             :     pg_locale_t locale;
    2321                 :             : 
    2322                 :        5398 :     check_collation_set(collid);
    2323                 :             : 
    2324                 :        5398 :     locale = pg_newlocale_from_collation(collid);
    2325                 :             : 
    2326                 :        5398 :     PG_RETURN_BOOL(locale->deterministic);
    2327                 :             : }
    2328                 :             : 
    2329                 :             : Datum
    2330                 :      145885 : text_larger(PG_FUNCTION_ARGS)
    2331                 :             : {
    2332                 :      145885 :     text       *arg1 = PG_GETARG_TEXT_PP(0);
    2333                 :      145885 :     text       *arg2 = PG_GETARG_TEXT_PP(1);
    2334                 :             :     text       *result;
    2335                 :             : 
    2336         [ +  + ]:      145885 :     result = ((text_cmp(arg1, arg2, PG_GET_COLLATION()) > 0) ? arg1 : arg2);
    2337                 :             : 
    2338                 :      145885 :     PG_RETURN_TEXT_P(result);
    2339                 :             : }
    2340                 :             : 
    2341                 :             : Datum
    2342                 :       50562 : text_smaller(PG_FUNCTION_ARGS)
    2343                 :             : {
    2344                 :       50562 :     text       *arg1 = PG_GETARG_TEXT_PP(0);
    2345                 :       50562 :     text       *arg2 = PG_GETARG_TEXT_PP(1);
    2346                 :             :     text       *result;
    2347                 :             : 
    2348         [ +  + ]:       50562 :     result = ((text_cmp(arg1, arg2, PG_GET_COLLATION()) < 0) ? arg1 : arg2);
    2349                 :             : 
    2350                 :       50562 :     PG_RETURN_TEXT_P(result);
    2351                 :             : }
    2352                 :             : 
    2353                 :             : 
    2354                 :             : /*
    2355                 :             :  * Cross-type comparison functions for types text and name.
    2356                 :             :  */
    2357                 :             : 
    2358                 :             : Datum
    2359                 :      298459 : nameeqtext(PG_FUNCTION_ARGS)
    2360                 :             : {
    2361                 :      298459 :     Name        arg1 = PG_GETARG_NAME(0);
    2362                 :      298459 :     text       *arg2 = PG_GETARG_TEXT_PP(1);
    2363                 :      298459 :     size_t      len1 = strlen(NameStr(*arg1));
    2364                 :      298459 :     size_t      len2 = VARSIZE_ANY_EXHDR(arg2);
    2365                 :      298459 :     Oid         collid = PG_GET_COLLATION();
    2366                 :             :     bool        result;
    2367                 :             : 
    2368                 :      298459 :     check_collation_set(collid);
    2369                 :             : 
    2370         [ +  + ]:      298459 :     if (collid == C_COLLATION_OID)
    2371         [ +  + ]:      294993 :         result = (len1 == len2 &&
    2372         [ +  + ]:       97146 :                   memcmp(NameStr(*arg1), VARDATA_ANY(arg2), len1) == 0);
    2373                 :             :     else
    2374                 :      100612 :         result = (varstr_cmp(NameStr(*arg1), len1,
    2375                 :      100612 :                              VARDATA_ANY(arg2), len2,
    2376                 :             :                              collid) == 0);
    2377                 :             : 
    2378         [ -  + ]:      298459 :     PG_FREE_IF_COPY(arg2, 1);
    2379                 :             : 
    2380                 :      298459 :     PG_RETURN_BOOL(result);
    2381                 :             : }
    2382                 :             : 
    2383                 :             : Datum
    2384                 :        5474 : texteqname(PG_FUNCTION_ARGS)
    2385                 :             : {
    2386                 :        5474 :     text       *arg1 = PG_GETARG_TEXT_PP(0);
    2387                 :        5474 :     Name        arg2 = PG_GETARG_NAME(1);
    2388                 :        5474 :     size_t      len1 = VARSIZE_ANY_EXHDR(arg1);
    2389                 :        5474 :     size_t      len2 = strlen(NameStr(*arg2));
    2390                 :        5474 :     Oid         collid = PG_GET_COLLATION();
    2391                 :             :     bool        result;
    2392                 :             : 
    2393                 :        5474 :     check_collation_set(collid);
    2394                 :             : 
    2395         [ +  + ]:        5474 :     if (collid == C_COLLATION_OID)
    2396         [ +  + ]:         378 :         result = (len1 == len2 &&
    2397         [ +  - ]:         121 :                   memcmp(VARDATA_ANY(arg1), NameStr(*arg2), len1) == 0);
    2398                 :             :     else
    2399                 :        5217 :         result = (varstr_cmp(VARDATA_ANY(arg1), len1,
    2400                 :        5217 :                              NameStr(*arg2), len2,
    2401                 :             :                              collid) == 0);
    2402                 :             : 
    2403         [ -  + ]:        5474 :     PG_FREE_IF_COPY(arg1, 0);
    2404                 :             : 
    2405                 :        5474 :     PG_RETURN_BOOL(result);
    2406                 :             : }
    2407                 :             : 
    2408                 :             : Datum
    2409                 :          27 : namenetext(PG_FUNCTION_ARGS)
    2410                 :             : {
    2411                 :          27 :     Name        arg1 = PG_GETARG_NAME(0);
    2412                 :          27 :     text       *arg2 = PG_GETARG_TEXT_PP(1);
    2413                 :          27 :     size_t      len1 = strlen(NameStr(*arg1));
    2414                 :          27 :     size_t      len2 = VARSIZE_ANY_EXHDR(arg2);
    2415                 :          27 :     Oid         collid = PG_GET_COLLATION();
    2416                 :             :     bool        result;
    2417                 :             : 
    2418                 :          27 :     check_collation_set(collid);
    2419                 :             : 
    2420         [ +  + ]:          27 :     if (collid == C_COLLATION_OID)
    2421         [ -  + ]:          15 :         result = !(len1 == len2 &&
    2422         [ #  # ]:           0 :                    memcmp(NameStr(*arg1), VARDATA_ANY(arg2), len1) == 0);
    2423                 :             :     else
    2424                 :          12 :         result = !(varstr_cmp(NameStr(*arg1), len1,
    2425                 :          12 :                               VARDATA_ANY(arg2), len2,
    2426                 :             :                               collid) == 0);
    2427                 :             : 
    2428         [ -  + ]:          27 :     PG_FREE_IF_COPY(arg2, 1);
    2429                 :             : 
    2430                 :          27 :     PG_RETURN_BOOL(result);
    2431                 :             : }
    2432                 :             : 
    2433                 :             : Datum
    2434                 :          12 : textnename(PG_FUNCTION_ARGS)
    2435                 :             : {
    2436                 :          12 :     text       *arg1 = PG_GETARG_TEXT_PP(0);
    2437                 :          12 :     Name        arg2 = PG_GETARG_NAME(1);
    2438                 :          12 :     size_t      len1 = VARSIZE_ANY_EXHDR(arg1);
    2439                 :          12 :     size_t      len2 = strlen(NameStr(*arg2));
    2440                 :          12 :     Oid         collid = PG_GET_COLLATION();
    2441                 :             :     bool        result;
    2442                 :             : 
    2443                 :          12 :     check_collation_set(collid);
    2444                 :             : 
    2445         [ -  + ]:          12 :     if (collid == C_COLLATION_OID)
    2446         [ #  # ]:           0 :         result = !(len1 == len2 &&
    2447         [ #  # ]:           0 :                    memcmp(VARDATA_ANY(arg1), NameStr(*arg2), len1) == 0);
    2448                 :             :     else
    2449                 :          12 :         result = !(varstr_cmp(VARDATA_ANY(arg1), len1,
    2450                 :          12 :                               NameStr(*arg2), len2,
    2451                 :             :                               collid) == 0);
    2452                 :             : 
    2453         [ -  + ]:          12 :     PG_FREE_IF_COPY(arg1, 0);
    2454                 :             : 
    2455                 :          12 :     PG_RETURN_BOOL(result);
    2456                 :             : }
    2457                 :             : 
    2458                 :             : Datum
    2459                 :      175857 : btnametextcmp(PG_FUNCTION_ARGS)
    2460                 :             : {
    2461                 :      175857 :     Name        arg1 = PG_GETARG_NAME(0);
    2462                 :      175857 :     text       *arg2 = PG_GETARG_TEXT_PP(1);
    2463                 :             :     int32       result;
    2464                 :             : 
    2465                 :      175857 :     result = varstr_cmp(NameStr(*arg1), strlen(NameStr(*arg1)),
    2466                 :      175857 :                         VARDATA_ANY(arg2), VARSIZE_ANY_EXHDR(arg2),
    2467                 :             :                         PG_GET_COLLATION());
    2468                 :             : 
    2469         [ -  + ]:      175857 :     PG_FREE_IF_COPY(arg2, 1);
    2470                 :             : 
    2471                 :      175857 :     PG_RETURN_INT32(result);
    2472                 :             : }
    2473                 :             : 
    2474                 :             : Datum
    2475                 :          22 : bttextnamecmp(PG_FUNCTION_ARGS)
    2476                 :             : {
    2477                 :          22 :     text       *arg1 = PG_GETARG_TEXT_PP(0);
    2478                 :          22 :     Name        arg2 = PG_GETARG_NAME(1);
    2479                 :             :     int32       result;
    2480                 :             : 
    2481                 :          22 :     result = varstr_cmp(VARDATA_ANY(arg1), VARSIZE_ANY_EXHDR(arg1),
    2482                 :          22 :                         NameStr(*arg2), strlen(NameStr(*arg2)),
    2483                 :             :                         PG_GET_COLLATION());
    2484                 :             : 
    2485         [ -  + ]:          22 :     PG_FREE_IF_COPY(arg1, 0);
    2486                 :             : 
    2487                 :          22 :     PG_RETURN_INT32(result);
    2488                 :             : }
    2489                 :             : 
    2490                 :             : #define CmpCall(cmpfunc) \
    2491                 :             :     DatumGetInt32(DirectFunctionCall2Coll(cmpfunc, \
    2492                 :             :                                           PG_GET_COLLATION(), \
    2493                 :             :                                           PG_GETARG_DATUM(0), \
    2494                 :             :                                           PG_GETARG_DATUM(1)))
    2495                 :             : 
    2496                 :             : Datum
    2497                 :       60744 : namelttext(PG_FUNCTION_ARGS)
    2498                 :             : {
    2499                 :       60744 :     PG_RETURN_BOOL(CmpCall(btnametextcmp) < 0);
    2500                 :             : }
    2501                 :             : 
    2502                 :             : Datum
    2503                 :           0 : nameletext(PG_FUNCTION_ARGS)
    2504                 :             : {
    2505                 :           0 :     PG_RETURN_BOOL(CmpCall(btnametextcmp) <= 0);
    2506                 :             : }
    2507                 :             : 
    2508                 :             : Datum
    2509                 :           0 : namegttext(PG_FUNCTION_ARGS)
    2510                 :             : {
    2511                 :           0 :     PG_RETURN_BOOL(CmpCall(btnametextcmp) > 0);
    2512                 :             : }
    2513                 :             : 
    2514                 :             : Datum
    2515                 :       55855 : namegetext(PG_FUNCTION_ARGS)
    2516                 :             : {
    2517                 :       55855 :     PG_RETURN_BOOL(CmpCall(btnametextcmp) >= 0);
    2518                 :             : }
    2519                 :             : 
    2520                 :             : Datum
    2521                 :           0 : textltname(PG_FUNCTION_ARGS)
    2522                 :             : {
    2523                 :           0 :     PG_RETURN_BOOL(CmpCall(bttextnamecmp) < 0);
    2524                 :             : }
    2525                 :             : 
    2526                 :             : Datum
    2527                 :           0 : textlename(PG_FUNCTION_ARGS)
    2528                 :             : {
    2529                 :           0 :     PG_RETURN_BOOL(CmpCall(bttextnamecmp) <= 0);
    2530                 :             : }
    2531                 :             : 
    2532                 :             : Datum
    2533                 :           0 : textgtname(PG_FUNCTION_ARGS)
    2534                 :             : {
    2535                 :           0 :     PG_RETURN_BOOL(CmpCall(bttextnamecmp) > 0);
    2536                 :             : }
    2537                 :             : 
    2538                 :             : Datum
    2539                 :           0 : textgename(PG_FUNCTION_ARGS)
    2540                 :             : {
    2541                 :           0 :     PG_RETURN_BOOL(CmpCall(bttextnamecmp) >= 0);
    2542                 :             : }
    2543                 :             : 
    2544                 :             : #undef CmpCall
    2545                 :             : 
    2546                 :             : 
    2547                 :             : /*
    2548                 :             :  * The following operators support character-by-character comparison
    2549                 :             :  * of text datums, to allow building indexes suitable for LIKE clauses.
    2550                 :             :  * Note that the regular texteq/textne comparison operators, and regular
    2551                 :             :  * support functions 1 and 2 with "C" collation are assumed to be
    2552                 :             :  * compatible with these!
    2553                 :             :  */
    2554                 :             : 
    2555                 :             : static int
    2556                 :      107164 : internal_text_pattern_compare(text *arg1, text *arg2)
    2557                 :             : {
    2558                 :             :     int         result;
    2559                 :             :     int         len1,
    2560                 :             :                 len2;
    2561                 :             : 
    2562                 :      107164 :     len1 = VARSIZE_ANY_EXHDR(arg1);
    2563                 :      107164 :     len2 = VARSIZE_ANY_EXHDR(arg2);
    2564                 :             : 
    2565                 :      107164 :     result = memcmp(VARDATA_ANY(arg1), VARDATA_ANY(arg2), Min(len1, len2));
    2566         [ +  + ]:      107164 :     if (result != 0)
    2567                 :      107076 :         return result;
    2568         [ -  + ]:          88 :     else if (len1 < len2)
    2569                 :           0 :         return -1;
    2570         [ +  + ]:          88 :     else if (len1 > len2)
    2571                 :          56 :         return 1;
    2572                 :             :     else
    2573                 :          32 :         return 0;
    2574                 :             : }
    2575                 :             : 
    2576                 :             : 
    2577                 :             : Datum
    2578                 :       32112 : text_pattern_lt(PG_FUNCTION_ARGS)
    2579                 :             : {
    2580                 :       32112 :     text       *arg1 = PG_GETARG_TEXT_PP(0);
    2581                 :       32112 :     text       *arg2 = PG_GETARG_TEXT_PP(1);
    2582                 :             :     int         result;
    2583                 :             : 
    2584                 :       32112 :     result = internal_text_pattern_compare(arg1, arg2);
    2585                 :             : 
    2586         [ -  + ]:       32112 :     PG_FREE_IF_COPY(arg1, 0);
    2587         [ -  + ]:       32112 :     PG_FREE_IF_COPY(arg2, 1);
    2588                 :             : 
    2589                 :       32112 :     PG_RETURN_BOOL(result < 0);
    2590                 :             : }
    2591                 :             : 
    2592                 :             : 
    2593                 :             : Datum
    2594                 :       25006 : text_pattern_le(PG_FUNCTION_ARGS)
    2595                 :             : {
    2596                 :       25006 :     text       *arg1 = PG_GETARG_TEXT_PP(0);
    2597                 :       25006 :     text       *arg2 = PG_GETARG_TEXT_PP(1);
    2598                 :             :     int         result;
    2599                 :             : 
    2600                 :       25006 :     result = internal_text_pattern_compare(arg1, arg2);
    2601                 :             : 
    2602         [ -  + ]:       25006 :     PG_FREE_IF_COPY(arg1, 0);
    2603         [ -  + ]:       25006 :     PG_FREE_IF_COPY(arg2, 1);
    2604                 :             : 
    2605                 :       25006 :     PG_RETURN_BOOL(result <= 0);
    2606                 :             : }
    2607                 :             : 
    2608                 :             : 
    2609                 :             : Datum
    2610                 :       25022 : text_pattern_ge(PG_FUNCTION_ARGS)
    2611                 :             : {
    2612                 :       25022 :     text       *arg1 = PG_GETARG_TEXT_PP(0);
    2613                 :       25022 :     text       *arg2 = PG_GETARG_TEXT_PP(1);
    2614                 :             :     int         result;
    2615                 :             : 
    2616                 :       25022 :     result = internal_text_pattern_compare(arg1, arg2);
    2617                 :             : 
    2618         [ -  + ]:       25022 :     PG_FREE_IF_COPY(arg1, 0);
    2619         [ -  + ]:       25022 :     PG_FREE_IF_COPY(arg2, 1);
    2620                 :             : 
    2621                 :       25022 :     PG_RETURN_BOOL(result >= 0);
    2622                 :             : }
    2623                 :             : 
    2624                 :             : 
    2625                 :             : Datum
    2626                 :       25006 : text_pattern_gt(PG_FUNCTION_ARGS)
    2627                 :             : {
    2628                 :       25006 :     text       *arg1 = PG_GETARG_TEXT_PP(0);
    2629                 :       25006 :     text       *arg2 = PG_GETARG_TEXT_PP(1);
    2630                 :             :     int         result;
    2631                 :             : 
    2632                 :       25006 :     result = internal_text_pattern_compare(arg1, arg2);
    2633                 :             : 
    2634         [ -  + ]:       25006 :     PG_FREE_IF_COPY(arg1, 0);
    2635         [ -  + ]:       25006 :     PG_FREE_IF_COPY(arg2, 1);
    2636                 :             : 
    2637                 :       25006 :     PG_RETURN_BOOL(result > 0);
    2638                 :             : }
    2639                 :             : 
    2640                 :             : 
    2641                 :             : Datum
    2642                 :          18 : bttext_pattern_cmp(PG_FUNCTION_ARGS)
    2643                 :             : {
    2644                 :          18 :     text       *arg1 = PG_GETARG_TEXT_PP(0);
    2645                 :          18 :     text       *arg2 = PG_GETARG_TEXT_PP(1);
    2646                 :             :     int         result;
    2647                 :             : 
    2648                 :          18 :     result = internal_text_pattern_compare(arg1, arg2);
    2649                 :             : 
    2650         [ -  + ]:          18 :     PG_FREE_IF_COPY(arg1, 0);
    2651         [ -  + ]:          18 :     PG_FREE_IF_COPY(arg2, 1);
    2652                 :             : 
    2653                 :          18 :     PG_RETURN_INT32(result);
    2654                 :             : }
    2655                 :             : 
    2656                 :             : 
    2657                 :             : Datum
    2658                 :          77 : bttext_pattern_sortsupport(PG_FUNCTION_ARGS)
    2659                 :             : {
    2660                 :          77 :     SortSupport ssup = (SortSupport) PG_GETARG_POINTER(0);
    2661                 :             :     MemoryContext oldcontext;
    2662                 :             : 
    2663                 :          77 :     oldcontext = MemoryContextSwitchTo(ssup->ssup_cxt);
    2664                 :             : 
    2665                 :             :     /* Use generic string SortSupport, forcing "C" collation */
    2666                 :          77 :     varstr_sortsupport(ssup, TEXTOID, C_COLLATION_OID);
    2667                 :             : 
    2668                 :          77 :     MemoryContextSwitchTo(oldcontext);
    2669                 :             : 
    2670                 :          77 :     PG_RETURN_VOID();
    2671                 :             : }
    2672                 :             : 
    2673                 :             : 
    2674                 :             : /*
    2675                 :             :  * text_name()
    2676                 :             :  * Converts a text type to a Name type.
    2677                 :             :  */
    2678                 :             : Datum
    2679                 :       17759 : text_name(PG_FUNCTION_ARGS)
    2680                 :             : {
    2681                 :       17759 :     text       *s = PG_GETARG_TEXT_PP(0);
    2682                 :             :     Name        result;
    2683                 :             :     int         len;
    2684                 :             : 
    2685                 :       17759 :     len = VARSIZE_ANY_EXHDR(s);
    2686                 :             : 
    2687                 :             :     /* Truncate oversize input */
    2688         [ +  + ]:       17759 :     if (len >= NAMEDATALEN)
    2689                 :           5 :         len = pg_mbcliplen(VARDATA_ANY(s), len, NAMEDATALEN - 1);
    2690                 :             : 
    2691                 :             :     /* We use palloc0 here to ensure result is zero-padded */
    2692                 :       17759 :     result = (Name) palloc0(NAMEDATALEN);
    2693                 :       17759 :     memcpy(NameStr(*result), VARDATA_ANY(s), len);
    2694                 :             : 
    2695                 :       17759 :     PG_RETURN_NAME(result);
    2696                 :             : }
    2697                 :             : 
    2698                 :             : /*
    2699                 :             :  * name_text()
    2700                 :             :  * Converts a Name type to a text type.
    2701                 :             :  */
    2702                 :             : Datum
    2703                 :      428088 : name_text(PG_FUNCTION_ARGS)
    2704                 :             : {
    2705                 :      428088 :     Name        s = PG_GETARG_NAME(0);
    2706                 :             : 
    2707                 :      428088 :     PG_RETURN_TEXT_P(cstring_to_text(NameStr(*s)));
    2708                 :             : }
    2709                 :             : 
    2710                 :             : 
    2711                 :             : /*
    2712                 :             :  * textToQualifiedNameList - convert a text object to list of names
    2713                 :             :  *
    2714                 :             :  * This implements the input parsing needed by nextval() and other
    2715                 :             :  * functions that take a text parameter representing a qualified name.
    2716                 :             :  * We split the name at dots, downcase if not double-quoted, and
    2717                 :             :  * truncate names if they're too long.
    2718                 :             :  */
    2719                 :             : List *
    2720                 :        3126 : textToQualifiedNameList(text *textval)
    2721                 :             : {
    2722                 :             :     char       *rawname;
    2723                 :        3126 :     List       *result = NIL;
    2724                 :             :     List       *namelist;
    2725                 :             :     ListCell   *l;
    2726                 :             : 
    2727                 :             :     /* Convert to C string (handles possible detoasting). */
    2728                 :             :     /* Note we rely on being able to modify rawname below. */
    2729                 :        3126 :     rawname = text_to_cstring(textval);
    2730                 :             : 
    2731         [ -  + ]:        3126 :     if (!SplitIdentifierString(rawname, '.', &namelist))
    2732         [ #  # ]:           0 :         ereport(ERROR,
    2733                 :             :                 (errcode(ERRCODE_INVALID_NAME),
    2734                 :             :                  errmsg("invalid name syntax")));
    2735                 :             : 
    2736         [ -  + ]:        3126 :     if (namelist == NIL)
    2737         [ #  # ]:           0 :         ereport(ERROR,
    2738                 :             :                 (errcode(ERRCODE_INVALID_NAME),
    2739                 :             :                  errmsg("invalid name syntax")));
    2740                 :             : 
    2741   [ +  -  +  +  :        6446 :     foreach(l, namelist)
                   +  + ]
    2742                 :             :     {
    2743                 :        3320 :         char       *curname = (char *) lfirst(l);
    2744                 :             : 
    2745                 :        3320 :         result = lappend(result, makeString(pstrdup(curname)));
    2746                 :             :     }
    2747                 :             : 
    2748                 :        3126 :     pfree(rawname);
    2749                 :        3126 :     list_free(namelist);
    2750                 :             : 
    2751                 :        3126 :     return result;
    2752                 :             : }
    2753                 :             : 
    2754                 :             : /*
    2755                 :             :  * scan_quoted_identifier - In-place scanner for quoted identifiers.
    2756                 :             :  *
    2757                 :             :  * *nextp should point to the opening double-quote character, and will be
    2758                 :             :  * updated to point just past the end.  *endp is set to the position of
    2759                 :             :  * the closing quote. The return value is the identifier, or NULL if the
    2760                 :             :  * matching close-quote cannot be found.
    2761                 :             :  *
    2762                 :             :  * If we find two consecutive double quote characters, that doesn't end the
    2763                 :             :  * identifier: instead, we collapse them into a double quote and include them
    2764                 :             :  * in the resulting token. Note that this requires overwriting the rest of the
    2765                 :             :  * string in place, including the portion beyond the final value of *nextp.
    2766                 :             :  */
    2767                 :             : char *
    2768                 :       26191 : scan_quoted_identifier(char **endp, char **nextp)
    2769                 :             : {
    2770                 :       26191 :     char       *token = *nextp + 1;
    2771                 :             : 
    2772                 :             :     for (;;)
    2773                 :             :     {
    2774                 :       26201 :         *endp = strchr(*nextp + 1, '"');
    2775         [ +  + ]:       26196 :         if (*endp == NULL)
    2776                 :           2 :             return NULL;        /* mismatched quotes */
    2777         [ +  + ]:       26194 :         if ((*endp)[1] != '"')
    2778                 :       26189 :             break;              /* found end of quoted identifier */
    2779                 :             :         /* Collapse adjacent quotes into one quote, and look again */
    2780                 :           5 :         memmove(*endp, *endp + 1, strlen(*endp));
    2781                 :           5 :         *nextp = *endp;
    2782                 :             :     }
    2783                 :             :     /* *endp now points at the terminating quote */
    2784                 :       26189 :     *nextp = *endp + 1;
    2785                 :             : 
    2786                 :       26189 :     return token;
    2787                 :             : }
    2788                 :             : 
    2789                 :             : /*
    2790                 :             :  * scan_identifier - In-place scanner for quoted or unquoted identifiers.
    2791                 :             :  *
    2792                 :             :  * On success, *endp is set to the position where the caller should write '\0'
    2793                 :             :  * to null-terminate the token, and *nextp is advanced past the token (and past
    2794                 :             :  * the closing quote, if any).  The return value is the token content, or NULL
    2795                 :             :  * if there is a syntax error (mismatched quotes or empty unquoted token).
    2796                 :             :  *
    2797                 :             :  * Unquoted identifiers are terminated by whitespace or the first occurrence
    2798                 :             :  * of the separator character. Additionally, if downcase_unquoted = true,
    2799                 :             :  * unquoted identifiers are downcased in place. See scan_quoted_identifier for
    2800                 :             :  * an additional way in which we modify the string in place.
    2801                 :             :  */
    2802                 :             : char *
    2803                 :      380274 : scan_identifier(char **endp, char **nextp, char separator, bool downcase_unquoted)
    2804                 :             : {
    2805                 :             :     char       *token;
    2806                 :             : 
    2807         [ +  + ]:      380274 :     if (**nextp == '"')
    2808                 :       26191 :         return scan_quoted_identifier(endp, nextp);
    2809                 :             : 
    2810                 :             :     /* Unquoted identifier --- extends to separator or whitespace */
    2811                 :      354083 :     token = *nextp;
    2812                 :             : 
    2813   [ +  +  +  +  :     3239985 :     while (**nextp && **nextp != separator && !scanner_isspace(**nextp))
                   +  + ]
    2814                 :     2885902 :         (*nextp)++;
    2815                 :             : 
    2816         [ +  + ]:      354083 :     if (*nextp == token)
    2817                 :           6 :         return NULL;            /* empty token */
    2818                 :             : 
    2819                 :      354077 :     *endp = *nextp;
    2820                 :             : 
    2821         [ +  + ]:      354077 :     if (downcase_unquoted)
    2822                 :             :     {
    2823                 :             :         /*
    2824                 :             :          * Downcase the identifier, using same code as main lexer does.
    2825                 :             :          *
    2826                 :             :          * XXX because we want to overwrite the input in-place, we cannot
    2827                 :             :          * support a downcasing transformation that increases the string
    2828                 :             :          * length.  This is not a problem given the current implementation of
    2829                 :             :          * downcase_truncate_identifier, but we'll probably have to do
    2830                 :             :          * something about this someday.
    2831                 :             :          */
    2832                 :      346574 :         int         len = *endp - token;
    2833                 :      346574 :         char       *downname = downcase_truncate_identifier(token, len, false);
    2834                 :             : 
    2835                 :             :         Assert(strlen(downname) <= len);
    2836                 :      346574 :         strncpy(token, downname, len);  /* strncpy is required here */
    2837                 :      346574 :         pfree(downname);
    2838                 :             :     }
    2839                 :             : 
    2840                 :      354077 :     return token;
    2841                 :             : }
    2842                 :             : 
    2843                 :             : 
    2844                 :             : /*
    2845                 :             :  * SplitIdentifierString --- parse a string containing identifiers
    2846                 :             :  *
    2847                 :             :  * This is the guts of textToQualifiedNameList, and is exported for use in
    2848                 :             :  * other situations such as parsing GUC variables.  In the GUC case, it's
    2849                 :             :  * important to avoid memory leaks, so the API is designed to minimize the
    2850                 :             :  * amount of stuff that needs to be allocated and freed.
    2851                 :             :  *
    2852                 :             :  * Inputs:
    2853                 :             :  *  rawstring: the input string; must be overwritable!  On return, it's
    2854                 :             :  *             been modified to contain the separated identifiers.
    2855                 :             :  *  separator: the separator punctuation expected between identifiers
    2856                 :             :  *             (typically '.' or ',').  Whitespace may also appear around
    2857                 :             :  *             identifiers.
    2858                 :             :  * Outputs:
    2859                 :             :  *  namelist: filled with a palloc'd list of pointers to identifiers within
    2860                 :             :  *            rawstring.  Caller should list_free() this even on error return.
    2861                 :             :  *
    2862                 :             :  * Returns true if okay, false if there is a syntax error in the string.
    2863                 :             :  *
    2864                 :             :  * Note that an empty string is considered okay here, though not in
    2865                 :             :  * textToQualifiedNameList.
    2866                 :             :  */
    2867                 :             : bool
    2868                 :      223794 : SplitIdentifierString(char *rawstring, char separator,
    2869                 :             :                       List **namelist)
    2870                 :             : {
    2871                 :      223794 :     char       *nextp = rawstring;
    2872                 :      223794 :     bool        done = false;
    2873                 :             : 
    2874                 :      223794 :     *namelist = NIL;
    2875                 :             : 
    2876         [ +  + ]:      223798 :     while (scanner_isspace(*nextp))
    2877                 :           4 :         nextp++;                /* skip leading whitespace */
    2878                 :             : 
    2879         [ +  + ]:      223794 :     if (*nextp == '\0')
    2880                 :       23316 :         return true;            /* empty string represents empty list */
    2881                 :             : 
    2882                 :             :     /* At the top of the loop, we are at start of a new identifier. */
    2883                 :             :     do
    2884                 :             :     {
    2885                 :             :         char       *curname;
    2886                 :             :         char       *endp;
    2887                 :             : 
    2888                 :      372701 :         curname = scan_identifier(&endp, &nextp, separator, true);
    2889         [ -  + ]:      372701 :         if (curname == NULL)
    2890                 :           1 :             return false;       /* mismatched quotes or empty name */
    2891                 :             : 
    2892         [ +  + ]:      372702 :         while (scanner_isspace(*nextp))
    2893                 :           1 :             nextp++;            /* skip trailing whitespace */
    2894                 :             : 
    2895         [ +  + ]:      372701 :         if (*nextp == separator)
    2896                 :             :         {
    2897                 :      172223 :             nextp++;
    2898         [ +  + ]:      329540 :             while (scanner_isspace(*nextp))
    2899                 :      157317 :                 nextp++;        /* skip leading whitespace for next */
    2900                 :             :             /* we expect another name, so done remains false */
    2901                 :             :         }
    2902         [ +  + ]:      200478 :         else if (*nextp == '\0')
    2903                 :      200477 :             done = true;
    2904                 :             :         else
    2905                 :           1 :             return false;       /* invalid syntax */
    2906                 :             : 
    2907                 :             :         /* Now safe to overwrite separator with a null */
    2908                 :      372700 :         *endp = '\0';
    2909                 :             : 
    2910                 :             :         /* Truncate name if it's overlength */
    2911                 :      372700 :         truncate_identifier(curname, strlen(curname), false);
    2912                 :             : 
    2913                 :             :         /*
    2914                 :             :          * Finished isolating current name --- add it to list
    2915                 :             :          */
    2916                 :      372700 :         *namelist = lappend(*namelist, curname);
    2917                 :             : 
    2918                 :             :         /* Loop back if we didn't reach end of string */
    2919         [ +  + ]:      372700 :     } while (!done);
    2920                 :             : 
    2921                 :      200477 :     return true;
    2922                 :             : }
    2923                 :             : 
    2924                 :             : 
    2925                 :             : /*
    2926                 :             :  * SplitDirectoriesString --- parse a string containing file/directory names
    2927                 :             :  *
    2928                 :             :  * This works fine on file names too; the function name is historical.
    2929                 :             :  *
    2930                 :             :  * This is similar to SplitIdentifierString, except that the parsing
    2931                 :             :  * rules are meant to handle pathnames instead of identifiers: there is
    2932                 :             :  * no downcasing, embedded spaces are allowed, the max length is MAXPGPATH-1,
    2933                 :             :  * and we apply canonicalize_path() to each extracted string.  Because of the
    2934                 :             :  * last, the returned strings are separately palloc'd rather than being
    2935                 :             :  * pointers into rawstring --- but we still scribble on rawstring.
    2936                 :             :  *
    2937                 :             :  * Inputs:
    2938                 :             :  *  rawstring: the input string; must be modifiable!
    2939                 :             :  *  separator: the separator punctuation expected between directories
    2940                 :             :  *             (typically ',' or ';').  Whitespace may also appear around
    2941                 :             :  *             directories.
    2942                 :             :  * Outputs:
    2943                 :             :  *  namelist: filled with a palloc'd list of directory names.
    2944                 :             :  *            Caller should list_free_deep() this even on error return.
    2945                 :             :  *
    2946                 :             :  * Returns true if okay, false if there is a syntax error in the string.
    2947                 :             :  *
    2948                 :             :  * Note that an empty string is considered okay here.
    2949                 :             :  */
    2950                 :             : bool
    2951                 :        1160 : SplitDirectoriesString(char *rawstring, char separator,
    2952                 :             :                        List **namelist)
    2953                 :             : {
    2954                 :        1160 :     char       *nextp = rawstring;
    2955                 :        1160 :     bool        done = false;
    2956                 :             : 
    2957                 :        1160 :     *namelist = NIL;
    2958                 :             : 
    2959         [ -  + ]:        1160 :     while (scanner_isspace(*nextp))
    2960                 :           0 :         nextp++;                /* skip leading whitespace */
    2961                 :             : 
    2962         [ +  + ]:        1160 :     if (*nextp == '\0')
    2963                 :           1 :         return true;            /* empty string represents empty list */
    2964                 :             : 
    2965                 :             :     /* At the top of the loop, we are at start of a new directory. */
    2966                 :             :     do
    2967                 :             :     {
    2968                 :             :         char       *curname;
    2969                 :             :         char       *endp;
    2970                 :             : 
    2971         [ -  + ]:        1189 :         if (*nextp == '"')
    2972                 :             :         {
    2973                 :             :             /* Quoted name --- collapse quote-quote pairs */
    2974                 :           0 :             curname = scan_quoted_identifier(&endp, &nextp);
    2975         [ #  # ]:           0 :             if (curname == NULL)
    2976                 :           0 :                 return false;   /* mismatched quotes */
    2977                 :             :         }
    2978                 :             :         else
    2979                 :             :         {
    2980                 :             :             /* Unquoted name --- extends to separator or end of string */
    2981                 :        1189 :             curname = endp = nextp;
    2982   [ +  +  +  + ]:       19823 :             while (*nextp && *nextp != separator)
    2983                 :             :             {
    2984                 :             :                 /* trailing whitespace should not be included in name */
    2985         [ +  - ]:       18634 :                 if (!scanner_isspace(*nextp))
    2986                 :       18634 :                     endp = nextp + 1;
    2987                 :       18634 :                 nextp++;
    2988                 :             :             }
    2989         [ -  + ]:        1189 :             if (curname == endp)
    2990                 :           0 :                 return false;   /* empty unquoted name not allowed */
    2991                 :             :         }
    2992                 :             : 
    2993         [ -  + ]:        1189 :         while (scanner_isspace(*nextp))
    2994                 :           0 :             nextp++;            /* skip trailing whitespace */
    2995                 :             : 
    2996         [ +  + ]:        1189 :         if (*nextp == separator)
    2997                 :             :         {
    2998                 :          30 :             nextp++;
    2999         [ +  + ]:          43 :             while (scanner_isspace(*nextp))
    3000                 :          13 :                 nextp++;        /* skip leading whitespace for next */
    3001                 :             :             /* we expect another name, so done remains false */
    3002                 :             :         }
    3003         [ +  - ]:        1159 :         else if (*nextp == '\0')
    3004                 :        1159 :             done = true;
    3005                 :             :         else
    3006                 :           0 :             return false;       /* invalid syntax */
    3007                 :             : 
    3008                 :             :         /* Now safe to overwrite separator with a null */
    3009                 :        1189 :         *endp = '\0';
    3010                 :             : 
    3011                 :             :         /* Truncate path if it's overlength */
    3012         [ -  + ]:        1189 :         if (strlen(curname) >= MAXPGPATH)
    3013                 :           0 :             curname[MAXPGPATH - 1] = '\0';
    3014                 :             : 
    3015                 :             :         /*
    3016                 :             :          * Finished isolating current name --- add it to list
    3017                 :             :          */
    3018                 :        1189 :         curname = pstrdup(curname);
    3019                 :        1189 :         canonicalize_path(curname);
    3020                 :        1189 :         *namelist = lappend(*namelist, curname);
    3021                 :             : 
    3022                 :             :         /* Loop back if we didn't reach end of string */
    3023         [ +  + ]:        1189 :     } while (!done);
    3024                 :             : 
    3025                 :        1159 :     return true;
    3026                 :             : }
    3027                 :             : 
    3028                 :             : 
    3029                 :             : /*
    3030                 :             :  * SplitGUCList --- parse a string containing identifiers or file names
    3031                 :             :  *
    3032                 :             :  * This is used to split the value of a GUC_LIST_QUOTE GUC variable, without
    3033                 :             :  * presuming whether the elements will be taken as identifiers or file names.
    3034                 :             :  * We assume the input has already been through flatten_set_variable_args(),
    3035                 :             :  * so that we need never downcase (if appropriate, that was done already).
    3036                 :             :  * Nor do we ever truncate, since we don't know the correct max length.
    3037                 :             :  * We disallow embedded whitespace for simplicity (it shouldn't matter,
    3038                 :             :  * because any embedded whitespace should have led to double-quoting).
    3039                 :             :  * Otherwise the API is identical to SplitIdentifierString.
    3040                 :             :  *
    3041                 :             :  * XXX it's annoying to have so many copies of this string-splitting logic.
    3042                 :             :  * However, it's not clear that having one function with a bunch of option
    3043                 :             :  * flags would be much better.
    3044                 :             :  *
    3045                 :             :  * XXX there is a version of this function in src/fe_utils/string_utils.c.
    3046                 :             :  * Be sure to update that if you have to change this.
    3047                 :             :  *
    3048                 :             :  * Inputs:
    3049                 :             :  *  rawstring: the input string; must be overwritable!  On return, it's
    3050                 :             :  *             been modified to contain the separated identifiers.
    3051                 :             :  *  separator: the separator punctuation expected between identifiers
    3052                 :             :  *             (typically '.' or ',').  Whitespace may also appear around
    3053                 :             :  *             identifiers.
    3054                 :             :  * Outputs:
    3055                 :             :  *  namelist: filled with a palloc'd list of pointers to identifiers within
    3056                 :             :  *            rawstring.  Caller should list_free() this even on error return.
    3057                 :             :  *
    3058                 :             :  * Returns true if okay, false if there is a syntax error in the string.
    3059                 :             :  */
    3060                 :             : bool
    3061                 :        7145 : SplitGUCList(char *rawstring, char separator,
    3062                 :             :              List **namelist)
    3063                 :             : {
    3064                 :        7145 :     char       *nextp = rawstring;
    3065                 :        7145 :     bool        done = false;
    3066                 :             : 
    3067                 :        7145 :     *namelist = NIL;
    3068                 :             : 
    3069         [ -  + ]:        7145 :     while (scanner_isspace(*nextp))
    3070                 :           0 :         nextp++;                /* skip leading whitespace */
    3071                 :             : 
    3072         [ +  + ]:        7145 :     if (*nextp == '\0')
    3073                 :        2457 :         return true;            /* empty string represents empty list */
    3074                 :             : 
    3075                 :             :     /* At the top of the loop, we are at start of a new identifier. */
    3076                 :             :     do
    3077                 :             :     {
    3078                 :             :         char       *curname;
    3079                 :             :         char       *endp;
    3080                 :             : 
    3081                 :        7523 :         curname = scan_identifier(&endp, &nextp, separator, false);
    3082         [ +  + ]:        7523 :         if (curname == NULL)
    3083                 :           4 :             return false;       /* mismatched quotes or empty name */
    3084                 :             : 
    3085         [ -  + ]:        7519 :         while (scanner_isspace(*nextp))
    3086                 :           0 :             nextp++;            /* skip trailing whitespace */
    3087                 :             : 
    3088         [ +  + ]:        7519 :         if (*nextp == separator)
    3089                 :             :         {
    3090                 :        2835 :             nextp++;
    3091         [ +  + ]:        5662 :             while (scanner_isspace(*nextp))
    3092                 :        2827 :                 nextp++;        /* skip leading whitespace for next */
    3093                 :             :             /* we expect another name, so done remains false */
    3094                 :             :         }
    3095         [ +  - ]:        4684 :         else if (*nextp == '\0')
    3096                 :        4684 :             done = true;
    3097                 :             :         else
    3098                 :           0 :             return false;       /* invalid syntax */
    3099                 :             : 
    3100                 :             :         /* Now safe to overwrite separator with a null */
    3101                 :        7519 :         *endp = '\0';
    3102                 :             : 
    3103                 :             :         /*
    3104                 :             :          * Finished isolating current name --- add it to list
    3105                 :             :          */
    3106                 :        7519 :         *namelist = lappend(*namelist, curname);
    3107                 :             : 
    3108                 :             :         /* Loop back if we didn't reach end of string */
    3109         [ +  + ]:        7519 :     } while (!done);
    3110                 :             : 
    3111                 :        4684 :     return true;
    3112                 :             : }
    3113                 :             : 
    3114                 :             : /*
    3115                 :             :  * appendStringInfoText
    3116                 :             :  *
    3117                 :             :  * Append a text to str.
    3118                 :             :  * Like appendStringInfoString(str, text_to_cstring(t)) but faster.
    3119                 :             :  */
    3120                 :             : static void
    3121                 :     1366806 : appendStringInfoText(StringInfo str, const text *t)
    3122                 :             : {
    3123                 :     1366806 :     appendBinaryStringInfo(str, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
    3124                 :     1366806 : }
    3125                 :             : 
    3126                 :             : /*
    3127                 :             :  * replace_text
    3128                 :             :  * replace all occurrences of 'old_sub_str' in 'orig_str'
    3129                 :             :  * with 'new_sub_str' to form 'new_str'
    3130                 :             :  *
    3131                 :             :  * returns 'orig_str' if 'old_sub_str' == '' or 'orig_str' == ''
    3132                 :             :  * otherwise returns 'new_str'
    3133                 :             :  */
    3134                 :             : Datum
    3135                 :        1022 : replace_text(PG_FUNCTION_ARGS)
    3136                 :             : {
    3137                 :        1022 :     text       *src_text = PG_GETARG_TEXT_PP(0);
    3138                 :        1022 :     text       *from_sub_text = PG_GETARG_TEXT_PP(1);
    3139                 :        1022 :     text       *to_sub_text = PG_GETARG_TEXT_PP(2);
    3140                 :             :     int         src_text_len;
    3141                 :             :     int         from_sub_text_len;
    3142                 :             :     TextPositionState state;
    3143                 :             :     text       *ret_text;
    3144                 :             :     int         chunk_len;
    3145                 :             :     char       *curr_ptr;
    3146                 :             :     char       *start_ptr;
    3147                 :             :     StringInfoData str;
    3148                 :             :     bool        found;
    3149                 :             : 
    3150                 :        1022 :     src_text_len = VARSIZE_ANY_EXHDR(src_text);
    3151                 :        1022 :     from_sub_text_len = VARSIZE_ANY_EXHDR(from_sub_text);
    3152                 :             : 
    3153                 :             :     /* Return unmodified source string if empty source or pattern */
    3154   [ +  -  -  + ]:        1022 :     if (src_text_len < 1 || from_sub_text_len < 1)
    3155                 :             :     {
    3156                 :           0 :         PG_RETURN_TEXT_P(src_text);
    3157                 :             :     }
    3158                 :             : 
    3159                 :        1022 :     text_position_setup(src_text, from_sub_text, PG_GET_COLLATION(), &state);
    3160                 :             : 
    3161                 :        1022 :     found = text_position_next(&state);
    3162                 :             : 
    3163                 :             :     /* When the from_sub_text is not found, there is nothing to do. */
    3164         [ +  + ]:        1022 :     if (!found)
    3165                 :             :     {
    3166                 :         201 :         text_position_cleanup(&state);
    3167                 :         201 :         PG_RETURN_TEXT_P(src_text);
    3168                 :             :     }
    3169                 :         821 :     curr_ptr = text_position_get_match_ptr(&state);
    3170                 :         821 :     start_ptr = VARDATA_ANY(src_text);
    3171                 :             : 
    3172                 :         821 :     initStringInfo(&str);
    3173                 :             : 
    3174                 :             :     do
    3175                 :             :     {
    3176         [ -  + ]:        4541 :         CHECK_FOR_INTERRUPTS();
    3177                 :             : 
    3178                 :             :         /* copy the data skipped over by last text_position_next() */
    3179                 :        4541 :         chunk_len = curr_ptr - start_ptr;
    3180                 :        4541 :         appendBinaryStringInfo(&str, start_ptr, chunk_len);
    3181                 :             : 
    3182                 :        4541 :         appendStringInfoText(&str, to_sub_text);
    3183                 :             : 
    3184                 :        4541 :         start_ptr = curr_ptr + state.last_match_len;
    3185                 :             : 
    3186                 :        4541 :         found = text_position_next(&state);
    3187         [ +  + ]:        4541 :         if (found)
    3188                 :        3720 :             curr_ptr = text_position_get_match_ptr(&state);
    3189                 :             :     }
    3190         [ +  + ]:        4541 :     while (found);
    3191                 :             : 
    3192                 :             :     /* copy trailing data */
    3193                 :         821 :     chunk_len = ((char *) src_text + VARSIZE_ANY(src_text)) - start_ptr;
    3194                 :         821 :     appendBinaryStringInfo(&str, start_ptr, chunk_len);
    3195                 :             : 
    3196                 :         821 :     text_position_cleanup(&state);
    3197                 :             : 
    3198                 :         821 :     ret_text = cstring_to_text_with_len(str.data, str.len);
    3199                 :         821 :     pfree(str.data);
    3200                 :             : 
    3201                 :         821 :     PG_RETURN_TEXT_P(ret_text);
    3202                 :             : }
    3203                 :             : 
    3204                 :             : /*
    3205                 :             :  * check_replace_text_has_escape
    3206                 :             :  *
    3207                 :             :  * Returns 0 if text contains no backslashes that need processing.
    3208                 :             :  * Returns 1 if text contains backslashes, but not regexp submatch specifiers.
    3209                 :             :  * Returns 2 if text contains regexp submatch specifiers (\1 .. \9).
    3210                 :             :  */
    3211                 :             : static int
    3212                 :       12587 : check_replace_text_has_escape(const text *replace_text)
    3213                 :             : {
    3214                 :       12587 :     int         result = 0;
    3215                 :       12587 :     const char *p = VARDATA_ANY(replace_text);
    3216                 :       12587 :     const char *p_end = p + VARSIZE_ANY_EXHDR(replace_text);
    3217                 :             : 
    3218         [ +  + ]:       25202 :     while (p < p_end)
    3219                 :             :     {
    3220                 :             :         /* Find next escape char, if any. */
    3221                 :       11885 :         p = memchr(p, '\\', p_end - p);
    3222         [ +  + ]:       11885 :         if (p == NULL)
    3223                 :       11321 :             break;
    3224                 :         564 :         p++;
    3225                 :             :         /* Note: a backslash at the end doesn't require extra processing. */
    3226         [ +  - ]:         564 :         if (p < p_end)
    3227                 :             :         {
    3228   [ +  +  +  + ]:         564 :             if (*p >= '1' && *p <= '9')
    3229                 :         536 :                 return 2;       /* Found a submatch specifier, so done */
    3230                 :          28 :             result = 1;         /* Found some other sequence, keep looking */
    3231                 :          28 :             p++;
    3232                 :             :         }
    3233                 :             :     }
    3234                 :       12051 :     return result;
    3235                 :             : }
    3236                 :             : 
    3237                 :             : /*
    3238                 :             :  * appendStringInfoRegexpSubstr
    3239                 :             :  *
    3240                 :             :  * Append replace_text to str, substituting regexp back references for
    3241                 :             :  * \n escapes.  start_ptr is the start of the match in the source string,
    3242                 :             :  * at logical character position data_pos.
    3243                 :             :  */
    3244                 :             : static void
    3245                 :         174 : appendStringInfoRegexpSubstr(StringInfo str, text *replace_text,
    3246                 :             :                              regmatch_t *pmatch,
    3247                 :             :                              char *start_ptr, int data_pos)
    3248                 :             : {
    3249                 :         174 :     const char *p = VARDATA_ANY(replace_text);
    3250                 :         174 :     const char *p_end = p + VARSIZE_ANY_EXHDR(replace_text);
    3251                 :             : 
    3252         [ +  + ]:         416 :     while (p < p_end)
    3253                 :             :     {
    3254                 :         369 :         const char *replace_start = p;
    3255                 :             :         int         so;
    3256                 :             :         int         eo;
    3257                 :             : 
    3258                 :             :         /* Find next escape char, if any. */
    3259                 :         369 :         p = memchr(p, '\\', p_end - p);
    3260         [ +  + ]:         369 :         if (p == NULL)
    3261                 :         122 :             p = p_end;
    3262                 :             : 
    3263                 :             :         /* Copy the text we just scanned over, if any. */
    3264         [ +  + ]:         369 :         if (p > replace_start)
    3265                 :         229 :             appendBinaryStringInfo(str, replace_start, p - replace_start);
    3266                 :             : 
    3267                 :             :         /* Done if at end of string, else advance over escape char. */
    3268         [ +  + ]:         369 :         if (p >= p_end)
    3269                 :         122 :             break;
    3270                 :         247 :         p++;
    3271                 :             : 
    3272         [ +  + ]:         247 :         if (p >= p_end)
    3273                 :             :         {
    3274                 :             :             /* Escape at very end of input.  Treat same as unexpected char */
    3275                 :           5 :             appendStringInfoChar(str, '\\');
    3276                 :           5 :             break;
    3277                 :             :         }
    3278                 :             : 
    3279   [ +  +  +  + ]:         242 :         if (*p >= '1' && *p <= '9')
    3280                 :         198 :         {
    3281                 :             :             /* Use the back reference of regexp. */
    3282                 :         198 :             int         idx = *p - '0';
    3283                 :             : 
    3284                 :         198 :             so = pmatch[idx].rm_so;
    3285                 :         198 :             eo = pmatch[idx].rm_eo;
    3286                 :         198 :             p++;
    3287                 :             :         }
    3288         [ +  + ]:          44 :         else if (*p == '&')
    3289                 :             :         {
    3290                 :             :             /* Use the entire matched string. */
    3291                 :          15 :             so = pmatch[0].rm_so;
    3292                 :          15 :             eo = pmatch[0].rm_eo;
    3293                 :          15 :             p++;
    3294                 :             :         }
    3295         [ +  + ]:          29 :         else if (*p == '\\')
    3296                 :             :         {
    3297                 :             :             /* \\ means transfer one \ to output. */
    3298                 :          24 :             appendStringInfoChar(str, '\\');
    3299                 :          24 :             p++;
    3300                 :          24 :             continue;
    3301                 :             :         }
    3302                 :             :         else
    3303                 :             :         {
    3304                 :             :             /*
    3305                 :             :              * If escape char is not followed by any expected char, just treat
    3306                 :             :              * it as ordinary data to copy.  (XXX would it be better to throw
    3307                 :             :              * an error?)
    3308                 :             :              */
    3309                 :           5 :             appendStringInfoChar(str, '\\');
    3310                 :           5 :             continue;
    3311                 :             :         }
    3312                 :             : 
    3313   [ +  -  +  - ]:         213 :         if (so >= 0 && eo >= 0)
    3314                 :             :         {
    3315                 :             :             /*
    3316                 :             :              * Copy the text that is back reference of regexp.  Note so and eo
    3317                 :             :              * are counted in characters not bytes.
    3318                 :             :              */
    3319                 :             :             char       *chunk_start;
    3320                 :             :             int         chunk_len;
    3321                 :             : 
    3322                 :             :             Assert(so >= data_pos);
    3323                 :         213 :             chunk_start = start_ptr;
    3324                 :         213 :             chunk_start += charlen_to_bytelen(chunk_start, so - data_pos);
    3325                 :         213 :             chunk_len = charlen_to_bytelen(chunk_start, eo - so);
    3326                 :         213 :             appendBinaryStringInfo(str, chunk_start, chunk_len);
    3327                 :             :         }
    3328                 :             :     }
    3329                 :         174 : }
    3330                 :             : 
    3331                 :             : /*
    3332                 :             :  * replace_text_regexp
    3333                 :             :  *
    3334                 :             :  * replace substring(s) in src_text that match pattern with replace_text.
    3335                 :             :  * The replace_text can contain backslash markers to substitute
    3336                 :             :  * (parts of) the matched text.
    3337                 :             :  *
    3338                 :             :  * cflags: regexp compile flags.
    3339                 :             :  * collation: collation to use.
    3340                 :             :  * search_start: the character (not byte) offset in src_text at which to
    3341                 :             :  * begin searching.
    3342                 :             :  * n: if 0, replace all matches; if > 0, replace only the N'th match.
    3343                 :             :  */
    3344                 :             : text *
    3345                 :       12587 : replace_text_regexp(text *src_text, text *pattern_text,
    3346                 :             :                     text *replace_text,
    3347                 :             :                     int cflags, Oid collation,
    3348                 :             :                     int search_start, int n)
    3349                 :             : {
    3350                 :             :     text       *ret_text;
    3351                 :             :     regex_t    *re;
    3352                 :       12587 :     int         src_text_len = VARSIZE_ANY_EXHDR(src_text);
    3353                 :       12587 :     int         nmatches = 0;
    3354                 :             :     StringInfoData buf;
    3355                 :             :     regmatch_t  pmatch[10];     /* main match, plus \1 to \9 */
    3356                 :       12587 :     int         nmatch = lengthof(pmatch);
    3357                 :             :     pg_wchar   *data;
    3358                 :             :     size_t      data_len;
    3359                 :             :     int         data_pos;
    3360                 :             :     char       *start_ptr;
    3361                 :             :     int         escape_status;
    3362                 :             : 
    3363                 :       12587 :     initStringInfo(&buf);
    3364                 :             : 
    3365                 :             :     /* Convert data string to wide characters. */
    3366                 :       12587 :     data = (pg_wchar *) palloc((src_text_len + 1) * sizeof(pg_wchar));
    3367                 :       12587 :     data_len = pg_mb2wchar_with_len(VARDATA_ANY(src_text), data, src_text_len);
    3368                 :             : 
    3369                 :             :     /* Check whether replace_text has escapes, especially regexp submatches. */
    3370                 :       12587 :     escape_status = check_replace_text_has_escape(replace_text);
    3371                 :             : 
    3372                 :             :     /* If no regexp submatches, we can use REG_NOSUB. */
    3373         [ +  + ]:       12587 :     if (escape_status < 2)
    3374                 :             :     {
    3375                 :       12051 :         cflags |= REG_NOSUB;
    3376                 :             :         /* Also tell pg_regexec we only want the whole-match location. */
    3377                 :       12051 :         nmatch = 1;
    3378                 :             :     }
    3379                 :             : 
    3380                 :             :     /* Prepare the regexp. */
    3381                 :       12587 :     re = RE_compile_and_cache(pattern_text, cflags, collation);
    3382                 :             : 
    3383                 :             :     /* start_ptr points to the data_pos'th character of src_text */
    3384                 :       12587 :     start_ptr = (char *) VARDATA_ANY(src_text);
    3385                 :       12587 :     data_pos = 0;
    3386                 :             : 
    3387         [ +  + ]:       17184 :     while (search_start <= data_len)
    3388                 :             :     {
    3389                 :             :         int         regexec_result;
    3390                 :             : 
    3391         [ -  + ]:       17179 :         CHECK_FOR_INTERRUPTS();
    3392                 :             : 
    3393                 :       17179 :         regexec_result = pg_regexec(re,
    3394                 :             :                                     data,
    3395                 :             :                                     data_len,
    3396                 :             :                                     search_start,
    3397                 :             :                                     NULL,   /* no details */
    3398                 :             :                                     nmatch,
    3399                 :             :                                     pmatch,
    3400                 :             :                                     0);
    3401                 :             : 
    3402         [ +  + ]:       17179 :         if (regexec_result == REG_NOMATCH)
    3403                 :       11138 :             break;
    3404                 :             : 
    3405         [ -  + ]:        6041 :         if (regexec_result != REG_OKAY)
    3406                 :             :         {
    3407                 :             :             char        errMsg[100];
    3408                 :             : 
    3409                 :           0 :             pg_regerror(regexec_result, re, errMsg, sizeof(errMsg));
    3410         [ #  # ]:           0 :             ereport(ERROR,
    3411                 :             :                     (errcode(ERRCODE_INVALID_REGULAR_EXPRESSION),
    3412                 :             :                      errmsg("regular expression failed: %s", errMsg)));
    3413                 :             :         }
    3414                 :             : 
    3415                 :             :         /*
    3416                 :             :          * Count matches, and decide whether to replace this match.
    3417                 :             :          */
    3418                 :        6041 :         nmatches++;
    3419   [ +  +  +  + ]:        6041 :         if (n > 0 && nmatches != n)
    3420                 :             :         {
    3421                 :             :             /*
    3422                 :             :              * No, so advance search_start, but not start_ptr/data_pos. (Thus,
    3423                 :             :              * we treat the matched text as if it weren't matched, and copy it
    3424                 :             :              * to the output later.)
    3425                 :             :              */
    3426                 :          50 :             search_start = pmatch[0].rm_eo;
    3427         [ -  + ]:          50 :             if (pmatch[0].rm_so == pmatch[0].rm_eo)
    3428                 :           0 :                 search_start++;
    3429                 :          50 :             continue;
    3430                 :             :         }
    3431                 :             : 
    3432                 :             :         /*
    3433                 :             :          * Copy the text to the left of the match position.  Note we are given
    3434                 :             :          * character not byte indexes.
    3435                 :             :          */
    3436         [ +  + ]:        5991 :         if (pmatch[0].rm_so - data_pos > 0)
    3437                 :             :         {
    3438                 :             :             int         chunk_len;
    3439                 :             : 
    3440                 :        5863 :             chunk_len = charlen_to_bytelen(start_ptr,
    3441                 :        5863 :                                            pmatch[0].rm_so - data_pos);
    3442                 :        5863 :             appendBinaryStringInfo(&buf, start_ptr, chunk_len);
    3443                 :             : 
    3444                 :             :             /*
    3445                 :             :              * Advance start_ptr over that text, to avoid multiple rescans of
    3446                 :             :              * it if the replace_text contains multiple back-references.
    3447                 :             :              */
    3448                 :        5863 :             start_ptr += chunk_len;
    3449                 :        5863 :             data_pos = pmatch[0].rm_so;
    3450                 :             :         }
    3451                 :             : 
    3452                 :             :         /*
    3453                 :             :          * Copy the replace_text, processing escapes if any are present.
    3454                 :             :          */
    3455         [ +  + ]:        5991 :         if (escape_status > 0)
    3456                 :         174 :             appendStringInfoRegexpSubstr(&buf, replace_text, pmatch,
    3457                 :             :                                          start_ptr, data_pos);
    3458                 :             :         else
    3459                 :        5817 :             appendStringInfoText(&buf, replace_text);
    3460                 :             : 
    3461                 :             :         /* Advance start_ptr and data_pos over the matched text. */
    3462                 :       11982 :         start_ptr += charlen_to_bytelen(start_ptr,
    3463                 :        5991 :                                         pmatch[0].rm_eo - data_pos);
    3464                 :        5991 :         data_pos = pmatch[0].rm_eo;
    3465                 :             : 
    3466                 :             :         /*
    3467                 :             :          * If we only want to replace one occurrence, we're done.
    3468                 :             :          */
    3469         [ +  + ]:        5991 :         if (n > 0)
    3470                 :        1444 :             break;
    3471                 :             : 
    3472                 :             :         /*
    3473                 :             :          * Advance search position.  Normally we start the next search at the
    3474                 :             :          * end of the previous match; but if the match was of zero length, we
    3475                 :             :          * have to advance by one character, or we'd just find the same match
    3476                 :             :          * again.
    3477                 :             :          */
    3478                 :        4547 :         search_start = data_pos;
    3479         [ +  + ]:        4547 :         if (pmatch[0].rm_so == pmatch[0].rm_eo)
    3480                 :          10 :             search_start++;
    3481                 :             :     }
    3482                 :             : 
    3483                 :             :     /*
    3484                 :             :      * Copy the text to the right of the last match.
    3485                 :             :      */
    3486         [ +  + ]:       12587 :     if (data_pos < data_len)
    3487                 :             :     {
    3488                 :             :         int         chunk_len;
    3489                 :             : 
    3490                 :       11936 :         chunk_len = ((char *) src_text + VARSIZE_ANY(src_text)) - start_ptr;
    3491                 :       11936 :         appendBinaryStringInfo(&buf, start_ptr, chunk_len);
    3492                 :             :     }
    3493                 :             : 
    3494                 :       12587 :     ret_text = cstring_to_text_with_len(buf.data, buf.len);
    3495                 :       12587 :     pfree(buf.data);
    3496                 :       12587 :     pfree(data);
    3497                 :             : 
    3498                 :       12587 :     return ret_text;
    3499                 :             : }
    3500                 :             : 
    3501                 :             : /*
    3502                 :             :  * split_part
    3503                 :             :  * parse input string based on provided field separator
    3504                 :             :  * return N'th item (1 based, negative counts from end)
    3505                 :             :  */
    3506                 :             : Datum
    3507                 :         128 : split_part(PG_FUNCTION_ARGS)
    3508                 :             : {
    3509                 :         128 :     text       *inputstring = PG_GETARG_TEXT_PP(0);
    3510                 :         128 :     text       *fldsep = PG_GETARG_TEXT_PP(1);
    3511                 :         128 :     int         fldnum = PG_GETARG_INT32(2);
    3512                 :             :     int         inputstring_len;
    3513                 :             :     int         fldsep_len;
    3514                 :             :     TextPositionState state;
    3515                 :             :     char       *start_ptr;
    3516                 :             :     char       *end_ptr;
    3517                 :             :     text       *result_text;
    3518                 :             :     bool        found;
    3519                 :             : 
    3520                 :             :     /* field number is 1 based */
    3521         [ +  + ]:         128 :     if (fldnum == 0)
    3522         [ +  - ]:           4 :         ereport(ERROR,
    3523                 :             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    3524                 :             :                  errmsg("field position must not be zero")));
    3525                 :             : 
    3526                 :         124 :     inputstring_len = VARSIZE_ANY_EXHDR(inputstring);
    3527                 :         124 :     fldsep_len = VARSIZE_ANY_EXHDR(fldsep);
    3528                 :             : 
    3529                 :             :     /* return empty string for empty input string */
    3530         [ +  + ]:         124 :     if (inputstring_len < 1)
    3531                 :          10 :         PG_RETURN_TEXT_P(cstring_to_text(""));
    3532                 :             : 
    3533                 :             :     /* handle empty field separator */
    3534         [ +  + ]:         114 :     if (fldsep_len < 1)
    3535                 :             :     {
    3536                 :             :         /* if first or last field, return input string, else empty string */
    3537   [ +  +  +  + ]:          20 :         if (fldnum == 1 || fldnum == -1)
    3538                 :          10 :             PG_RETURN_TEXT_P(inputstring);
    3539                 :             :         else
    3540                 :          10 :             PG_RETURN_TEXT_P(cstring_to_text(""));
    3541                 :             :     }
    3542                 :             : 
    3543                 :             :     /* find the first field separator */
    3544                 :          94 :     text_position_setup(inputstring, fldsep, PG_GET_COLLATION(), &state);
    3545                 :             : 
    3546                 :          94 :     found = text_position_next(&state);
    3547                 :             : 
    3548                 :             :     /* special case if fldsep not found at all */
    3549         [ +  + ]:          94 :     if (!found)
    3550                 :             :     {
    3551                 :          18 :         text_position_cleanup(&state);
    3552                 :             :         /* if first or last field, return input string, else empty string */
    3553   [ +  +  +  + ]:          18 :         if (fldnum == 1 || fldnum == -1)
    3554                 :           9 :             PG_RETURN_TEXT_P(inputstring);
    3555                 :             :         else
    3556                 :           9 :             PG_RETURN_TEXT_P(cstring_to_text(""));
    3557                 :             :     }
    3558                 :             : 
    3559                 :             :     /*
    3560                 :             :      * take care of a negative field number (i.e. count from the right) by
    3561                 :             :      * converting to a positive field number; we need total number of fields
    3562                 :             :      */
    3563         [ +  + ]:          76 :     if (fldnum < 0)
    3564                 :             :     {
    3565                 :             :         /* we found a fldsep, so there are at least two fields */
    3566                 :          36 :         int         numfields = 2;
    3567                 :             : 
    3568         [ +  + ]:          54 :         while (text_position_next(&state))
    3569                 :          18 :             numfields++;
    3570                 :             : 
    3571                 :             :         /* special case of last field does not require an extra pass */
    3572         [ +  + ]:          36 :         if (fldnum == -1)
    3573                 :             :         {
    3574                 :          17 :             start_ptr = text_position_get_match_ptr(&state) + state.last_match_len;
    3575                 :          17 :             end_ptr = VARDATA_ANY(inputstring) + inputstring_len;
    3576                 :          17 :             text_position_cleanup(&state);
    3577                 :          17 :             PG_RETURN_TEXT_P(cstring_to_text_with_len(start_ptr,
    3578                 :             :                                                       end_ptr - start_ptr));
    3579                 :             :         }
    3580                 :             : 
    3581                 :             :         /* else, convert fldnum to positive notation */
    3582                 :          19 :         fldnum += numfields + 1;
    3583                 :             : 
    3584                 :             :         /* if nonexistent field, return empty string */
    3585         [ +  + ]:          19 :         if (fldnum <= 0)
    3586                 :             :         {
    3587                 :           5 :             text_position_cleanup(&state);
    3588                 :           5 :             PG_RETURN_TEXT_P(cstring_to_text(""));
    3589                 :             :         }
    3590                 :             : 
    3591                 :             :         /* reset to pointing at first match, but now with positive fldnum */
    3592                 :          14 :         text_position_reset(&state);
    3593                 :          14 :         found = text_position_next(&state);
    3594                 :             :         Assert(found);
    3595                 :             :     }
    3596                 :             : 
    3597                 :             :     /* identify bounds of first field */
    3598                 :          54 :     start_ptr = VARDATA_ANY(inputstring);
    3599                 :          54 :     end_ptr = text_position_get_match_ptr(&state);
    3600                 :             : 
    3601   [ +  +  +  + ]:         107 :     while (found && --fldnum > 0)
    3602                 :             :     {
    3603                 :             :         /* identify bounds of next field */
    3604                 :          53 :         start_ptr = end_ptr + state.last_match_len;
    3605                 :          53 :         found = text_position_next(&state);
    3606         [ +  + ]:          53 :         if (found)
    3607                 :          31 :             end_ptr = text_position_get_match_ptr(&state);
    3608                 :             :     }
    3609                 :             : 
    3610                 :          54 :     text_position_cleanup(&state);
    3611                 :             : 
    3612         [ +  + ]:          54 :     if (fldnum > 0)
    3613                 :             :     {
    3614                 :             :         /* N'th field separator not found */
    3615                 :             :         /* if last field requested, return it, else empty string */
    3616         [ +  + ]:          22 :         if (fldnum == 1)
    3617                 :             :         {
    3618                 :          17 :             int         last_len = start_ptr - VARDATA_ANY(inputstring);
    3619                 :             : 
    3620                 :          17 :             result_text = cstring_to_text_with_len(start_ptr,
    3621                 :             :                                                    inputstring_len - last_len);
    3622                 :             :         }
    3623                 :             :         else
    3624                 :           5 :             result_text = cstring_to_text("");
    3625                 :             :     }
    3626                 :             :     else
    3627                 :             :     {
    3628                 :             :         /* non-last field requested */
    3629                 :          32 :         result_text = cstring_to_text_with_len(start_ptr, end_ptr - start_ptr);
    3630                 :             :     }
    3631                 :             : 
    3632                 :          54 :     PG_RETURN_TEXT_P(result_text);
    3633                 :             : }
    3634                 :             : 
    3635                 :             : /*
    3636                 :             :  * Convenience function to return true when two text params are equal.
    3637                 :             :  */
    3638                 :             : static bool
    3639                 :         306 : text_isequal(text *txt1, text *txt2, Oid collid)
    3640                 :             : {
    3641                 :         306 :     return DatumGetBool(DirectFunctionCall2Coll(texteq,
    3642                 :             :                                                 collid,
    3643                 :             :                                                 PointerGetDatum(txt1),
    3644                 :             :                                                 PointerGetDatum(txt2)));
    3645                 :             : }
    3646                 :             : 
    3647                 :             : /*
    3648                 :             :  * text_to_array
    3649                 :             :  * parse input string and return text array of elements,
    3650                 :             :  * based on provided field separator
    3651                 :             :  */
    3652                 :             : Datum
    3653                 :         136 : text_to_array(PG_FUNCTION_ARGS)
    3654                 :             : {
    3655                 :             :     SplitTextOutputData tstate;
    3656                 :             : 
    3657                 :             :     /* For array output, tstate should start as all zeroes */
    3658                 :         136 :     memset(&tstate, 0, sizeof(tstate));
    3659                 :             : 
    3660         [ +  + ]:         136 :     if (!split_text(fcinfo, &tstate))
    3661                 :           5 :         PG_RETURN_NULL();
    3662                 :             : 
    3663         [ +  + ]:         131 :     if (tstate.astate == NULL)
    3664                 :           5 :         PG_RETURN_ARRAYTYPE_P(construct_empty_array(TEXTOID));
    3665                 :             : 
    3666                 :         126 :     PG_RETURN_DATUM(makeArrayResult(tstate.astate,
    3667                 :             :                                     CurrentMemoryContext));
    3668                 :             : }
    3669                 :             : 
    3670                 :             : /*
    3671                 :             :  * text_to_array_null
    3672                 :             :  * parse input string and return text array of elements,
    3673                 :             :  * based on provided field separator and null string
    3674                 :             :  *
    3675                 :             :  * This is a separate entry point only to prevent the regression tests from
    3676                 :             :  * complaining about different argument sets for the same internal function.
    3677                 :             :  */
    3678                 :             : Datum
    3679                 :          50 : text_to_array_null(PG_FUNCTION_ARGS)
    3680                 :             : {
    3681                 :          50 :     return text_to_array(fcinfo);
    3682                 :             : }
    3683                 :             : 
    3684                 :             : /*
    3685                 :             :  * text_to_table
    3686                 :             :  * parse input string and return table of elements,
    3687                 :             :  * based on provided field separator
    3688                 :             :  */
    3689                 :             : Datum
    3690                 :          56 : text_to_table(PG_FUNCTION_ARGS)
    3691                 :             : {
    3692                 :          56 :     ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
    3693                 :             :     SplitTextOutputData tstate;
    3694                 :             : 
    3695                 :          56 :     tstate.astate = NULL;
    3696                 :          56 :     InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC);
    3697                 :          56 :     tstate.tupstore = rsi->setResult;
    3698                 :          56 :     tstate.tupdesc = rsi->setDesc;
    3699                 :             : 
    3700                 :          56 :     (void) split_text(fcinfo, &tstate);
    3701                 :             : 
    3702                 :          56 :     return (Datum) 0;
    3703                 :             : }
    3704                 :             : 
    3705                 :             : /*
    3706                 :             :  * text_to_table_null
    3707                 :             :  * parse input string and return table of elements,
    3708                 :             :  * based on provided field separator and null string
    3709                 :             :  *
    3710                 :             :  * This is a separate entry point only to prevent the regression tests from
    3711                 :             :  * complaining about different argument sets for the same internal function.
    3712                 :             :  */
    3713                 :             : Datum
    3714                 :          16 : text_to_table_null(PG_FUNCTION_ARGS)
    3715                 :             : {
    3716                 :          16 :     return text_to_table(fcinfo);
    3717                 :             : }
    3718                 :             : 
    3719                 :             : /*
    3720                 :             :  * Common code for text_to_array, text_to_array_null, text_to_table
    3721                 :             :  * and text_to_table_null functions.
    3722                 :             :  *
    3723                 :             :  * These are not strict so we have to test for null inputs explicitly.
    3724                 :             :  * Returns false if result is to be null, else returns true.
    3725                 :             :  *
    3726                 :             :  * Note that if the result is valid but empty (zero elements), we return
    3727                 :             :  * without changing *tstate --- caller must handle that case, too.
    3728                 :             :  */
    3729                 :             : static bool
    3730                 :         192 : split_text(FunctionCallInfo fcinfo, SplitTextOutputData *tstate)
    3731                 :             : {
    3732                 :             :     text       *inputstring;
    3733                 :             :     text       *fldsep;
    3734                 :             :     text       *null_string;
    3735                 :         192 :     Oid         collation = PG_GET_COLLATION();
    3736                 :             :     int         inputstring_len;
    3737                 :             :     int         fldsep_len;
    3738                 :             :     char       *start_ptr;
    3739                 :             :     text       *result_text;
    3740                 :             : 
    3741                 :             :     /* when input string is NULL, then result is NULL too */
    3742         [ +  + ]:         192 :     if (PG_ARGISNULL(0))
    3743                 :           9 :         return false;
    3744                 :             : 
    3745                 :         183 :     inputstring = PG_GETARG_TEXT_PP(0);
    3746                 :             : 
    3747                 :             :     /* fldsep can be NULL */
    3748         [ +  + ]:         183 :     if (!PG_ARGISNULL(1))
    3749                 :         159 :         fldsep = PG_GETARG_TEXT_PP(1);
    3750                 :             :     else
    3751                 :          24 :         fldsep = NULL;
    3752                 :             : 
    3753                 :             :     /* null_string can be NULL or omitted */
    3754   [ +  +  +  - ]:         183 :     if (PG_NARGS() > 2 && !PG_ARGISNULL(2))
    3755                 :          66 :         null_string = PG_GETARG_TEXT_PP(2);
    3756                 :             :     else
    3757                 :         117 :         null_string = NULL;
    3758                 :             : 
    3759         [ +  + ]:         183 :     if (fldsep != NULL)
    3760                 :             :     {
    3761                 :             :         /*
    3762                 :             :          * Normal case with non-null fldsep.  Use the text_position machinery
    3763                 :             :          * to search for occurrences of fldsep.
    3764                 :             :          */
    3765                 :             :         TextPositionState state;
    3766                 :             : 
    3767                 :         159 :         inputstring_len = VARSIZE_ANY_EXHDR(inputstring);
    3768                 :         159 :         fldsep_len = VARSIZE_ANY_EXHDR(fldsep);
    3769                 :             : 
    3770                 :             :         /* return empty set for empty input string */
    3771         [ +  + ]:         159 :         if (inputstring_len < 1)
    3772                 :          46 :             return true;
    3773                 :             : 
    3774                 :             :         /* empty field separator: return input string as a one-element set */
    3775         [ +  + ]:         150 :         if (fldsep_len < 1)
    3776                 :             :         {
    3777                 :          37 :             split_text_accum_result(tstate, inputstring,
    3778                 :             :                                     null_string, collation);
    3779                 :          37 :             return true;
    3780                 :             :         }
    3781                 :             : 
    3782                 :         113 :         text_position_setup(inputstring, fldsep, collation, &state);
    3783                 :             : 
    3784                 :         113 :         start_ptr = VARDATA_ANY(inputstring);
    3785                 :             : 
    3786                 :             :         for (;;)
    3787                 :         371 :         {
    3788                 :             :             bool        found;
    3789                 :             :             char       *end_ptr;
    3790                 :             :             int         chunk_len;
    3791                 :             : 
    3792         [ -  + ]:         484 :             CHECK_FOR_INTERRUPTS();
    3793                 :             : 
    3794                 :         484 :             found = text_position_next(&state);
    3795         [ +  + ]:         484 :             if (!found)
    3796                 :             :             {
    3797                 :             :                 /* fetch last field */
    3798                 :         113 :                 chunk_len = ((char *) inputstring + VARSIZE_ANY(inputstring)) - start_ptr;
    3799                 :         113 :                 end_ptr = NULL; /* not used, but some compilers complain */
    3800                 :             :             }
    3801                 :             :             else
    3802                 :             :             {
    3803                 :             :                 /* fetch non-last field */
    3804                 :         371 :                 end_ptr = text_position_get_match_ptr(&state);
    3805                 :         371 :                 chunk_len = end_ptr - start_ptr;
    3806                 :             :             }
    3807                 :             : 
    3808                 :             :             /* build a temp text datum to pass to split_text_accum_result */
    3809                 :         484 :             result_text = cstring_to_text_with_len(start_ptr, chunk_len);
    3810                 :             : 
    3811                 :             :             /* stash away this field */
    3812                 :         484 :             split_text_accum_result(tstate, result_text,
    3813                 :             :                                     null_string, collation);
    3814                 :             : 
    3815                 :         484 :             pfree(result_text);
    3816                 :             : 
    3817         [ +  + ]:         484 :             if (!found)
    3818                 :         113 :                 break;
    3819                 :             : 
    3820                 :         371 :             start_ptr = end_ptr + state.last_match_len;
    3821                 :             :         }
    3822                 :             : 
    3823                 :         113 :         text_position_cleanup(&state);
    3824                 :             :     }
    3825                 :             :     else
    3826                 :             :     {
    3827                 :             :         const char *end_ptr;
    3828                 :             : 
    3829                 :             :         /*
    3830                 :             :          * When fldsep is NULL, each character in the input string becomes a
    3831                 :             :          * separate element in the result set.  The separator is effectively
    3832                 :             :          * the space between characters.
    3833                 :             :          */
    3834                 :          24 :         inputstring_len = VARSIZE_ANY_EXHDR(inputstring);
    3835                 :             : 
    3836                 :          24 :         start_ptr = VARDATA_ANY(inputstring);
    3837                 :          24 :         end_ptr = start_ptr + inputstring_len;
    3838                 :             : 
    3839         [ +  + ]:         204 :         while (inputstring_len > 0)
    3840                 :             :         {
    3841                 :         180 :             int         chunk_len = pg_mblen_range(start_ptr, end_ptr);
    3842                 :             : 
    3843         [ -  + ]:         180 :             CHECK_FOR_INTERRUPTS();
    3844                 :             : 
    3845                 :             :             /* build a temp text datum to pass to split_text_accum_result */
    3846                 :         180 :             result_text = cstring_to_text_with_len(start_ptr, chunk_len);
    3847                 :             : 
    3848                 :             :             /* stash away this field */
    3849                 :         180 :             split_text_accum_result(tstate, result_text,
    3850                 :             :                                     null_string, collation);
    3851                 :             : 
    3852                 :         180 :             pfree(result_text);
    3853                 :             : 
    3854                 :         180 :             start_ptr += chunk_len;
    3855                 :         180 :             inputstring_len -= chunk_len;
    3856                 :             :         }
    3857                 :             :     }
    3858                 :             : 
    3859                 :         137 :     return true;
    3860                 :             : }
    3861                 :             : 
    3862                 :             : /*
    3863                 :             :  * Add text item to result set (table or array).
    3864                 :             :  *
    3865                 :             :  * This is also responsible for checking to see if the item matches
    3866                 :             :  * the null_string, in which case we should emit NULL instead.
    3867                 :             :  */
    3868                 :             : static void
    3869                 :         701 : split_text_accum_result(SplitTextOutputData *tstate,
    3870                 :             :                         text *field_value,
    3871                 :             :                         text *null_string,
    3872                 :             :                         Oid collation)
    3873                 :             : {
    3874                 :         701 :     bool        is_null = false;
    3875                 :             : 
    3876   [ +  +  +  + ]:         701 :     if (null_string && text_isequal(field_value, null_string, collation))
    3877                 :          56 :         is_null = true;
    3878                 :             : 
    3879         [ +  + ]:         701 :     if (tstate->tupstore)
    3880                 :             :     {
    3881                 :             :         Datum       values[1];
    3882                 :             :         bool        nulls[1];
    3883                 :             : 
    3884                 :         152 :         values[0] = PointerGetDatum(field_value);
    3885                 :         152 :         nulls[0] = is_null;
    3886                 :             : 
    3887                 :         152 :         tuplestore_putvalues(tstate->tupstore,
    3888                 :             :                              tstate->tupdesc,
    3889                 :             :                              values,
    3890                 :             :                              nulls);
    3891                 :             :     }
    3892                 :             :     else
    3893                 :             :     {
    3894                 :         549 :         tstate->astate = accumArrayResult(tstate->astate,
    3895                 :             :                                           PointerGetDatum(field_value),
    3896                 :             :                                           is_null,
    3897                 :             :                                           TEXTOID,
    3898                 :             :                                           CurrentMemoryContext);
    3899                 :             :     }
    3900                 :         701 : }
    3901                 :             : 
    3902                 :             : /*
    3903                 :             :  * array_to_text
    3904                 :             :  * concatenate Cstring representation of input array elements
    3905                 :             :  * using provided field separator
    3906                 :             :  */
    3907                 :             : Datum
    3908                 :       44767 : array_to_text(PG_FUNCTION_ARGS)
    3909                 :             : {
    3910                 :       44767 :     ArrayType  *v = PG_GETARG_ARRAYTYPE_P(0);
    3911                 :       44767 :     char       *fldsep = text_to_cstring(PG_GETARG_TEXT_PP(1));
    3912                 :             : 
    3913                 :       44767 :     PG_RETURN_TEXT_P(array_to_text_internal(fcinfo, v, fldsep, NULL));
    3914                 :             : }
    3915                 :             : 
    3916                 :             : /*
    3917                 :             :  * array_to_text_null
    3918                 :             :  * concatenate Cstring representation of input array elements
    3919                 :             :  * using provided field separator and null string
    3920                 :             :  *
    3921                 :             :  * This version is not strict so we have to test for null inputs explicitly.
    3922                 :             :  */
    3923                 :             : Datum
    3924                 :           8 : array_to_text_null(PG_FUNCTION_ARGS)
    3925                 :             : {
    3926                 :             :     ArrayType  *v;
    3927                 :             :     char       *fldsep;
    3928                 :             :     char       *null_string;
    3929                 :             : 
    3930                 :             :     /* returns NULL when first or second parameter is NULL */
    3931   [ +  -  -  + ]:           8 :     if (PG_ARGISNULL(0) || PG_ARGISNULL(1))
    3932                 :           0 :         PG_RETURN_NULL();
    3933                 :             : 
    3934                 :           8 :     v = PG_GETARG_ARRAYTYPE_P(0);
    3935                 :           8 :     fldsep = text_to_cstring(PG_GETARG_TEXT_PP(1));
    3936                 :             : 
    3937                 :             :     /* NULL null string is passed through as a null pointer */
    3938         [ +  + ]:           8 :     if (!PG_ARGISNULL(2))
    3939                 :           4 :         null_string = text_to_cstring(PG_GETARG_TEXT_PP(2));
    3940                 :             :     else
    3941                 :           4 :         null_string = NULL;
    3942                 :             : 
    3943                 :           8 :     PG_RETURN_TEXT_P(array_to_text_internal(fcinfo, v, fldsep, null_string));
    3944                 :             : }
    3945                 :             : 
    3946                 :             : /*
    3947                 :             :  * common code for array_to_text and array_to_text_null functions
    3948                 :             :  */
    3949                 :             : static text *
    3950                 :       44787 : array_to_text_internal(FunctionCallInfo fcinfo, ArrayType *v,
    3951                 :             :                        const char *fldsep, const char *null_string)
    3952                 :             : {
    3953                 :             :     text       *result;
    3954                 :             :     int         nitems,
    3955                 :             :                *dims,
    3956                 :             :                 ndims;
    3957                 :             :     Oid         element_type;
    3958                 :             :     int         typlen;
    3959                 :             :     bool        typbyval;
    3960                 :             :     char        typalign;
    3961                 :             :     uint8       typalignby;
    3962                 :             :     StringInfoData buf;
    3963                 :       44787 :     bool        printed = false;
    3964                 :             :     char       *p;
    3965                 :             :     uint8      *bitmap;
    3966                 :             :     int         bitmask;
    3967                 :             :     int         i;
    3968                 :             :     ArrayMetaState *my_extra;
    3969                 :             : 
    3970                 :       44787 :     ndims = ARR_NDIM(v);
    3971                 :       44787 :     dims = ARR_DIMS(v);
    3972                 :       44787 :     nitems = ArrayGetNItems(ndims, dims);
    3973                 :             : 
    3974                 :             :     /* if there are no elements, return an empty string */
    3975         [ +  + ]:       44787 :     if (nitems == 0)
    3976                 :       27974 :         return cstring_to_text_with_len("", 0);
    3977                 :             : 
    3978                 :       16813 :     element_type = ARR_ELEMTYPE(v);
    3979                 :       16813 :     initStringInfo(&buf);
    3980                 :             : 
    3981                 :             :     /*
    3982                 :             :      * We arrange to look up info about element type, including its output
    3983                 :             :      * conversion proc, only once per series of calls, assuming the element
    3984                 :             :      * type doesn't change underneath us.
    3985                 :             :      */
    3986                 :       16813 :     my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
    3987         [ +  + ]:       16813 :     if (my_extra == NULL)
    3988                 :             :     {
    3989                 :         891 :         fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
    3990                 :             :                                                       sizeof(ArrayMetaState));
    3991                 :         891 :         my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
    3992                 :         891 :         my_extra->element_type = ~element_type;
    3993                 :             :     }
    3994                 :             : 
    3995         [ +  + ]:       16813 :     if (my_extra->element_type != element_type)
    3996                 :             :     {
    3997                 :             :         /*
    3998                 :             :          * Get info about element type, including its output conversion proc
    3999                 :             :          */
    4000                 :         891 :         get_type_io_data(element_type, IOFunc_output,
    4001                 :             :                          &my_extra->typlen, &my_extra->typbyval,
    4002                 :             :                          &my_extra->typalign, &my_extra->typdelim,
    4003                 :             :                          &my_extra->typioparam, &my_extra->typiofunc);
    4004                 :         891 :         fmgr_info_cxt(my_extra->typiofunc, &my_extra->proc,
    4005                 :         891 :                       fcinfo->flinfo->fn_mcxt);
    4006                 :         891 :         my_extra->element_type = element_type;
    4007                 :             :     }
    4008                 :       16813 :     typlen = my_extra->typlen;
    4009                 :       16813 :     typbyval = my_extra->typbyval;
    4010                 :       16813 :     typalign = my_extra->typalign;
    4011                 :       16813 :     typalignby = typalign_to_alignby(typalign);
    4012                 :             : 
    4013         [ +  + ]:       16813 :     p = ARR_DATA_PTR(v);
    4014         [ +  + ]:       16813 :     bitmap = ARR_NULLBITMAP(v);
    4015                 :       16813 :     bitmask = 1;
    4016                 :             : 
    4017         [ +  + ]:       56818 :     for (i = 0; i < nitems; i++)
    4018                 :             :     {
    4019                 :             :         Datum       itemvalue;
    4020                 :             :         char       *value;
    4021                 :             : 
    4022                 :             :         /* Get source element, checking for NULL */
    4023   [ +  +  +  + ]:       40005 :         if (bitmap && (*bitmap & bitmask) == 0)
    4024                 :             :         {
    4025                 :             :             /* if null_string is NULL, we just ignore null elements */
    4026         [ +  + ]:          12 :             if (null_string != NULL)
    4027                 :             :             {
    4028         [ +  - ]:           4 :                 if (printed)
    4029                 :           4 :                     appendStringInfo(&buf, "%s%s", fldsep, null_string);
    4030                 :             :                 else
    4031                 :           0 :                     appendStringInfoString(&buf, null_string);
    4032                 :           4 :                 printed = true;
    4033                 :             :             }
    4034                 :             :         }
    4035                 :             :         else
    4036                 :             :         {
    4037                 :       39993 :             itemvalue = fetch_att(p, typbyval, typlen);
    4038                 :             : 
    4039                 :       39993 :             value = OutputFunctionCall(&my_extra->proc, itemvalue);
    4040                 :             : 
    4041         [ +  + ]:       39993 :             if (printed)
    4042                 :       23180 :                 appendStringInfo(&buf, "%s%s", fldsep, value);
    4043                 :             :             else
    4044                 :       16813 :                 appendStringInfoString(&buf, value);
    4045                 :       39993 :             printed = true;
    4046                 :             : 
    4047   [ +  +  +  - ]:       39993 :             p = att_addlength_pointer(p, typlen, p);
    4048                 :       39993 :             p = (char *) att_nominal_alignby(p, typalignby);
    4049                 :             :         }
    4050                 :             : 
    4051                 :             :         /* advance bitmap pointer if any */
    4052         [ +  + ]:       40005 :         if (bitmap)
    4053                 :             :         {
    4054                 :          72 :             bitmask <<= 1;
    4055         [ -  + ]:          72 :             if (bitmask == 0x100)
    4056                 :             :             {
    4057                 :           0 :                 bitmap++;
    4058                 :           0 :                 bitmask = 1;
    4059                 :             :             }
    4060                 :             :         }
    4061                 :             :     }
    4062                 :             : 
    4063                 :       16813 :     result = cstring_to_text_with_len(buf.data, buf.len);
    4064                 :       16813 :     pfree(buf.data);
    4065                 :             : 
    4066                 :       16813 :     return result;
    4067                 :             : }
    4068                 :             : 
    4069                 :             : /*
    4070                 :             :  * Workhorse for to_bin, to_oct, and to_hex.  Note that base must be > 1 and <=
    4071                 :             :  * 16.
    4072                 :             :  */
    4073                 :             : static inline text *
    4074                 :       20389 : convert_to_base(uint64 value, int base)
    4075                 :             : {
    4076                 :       20389 :     const char *digits = "0123456789abcdef";
    4077                 :             : 
    4078                 :             :     /* We size the buffer for to_bin's longest possible return value. */
    4079                 :             :     char        buf[sizeof(uint64) * BITS_PER_BYTE];
    4080                 :       20389 :     char       *const end = buf + sizeof(buf);
    4081                 :       20389 :     char       *ptr = end;
    4082                 :             : 
    4083                 :             :     Assert(base > 1);
    4084                 :             :     Assert(base <= 16);
    4085                 :             : 
    4086                 :             :     do
    4087                 :             :     {
    4088                 :       40305 :         *--ptr = digits[value % base];
    4089                 :       40305 :         value /= base;
    4090   [ +  +  +  + ]:       40305 :     } while (ptr > buf && value);
    4091                 :             : 
    4092                 :       20389 :     return cstring_to_text_with_len(ptr, end - ptr);
    4093                 :             : }
    4094                 :             : 
    4095                 :             : /*
    4096                 :             :  * Convert an integer to a string containing a base-2 (binary) representation
    4097                 :             :  * of the number.
    4098                 :             :  */
    4099                 :             : Datum
    4100                 :          10 : to_bin32(PG_FUNCTION_ARGS)
    4101                 :             : {
    4102                 :          10 :     uint64      value = (uint32) PG_GETARG_INT32(0);
    4103                 :             : 
    4104                 :          10 :     PG_RETURN_TEXT_P(convert_to_base(value, 2));
    4105                 :             : }
    4106                 :             : Datum
    4107                 :          10 : to_bin64(PG_FUNCTION_ARGS)
    4108                 :             : {
    4109                 :          10 :     uint64      value = (uint64) PG_GETARG_INT64(0);
    4110                 :             : 
    4111                 :          10 :     PG_RETURN_TEXT_P(convert_to_base(value, 2));
    4112                 :             : }
    4113                 :             : 
    4114                 :             : /*
    4115                 :             :  * Convert an integer to a string containing a base-8 (oct) representation of
    4116                 :             :  * the number.
    4117                 :             :  */
    4118                 :             : Datum
    4119                 :          10 : to_oct32(PG_FUNCTION_ARGS)
    4120                 :             : {
    4121                 :          10 :     uint64      value = (uint32) PG_GETARG_INT32(0);
    4122                 :             : 
    4123                 :          10 :     PG_RETURN_TEXT_P(convert_to_base(value, 8));
    4124                 :             : }
    4125                 :             : Datum
    4126                 :          10 : to_oct64(PG_FUNCTION_ARGS)
    4127                 :             : {
    4128                 :          10 :     uint64      value = (uint64) PG_GETARG_INT64(0);
    4129                 :             : 
    4130                 :          10 :     PG_RETURN_TEXT_P(convert_to_base(value, 8));
    4131                 :             : }
    4132                 :             : 
    4133                 :             : /*
    4134                 :             :  * Convert an integer to a string containing a base-16 (hex) representation of
    4135                 :             :  * the number.
    4136                 :             :  */
    4137                 :             : Datum
    4138                 :       20339 : to_hex32(PG_FUNCTION_ARGS)
    4139                 :             : {
    4140                 :       20339 :     uint64      value = (uint32) PG_GETARG_INT32(0);
    4141                 :             : 
    4142                 :       20339 :     PG_RETURN_TEXT_P(convert_to_base(value, 16));
    4143                 :             : }
    4144                 :             : Datum
    4145                 :          10 : to_hex64(PG_FUNCTION_ARGS)
    4146                 :             : {
    4147                 :          10 :     uint64      value = (uint64) PG_GETARG_INT64(0);
    4148                 :             : 
    4149                 :          10 :     PG_RETURN_TEXT_P(convert_to_base(value, 16));
    4150                 :             : }
    4151                 :             : 
    4152                 :             : /*
    4153                 :             :  * Return the size of a datum, possibly compressed
    4154                 :             :  *
    4155                 :             :  * Works on any data type
    4156                 :             :  */
    4157                 :             : Datum
    4158                 :          76 : pg_column_size(PG_FUNCTION_ARGS)
    4159                 :             : {
    4160                 :          76 :     Datum       value = PG_GETARG_DATUM(0);
    4161                 :             :     int32       result;
    4162                 :             :     int         typlen;
    4163                 :             : 
    4164                 :             :     /* On first call, get the input type's typlen, and save at *fn_extra */
    4165         [ +  + ]:          76 :     if (fcinfo->flinfo->fn_extra == NULL)
    4166                 :             :     {
    4167                 :             :         /* Lookup the datatype of the supplied argument */
    4168                 :          73 :         Oid         argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
    4169                 :             : 
    4170                 :          73 :         typlen = get_typlen(argtypeid);
    4171         [ -  + ]:          73 :         if (typlen == 0)        /* should not happen */
    4172         [ #  # ]:           0 :             elog(ERROR, "cache lookup failed for type %u", argtypeid);
    4173                 :             : 
    4174                 :          73 :         fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
    4175                 :             :                                                       sizeof(int));
    4176                 :          73 :         *((int *) fcinfo->flinfo->fn_extra) = typlen;
    4177                 :             :     }
    4178                 :             :     else
    4179                 :           3 :         typlen = *((int *) fcinfo->flinfo->fn_extra);
    4180                 :             : 
    4181         [ +  - ]:          76 :     if (typlen == -1)
    4182                 :             :     {
    4183                 :             :         /* varlena type, possibly toasted */
    4184                 :          76 :         result = toast_datum_size(value);
    4185                 :             :     }
    4186         [ #  # ]:           0 :     else if (typlen == -2)
    4187                 :             :     {
    4188                 :             :         /* cstring */
    4189                 :           0 :         result = strlen(DatumGetCString(value)) + 1;
    4190                 :             :     }
    4191                 :             :     else
    4192                 :             :     {
    4193                 :             :         /* ordinary fixed-width type */
    4194                 :           0 :         result = typlen;
    4195                 :             :     }
    4196                 :             : 
    4197                 :          76 :     PG_RETURN_INT32(result);
    4198                 :             : }
    4199                 :             : 
    4200                 :             : /*
    4201                 :             :  * Return the compression method stored in the compressed attribute.  Return
    4202                 :             :  * NULL for non varlena type or uncompressed data.
    4203                 :             :  */
    4204                 :             : Datum
    4205                 :         170 : pg_column_compression(PG_FUNCTION_ARGS)
    4206                 :             : {
    4207                 :             :     int         typlen;
    4208                 :             :     char       *result;
    4209                 :             :     ToastCompressionId cmid;
    4210                 :             : 
    4211                 :             :     /* On first call, get the input type's typlen, and save at *fn_extra */
    4212         [ +  + ]:         170 :     if (fcinfo->flinfo->fn_extra == NULL)
    4213                 :             :     {
    4214                 :             :         /* Lookup the datatype of the supplied argument */
    4215                 :         131 :         Oid         argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
    4216                 :             : 
    4217                 :         131 :         typlen = get_typlen(argtypeid);
    4218         [ -  + ]:         131 :         if (typlen == 0)        /* should not happen */
    4219         [ #  # ]:           0 :             elog(ERROR, "cache lookup failed for type %u", argtypeid);
    4220                 :             : 
    4221                 :         131 :         fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
    4222                 :             :                                                       sizeof(int));
    4223                 :         131 :         *((int *) fcinfo->flinfo->fn_extra) = typlen;
    4224                 :             :     }
    4225                 :             :     else
    4226                 :          39 :         typlen = *((int *) fcinfo->flinfo->fn_extra);
    4227                 :             : 
    4228         [ -  + ]:         170 :     if (typlen != -1)
    4229                 :           0 :         PG_RETURN_NULL();
    4230                 :             : 
    4231                 :             :     /* get the compression method id stored in the compressed varlena */
    4232                 :         170 :     cmid = toast_get_compression_id((varlena *)
    4233                 :         170 :                                     DatumGetPointer(PG_GETARG_DATUM(0)));
    4234         [ +  + ]:         170 :     if (cmid == TOAST_INVALID_COMPRESSION_ID)
    4235                 :          51 :         PG_RETURN_NULL();
    4236                 :             : 
    4237                 :             :     /* convert compression method id to compression method name */
    4238      [ +  +  - ]:         119 :     switch (cmid)
    4239                 :             :     {
    4240                 :          67 :         case TOAST_PGLZ_COMPRESSION_ID:
    4241                 :          67 :             result = "pglz";
    4242                 :          67 :             break;
    4243                 :          52 :         case TOAST_LZ4_COMPRESSION_ID:
    4244                 :          52 :             result = "lz4";
    4245                 :          52 :             break;
    4246                 :           0 :         default:
    4247         [ #  # ]:           0 :             elog(ERROR, "invalid compression method id %d", cmid);
    4248                 :             :     }
    4249                 :             : 
    4250                 :         119 :     PG_RETURN_TEXT_P(cstring_to_text(result));
    4251                 :             : }
    4252                 :             : 
    4253                 :             : /*
    4254                 :             :  * Return the chunk_id of the on-disk TOASTed value.  Return NULL if the value
    4255                 :             :  * is un-TOASTed or not on-disk.
    4256                 :             :  */
    4257                 :             : Datum
    4258                 :         215 : pg_column_toast_chunk_id(PG_FUNCTION_ARGS)
    4259                 :             : {
    4260                 :             :     int         typlen;
    4261                 :             :     varlena    *attr;
    4262                 :             :     toast_external_data toast_ext_data;
    4263                 :             : 
    4264                 :             :     /* On first call, get the input type's typlen, and save at *fn_extra */
    4265         [ +  + ]:         215 :     if (fcinfo->flinfo->fn_extra == NULL)
    4266                 :             :     {
    4267                 :             :         /* Lookup the datatype of the supplied argument */
    4268                 :          45 :         Oid         argtypeid = get_fn_expr_argtype(fcinfo->flinfo, 0);
    4269                 :             : 
    4270                 :          45 :         typlen = get_typlen(argtypeid);
    4271         [ -  + ]:          45 :         if (typlen == 0)        /* should not happen */
    4272         [ #  # ]:           0 :             elog(ERROR, "cache lookup failed for type %u", argtypeid);
    4273                 :             : 
    4274                 :          45 :         fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
    4275                 :             :                                                       sizeof(int));
    4276                 :          45 :         *((int *) fcinfo->flinfo->fn_extra) = typlen;
    4277                 :             :     }
    4278                 :             :     else
    4279                 :         170 :         typlen = *((int *) fcinfo->flinfo->fn_extra);
    4280                 :             : 
    4281         [ -  + ]:         215 :     if (typlen != -1)
    4282                 :           0 :         PG_RETURN_NULL();
    4283                 :             : 
    4284                 :         215 :     attr = (varlena *) DatumGetPointer(PG_GETARG_DATUM(0));
    4285                 :             : 
    4286         [ +  + ]:         215 :     if (!VARATT_IS_EXTERNAL_ONDISK(attr))
    4287                 :          74 :         PG_RETURN_NULL();
    4288                 :             : 
    4289                 :         141 :     toast_external_info_get(attr, &toast_ext_data);
    4290                 :             : 
    4291                 :         141 :     PG_RETURN_OID8(toast_ext_data.valueid);
    4292                 :             : }
    4293                 :             : 
    4294                 :             : /*
    4295                 :             :  * string_agg - Concatenates values and returns string.
    4296                 :             :  *
    4297                 :             :  * Syntax: string_agg(value text, delimiter text) RETURNS text
    4298                 :             :  *
    4299                 :             :  * Note: Any NULL values are ignored. The first-call delimiter isn't
    4300                 :             :  * actually used at all, and on subsequent calls the delimiter precedes
    4301                 :             :  * the associated value.
    4302                 :             :  */
    4303                 :             : 
    4304                 :             : /* subroutine to initialize state */
    4305                 :             : static StringInfo
    4306                 :        1677 : makeStringAggState(FunctionCallInfo fcinfo)
    4307                 :             : {
    4308                 :             :     StringInfo  state;
    4309                 :             :     MemoryContext aggcontext;
    4310                 :             :     MemoryContext oldcontext;
    4311                 :             : 
    4312         [ -  + ]:        1677 :     if (!AggCheckCallContext(fcinfo, &aggcontext))
    4313                 :             :     {
    4314                 :             :         /* cannot be called directly because of internal-type argument */
    4315         [ #  # ]:           0 :         elog(ERROR, "string_agg_transfn called in non-aggregate context");
    4316                 :             :     }
    4317                 :             : 
    4318                 :             :     /*
    4319                 :             :      * Create state in aggregate context.  It'll stay there across subsequent
    4320                 :             :      * calls.
    4321                 :             :      */
    4322                 :        1677 :     oldcontext = MemoryContextSwitchTo(aggcontext);
    4323                 :        1677 :     state = makeStringInfo();
    4324                 :        1677 :     MemoryContextSwitchTo(oldcontext);
    4325                 :             : 
    4326                 :        1677 :     return state;
    4327                 :             : }
    4328                 :             : 
    4329                 :             : Datum
    4330                 :      688256 : string_agg_transfn(PG_FUNCTION_ARGS)
    4331                 :             : {
    4332                 :             :     StringInfo  state;
    4333                 :             : 
    4334         [ +  + ]:      688256 :     state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
    4335                 :             : 
    4336                 :             :     /* Append the value unless null, preceding it with the delimiter. */
    4337         [ +  + ]:      688256 :     if (!PG_ARGISNULL(1))
    4338                 :             :     {
    4339                 :      678224 :         text       *value = PG_GETARG_TEXT_PP(1);
    4340                 :      678224 :         bool        isfirst = false;
    4341                 :             : 
    4342                 :             :         /*
    4343                 :             :          * You might think we can just throw away the first delimiter, however
    4344                 :             :          * we must keep it as we may be a parallel worker doing partial
    4345                 :             :          * aggregation building a state to send to the main process.  We need
    4346                 :             :          * to keep the delimiter of every aggregation so that the combine
    4347                 :             :          * function can properly join up the strings of two separately
    4348                 :             :          * partially aggregated results.  The first delimiter is only stripped
    4349                 :             :          * off in the final function.  To know how much to strip off the front
    4350                 :             :          * of the string, we store the length of the first delimiter in the
    4351                 :             :          * StringInfo's cursor field, which we don't otherwise need here.
    4352                 :             :          */
    4353         [ +  + ]:      678224 :         if (state == NULL)
    4354                 :             :         {
    4355                 :        1437 :             state = makeStringAggState(fcinfo);
    4356                 :        1437 :             isfirst = true;
    4357                 :             :         }
    4358                 :             : 
    4359         [ +  - ]:      678224 :         if (!PG_ARGISNULL(2))
    4360                 :             :         {
    4361                 :      678224 :             text       *delim = PG_GETARG_TEXT_PP(2);
    4362                 :             : 
    4363                 :      678224 :             appendStringInfoText(state, delim);
    4364         [ +  + ]:      678224 :             if (isfirst)
    4365                 :        1437 :                 state->cursor = VARSIZE_ANY_EXHDR(delim);
    4366                 :             :         }
    4367                 :             : 
    4368                 :      678224 :         appendStringInfoText(state, value);
    4369                 :             :     }
    4370                 :             : 
    4371                 :             :     /*
    4372                 :             :      * The transition type for string_agg() is declared to be "internal",
    4373                 :             :      * which is a pass-by-value type the same size as a pointer.
    4374                 :             :      */
    4375         [ +  + ]:      688256 :     if (state)
    4376                 :      688194 :         PG_RETURN_POINTER(state);
    4377                 :          62 :     PG_RETURN_NULL();
    4378                 :             : }
    4379                 :             : 
    4380                 :             : /*
    4381                 :             :  * string_agg_combine
    4382                 :             :  *      Aggregate combine function for string_agg(text) and string_agg(bytea)
    4383                 :             :  */
    4384                 :             : Datum
    4385                 :         160 : string_agg_combine(PG_FUNCTION_ARGS)
    4386                 :             : {
    4387                 :             :     StringInfo  state1;
    4388                 :             :     StringInfo  state2;
    4389                 :             :     MemoryContext agg_context;
    4390                 :             : 
    4391         [ -  + ]:         160 :     if (!AggCheckCallContext(fcinfo, &agg_context))
    4392         [ #  # ]:           0 :         elog(ERROR, "aggregate function called in non-aggregate context");
    4393                 :             : 
    4394         [ +  + ]:         160 :     state1 = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
    4395         [ +  - ]:         160 :     state2 = PG_ARGISNULL(1) ? NULL : (StringInfo) PG_GETARG_POINTER(1);
    4396                 :             : 
    4397         [ -  + ]:         160 :     if (state2 == NULL)
    4398                 :             :     {
    4399                 :             :         /*
    4400                 :             :          * NULL state2 is easy, just return state1, which we know is already
    4401                 :             :          * in the agg_context
    4402                 :             :          */
    4403         [ #  # ]:           0 :         if (state1 == NULL)
    4404                 :           0 :             PG_RETURN_NULL();
    4405                 :           0 :         PG_RETURN_POINTER(state1);
    4406                 :             :     }
    4407                 :             : 
    4408         [ +  + ]:         160 :     if (state1 == NULL)
    4409                 :             :     {
    4410                 :             :         /* We must copy state2's data into the agg_context */
    4411                 :             :         MemoryContext old_context;
    4412                 :             : 
    4413                 :          80 :         old_context = MemoryContextSwitchTo(agg_context);
    4414                 :          80 :         state1 = makeStringAggState(fcinfo);
    4415                 :          80 :         appendBinaryStringInfo(state1, state2->data, state2->len);
    4416                 :          80 :         state1->cursor = state2->cursor;
    4417                 :          80 :         MemoryContextSwitchTo(old_context);
    4418                 :             :     }
    4419         [ +  - ]:          80 :     else if (state2->len > 0)
    4420                 :             :     {
    4421                 :             :         /* Combine ... state1->cursor does not change in this case */
    4422                 :          80 :         appendBinaryStringInfo(state1, state2->data, state2->len);
    4423                 :             :     }
    4424                 :             : 
    4425                 :         160 :     PG_RETURN_POINTER(state1);
    4426                 :             : }
    4427                 :             : 
    4428                 :             : /*
    4429                 :             :  * string_agg_serialize
    4430                 :             :  *      Aggregate serialize function for string_agg(text) and string_agg(bytea)
    4431                 :             :  *
    4432                 :             :  * This is strict, so we need not handle NULL input
    4433                 :             :  */
    4434                 :             : Datum
    4435                 :         160 : string_agg_serialize(PG_FUNCTION_ARGS)
    4436                 :             : {
    4437                 :             :     StringInfo  state;
    4438                 :             :     StringInfoData buf;
    4439                 :             :     bytea      *result;
    4440                 :             : 
    4441                 :             :     /* cannot be called directly because of internal-type argument */
    4442                 :             :     Assert(AggCheckCallContext(fcinfo, NULL));
    4443                 :             : 
    4444                 :         160 :     state = (StringInfo) PG_GETARG_POINTER(0);
    4445                 :             : 
    4446                 :         160 :     pq_begintypsend(&buf);
    4447                 :             : 
    4448                 :             :     /* cursor */
    4449                 :         160 :     pq_sendint(&buf, state->cursor, 4);
    4450                 :             : 
    4451                 :             :     /* data */
    4452                 :         160 :     pq_sendbytes(&buf, state->data, state->len);
    4453                 :             : 
    4454                 :         160 :     result = pq_endtypsend(&buf);
    4455                 :             : 
    4456                 :         160 :     PG_RETURN_BYTEA_P(result);
    4457                 :             : }
    4458                 :             : 
    4459                 :             : /*
    4460                 :             :  * string_agg_deserialize
    4461                 :             :  *      Aggregate deserial function for string_agg(text) and string_agg(bytea)
    4462                 :             :  *
    4463                 :             :  * This is strict, so we need not handle NULL input
    4464                 :             :  */
    4465                 :             : Datum
    4466                 :         160 : string_agg_deserialize(PG_FUNCTION_ARGS)
    4467                 :             : {
    4468                 :             :     bytea      *sstate;
    4469                 :             :     StringInfo  result;
    4470                 :             :     StringInfoData buf;
    4471                 :             :     const char *data;
    4472                 :             :     int         datalen;
    4473                 :             : 
    4474                 :             :     /* cannot be called directly because of internal-type argument */
    4475                 :             :     Assert(AggCheckCallContext(fcinfo, NULL));
    4476                 :             : 
    4477                 :         160 :     sstate = PG_GETARG_BYTEA_PP(0);
    4478                 :             : 
    4479                 :             :     /*
    4480                 :             :      * Initialize a StringInfo so that we can "receive" it using the standard
    4481                 :             :      * recv-function infrastructure.
    4482                 :             :      */
    4483                 :         160 :     initReadOnlyStringInfo(&buf, VARDATA_ANY(sstate),
    4484                 :         160 :                            VARSIZE_ANY_EXHDR(sstate));
    4485                 :             : 
    4486                 :         160 :     result = makeStringAggState(fcinfo);
    4487                 :             : 
    4488                 :             :     /* cursor */
    4489                 :         160 :     result->cursor = pq_getmsgint(&buf, 4);
    4490                 :             : 
    4491                 :             :     /* data */
    4492                 :         160 :     datalen = VARSIZE_ANY_EXHDR(sstate) - 4;
    4493                 :         160 :     data = pq_getmsgbytes(&buf, datalen);
    4494                 :         160 :     appendBinaryStringInfo(result, data, datalen);
    4495                 :             : 
    4496                 :         160 :     pq_getmsgend(&buf);
    4497                 :             : 
    4498                 :         160 :     PG_RETURN_POINTER(result);
    4499                 :             : }
    4500                 :             : 
    4501                 :             : Datum
    4502                 :        1453 : string_agg_finalfn(PG_FUNCTION_ARGS)
    4503                 :             : {
    4504                 :             :     StringInfo  state;
    4505                 :             : 
    4506                 :             :     /* cannot be called directly because of internal-type argument */
    4507                 :             :     Assert(AggCheckCallContext(fcinfo, NULL));
    4508                 :             : 
    4509         [ +  + ]:        1453 :     state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
    4510                 :             : 
    4511         [ +  + ]:        1453 :     if (state != NULL)
    4512                 :             :     {
    4513                 :             :         /* As per comment in transfn, strip data before the cursor position */
    4514                 :        1397 :         PG_RETURN_TEXT_P(cstring_to_text_with_len(&state->data[state->cursor],
    4515                 :             :                                                   state->len - state->cursor));
    4516                 :             :     }
    4517                 :             :     else
    4518                 :          56 :         PG_RETURN_NULL();
    4519                 :             : }
    4520                 :             : 
    4521                 :             : /*
    4522                 :             :  * Prepare cache with fmgr info for the output functions of the datatypes of
    4523                 :             :  * the arguments of a concat-like function, beginning with argument "argidx".
    4524                 :             :  * (Arguments before that will have corresponding slots in the resulting
    4525                 :             :  * FmgrInfo array, but we don't fill those slots.)
    4526                 :             :  */
    4527                 :             : static FmgrInfo *
    4528                 :          74 : build_concat_foutcache(FunctionCallInfo fcinfo, int argidx)
    4529                 :             : {
    4530                 :             :     FmgrInfo   *foutcache;
    4531                 :             :     int         i;
    4532                 :             : 
    4533                 :             :     /* We keep the info in fn_mcxt so it survives across calls */
    4534                 :          74 :     foutcache = (FmgrInfo *) MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
    4535                 :          74 :                                                 PG_NARGS() * sizeof(FmgrInfo));
    4536                 :             : 
    4537         [ +  + ]:         272 :     for (i = argidx; i < PG_NARGS(); i++)
    4538                 :             :     {
    4539                 :             :         Oid         valtype;
    4540                 :             :         Oid         typOutput;
    4541                 :             :         bool        typIsVarlena;
    4542                 :             : 
    4543                 :         198 :         valtype = get_fn_expr_argtype(fcinfo->flinfo, i);
    4544         [ -  + ]:         198 :         if (!OidIsValid(valtype))
    4545         [ #  # ]:           0 :             elog(ERROR, "could not determine data type of concat() input");
    4546                 :             : 
    4547                 :         198 :         getTypeOutputInfo(valtype, &typOutput, &typIsVarlena);
    4548                 :         198 :         fmgr_info_cxt(typOutput, &foutcache[i], fcinfo->flinfo->fn_mcxt);
    4549                 :             :     }
    4550                 :             : 
    4551                 :          74 :     fcinfo->flinfo->fn_extra = foutcache;
    4552                 :             : 
    4553                 :          74 :     return foutcache;
    4554                 :             : }
    4555                 :             : 
    4556                 :             : /*
    4557                 :             :  * Implementation of both concat() and concat_ws().
    4558                 :             :  *
    4559                 :             :  * sepstr is the separator string to place between values.
    4560                 :             :  * argidx identifies the first argument to concatenate (counting from zero);
    4561                 :             :  * note that this must be constant across any one series of calls.
    4562                 :             :  *
    4563                 :             :  * Returns NULL if result should be NULL, else text value.
    4564                 :             :  */
    4565                 :             : static text *
    4566                 :         179 : concat_internal(const char *sepstr, int argidx,
    4567                 :             :                 FunctionCallInfo fcinfo)
    4568                 :             : {
    4569                 :             :     text       *result;
    4570                 :             :     StringInfoData str;
    4571                 :             :     FmgrInfo   *foutcache;
    4572                 :         179 :     bool        first_arg = true;
    4573                 :             :     int         i;
    4574                 :             : 
    4575                 :             :     /*
    4576                 :             :      * concat(VARIADIC some-array) is essentially equivalent to
    4577                 :             :      * array_to_text(), ie concat the array elements with the given separator.
    4578                 :             :      * So we just pass the case off to that code.
    4579                 :             :      */
    4580         [ +  + ]:         179 :     if (get_fn_expr_variadic(fcinfo->flinfo))
    4581                 :             :     {
    4582                 :             :         ArrayType  *arr;
    4583                 :             : 
    4584                 :             :         /* Should have just the one argument */
    4585                 :             :         Assert(argidx == PG_NARGS() - 1);
    4586                 :             : 
    4587                 :             :         /* concat(VARIADIC NULL) is defined as NULL */
    4588         [ +  + ]:          20 :         if (PG_ARGISNULL(argidx))
    4589                 :           8 :             return NULL;
    4590                 :             : 
    4591                 :             :         /*
    4592                 :             :          * Non-null argument had better be an array.  We assume that any call
    4593                 :             :          * context that could let get_fn_expr_variadic return true will have
    4594                 :             :          * checked that a VARIADIC-labeled parameter actually is an array.  So
    4595                 :             :          * it should be okay to just Assert that it's an array rather than
    4596                 :             :          * doing a full-fledged error check.
    4597                 :             :          */
    4598                 :             :         Assert(OidIsValid(get_base_element_type(get_fn_expr_argtype(fcinfo->flinfo, argidx))));
    4599                 :             : 
    4600                 :             :         /* OK, safe to fetch the array value */
    4601                 :          12 :         arr = PG_GETARG_ARRAYTYPE_P(argidx);
    4602                 :             : 
    4603                 :             :         /*
    4604                 :             :          * And serialize the array.  We tell array_to_text to ignore null
    4605                 :             :          * elements, which matches the behavior of the loop below.
    4606                 :             :          */
    4607                 :          12 :         return array_to_text_internal(fcinfo, arr, sepstr, NULL);
    4608                 :             :     }
    4609                 :             : 
    4610                 :             :     /* Normal case without explicit VARIADIC marker */
    4611                 :         159 :     initStringInfo(&str);
    4612                 :             : 
    4613                 :             :     /* Get output function info, building it if first time through */
    4614                 :         159 :     foutcache = (FmgrInfo *) fcinfo->flinfo->fn_extra;
    4615         [ +  + ]:         159 :     if (foutcache == NULL)
    4616                 :          74 :         foutcache = build_concat_foutcache(fcinfo, argidx);
    4617                 :             : 
    4618         [ +  + ]:         552 :     for (i = argidx; i < PG_NARGS(); i++)
    4619                 :             :     {
    4620         [ +  + ]:         393 :         if (!PG_ARGISNULL(i))
    4621                 :             :         {
    4622                 :         341 :             Datum       value = PG_GETARG_DATUM(i);
    4623                 :             : 
    4624                 :             :             /* add separator if appropriate */
    4625         [ +  + ]:         341 :             if (first_arg)
    4626                 :         155 :                 first_arg = false;
    4627                 :             :             else
    4628                 :         186 :                 appendStringInfoString(&str, sepstr);
    4629                 :             : 
    4630                 :             :             /* call the appropriate type output function, append the result */
    4631                 :         341 :             appendStringInfoString(&str,
    4632                 :         341 :                                    OutputFunctionCall(&foutcache[i], value));
    4633                 :             :         }
    4634                 :             :     }
    4635                 :             : 
    4636                 :         159 :     result = cstring_to_text_with_len(str.data, str.len);
    4637                 :         159 :     pfree(str.data);
    4638                 :             : 
    4639                 :         159 :     return result;
    4640                 :             : }
    4641                 :             : 
    4642                 :             : /*
    4643                 :             :  * Concatenate all arguments. NULL arguments are ignored.
    4644                 :             :  */
    4645                 :             : Datum
    4646                 :         127 : text_concat(PG_FUNCTION_ARGS)
    4647                 :             : {
    4648                 :             :     text       *result;
    4649                 :             : 
    4650                 :         127 :     result = concat_internal("", 0, fcinfo);
    4651         [ +  + ]:         127 :     if (result == NULL)
    4652                 :           4 :         PG_RETURN_NULL();
    4653                 :         123 :     PG_RETURN_TEXT_P(result);
    4654                 :             : }
    4655                 :             : 
    4656                 :             : /*
    4657                 :             :  * Concatenate all but first argument value with separators. The first
    4658                 :             :  * parameter is used as the separator. NULL arguments are ignored.
    4659                 :             :  */
    4660                 :             : Datum
    4661                 :          56 : text_concat_ws(PG_FUNCTION_ARGS)
    4662                 :             : {
    4663                 :             :     char       *sep;
    4664                 :             :     text       *result;
    4665                 :             : 
    4666                 :             :     /* return NULL when separator is NULL */
    4667         [ +  + ]:          56 :     if (PG_ARGISNULL(0))
    4668                 :           4 :         PG_RETURN_NULL();
    4669                 :          52 :     sep = text_to_cstring(PG_GETARG_TEXT_PP(0));
    4670                 :             : 
    4671                 :          52 :     result = concat_internal(sep, 1, fcinfo);
    4672         [ +  + ]:          52 :     if (result == NULL)
    4673                 :           4 :         PG_RETURN_NULL();
    4674                 :          48 :     PG_RETURN_TEXT_P(result);
    4675                 :             : }
    4676                 :             : 
    4677                 :             : /*
    4678                 :             :  * Return first n characters in the string. When n is negative,
    4679                 :             :  * return all but last |n| characters.
    4680                 :             :  */
    4681                 :             : Datum
    4682                 :        1440 : text_left(PG_FUNCTION_ARGS)
    4683                 :             : {
    4684                 :        1440 :     int         n = PG_GETARG_INT32(1);
    4685                 :             : 
    4686         [ +  + ]:        1440 :     if (n < 0)
    4687                 :             :     {
    4688                 :          25 :         text       *str = PG_GETARG_TEXT_PP(0);
    4689                 :          25 :         const char *p = VARDATA_ANY(str);
    4690                 :          25 :         int         len = VARSIZE_ANY_EXHDR(str);
    4691                 :             :         int         rlen;
    4692                 :             : 
    4693                 :          25 :         n = pg_mbstrlen_with_len(p, len) + n;
    4694                 :          25 :         rlen = pg_mbcharcliplen(p, len, n);
    4695                 :          25 :         PG_RETURN_TEXT_P(cstring_to_text_with_len(p, rlen));
    4696                 :             :     }
    4697                 :             :     else
    4698                 :        1415 :         PG_RETURN_TEXT_P(text_substring(PG_GETARG_DATUM(0), 1, n, false));
    4699                 :             : }
    4700                 :             : 
    4701                 :             : /*
    4702                 :             :  * Return last n characters in the string. When n is negative,
    4703                 :             :  * return all but first |n| characters.
    4704                 :             :  */
    4705                 :             : Datum
    4706                 :          49 : text_right(PG_FUNCTION_ARGS)
    4707                 :             : {
    4708                 :          49 :     text       *str = PG_GETARG_TEXT_PP(0);
    4709                 :          49 :     const char *p = VARDATA_ANY(str);
    4710                 :          49 :     int         len = VARSIZE_ANY_EXHDR(str);
    4711                 :          49 :     int         n = PG_GETARG_INT32(1);
    4712                 :             :     int         off;
    4713                 :             : 
    4714         [ +  + ]:          49 :     if (n < 0)
    4715                 :             :     {
    4716                 :             :         /*
    4717                 :             :          * Negating PG_INT32_MIN would overflow, so clamp instead.  Any n
    4718                 :             :          * whose absolute value is at least the string's length skips the
    4719                 :             :          * whole string, and len can't exceed PG_INT32_MAX, so this is
    4720                 :             :          * equivalent.
    4721                 :             :          */
    4722         [ +  + ]:          25 :         if (unlikely(n == PG_INT32_MIN))
    4723                 :           5 :             n = PG_INT32_MAX;
    4724                 :             :         else
    4725                 :          20 :             n = -n;
    4726                 :             :     }
    4727                 :             :     else
    4728                 :          24 :         n = pg_mbstrlen_with_len(p, len) - n;
    4729                 :          49 :     off = pg_mbcharcliplen(p, len, n);
    4730                 :             : 
    4731                 :          49 :     PG_RETURN_TEXT_P(cstring_to_text_with_len(p + off, len - off));
    4732                 :             : }
    4733                 :             : 
    4734                 :             : /*
    4735                 :             :  * Return reversed string
    4736                 :             :  */
    4737                 :             : Datum
    4738                 :          29 : text_reverse(PG_FUNCTION_ARGS)
    4739                 :             : {
    4740                 :          29 :     text       *str = PG_GETARG_TEXT_PP(0);
    4741                 :          29 :     const char *p = VARDATA_ANY(str);
    4742                 :          29 :     int         len = VARSIZE_ANY_EXHDR(str);
    4743                 :          29 :     const char *endp = p + len;
    4744                 :             :     text       *result;
    4745                 :             :     char       *dst;
    4746                 :             : 
    4747                 :          29 :     result = palloc(len + VARHDRSZ);
    4748                 :          29 :     dst = (char *) VARDATA(result) + len;
    4749                 :          29 :     SET_VARSIZE(result, len + VARHDRSZ);
    4750                 :             : 
    4751         [ +  - ]:          29 :     if (pg_database_encoding_max_length() > 1)
    4752                 :             :     {
    4753                 :             :         /* multibyte version */
    4754         [ +  + ]:         222 :         while (p < endp)
    4755                 :             :         {
    4756                 :             :             int         sz;
    4757                 :             : 
    4758                 :         197 :             sz = pg_mblen_range(p, endp);
    4759                 :         193 :             dst -= sz;
    4760                 :         193 :             memcpy(dst, p, sz);
    4761                 :         193 :             p += sz;
    4762                 :             :         }
    4763                 :             :     }
    4764                 :             :     else
    4765                 :             :     {
    4766                 :             :         /* single byte version */
    4767         [ #  # ]:           0 :         while (p < endp)
    4768                 :           0 :             *(--dst) = *p++;
    4769                 :             :     }
    4770                 :             : 
    4771                 :          25 :     PG_RETURN_TEXT_P(result);
    4772                 :             : }
    4773                 :             : 
    4774                 :             : 
    4775                 :             : /*
    4776                 :             :  * Support macros for text_format()
    4777                 :             :  */
    4778                 :             : #define TEXT_FORMAT_FLAG_MINUS  0x0001  /* is minus flag present? */
    4779                 :             : 
    4780                 :             : #define ADVANCE_PARSE_POINTER(ptr,end_ptr) \
    4781                 :             :     do { \
    4782                 :             :         if (++(ptr) >= (end_ptr)) \
    4783                 :             :             ereport(ERROR, \
    4784                 :             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE), \
    4785                 :             :                      errmsg("unterminated format() type specifier"), \
    4786                 :             :                      errhint("For a single \"%%\" use \"%%%%\"."))); \
    4787                 :             :     } while (0)
    4788                 :             : 
    4789                 :             : /*
    4790                 :             :  * Returns a formatted string
    4791                 :             :  */
    4792                 :             : Datum
    4793                 :       24097 : text_format(PG_FUNCTION_ARGS)
    4794                 :             : {
    4795                 :             :     text       *fmt;
    4796                 :             :     StringInfoData result_str;
    4797                 :             :     const char *cp;
    4798                 :             :     const char *start_ptr;
    4799                 :             :     const char *end_ptr;
    4800                 :             :     text       *result;
    4801                 :             :     int         arg;
    4802                 :             :     bool        funcvariadic;
    4803                 :             :     int         nargs;
    4804                 :       24097 :     Datum      *elements = NULL;
    4805                 :       24097 :     bool       *nulls = NULL;
    4806                 :       24097 :     Oid         element_type = InvalidOid;
    4807                 :       24097 :     Oid         prev_type = InvalidOid;
    4808                 :       24097 :     Oid         prev_width_type = InvalidOid;
    4809                 :             :     FmgrInfo    typoutputfinfo;
    4810                 :             :     FmgrInfo    typoutputinfo_width;
    4811                 :             : 
    4812                 :             :     /* When format string is null, immediately return null */
    4813         [ +  + ]:       24097 :     if (PG_ARGISNULL(0))
    4814                 :           4 :         PG_RETURN_NULL();
    4815                 :             : 
    4816                 :             :     /* If argument is marked VARIADIC, expand array into elements */
    4817         [ +  + ]:       24093 :     if (get_fn_expr_variadic(fcinfo->flinfo))
    4818                 :             :     {
    4819                 :             :         ArrayType  *arr;
    4820                 :             :         int16       elmlen;
    4821                 :             :         bool        elmbyval;
    4822                 :             :         char        elmalign;
    4823                 :             :         int         nitems;
    4824                 :             : 
    4825                 :             :         /* Should have just the one argument */
    4826                 :             :         Assert(PG_NARGS() == 2);
    4827                 :             : 
    4828                 :             :         /* If argument is NULL, we treat it as zero-length array */
    4829         [ +  + ]:          32 :         if (PG_ARGISNULL(1))
    4830                 :           4 :             nitems = 0;
    4831                 :             :         else
    4832                 :             :         {
    4833                 :             :             /*
    4834                 :             :              * Non-null argument had better be an array.  We assume that any
    4835                 :             :              * call context that could let get_fn_expr_variadic return true
    4836                 :             :              * will have checked that a VARIADIC-labeled parameter actually is
    4837                 :             :              * an array.  So it should be okay to just Assert that it's an
    4838                 :             :              * array rather than doing a full-fledged error check.
    4839                 :             :              */
    4840                 :             :             Assert(OidIsValid(get_base_element_type(get_fn_expr_argtype(fcinfo->flinfo, 1))));
    4841                 :             : 
    4842                 :             :             /* OK, safe to fetch the array value */
    4843                 :          28 :             arr = PG_GETARG_ARRAYTYPE_P(1);
    4844                 :             : 
    4845                 :             :             /* Get info about array element type */
    4846                 :          28 :             element_type = ARR_ELEMTYPE(arr);
    4847                 :          28 :             get_typlenbyvalalign(element_type,
    4848                 :             :                                  &elmlen, &elmbyval, &elmalign);
    4849                 :             : 
    4850                 :             :             /* Extract all array elements */
    4851                 :          28 :             deconstruct_array(arr, element_type, elmlen, elmbyval, elmalign,
    4852                 :             :                               &elements, &nulls, &nitems);
    4853                 :             :         }
    4854                 :             : 
    4855                 :          32 :         nargs = nitems + 1;
    4856                 :          32 :         funcvariadic = true;
    4857                 :             :     }
    4858                 :             :     else
    4859                 :             :     {
    4860                 :             :         /* Non-variadic case, we'll process the arguments individually */
    4861                 :       24061 :         nargs = PG_NARGS();
    4862                 :       24061 :         funcvariadic = false;
    4863                 :             :     }
    4864                 :             : 
    4865                 :             :     /* Setup for main loop. */
    4866                 :       24093 :     fmt = PG_GETARG_TEXT_PP(0);
    4867                 :       24093 :     start_ptr = VARDATA_ANY(fmt);
    4868                 :       24093 :     end_ptr = start_ptr + VARSIZE_ANY_EXHDR(fmt);
    4869                 :       24093 :     initStringInfo(&result_str);
    4870                 :       24093 :     arg = 1;                    /* next argument position to print */
    4871                 :             : 
    4872                 :             :     /* Scan format string, looking for conversion specifiers. */
    4873         [ +  + ]:      808146 :     for (cp = start_ptr; cp < end_ptr; cp++)
    4874                 :             :     {
    4875                 :             :         int         argpos;
    4876                 :             :         int         widthpos;
    4877                 :             :         int         flags;
    4878                 :             :         int         width;
    4879                 :             :         Datum       value;
    4880                 :             :         bool        isNull;
    4881                 :             :         Oid         typid;
    4882                 :             : 
    4883                 :             :         /*
    4884                 :             :          * If it's not the start of a conversion specifier, just copy it to
    4885                 :             :          * the output buffer.
    4886                 :             :          */
    4887         [ +  + ]:      784093 :         if (*cp != '%')
    4888                 :             :         {
    4889         [ -  + ]:      736487 :             appendStringInfoCharMacro(&result_str, *cp);
    4890                 :      736499 :             continue;
    4891                 :             :         }
    4892                 :             : 
    4893   [ -  +  -  - ]:       47606 :         ADVANCE_PARSE_POINTER(cp, end_ptr);
    4894                 :             : 
    4895                 :             :         /* Easy case: %% outputs a single % */
    4896         [ +  + ]:       47606 :         if (*cp == '%')
    4897                 :             :         {
    4898         [ -  + ]:          12 :             appendStringInfoCharMacro(&result_str, *cp);
    4899                 :          12 :             continue;
    4900                 :             :         }
    4901                 :             : 
    4902                 :             :         /* Parse the optional portions of the format specifier */
    4903                 :       47594 :         cp = text_format_parse_format(cp, end_ptr,
    4904                 :             :                                       &argpos, &widthpos,
    4905                 :             :                                       &flags, &width);
    4906                 :             : 
    4907                 :             :         /*
    4908                 :             :          * Next we should see the main conversion specifier.  Whether or not
    4909                 :             :          * an argument position was present, it's known that at least one
    4910                 :             :          * character remains in the string at this point.  Experience suggests
    4911                 :             :          * that it's worth checking that that character is one of the expected
    4912                 :             :          * ones before we try to fetch arguments, so as to produce the least
    4913                 :             :          * confusing response to a mis-formatted specifier.
    4914                 :             :          */
    4915         [ +  + ]:       47578 :         if (strchr("sIL", *cp) == NULL)
    4916         [ +  - ]:           4 :             ereport(ERROR,
    4917                 :             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    4918                 :             :                      errmsg("unrecognized format() type specifier \"%.*s\"",
    4919                 :             :                             pg_mblen_range(cp, end_ptr), cp),
    4920                 :             :                      errhint("For a single \"%%\" use \"%%%%\".")));
    4921                 :             : 
    4922                 :             :         /* If indirect width was specified, get its value */
    4923         [ +  + ]:       47574 :         if (widthpos >= 0)
    4924                 :             :         {
    4925                 :             :             /* Collect the specified or next argument position */
    4926         [ +  + ]:          28 :             if (widthpos > 0)
    4927                 :          24 :                 arg = widthpos;
    4928         [ -  + ]:          28 :             if (arg >= nargs)
    4929         [ #  # ]:           0 :                 ereport(ERROR,
    4930                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    4931                 :             :                          errmsg("too few arguments for format()")));
    4932                 :             : 
    4933                 :             :             /* Get the value and type of the selected argument */
    4934         [ +  - ]:          28 :             if (!funcvariadic)
    4935                 :             :             {
    4936                 :          28 :                 value = PG_GETARG_DATUM(arg);
    4937                 :          28 :                 isNull = PG_ARGISNULL(arg);
    4938                 :          28 :                 typid = get_fn_expr_argtype(fcinfo->flinfo, arg);
    4939                 :             :             }
    4940                 :             :             else
    4941                 :             :             {
    4942                 :           0 :                 value = elements[arg - 1];
    4943                 :           0 :                 isNull = nulls[arg - 1];
    4944                 :           0 :                 typid = element_type;
    4945                 :             :             }
    4946         [ -  + ]:          28 :             if (!OidIsValid(typid))
    4947         [ #  # ]:           0 :                 elog(ERROR, "could not determine data type of format() input");
    4948                 :             : 
    4949                 :          28 :             arg++;
    4950                 :             : 
    4951                 :             :             /* We can treat NULL width the same as zero */
    4952         [ +  + ]:          28 :             if (isNull)
    4953                 :           4 :                 width = 0;
    4954         [ +  - ]:          24 :             else if (typid == INT4OID)
    4955                 :          24 :                 width = DatumGetInt32(value);
    4956         [ #  # ]:           0 :             else if (typid == INT2OID)
    4957                 :           0 :                 width = DatumGetInt16(value);
    4958                 :             :             else
    4959                 :             :             {
    4960                 :             :                 /* For less-usual datatypes, convert to text then to int */
    4961                 :             :                 char       *str;
    4962                 :             : 
    4963         [ #  # ]:           0 :                 if (typid != prev_width_type)
    4964                 :             :                 {
    4965                 :             :                     Oid         typoutputfunc;
    4966                 :             :                     bool        typIsVarlena;
    4967                 :             : 
    4968                 :           0 :                     getTypeOutputInfo(typid, &typoutputfunc, &typIsVarlena);
    4969                 :           0 :                     fmgr_info(typoutputfunc, &typoutputinfo_width);
    4970                 :           0 :                     prev_width_type = typid;
    4971                 :             :                 }
    4972                 :             : 
    4973                 :           0 :                 str = OutputFunctionCall(&typoutputinfo_width, value);
    4974                 :             : 
    4975                 :             :                 /* pg_strtoint32 will complain about bad data or overflow */
    4976                 :           0 :                 width = pg_strtoint32(str);
    4977                 :             : 
    4978                 :           0 :                 pfree(str);
    4979                 :             :             }
    4980                 :             :         }
    4981                 :             : 
    4982                 :             :         /* Collect the specified or next argument position */
    4983         [ +  + ]:       47574 :         if (argpos > 0)
    4984                 :          88 :             arg = argpos;
    4985         [ +  + ]:       47574 :         if (arg >= nargs)
    4986         [ +  - ]:          16 :             ereport(ERROR,
    4987                 :             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    4988                 :             :                      errmsg("too few arguments for format()")));
    4989                 :             : 
    4990                 :             :         /* Get the value and type of the selected argument */
    4991         [ +  + ]:       47558 :         if (!funcvariadic)
    4992                 :             :         {
    4993                 :       46710 :             value = PG_GETARG_DATUM(arg);
    4994                 :       46710 :             isNull = PG_ARGISNULL(arg);
    4995                 :       46710 :             typid = get_fn_expr_argtype(fcinfo->flinfo, arg);
    4996                 :             :         }
    4997                 :             :         else
    4998                 :             :         {
    4999                 :         848 :             value = elements[arg - 1];
    5000                 :         848 :             isNull = nulls[arg - 1];
    5001                 :         848 :             typid = element_type;
    5002                 :             :         }
    5003         [ -  + ]:       47558 :         if (!OidIsValid(typid))
    5004         [ #  # ]:           0 :             elog(ERROR, "could not determine data type of format() input");
    5005                 :             : 
    5006                 :       47558 :         arg++;
    5007                 :             : 
    5008                 :             :         /*
    5009                 :             :          * Get the appropriate typOutput function, reusing previous one if
    5010                 :             :          * same type as previous argument.  That's particularly useful in the
    5011                 :             :          * variadic-array case, but often saves work even for ordinary calls.
    5012                 :             :          */
    5013         [ +  + ]:       47558 :         if (typid != prev_type)
    5014                 :             :         {
    5015                 :             :             Oid         typoutputfunc;
    5016                 :             :             bool        typIsVarlena;
    5017                 :             : 
    5018                 :       25423 :             getTypeOutputInfo(typid, &typoutputfunc, &typIsVarlena);
    5019                 :       25423 :             fmgr_info(typoutputfunc, &typoutputfinfo);
    5020                 :       25423 :             prev_type = typid;
    5021                 :             :         }
    5022                 :             : 
    5023                 :             :         /*
    5024                 :             :          * And now we can format the value.
    5025                 :             :          */
    5026         [ +  - ]:       47558 :         switch (*cp)
    5027                 :             :         {
    5028                 :       47558 :             case 's':
    5029                 :             :             case 'I':
    5030                 :             :             case 'L':
    5031                 :       47558 :                 text_format_string_conversion(&result_str, *cp, &typoutputfinfo,
    5032                 :             :                                               value, isNull,
    5033                 :             :                                               flags, width);
    5034                 :       47554 :                 break;
    5035                 :           0 :             default:
    5036                 :             :                 /* should not get here, because of previous check */
    5037         [ #  # ]:           0 :                 ereport(ERROR,
    5038                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    5039                 :             :                          errmsg("unrecognized format() type specifier \"%.*s\"",
    5040                 :             :                                 pg_mblen_range(cp, end_ptr), cp),
    5041                 :             :                          errhint("For a single \"%%\" use \"%%%%\".")));
    5042                 :             :                 break;
    5043                 :             :         }
    5044                 :             :     }
    5045                 :             : 
    5046                 :             :     /* Don't need deconstruct_array results anymore. */
    5047         [ +  + ]:       24053 :     if (elements != NULL)
    5048                 :          28 :         pfree(elements);
    5049         [ +  + ]:       24053 :     if (nulls != NULL)
    5050                 :          28 :         pfree(nulls);
    5051                 :             : 
    5052                 :             :     /* Generate results. */
    5053                 :       24053 :     result = cstring_to_text_with_len(result_str.data, result_str.len);
    5054                 :       24053 :     pfree(result_str.data);
    5055                 :             : 
    5056                 :       24053 :     PG_RETURN_TEXT_P(result);
    5057                 :             : }
    5058                 :             : 
    5059                 :             : /*
    5060                 :             :  * Parse contiguous digits as a decimal number.
    5061                 :             :  *
    5062                 :             :  * Returns true if some digits could be parsed.
    5063                 :             :  * The value is returned into *value, and *ptr is advanced to the next
    5064                 :             :  * character to be parsed.
    5065                 :             :  *
    5066                 :             :  * Note parsing invariant: at least one character is known available before
    5067                 :             :  * string end (end_ptr) at entry, and this is still true at exit.
    5068                 :             :  */
    5069                 :             : static bool
    5070                 :       95164 : text_format_parse_digits(const char **ptr, const char *end_ptr, int *value)
    5071                 :             : {
    5072                 :       95164 :     bool        found = false;
    5073                 :       95164 :     const char *cp = *ptr;
    5074                 :       95164 :     int         val = 0;
    5075                 :             : 
    5076   [ +  +  +  + ]:       95372 :     while (*cp >= '0' && *cp <= '9')
    5077                 :             :     {
    5078                 :         212 :         int8        digit = (*cp - '0');
    5079                 :             : 
    5080         [ +  - ]:         212 :         if (unlikely(pg_mul_s32_overflow(val, 10, &val)) ||
    5081         [ -  + ]:         212 :             unlikely(pg_add_s32_overflow(val, digit, &val)))
    5082         [ #  # ]:           0 :             ereport(ERROR,
    5083                 :             :                     (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    5084                 :             :                      errmsg("number is out of range")));
    5085   [ +  +  +  - ]:         212 :         ADVANCE_PARSE_POINTER(cp, end_ptr);
    5086                 :         208 :         found = true;
    5087                 :             :     }
    5088                 :             : 
    5089                 :       95160 :     *ptr = cp;
    5090                 :       95160 :     *value = val;
    5091                 :             : 
    5092                 :       95160 :     return found;
    5093                 :             : }
    5094                 :             : 
    5095                 :             : /*
    5096                 :             :  * Parse a format specifier (generally following the SUS printf spec).
    5097                 :             :  *
    5098                 :             :  * We have already advanced over the initial '%', and we are looking for
    5099                 :             :  * [argpos][flags][width]type (but the type character is not consumed here).
    5100                 :             :  *
    5101                 :             :  * Inputs are start_ptr (the position after '%') and end_ptr (string end + 1).
    5102                 :             :  * Output parameters:
    5103                 :             :  *  argpos: argument position for value to be printed.  -1 means unspecified.
    5104                 :             :  *  widthpos: argument position for width.  Zero means the argument position
    5105                 :             :  *          was unspecified (ie, take the next arg) and -1 means no width
    5106                 :             :  *          argument (width was omitted or specified as a constant).
    5107                 :             :  *  flags: bitmask of flags.
    5108                 :             :  *  width: directly-specified width value.  Zero means the width was omitted
    5109                 :             :  *          (note it's not necessary to distinguish this case from an explicit
    5110                 :             :  *          zero width value).
    5111                 :             :  *
    5112                 :             :  * The function result is the next character position to be parsed, ie, the
    5113                 :             :  * location where the type character is/should be.
    5114                 :             :  *
    5115                 :             :  * Note parsing invariant: at least one character is known available before
    5116                 :             :  * string end (end_ptr) at entry, and this is still true at exit.
    5117                 :             :  */
    5118                 :             : static const char *
    5119                 :       47594 : text_format_parse_format(const char *start_ptr, const char *end_ptr,
    5120                 :             :                          int *argpos, int *widthpos,
    5121                 :             :                          int *flags, int *width)
    5122                 :             : {
    5123                 :       47594 :     const char *cp = start_ptr;
    5124                 :             :     int         n;
    5125                 :             : 
    5126                 :             :     /* set defaults for output parameters */
    5127                 :       47594 :     *argpos = -1;
    5128                 :       47594 :     *widthpos = -1;
    5129                 :       47594 :     *flags = 0;
    5130                 :       47594 :     *width = 0;
    5131                 :             : 
    5132                 :             :     /* try to identify first number */
    5133         [ +  + ]:       47594 :     if (text_format_parse_digits(&cp, end_ptr, &n))
    5134                 :             :     {
    5135         [ +  + ]:         116 :         if (*cp != '$')
    5136                 :             :         {
    5137                 :             :             /* Must be just a width and a type, so we're done */
    5138                 :          16 :             *width = n;
    5139                 :          16 :             return cp;
    5140                 :             :         }
    5141                 :             :         /* The number was argument position */
    5142                 :         100 :         *argpos = n;
    5143                 :             :         /* Explicit 0 for argument index is immediately refused */
    5144         [ +  + ]:         100 :         if (n == 0)
    5145         [ +  - ]:           4 :             ereport(ERROR,
    5146                 :             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    5147                 :             :                      errmsg("format specifies argument 0, but arguments are numbered from 1")));
    5148   [ +  +  +  - ]:          96 :         ADVANCE_PARSE_POINTER(cp, end_ptr);
    5149                 :             :     }
    5150                 :             : 
    5151                 :             :     /* Handle flags (only minus is supported now) */
    5152         [ +  + ]:       47590 :     while (*cp == '-')
    5153                 :             :     {
    5154                 :          20 :         *flags |= TEXT_FORMAT_FLAG_MINUS;
    5155   [ -  +  -  - ]:          20 :         ADVANCE_PARSE_POINTER(cp, end_ptr);
    5156                 :             :     }
    5157                 :             : 
    5158         [ +  + ]:       47570 :     if (*cp == '*')
    5159                 :             :     {
    5160                 :             :         /* Handle indirect width */
    5161   [ -  +  -  - ]:          32 :         ADVANCE_PARSE_POINTER(cp, end_ptr);
    5162         [ +  + ]:          32 :         if (text_format_parse_digits(&cp, end_ptr, &n))
    5163                 :             :         {
    5164                 :             :             /* number in this position must be closed by $ */
    5165         [ -  + ]:          28 :             if (*cp != '$')
    5166         [ #  # ]:           0 :                 ereport(ERROR,
    5167                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    5168                 :             :                          errmsg("width argument position must be ended by \"$\"")));
    5169                 :             :             /* The number was width argument position */
    5170                 :          28 :             *widthpos = n;
    5171                 :             :             /* Explicit 0 for argument index is immediately refused */
    5172         [ +  + ]:          28 :             if (n == 0)
    5173         [ +  - ]:           4 :                 ereport(ERROR,
    5174                 :             :                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    5175                 :             :                          errmsg("format specifies argument 0, but arguments are numbered from 1")));
    5176   [ -  +  -  - ]:          24 :             ADVANCE_PARSE_POINTER(cp, end_ptr);
    5177                 :             :         }
    5178                 :             :         else
    5179                 :           4 :             *widthpos = 0;      /* width's argument position is unspecified */
    5180                 :             :     }
    5181                 :             :     else
    5182                 :             :     {
    5183                 :             :         /* Check for direct width specification */
    5184         [ +  + ]:       47538 :         if (text_format_parse_digits(&cp, end_ptr, &n))
    5185                 :          20 :             *width = n;
    5186                 :             :     }
    5187                 :             : 
    5188                 :             :     /* cp should now be pointing at type character */
    5189                 :       47562 :     return cp;
    5190                 :             : }
    5191                 :             : 
    5192                 :             : /*
    5193                 :             :  * Format a %s, %I, or %L conversion
    5194                 :             :  */
    5195                 :             : static void
    5196                 :       47558 : text_format_string_conversion(StringInfo buf, char conversion,
    5197                 :             :                               FmgrInfo *typOutputInfo,
    5198                 :             :                               Datum value, bool isNull,
    5199                 :             :                               int flags, int width)
    5200                 :             : {
    5201                 :             :     char       *str;
    5202                 :             : 
    5203                 :             :     /* Handle NULL arguments before trying to stringify the value. */
    5204         [ +  + ]:       47558 :     if (isNull)
    5205                 :             :     {
    5206         [ +  + ]:         228 :         if (conversion == 's')
    5207                 :         180 :             text_format_append_string(buf, "", flags, width);
    5208         [ +  + ]:          48 :         else if (conversion == 'L')
    5209                 :          44 :             text_format_append_string(buf, "NULL", flags, width);
    5210         [ +  - ]:           4 :         else if (conversion == 'I')
    5211         [ +  - ]:           4 :             ereport(ERROR,
    5212                 :             :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    5213                 :             :                      errmsg("null values cannot be formatted as an SQL identifier")));
    5214                 :         224 :         return;
    5215                 :             :     }
    5216                 :             : 
    5217                 :             :     /* Stringify. */
    5218                 :       47330 :     str = OutputFunctionCall(typOutputInfo, value);
    5219                 :             : 
    5220                 :             :     /* Escape. */
    5221         [ +  + ]:       47330 :     if (conversion == 'I')
    5222                 :             :     {
    5223                 :             :         /* quote_identifier may or may not allocate a new string. */
    5224                 :        3269 :         text_format_append_string(buf, quote_identifier(str), flags, width);
    5225                 :             :     }
    5226         [ +  + ]:       44061 :     else if (conversion == 'L')
    5227                 :             :     {
    5228                 :        2168 :         char       *qstr = quote_literal_cstr(str);
    5229                 :             : 
    5230                 :        2168 :         text_format_append_string(buf, qstr, flags, width);
    5231                 :             :         /* quote_literal_cstr() always allocates a new string */
    5232                 :        2168 :         pfree(qstr);
    5233                 :             :     }
    5234                 :             :     else
    5235                 :       41893 :         text_format_append_string(buf, str, flags, width);
    5236                 :             : 
    5237                 :             :     /* Cleanup. */
    5238                 :       47330 :     pfree(str);
    5239                 :             : }
    5240                 :             : 
    5241                 :             : /*
    5242                 :             :  * Append str to buf, padding as directed by flags/width
    5243                 :             :  */
    5244                 :             : static void
    5245                 :       47554 : text_format_append_string(StringInfo buf, const char *str,
    5246                 :             :                           int flags, int width)
    5247                 :             : {
    5248                 :       47554 :     bool        align_to_left = false;
    5249                 :             :     int         len;
    5250                 :             : 
    5251                 :             :     /* fast path for typical easy case */
    5252         [ +  + ]:       47554 :     if (width == 0)
    5253                 :             :     {
    5254                 :       47498 :         appendStringInfoString(buf, str);
    5255                 :       47498 :         return;
    5256                 :             :     }
    5257                 :             : 
    5258         [ +  + ]:          56 :     if (width < 0)
    5259                 :             :     {
    5260                 :             :         /* Negative width: implicit '-' flag, then take absolute value */
    5261                 :           4 :         align_to_left = true;
    5262                 :             :         /* -INT_MIN is undefined */
    5263         [ -  + ]:           4 :         if (width <= INT_MIN)
    5264         [ #  # ]:           0 :             ereport(ERROR,
    5265                 :             :                     (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    5266                 :             :                      errmsg("number is out of range")));
    5267                 :           4 :         width = -width;
    5268                 :             :     }
    5269         [ +  + ]:          52 :     else if (flags & TEXT_FORMAT_FLAG_MINUS)
    5270                 :          16 :         align_to_left = true;
    5271                 :             : 
    5272                 :          56 :     len = pg_mbstrlen(str);
    5273         [ +  + ]:          56 :     if (align_to_left)
    5274                 :             :     {
    5275                 :             :         /* left justify */
    5276                 :          20 :         appendStringInfoString(buf, str);
    5277         [ +  - ]:          20 :         if (len < width)
    5278                 :          20 :             appendStringInfoSpaces(buf, width - len);
    5279                 :             :     }
    5280                 :             :     else
    5281                 :             :     {
    5282                 :             :         /* right justify */
    5283         [ +  - ]:          36 :         if (len < width)
    5284                 :          36 :             appendStringInfoSpaces(buf, width - len);
    5285                 :          36 :         appendStringInfoString(buf, str);
    5286                 :             :     }
    5287                 :             : }
    5288                 :             : 
    5289                 :             : /*
    5290                 :             :  * text_format_nv - nonvariadic wrapper for text_format function.
    5291                 :             :  *
    5292                 :             :  * note: this wrapper is necessary to pass the sanity check in opr_sanity,
    5293                 :             :  * which checks that all built-in functions that share the implementing C
    5294                 :             :  * function take the same number of arguments.
    5295                 :             :  */
    5296                 :             : Datum
    5297                 :        1910 : text_format_nv(PG_FUNCTION_ARGS)
    5298                 :             : {
    5299                 :        1910 :     return text_format(fcinfo);
    5300                 :             : }
    5301                 :             : 
    5302                 :             : /*
    5303                 :             :  * Helper function for Levenshtein distance functions. Faster than memcmp(),
    5304                 :             :  * for this use case.
    5305                 :             :  */
    5306                 :             : static inline bool
    5307                 :           0 : rest_of_char_same(const char *s1, const char *s2, int len)
    5308                 :             : {
    5309         [ #  # ]:           0 :     while (len > 0)
    5310                 :             :     {
    5311                 :           0 :         len--;
    5312         [ #  # ]:           0 :         if (s1[len] != s2[len])
    5313                 :           0 :             return false;
    5314                 :             :     }
    5315                 :           0 :     return true;
    5316                 :             : }
    5317                 :             : 
    5318                 :             : /*
    5319                 :             :  * Helper function for checking return value of Levenshtein distance functions.
    5320                 :             :  * We calculate it as an int64, but the distance functions return an int32.
    5321                 :             :  */
    5322                 :             : static inline int
    5323                 :        2038 : levenshtein_result(int64 res)
    5324                 :             : {
    5325   [ +  -  +  +  :        2038 :     if (unlikely(res < PG_INT32_MIN || res > PG_INT32_MAX))
                   +  + ]
    5326         [ +  - ]:           1 :         ereport(ERROR,
    5327                 :             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    5328                 :             :                  errmsg("levenshtein distance out of range")));
    5329                 :        2037 :     return res;
    5330                 :             : }
    5331                 :             : 
    5332                 :             : /* Expand each Levenshtein distance variant */
    5333                 :             : #include "levenshtein.c"
    5334                 :             : #define LEVENSHTEIN_LESS_EQUAL
    5335                 :             : #include "levenshtein.c"
    5336                 :             : 
    5337                 :             : 
    5338                 :             : /*
    5339                 :             :  * The following *ClosestMatch() functions can be used to determine whether a
    5340                 :             :  * user-provided string resembles any known valid values, which is useful for
    5341                 :             :  * providing hints in log messages, among other things.  Use these functions
    5342                 :             :  * like so:
    5343                 :             :  *
    5344                 :             :  *      initClosestMatch(&state, source_string, max_distance);
    5345                 :             :  *
    5346                 :             :  *      for (int i = 0; i < num_valid_strings; i++)
    5347                 :             :  *          updateClosestMatch(&state, valid_strings[i]);
    5348                 :             :  *
    5349                 :             :  *      closestMatch = getClosestMatch(&state);
    5350                 :             :  */
    5351                 :             : 
    5352                 :             : /*
    5353                 :             :  * Initialize the given state with the source string and maximum Levenshtein
    5354                 :             :  * distance to consider.
    5355                 :             :  */
    5356                 :             : void
    5357                 :          49 : initClosestMatch(ClosestMatchState *state, const char *source, int max_d)
    5358                 :             : {
    5359                 :             :     Assert(state);
    5360                 :             :     Assert(max_d >= 0);
    5361                 :             : 
    5362                 :          49 :     state->source = source;
    5363                 :          49 :     state->min_d = -1;
    5364                 :          49 :     state->max_d = max_d;
    5365                 :          49 :     state->match = NULL;
    5366                 :          49 : }
    5367                 :             : 
    5368                 :             : /*
    5369                 :             :  * If the candidate string is a closer match than the current one saved (or
    5370                 :             :  * there is no match saved), save it as the closest match.
    5371                 :             :  *
    5372                 :             :  * If the source or candidate string is NULL, empty, or too long, this function
    5373                 :             :  * takes no action.  Likewise, if the Levenshtein distance exceeds the maximum
    5374                 :             :  * allowed or more than half the characters are different, no action is taken.
    5375                 :             :  */
    5376                 :             : void
    5377                 :         531 : updateClosestMatch(ClosestMatchState *state, const char *candidate)
    5378                 :             : {
    5379                 :             :     int         dist;
    5380                 :             : 
    5381                 :             :     Assert(state);
    5382                 :             : 
    5383   [ +  -  +  -  :         531 :     if (state->source == NULL || state->source[0] == '\0' ||
                   +  - ]
    5384         [ -  + ]:         531 :         candidate == NULL || candidate[0] == '\0')
    5385                 :           0 :         return;
    5386                 :             : 
    5387                 :             :     /*
    5388                 :             :      * To avoid ERROR-ing, we check the lengths here instead of setting
    5389                 :             :      * 'trusted' to false in the call to varstr_levenshtein_less_equal().
    5390                 :             :      */
    5391         [ +  - ]:         531 :     if (strlen(state->source) > MAX_LEVENSHTEIN_STRLEN ||
    5392         [ -  + ]:         531 :         strlen(candidate) > MAX_LEVENSHTEIN_STRLEN)
    5393                 :           0 :         return;
    5394                 :             : 
    5395                 :         531 :     dist = varstr_levenshtein_less_equal(state->source, strlen(state->source),
    5396                 :         531 :                                          candidate, strlen(candidate), 1, 1, 1,
    5397                 :             :                                          state->max_d, true);
    5398         [ +  + ]:         531 :     if (dist <= state->max_d &&
    5399         [ +  + ]:          39 :         dist <= strlen(state->source) / 2 &&
    5400   [ -  +  -  - ]:           9 :         (state->min_d == -1 || dist < state->min_d))
    5401                 :             :     {
    5402                 :           9 :         state->min_d = dist;
    5403                 :           9 :         state->match = candidate;
    5404                 :             :     }
    5405                 :             : }
    5406                 :             : 
    5407                 :             : /*
    5408                 :             :  * Return the closest match.  If no suitable candidates were provided via
    5409                 :             :  * updateClosestMatch(), return NULL.
    5410                 :             :  */
    5411                 :             : const char *
    5412                 :          49 : getClosestMatch(ClosestMatchState *state)
    5413                 :             : {
    5414                 :             :     Assert(state);
    5415                 :             : 
    5416                 :          49 :     return state->match;
    5417                 :             : }
    5418                 :             : 
    5419                 :             : 
    5420                 :             : /*
    5421                 :             :  * Unicode support
    5422                 :             :  */
    5423                 :             : 
    5424                 :             : static UnicodeNormalizationForm
    5425                 :        1068 : unicode_norm_form_from_text(text *formtxt)
    5426                 :             : {
    5427                 :        1068 :     const char *formstr = VARDATA_ANY(formtxt);
    5428                 :        1068 :     int         formlen = VARSIZE_ANY_EXHDR(formtxt);
    5429                 :        1068 :     UnicodeNormalizationForm form = -1;
    5430                 :             : 
    5431                 :             :     /*
    5432                 :             :      * Might as well check this while we're here.
    5433                 :             :      */
    5434         [ -  + ]:        1068 :     if (GetDatabaseEncoding() != PG_UTF8)
    5435         [ #  # ]:           0 :         ereport(ERROR,
    5436                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5437                 :             :                  errmsg("Unicode normalization can only be performed if server encoding is UTF8")));
    5438                 :             : 
    5439   [ +  +  +  + ]:        1068 :     if (formlen == 3 && pg_strncasecmp(formstr, "NFC", 3) == 0)
    5440                 :         782 :         form = UNICODE_NFC;
    5441   [ +  +  +  + ]:         286 :     else if (formlen == 3 && pg_strncasecmp(formstr, "NFD", 3) == 0)
    5442                 :         220 :         form = UNICODE_NFD;
    5443   [ +  +  +  + ]:          66 :     else if (formlen == 4 && pg_strncasecmp(formstr, "NFKC", 4) == 0)
    5444                 :          25 :         form = UNICODE_NFKC;
    5445   [ +  +  +  + ]:          41 :     else if (formlen == 4 && pg_strncasecmp(formstr, "NFKD", 4) == 0)
    5446                 :          25 :         form = UNICODE_NFKD;
    5447                 :             :     else
    5448         [ +  - ]:          16 :         ereport(ERROR,
    5449                 :             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    5450                 :             :                  errmsg("invalid normalization form: %s", text_to_cstring(formtxt))));
    5451                 :             : 
    5452                 :        1052 :     return form;
    5453                 :             : }
    5454                 :             : 
    5455                 :             : /*
    5456                 :             :  * Returns version of Unicode used by Postgres in "major.minor" format (the
    5457                 :             :  * same format as the Unicode version reported by ICU). The third component
    5458                 :             :  * ("update version") never involves additions to the character repertoire and
    5459                 :             :  * is unimportant for most purposes.
    5460                 :             :  *
    5461                 :             :  * See: https://unicode.org/versions/
    5462                 :             :  */
    5463                 :             : Datum
    5464                 :          23 : unicode_version(PG_FUNCTION_ARGS)
    5465                 :             : {
    5466                 :          23 :     PG_RETURN_TEXT_P(cstring_to_text(PG_UNICODE_VERSION));
    5467                 :             : }
    5468                 :             : 
    5469                 :             : /*
    5470                 :             :  * Returns version of Unicode used by ICU, if enabled; otherwise NULL.
    5471                 :             :  */
    5472                 :             : Datum
    5473                 :           1 : icu_unicode_version(PG_FUNCTION_ARGS)
    5474                 :             : {
    5475                 :           1 :     const char *version = pg_icu_unicode_version();
    5476                 :             : 
    5477         [ +  - ]:           1 :     if (version)
    5478                 :           1 :         PG_RETURN_TEXT_P(cstring_to_text(version));
    5479                 :             :     else
    5480                 :           0 :         PG_RETURN_NULL();
    5481                 :             : }
    5482                 :             : 
    5483                 :             : /*
    5484                 :             :  * Return the length of an initial portion of s[0..len) that is valid ASCII,
    5485                 :             :  * that is, contains no zero bytes and no bytes with the high bit set, or
    5486                 :             :  * len if all of it is.  The result can be a little short of the full valid
    5487                 :             :  * ASCII prefix; callers must not rely on it being exact.
    5488                 :             :  */
    5489                 :             : static int
    5490                 :        1395 : valid_ascii_prefix_len(const unsigned char *s, int len)
    5491                 :             : {
    5492                 :        1395 :     int         chunk_len = len - (len % sizeof(Vector8));
    5493                 :             : 
    5494                 :             :     /*
    5495                 :             :      * is_valid_ascii() requires a length that is a multiple of
    5496                 :             :      * sizeof(Vector8), so check one chunk at a time with it and then the
    5497                 :             :      * remainder byte by byte.  A failure inside a chunk is reported at the
    5498                 :             :      * start of that chunk, so the result can be up to sizeof(Vector8) - 1
    5499                 :             :      * bytes short of the full valid ASCII prefix.
    5500                 :             :      */
    5501         [ +  + ]:        3491 :     for (int i = 0; i < chunk_len; i += sizeof(Vector8))
    5502         [ +  + ]:        2680 :         if (!is_valid_ascii(s + i, sizeof(Vector8)))
    5503                 :         584 :             return i;
    5504                 :             : 
    5505         [ +  + ]:        3810 :     for (int i = chunk_len; i < len; i++)
    5506   [ +  -  +  + ]:        3749 :         if (s[i] == 0 || IS_HIGHBIT_SET(s[i]))
    5507                 :         750 :             return i;
    5508                 :             : 
    5509                 :          61 :     return len;
    5510                 :             : }
    5511                 :             : 
    5512                 :             : /*
    5513                 :             :  * Check whether the string contains only assigned Unicode code
    5514                 :             :  * points. Requires that the database encoding is UTF-8.
    5515                 :             :  */
    5516                 :             : Datum
    5517                 :         343 : unicode_assigned(PG_FUNCTION_ARGS)
    5518                 :             : {
    5519                 :         343 :     text       *input = PG_GETARG_TEXT_PP(0);
    5520                 :             :     unsigned char *p;
    5521                 :             :     unsigned char *end;
    5522                 :             :     int         len;
    5523                 :             :     int         start;
    5524                 :             : 
    5525         [ -  + ]:         343 :     if (GetDatabaseEncoding() != PG_UTF8)
    5526         [ #  # ]:           0 :         ereport(ERROR,
    5527                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5528                 :             :                  errmsg("Unicode categorization can only be performed if server encoding is UTF8")));
    5529                 :             : 
    5530                 :             :     /* ASCII code points are always assigned, so only check the rest */
    5531                 :         343 :     len = VARSIZE_ANY_EXHDR(input);
    5532                 :         343 :     start = valid_ascii_prefix_len((unsigned char *) VARDATA_ANY(input), len);
    5533         [ +  + ]:         343 :     if (start == len)
    5534                 :          10 :         PG_RETURN_BOOL(true);
    5535                 :             : 
    5536                 :             :     /*
    5537                 :             :      * Check the remaining code points without first counting them.  A text
    5538                 :             :      * value cannot contain a NUL byte, so stopping at one is only a safeguard
    5539                 :             :      * against reading past a terminator in malformed input; the code that
    5540                 :             :      * counted code points before this change also treated NUL as the end of
    5541                 :             :      * the string.
    5542                 :             :      */
    5543                 :         333 :     p = (unsigned char *) VARDATA_ANY(input) + start;
    5544                 :         333 :     end = (unsigned char *) VARDATA_ANY(input) + len;
    5545   [ +  +  +  - ]:        5229 :     while (p < end && *p)
    5546                 :             :     {
    5547                 :        5065 :         char32_t    uchar = utf8_to_unicode(p);
    5548                 :        5065 :         int         category = unicode_category(uchar);
    5549                 :             : 
    5550         [ +  + ]:        5065 :         if (category == PG_U_UNASSIGNED)
    5551                 :         169 :             PG_RETURN_BOOL(false);
    5552                 :             : 
    5553                 :        4896 :         p += pg_utf_mblen(p);
    5554                 :             :     }
    5555                 :             : 
    5556                 :         164 :     PG_RETURN_BOOL(true);
    5557                 :             : }
    5558                 :             : 
    5559                 :             : Datum
    5560                 :         637 : unicode_normalize_func(PG_FUNCTION_ARGS)
    5561                 :             : {
    5562                 :         637 :     text       *input = PG_GETARG_TEXT_PP(0);
    5563                 :         637 :     text       *formtxt = PG_GETARG_TEXT_PP(1);
    5564                 :             :     UnicodeNormalizationForm form;
    5565                 :             :     size_t      size;
    5566                 :             :     char32_t   *input_chars;
    5567                 :             :     char32_t   *output_chars;
    5568                 :             :     unsigned char *p;
    5569                 :             :     text       *result;
    5570                 :             :     size_t      i;
    5571                 :             :     int         len;
    5572                 :             :     int         start;
    5573                 :             : 
    5574                 :         637 :     form = unicode_norm_form_from_text(formtxt);
    5575                 :             : 
    5576                 :             :     /*
    5577                 :             :      * ASCII characters have no decomposition and a combining class of zero,
    5578                 :             :      * so leading ASCII is unchanged by normalization in any form, except that
    5579                 :             :      * its last character might compose with a following combining mark.  No
    5580                 :             :      * canonical composition has an ASCII character as its second element, so
    5581                 :             :      * nothing before that last character can be affected.  So return an
    5582                 :             :      * all-ASCII string as is, and otherwise normalize only the rest of the
    5583                 :             :      * string, starting with that last ASCII character.
    5584                 :             :      */
    5585                 :         629 :     len = VARSIZE_ANY_EXHDR(input);
    5586                 :         629 :     start = valid_ascii_prefix_len((unsigned char *) VARDATA_ANY(input), len);
    5587         [ +  + ]:         629 :     if (start == len)
    5588                 :          30 :         PG_RETURN_TEXT_P(input);
    5589         [ +  + ]:         599 :     if (start > 0)
    5590                 :         436 :         start--;
    5591                 :             : 
    5592                 :             :     /* convert to char32_t */
    5593                 :         599 :     size = pg_mbstrlen_with_len(VARDATA_ANY(input) + start, len - start);
    5594                 :         599 :     input_chars = palloc_array(char32_t, size + 1);
    5595                 :         599 :     p = (unsigned char *) VARDATA_ANY(input) + start;
    5596         [ +  + ]:       10602 :     for (i = 0; i < size; i++)
    5597                 :             :     {
    5598                 :       10003 :         input_chars[i] = utf8_to_unicode(p);
    5599                 :       10003 :         p += pg_utf_mblen(p);
    5600                 :             :     }
    5601                 :         599 :     input_chars[i] = (char32_t) '\0';
    5602                 :             :     Assert((char *) p == VARDATA_ANY(input) + len);
    5603                 :             : 
    5604                 :             :     /* action */
    5605                 :         599 :     output_chars = unicode_normalize(form, input_chars);
    5606                 :             : 
    5607                 :             :     /* convert back to UTF-8 string, after the unchanged ASCII */
    5608                 :         599 :     size = start;
    5609         [ +  + ]:       10583 :     for (char32_t *wp = output_chars; *wp; wp++)
    5610                 :             :     {
    5611                 :             :         unsigned char buf[4];
    5612                 :             : 
    5613                 :        9984 :         unicode_to_utf8(*wp, buf);
    5614                 :        9984 :         size += pg_utf_mblen(buf);
    5615                 :             :     }
    5616                 :             : 
    5617                 :         599 :     result = palloc(size + VARHDRSZ);
    5618                 :         599 :     SET_VARSIZE(result, size + VARHDRSZ);
    5619                 :             : 
    5620                 :         599 :     p = (unsigned char *) VARDATA_ANY(result);
    5621                 :         599 :     memcpy(p, VARDATA_ANY(input), start);
    5622                 :         599 :     p += start;
    5623         [ +  + ]:       10583 :     for (char32_t *wp = output_chars; *wp; wp++)
    5624                 :             :     {
    5625                 :        9984 :         unicode_to_utf8(*wp, p);
    5626                 :        9984 :         p += pg_utf_mblen(p);
    5627                 :             :     }
    5628                 :             :     Assert((char *) p == (char *) result + size + VARHDRSZ);
    5629                 :             : 
    5630                 :         599 :     PG_RETURN_TEXT_P(result);
    5631                 :             : }
    5632                 :             : 
    5633                 :             : /*
    5634                 :             :  * Check whether the string is in the specified Unicode normalization form.
    5635                 :             :  *
    5636                 :             :  * This is done by converting the string to the specified normal form and then
    5637                 :             :  * comparing that to the original string.  To speed that up, we also apply the
    5638                 :             :  * "quick check" algorithm specified in UAX #15, which can give a yes or no
    5639                 :             :  * answer for many strings by just scanning the string once.
    5640                 :             :  *
    5641                 :             :  * This function should generally be optimized for the case where the string
    5642                 :             :  * is in fact normalized.  In that case, we'll end up looking at the entire
    5643                 :             :  * string, so it's probably not worth doing any incremental conversion etc.
    5644                 :             :  */
    5645                 :             : Datum
    5646                 :         431 : unicode_is_normalized(PG_FUNCTION_ARGS)
    5647                 :             : {
    5648                 :         431 :     text       *input = PG_GETARG_TEXT_PP(0);
    5649                 :         431 :     text       *formtxt = PG_GETARG_TEXT_PP(1);
    5650                 :             :     UnicodeNormalizationForm form;
    5651                 :             :     size_t      size;
    5652                 :             :     char32_t   *input_chars;
    5653                 :             :     char32_t   *output_chars;
    5654                 :             :     unsigned char *p;
    5655                 :             :     size_t      i;
    5656                 :             :     UnicodeNormalizationQC quickcheck;
    5657                 :             :     size_t      output_size;
    5658                 :             :     bool        result;
    5659                 :             :     int         len;
    5660                 :             :     int         start;
    5661                 :             : 
    5662                 :         431 :     form = unicode_norm_form_from_text(formtxt);
    5663                 :             : 
    5664                 :             :     /*
    5665                 :             :      * Leading ASCII is unchanged by normalization, except that its last
    5666                 :             :      * character might compose with a following combining mark (see
    5667                 :             :      * unicode_normalize_func()).  So an all-ASCII string is normalized in
    5668                 :             :      * every form, and otherwise only the rest of the string, starting with
    5669                 :             :      * that last ASCII character, needs to be checked.
    5670                 :             :      */
    5671                 :         423 :     len = VARSIZE_ANY_EXHDR(input);
    5672                 :         423 :     start = valid_ascii_prefix_len((unsigned char *) VARDATA_ANY(input), len);
    5673         [ +  + ]:         423 :     if (start == len)
    5674                 :          21 :         PG_RETURN_BOOL(true);
    5675         [ +  + ]:         402 :     if (start > 0)
    5676                 :         240 :         start--;
    5677                 :             : 
    5678                 :             :     /* convert to char32_t */
    5679                 :         402 :     size = pg_mbstrlen_with_len(VARDATA_ANY(input) + start, len - start);
    5680                 :         402 :     input_chars = palloc_array(char32_t, size + 1);
    5681                 :         402 :     p = (unsigned char *) VARDATA_ANY(input) + start;
    5682         [ +  + ]:        4816 :     for (i = 0; i < size; i++)
    5683                 :             :     {
    5684                 :        4414 :         input_chars[i] = utf8_to_unicode(p);
    5685                 :        4414 :         p += pg_utf_mblen(p);
    5686                 :             :     }
    5687                 :         402 :     input_chars[i] = (char32_t) '\0';
    5688                 :             :     Assert((char *) p == VARDATA_ANY(input) + len);
    5689                 :             : 
    5690                 :             :     /* quick check (see UAX #15) */
    5691                 :         402 :     quickcheck = unicode_is_normalized_quickcheck(form, input_chars);
    5692         [ +  + ]:         402 :     if (quickcheck == UNICODE_NORM_QC_YES)
    5693                 :          22 :         PG_RETURN_BOOL(true);
    5694         [ +  + ]:         380 :     else if (quickcheck == UNICODE_NORM_QC_NO)
    5695                 :           8 :         PG_RETURN_BOOL(false);
    5696                 :             : 
    5697                 :             :     /* normalize and compare with original */
    5698                 :         372 :     output_chars = unicode_normalize(form, input_chars);
    5699                 :             : 
    5700                 :         372 :     output_size = 0;
    5701         [ +  + ]:        4368 :     for (char32_t *wp = output_chars; *wp; wp++)
    5702                 :        3996 :         output_size++;
    5703                 :             : 
    5704         [ +  + ]:         388 :     result = (size == output_size) &&
    5705         [ +  + ]:          16 :         (memcmp(input_chars, output_chars, size * sizeof(char32_t)) == 0);
    5706                 :             : 
    5707                 :         372 :     PG_RETURN_BOOL(result);
    5708                 :             : }
    5709                 :             : 
    5710                 :             : /*
    5711                 :             :  * Check if first n chars are hexadecimal digits
    5712                 :             :  */
    5713                 :             : static bool
    5714                 :         111 : isxdigits_n(const char *instr, size_t n)
    5715                 :             : {
    5716         [ +  + ]:         469 :     for (size_t i = 0; i < n; i++)
    5717         [ +  + ]:         405 :         if (!isxdigit((unsigned char) instr[i]))
    5718                 :          47 :             return false;
    5719                 :             : 
    5720                 :          64 :     return true;
    5721                 :             : }
    5722                 :             : 
    5723                 :             : static unsigned int
    5724                 :         358 : hexval(unsigned char c)
    5725                 :             : {
    5726   [ +  -  +  + ]:         358 :     if (c >= '0' && c <= '9')
    5727                 :         278 :         return c - '0';
    5728   [ +  +  +  - ]:          80 :     if (c >= 'a' && c <= 'f')
    5729                 :          40 :         return c - 'a' + 0xA;
    5730   [ +  -  +  - ]:          40 :     if (c >= 'A' && c <= 'F')
    5731                 :          40 :         return c - 'A' + 0xA;
    5732         [ #  # ]:           0 :     elog(ERROR, "invalid hexadecimal digit");
    5733                 :             :     return 0;                   /* not reached */
    5734                 :             : }
    5735                 :             : 
    5736                 :             : /*
    5737                 :             :  * Translate string with hexadecimal digits to number
    5738                 :             :  */
    5739                 :             : static unsigned int
    5740                 :          64 : hexval_n(const char *instr, size_t n)
    5741                 :             : {
    5742                 :          64 :     unsigned int result = 0;
    5743                 :             : 
    5744         [ +  + ]:         422 :     for (size_t i = 0; i < n; i++)
    5745                 :         358 :         result += hexval(instr[i]) << (4 * (n - i - 1));
    5746                 :             : 
    5747                 :          64 :     return result;
    5748                 :             : }
    5749                 :             : 
    5750                 :             : /*
    5751                 :             :  * Replaces Unicode escape sequences by Unicode characters
    5752                 :             :  */
    5753                 :             : Datum
    5754                 :          47 : unistr(PG_FUNCTION_ARGS)
    5755                 :             : {
    5756                 :          47 :     text       *input_text = PG_GETARG_TEXT_PP(0);
    5757                 :             :     char       *instr;
    5758                 :             :     int         len;
    5759                 :             :     StringInfoData str;
    5760                 :             :     text       *result;
    5761                 :          47 :     char16_t    pair_first = 0;
    5762                 :             :     char        cbuf[MAX_UNICODE_EQUIVALENT_STRING + 1];
    5763                 :             : 
    5764                 :          47 :     instr = VARDATA_ANY(input_text);
    5765                 :          47 :     len = VARSIZE_ANY_EXHDR(input_text);
    5766                 :             : 
    5767                 :          47 :     initStringInfo(&str);
    5768                 :             : 
    5769         [ +  + ]:         356 :     while (len > 0)
    5770                 :             :     {
    5771         [ +  + ]:         337 :         if (instr[0] == '\\')
    5772                 :             :         {
    5773         [ +  - ]:          73 :             if (len >= 2 &&
    5774         [ +  + ]:          73 :                 instr[1] == '\\')
    5775                 :             :             {
    5776         [ -  + ]:           5 :                 if (pair_first)
    5777                 :           0 :                     goto invalid_pair;
    5778                 :           5 :                 appendStringInfoChar(&str, '\\');
    5779                 :           5 :                 instr += 2;
    5780                 :           5 :                 len -= 2;
    5781                 :             :             }
    5782   [ +  +  +  +  :          68 :             else if ((len >= 5 && isxdigits_n(instr + 1, 4)) ||
                   +  + ]
    5783   [ +  +  +  - ]:          47 :                      (len >= 6 && instr[1] == 'u' && isxdigits_n(instr + 2, 4)))
    5784                 :          22 :             {
    5785                 :             :                 char32_t    unicode;
    5786         [ +  + ]:          30 :                 int         offset = instr[1] == 'u' ? 2 : 1;
    5787                 :             : 
    5788                 :          30 :                 unicode = hexval_n(instr + offset, 4);
    5789                 :             : 
    5790         [ -  + ]:          30 :                 if (!is_valid_unicode_codepoint(unicode))
    5791         [ #  # ]:           0 :                     ereport(ERROR,
    5792                 :             :                             errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    5793                 :             :                             errmsg("invalid Unicode code point: %04X", unicode));
    5794                 :             : 
    5795         [ +  + ]:          30 :                 if (pair_first)
    5796                 :             :                 {
    5797         [ -  + ]:           8 :                     if (is_utf16_surrogate_second(unicode))
    5798                 :             :                     {
    5799                 :           0 :                         unicode = surrogate_pair_to_codepoint(pair_first, unicode);
    5800                 :           0 :                         pair_first = 0;
    5801                 :             :                     }
    5802                 :             :                     else
    5803                 :           8 :                         goto invalid_pair;
    5804                 :             :                 }
    5805         [ -  + ]:          22 :                 else if (is_utf16_surrogate_second(unicode))
    5806                 :           0 :                     goto invalid_pair;
    5807                 :             : 
    5808         [ +  + ]:          22 :                 if (is_utf16_surrogate_first(unicode))
    5809                 :          12 :                     pair_first = unicode;
    5810                 :             :                 else
    5811                 :             :                 {
    5812                 :          10 :                     pg_unicode_to_server(unicode, (unsigned char *) cbuf);
    5813                 :          10 :                     appendStringInfoString(&str, cbuf);
    5814                 :             :                 }
    5815                 :             : 
    5816                 :          22 :                 instr += 4 + offset;
    5817                 :          22 :                 len -= 4 + offset;
    5818                 :             :             }
    5819   [ +  +  +  +  :          38 :             else if (len >= 8 && instr[1] == '+' && isxdigits_n(instr + 2, 6))
                   +  - ]
    5820                 :           9 :             {
    5821                 :             :                 char32_t    unicode;
    5822                 :             : 
    5823                 :          17 :                 unicode = hexval_n(instr + 2, 6);
    5824                 :             : 
    5825         [ +  + ]:          17 :                 if (!is_valid_unicode_codepoint(unicode))
    5826         [ +  - ]:           4 :                     ereport(ERROR,
    5827                 :             :                             errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    5828                 :             :                             errmsg("invalid Unicode code point: %04X", unicode));
    5829                 :             : 
    5830         [ +  + ]:          13 :                 if (pair_first)
    5831                 :             :                 {
    5832         [ -  + ]:           4 :                     if (is_utf16_surrogate_second(unicode))
    5833                 :             :                     {
    5834                 :           0 :                         unicode = surrogate_pair_to_codepoint(pair_first, unicode);
    5835                 :           0 :                         pair_first = 0;
    5836                 :             :                     }
    5837                 :             :                     else
    5838                 :           4 :                         goto invalid_pair;
    5839                 :             :                 }
    5840         [ -  + ]:           9 :                 else if (is_utf16_surrogate_second(unicode))
    5841                 :           0 :                     goto invalid_pair;
    5842                 :             : 
    5843         [ +  + ]:           9 :                 if (is_utf16_surrogate_first(unicode))
    5844                 :           4 :                     pair_first = unicode;
    5845                 :             :                 else
    5846                 :             :                 {
    5847                 :           5 :                     pg_unicode_to_server(unicode, (unsigned char *) cbuf);
    5848                 :           5 :                     appendStringInfoString(&str, cbuf);
    5849                 :             :                 }
    5850                 :             : 
    5851                 :           9 :                 instr += 8;
    5852                 :           9 :                 len -= 8;
    5853                 :             :             }
    5854   [ +  +  +  -  :          21 :             else if (len >= 10 && instr[1] == 'U' && isxdigits_n(instr + 2, 8))
                   +  - ]
    5855                 :           9 :             {
    5856                 :             :                 char32_t    unicode;
    5857                 :             : 
    5858                 :          17 :                 unicode = hexval_n(instr + 2, 8);
    5859                 :             : 
    5860         [ +  + ]:          17 :                 if (!is_valid_unicode_codepoint(unicode))
    5861         [ +  - ]:           4 :                     ereport(ERROR,
    5862                 :             :                             errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    5863                 :             :                             errmsg("invalid Unicode code point: %04X", unicode));
    5864                 :             : 
    5865         [ +  + ]:          13 :                 if (pair_first)
    5866                 :             :                 {
    5867         [ -  + ]:           4 :                     if (is_utf16_surrogate_second(unicode))
    5868                 :             :                     {
    5869                 :           0 :                         unicode = surrogate_pair_to_codepoint(pair_first, unicode);
    5870                 :           0 :                         pair_first = 0;
    5871                 :             :                     }
    5872                 :             :                     else
    5873                 :           4 :                         goto invalid_pair;
    5874                 :             :                 }
    5875         [ -  + ]:           9 :                 else if (is_utf16_surrogate_second(unicode))
    5876                 :           0 :                     goto invalid_pair;
    5877                 :             : 
    5878         [ +  + ]:           9 :                 if (is_utf16_surrogate_first(unicode))
    5879                 :           4 :                     pair_first = unicode;
    5880                 :             :                 else
    5881                 :             :                 {
    5882                 :           5 :                     pg_unicode_to_server(unicode, (unsigned char *) cbuf);
    5883                 :           5 :                     appendStringInfoString(&str, cbuf);
    5884                 :             :                 }
    5885                 :             : 
    5886                 :           9 :                 instr += 10;
    5887                 :           9 :                 len -= 10;
    5888                 :             :             }
    5889                 :             :             else
    5890         [ +  - ]:           4 :                 ereport(ERROR,
    5891                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    5892                 :             :                          errmsg("invalid Unicode escape"),
    5893                 :             :                          errhint("Unicode escapes must be \\XXXX, \\+XXXXXX, \\uXXXX, or \\UXXXXXXXX.")));
    5894                 :             :         }
    5895                 :             :         else
    5896                 :             :         {
    5897         [ -  + ]:         264 :             if (pair_first)
    5898                 :           0 :                 goto invalid_pair;
    5899                 :             : 
    5900                 :         264 :             appendStringInfoChar(&str, *instr++);
    5901                 :         264 :             len--;
    5902                 :             :         }
    5903                 :             :     }
    5904                 :             : 
    5905                 :             :     /* unfinished surrogate pair? */
    5906         [ +  + ]:          19 :     if (pair_first)
    5907                 :           4 :         goto invalid_pair;
    5908                 :             : 
    5909                 :          15 :     result = cstring_to_text_with_len(str.data, str.len);
    5910                 :          15 :     pfree(str.data);
    5911                 :             : 
    5912                 :          15 :     PG_RETURN_TEXT_P(result);
    5913                 :             : 
    5914                 :          20 : invalid_pair:
    5915         [ +  - ]:          20 :     ereport(ERROR,
    5916                 :             :             (errcode(ERRCODE_SYNTAX_ERROR),
    5917                 :             :              errmsg("invalid Unicode surrogate pair")));
    5918                 :             :     PG_RETURN_NULL();           /* keep compiler quiet */
    5919                 :             : }
        

Generated by: LCOV version 2.0-1