LCOV - code coverage report
Current view: top level - src/backend/utils/adt - varlena.c (source / functions) Hit Total Coverage
Test: PostgreSQL 19devel Lines: 1711 1895 90.3 %
Date: 2026-02-03 07:18:05 Functions: 132 143 92.3 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.16