LCOV - code coverage report
Current view: top level - src/backend/utils/adt - varbit.c (source / functions) Hit Total Coverage
Test: PostgreSQL 12beta1 Lines: 579 697 83.1 %
Date: 2019-06-16 15:06:48 Functions: 43 48 89.6 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * varbit.c
       4             :  *    Functions for the SQL datatypes BIT() and BIT VARYING().
       5             :  *
       6             :  * Code originally contributed by Adriaan Joubert.
       7             :  *
       8             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
       9             :  * Portions Copyright (c) 1994, Regents of the University of California
      10             :  *
      11             :  * IDENTIFICATION
      12             :  *    src/backend/utils/adt/varbit.c
      13             :  *
      14             :  *-------------------------------------------------------------------------
      15             :  */
      16             : 
      17             : #include "postgres.h"
      18             : 
      19             : #include "access/htup_details.h"
      20             : #include "common/int.h"
      21             : #include "libpq/pqformat.h"
      22             : #include "nodes/nodeFuncs.h"
      23             : #include "nodes/supportnodes.h"
      24             : #include "utils/array.h"
      25             : #include "utils/builtins.h"
      26             : #include "utils/varbit.h"
      27             : 
      28             : #define HEXDIG(z)    ((z)<10 ? ((z)+'0') : ((z)-10+'A'))
      29             : 
      30             : static VarBit *bit_catenate(VarBit *arg1, VarBit *arg2);
      31             : static VarBit *bitsubstring(VarBit *arg, int32 s, int32 l,
      32             :                             bool length_not_specified);
      33             : static VarBit *bit_overlay(VarBit *t1, VarBit *t2, int sp, int sl);
      34             : 
      35             : 
      36             : /*
      37             :  * common code for bittypmodin and varbittypmodin
      38             :  */
      39             : static int32
      40        1200 : anybit_typmodin(ArrayType *ta, const char *typename)
      41             : {
      42             :     int32       typmod;
      43             :     int32      *tl;
      44             :     int         n;
      45             : 
      46        1200 :     tl = ArrayGetIntegerTypmods(ta, &n);
      47             : 
      48             :     /*
      49             :      * we're not too tense about good error message here because grammar
      50             :      * shouldn't allow wrong number of modifiers for BIT
      51             :      */
      52        1200 :     if (n != 1)
      53           0 :         ereport(ERROR,
      54             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
      55             :                  errmsg("invalid type modifier")));
      56             : 
      57        1200 :     if (*tl < 1)
      58           0 :         ereport(ERROR,
      59             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
      60             :                  errmsg("length for type %s must be at least 1",
      61             :                         typename)));
      62        1200 :     if (*tl > (MaxAttrSize * BITS_PER_BYTE))
      63           0 :         ereport(ERROR,
      64             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
      65             :                  errmsg("length for type %s cannot exceed %d",
      66             :                         typename, MaxAttrSize * BITS_PER_BYTE)));
      67             : 
      68        1200 :     typmod = *tl;
      69             : 
      70        1200 :     return typmod;
      71             : }
      72             : 
      73             : /*
      74             :  * common code for bittypmodout and varbittypmodout
      75             :  */
      76             : static char *
      77         220 : anybit_typmodout(int32 typmod)
      78             : {
      79         220 :     char       *res = (char *) palloc(64);
      80             : 
      81         220 :     if (typmod >= 0)
      82         220 :         snprintf(res, 64, "(%d)", typmod);
      83             :     else
      84           0 :         *res = '\0';
      85             : 
      86         220 :     return res;
      87             : }
      88             : 
      89             : 
      90             : /*----------
      91             :  *  attypmod -- contains the length of the bit string in bits, or for
      92             :  *             varying bits the maximum length.
      93             :  *
      94             :  *  The data structure contains the following elements:
      95             :  *    header  -- length of the whole data structure (incl header)
      96             :  *               in bytes. (as with all varying length datatypes)
      97             :  *    data section -- private data section for the bits data structures
      98             :  *      bitlength -- length of the bit string in bits
      99             :  *      bitdata   -- bit string, most significant byte first
     100             :  *
     101             :  *  The length of the bitdata vector should always be exactly as many
     102             :  *  bytes as are needed for the given bitlength.  If the bitlength is
     103             :  *  not a multiple of 8, the extra low-order padding bits of the last
     104             :  *  byte must be zeroes.
     105             :  *----------
     106             :  */
     107             : 
     108             : /*
     109             :  * bit_in -
     110             :  *    converts a char string to the internal representation of a bitstring.
     111             :  *        The length is determined by the number of bits required plus
     112             :  *        VARHDRSZ bytes or from atttypmod.
     113             :  */
     114             : Datum
     115        4112 : bit_in(PG_FUNCTION_ARGS)
     116             : {
     117        4112 :     char       *input_string = PG_GETARG_CSTRING(0);
     118             : 
     119             : #ifdef NOT_USED
     120             :     Oid         typelem = PG_GETARG_OID(1);
     121             : #endif
     122        4112 :     int32       atttypmod = PG_GETARG_INT32(2);
     123             :     VarBit     *result;         /* The resulting bit string           */
     124             :     char       *sp;             /* pointer into the character string  */
     125             :     bits8      *r;              /* pointer into the result */
     126             :     int         len,            /* Length of the whole data structure */
     127             :                 bitlen,         /* Number of bits in the bit string   */
     128             :                 slen;           /* Length of the input string         */
     129             :     bool        bit_not_hex;    /* false = hex string  true = bit string */
     130             :     int         bc;
     131        4112 :     bits8       x = 0;
     132             : 
     133             :     /* Check that the first character is a b or an x */
     134        4112 :     if (input_string[0] == 'b' || input_string[0] == 'B')
     135             :     {
     136         488 :         bit_not_hex = true;
     137         488 :         sp = input_string + 1;
     138             :     }
     139        3624 :     else if (input_string[0] == 'x' || input_string[0] == 'X')
     140             :     {
     141        2246 :         bit_not_hex = false;
     142        2246 :         sp = input_string + 1;
     143             :     }
     144             :     else
     145             :     {
     146             :         /*
     147             :          * Otherwise it's binary.  This allows things like cast('1001' as bit)
     148             :          * to work transparently.
     149             :          */
     150        1378 :         bit_not_hex = true;
     151        1378 :         sp = input_string;
     152             :     }
     153             : 
     154             :     /*
     155             :      * Determine bitlength from input string.  MaxAllocSize ensures a regular
     156             :      * input is small enough, but we must check hex input.
     157             :      */
     158        4112 :     slen = strlen(sp);
     159        4112 :     if (bit_not_hex)
     160        1866 :         bitlen = slen;
     161             :     else
     162             :     {
     163        2246 :         if (slen > VARBITMAXLEN / 4)
     164           0 :             ereport(ERROR,
     165             :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     166             :                      errmsg("bit string length exceeds the maximum allowed (%d)",
     167             :                             VARBITMAXLEN)));
     168        2246 :         bitlen = slen * 4;
     169             :     }
     170             : 
     171             :     /*
     172             :      * Sometimes atttypmod is not supplied. If it is supplied we need to make
     173             :      * sure that the bitstring fits.
     174             :      */
     175        4112 :     if (atttypmod <= 0)
     176        2820 :         atttypmod = bitlen;
     177        1292 :     else if (bitlen != atttypmod)
     178           0 :         ereport(ERROR,
     179             :                 (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH),
     180             :                  errmsg("bit string length %d does not match type bit(%d)",
     181             :                         bitlen, atttypmod)));
     182             : 
     183        4112 :     len = VARBITTOTALLEN(atttypmod);
     184             :     /* set to 0 so that *r is always initialised and string is zero-padded */
     185        4112 :     result = (VarBit *) palloc0(len);
     186        4112 :     SET_VARSIZE(result, len);
     187        4112 :     VARBITLEN(result) = atttypmod;
     188             : 
     189        4112 :     r = VARBITS(result);
     190        4112 :     if (bit_not_hex)
     191             :     {
     192             :         /* Parse the bit representation of the string */
     193             :         /* We know it fits, as bitlen was compared to atttypmod */
     194        1866 :         x = HIGHBIT;
     195       47934 :         for (; *sp; sp++)
     196             :         {
     197       46068 :             if (*sp == '1')
     198       22920 :                 *r |= x;
     199       23148 :             else if (*sp != '0')
     200           0 :                 ereport(ERROR,
     201             :                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     202             :                          errmsg("\"%c\" is not a valid binary digit",
     203             :                                 *sp)));
     204             : 
     205       46068 :             x >>= 1;
     206       46068 :             if (x == 0)
     207             :             {
     208        5396 :                 x = HIGHBIT;
     209        5396 :                 r++;
     210             :             }
     211             :         }
     212             :     }
     213             :     else
     214             :     {
     215             :         /* Parse the hex representation of the string */
     216       26774 :         for (bc = 0; *sp; sp++)
     217             :         {
     218       24528 :             if (*sp >= '0' && *sp <= '9')
     219       16864 :                 x = (bits8) (*sp - '0');
     220        7664 :             else if (*sp >= 'A' && *sp <= 'F')
     221          92 :                 x = (bits8) (*sp - 'A') + 10;
     222        7572 :             else if (*sp >= 'a' && *sp <= 'f')
     223        7572 :                 x = (bits8) (*sp - 'a') + 10;
     224             :             else
     225           0 :                 ereport(ERROR,
     226             :                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     227             :                          errmsg("\"%c\" is not a valid hexadecimal digit",
     228             :                                 *sp)));
     229             : 
     230       24528 :             if (bc)
     231             :             {
     232       12200 :                 *r++ |= x;
     233       12200 :                 bc = 0;
     234             :             }
     235             :             else
     236             :             {
     237       12328 :                 *r = x << 4;
     238       12328 :                 bc = 1;
     239             :             }
     240             :         }
     241             :     }
     242             : 
     243        4112 :     PG_RETURN_VARBIT_P(result);
     244             : }
     245             : 
     246             : 
     247             : Datum
     248        1636 : bit_out(PG_FUNCTION_ARGS)
     249             : {
     250             : #if 1
     251             :     /* same as varbit output */
     252        1636 :     return varbit_out(fcinfo);
     253             : #else
     254             : 
     255             :     /*
     256             :      * This is how one would print a hex string, in case someone wants to
     257             :      * write a formatting function.
     258             :      */
     259             :     VarBit     *s = PG_GETARG_VARBIT_P(0);
     260             :     char       *result,
     261             :                *r;
     262             :     bits8      *sp;
     263             :     int         i,
     264             :                 len,
     265             :                 bitlen;
     266             : 
     267             :     bitlen = VARBITLEN(s);
     268             :     len = (bitlen + 3) / 4;
     269             :     result = (char *) palloc(len + 2);
     270             :     sp = VARBITS(s);
     271             :     r = result;
     272             :     *r++ = 'X';
     273             :     /* we cheat by knowing that we store full bytes zero padded */
     274             :     for (i = 0; i < len; i += 2, sp++)
     275             :     {
     276             :         *r++ = HEXDIG((*sp) >> 4);
     277             :         *r++ = HEXDIG((*sp) & 0xF);
     278             :     }
     279             : 
     280             :     /*
     281             :      * Go back one step if we printed a hex number that was not part of the
     282             :      * bitstring anymore
     283             :      */
     284             :     if (i > len)
     285             :         r--;
     286             :     *r = '\0';
     287             : 
     288             :     PG_RETURN_CSTRING(result);
     289             : #endif
     290             : }
     291             : 
     292             : /*
     293             :  *      bit_recv            - converts external binary format to bit
     294             :  */
     295             : Datum
     296           0 : bit_recv(PG_FUNCTION_ARGS)
     297             : {
     298           0 :     StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
     299             : 
     300             : #ifdef NOT_USED
     301             :     Oid         typelem = PG_GETARG_OID(1);
     302             : #endif
     303           0 :     int32       atttypmod = PG_GETARG_INT32(2);
     304             :     VarBit     *result;
     305             :     int         len,
     306             :                 bitlen;
     307             :     int         ipad;
     308             :     bits8       mask;
     309             : 
     310           0 :     bitlen = pq_getmsgint(buf, sizeof(int32));
     311           0 :     if (bitlen < 0 || bitlen > VARBITMAXLEN)
     312           0 :         ereport(ERROR,
     313             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
     314             :                  errmsg("invalid length in external bit string")));
     315             : 
     316             :     /*
     317             :      * Sometimes atttypmod is not supplied. If it is supplied we need to make
     318             :      * sure that the bitstring fits.
     319             :      */
     320           0 :     if (atttypmod > 0 && bitlen != atttypmod)
     321           0 :         ereport(ERROR,
     322             :                 (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH),
     323             :                  errmsg("bit string length %d does not match type bit(%d)",
     324             :                         bitlen, atttypmod)));
     325             : 
     326           0 :     len = VARBITTOTALLEN(bitlen);
     327           0 :     result = (VarBit *) palloc(len);
     328           0 :     SET_VARSIZE(result, len);
     329           0 :     VARBITLEN(result) = bitlen;
     330             : 
     331           0 :     pq_copymsgbytes(buf, (char *) VARBITS(result), VARBITBYTES(result));
     332             : 
     333             :     /* Make sure last byte is zero-padded if needed */
     334           0 :     ipad = VARBITPAD(result);
     335           0 :     if (ipad > 0)
     336             :     {
     337           0 :         mask = BITMASK << ipad;
     338           0 :         *(VARBITS(result) + VARBITBYTES(result) - 1) &= mask;
     339             :     }
     340             : 
     341           0 :     PG_RETURN_VARBIT_P(result);
     342             : }
     343             : 
     344             : /*
     345             :  *      bit_send            - converts bit to binary format
     346             :  */
     347             : Datum
     348           0 : bit_send(PG_FUNCTION_ARGS)
     349             : {
     350             :     /* Exactly the same as varbit_send, so share code */
     351           0 :     return varbit_send(fcinfo);
     352             : }
     353             : 
     354             : /*
     355             :  * bit()
     356             :  * Converts a bit() type to a specific internal length.
     357             :  * len is the bitlength specified in the column definition.
     358             :  *
     359             :  * If doing implicit cast, raise error when source data is wrong length.
     360             :  * If doing explicit cast, silently truncate or zero-pad to specified length.
     361             :  */
     362             : Datum
     363         240 : bit(PG_FUNCTION_ARGS)
     364             : {
     365         240 :     VarBit     *arg = PG_GETARG_VARBIT_P(0);
     366         240 :     int32       len = PG_GETARG_INT32(1);
     367         240 :     bool        isExplicit = PG_GETARG_BOOL(2);
     368             :     VarBit     *result;
     369             :     int         rlen;
     370             :     int         ipad;
     371             :     bits8       mask;
     372             : 
     373             :     /* No work if typmod is invalid or supplied data matches it already */
     374         240 :     if (len <= 0 || len > VARBITMAXLEN || len == VARBITLEN(arg))
     375         220 :         PG_RETURN_VARBIT_P(arg);
     376             : 
     377          20 :     if (!isExplicit)
     378           8 :         ereport(ERROR,
     379             :                 (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH),
     380             :                  errmsg("bit string length %d does not match type bit(%d)",
     381             :                         VARBITLEN(arg), len)));
     382             : 
     383          12 :     rlen = VARBITTOTALLEN(len);
     384             :     /* set to 0 so that string is zero-padded */
     385          12 :     result = (VarBit *) palloc0(rlen);
     386          12 :     SET_VARSIZE(result, rlen);
     387          12 :     VARBITLEN(result) = len;
     388             : 
     389          12 :     memcpy(VARBITS(result), VARBITS(arg),
     390          12 :            Min(VARBITBYTES(result), VARBITBYTES(arg)));
     391             : 
     392             :     /*
     393             :      * Make sure last byte is zero-padded if needed.  This is useless but safe
     394             :      * if source data was shorter than target length (we assume the last byte
     395             :      * of the source data was itself correctly zero-padded).
     396             :      */
     397          12 :     ipad = VARBITPAD(result);
     398          12 :     if (ipad > 0)
     399             :     {
     400          12 :         mask = BITMASK << ipad;
     401          12 :         *(VARBITS(result) + VARBITBYTES(result) - 1) &= mask;
     402             :     }
     403             : 
     404          12 :     PG_RETURN_VARBIT_P(result);
     405             : }
     406             : 
     407             : Datum
     408        1032 : bittypmodin(PG_FUNCTION_ARGS)
     409             : {
     410        1032 :     ArrayType  *ta = PG_GETARG_ARRAYTYPE_P(0);
     411             : 
     412        1032 :     PG_RETURN_INT32(anybit_typmodin(ta, "bit"));
     413             : }
     414             : 
     415             : Datum
     416         134 : bittypmodout(PG_FUNCTION_ARGS)
     417             : {
     418         134 :     int32       typmod = PG_GETARG_INT32(0);
     419             : 
     420         134 :     PG_RETURN_CSTRING(anybit_typmodout(typmod));
     421             : }
     422             : 
     423             : 
     424             : /*
     425             :  * varbit_in -
     426             :  *    converts a string to the internal representation of a bitstring.
     427             :  *      This is the same as bit_in except that atttypmod is taken as
     428             :  *      the maximum length, not the exact length to force the bitstring to.
     429             :  */
     430             : Datum
     431        1428 : varbit_in(PG_FUNCTION_ARGS)
     432             : {
     433        1428 :     char       *input_string = PG_GETARG_CSTRING(0);
     434             : 
     435             : #ifdef NOT_USED
     436             :     Oid         typelem = PG_GETARG_OID(1);
     437             : #endif
     438        1428 :     int32       atttypmod = PG_GETARG_INT32(2);
     439             :     VarBit     *result;         /* The resulting bit string           */
     440             :     char       *sp;             /* pointer into the character string  */
     441             :     bits8      *r;              /* pointer into the result */
     442             :     int         len,            /* Length of the whole data structure */
     443             :                 bitlen,         /* Number of bits in the bit string   */
     444             :                 slen;           /* Length of the input string         */
     445             :     bool        bit_not_hex;    /* false = hex string  true = bit string */
     446             :     int         bc;
     447        1428 :     bits8       x = 0;
     448             : 
     449             :     /* Check that the first character is a b or an x */
     450        1428 :     if (input_string[0] == 'b' || input_string[0] == 'B')
     451             :     {
     452           0 :         bit_not_hex = true;
     453           0 :         sp = input_string + 1;
     454             :     }
     455        1428 :     else if (input_string[0] == 'x' || input_string[0] == 'X')
     456             :     {
     457          80 :         bit_not_hex = false;
     458          80 :         sp = input_string + 1;
     459             :     }
     460             :     else
     461             :     {
     462        1348 :         bit_not_hex = true;
     463        1348 :         sp = input_string;
     464             :     }
     465             : 
     466             :     /*
     467             :      * Determine bitlength from input string.  MaxAllocSize ensures a regular
     468             :      * input is small enough, but we must check hex input.
     469             :      */
     470        1428 :     slen = strlen(sp);
     471        1428 :     if (bit_not_hex)
     472        1348 :         bitlen = slen;
     473             :     else
     474             :     {
     475          80 :         if (slen > VARBITMAXLEN / 4)
     476           0 :             ereport(ERROR,
     477             :                     (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     478             :                      errmsg("bit string length exceeds the maximum allowed (%d)",
     479             :                             VARBITMAXLEN)));
     480          80 :         bitlen = slen * 4;
     481             :     }
     482             : 
     483             :     /*
     484             :      * Sometimes atttypmod is not supplied. If it is supplied we need to make
     485             :      * sure that the bitstring fits.
     486             :      */
     487        1428 :     if (atttypmod <= 0)
     488        1348 :         atttypmod = bitlen;
     489          80 :     else if (bitlen > atttypmod)
     490           0 :         ereport(ERROR,
     491             :                 (errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
     492             :                  errmsg("bit string too long for type bit varying(%d)",
     493             :                         atttypmod)));
     494             : 
     495        1428 :     len = VARBITTOTALLEN(bitlen);
     496             :     /* set to 0 so that *r is always initialised and string is zero-padded */
     497        1428 :     result = (VarBit *) palloc0(len);
     498        1428 :     SET_VARSIZE(result, len);
     499        1428 :     VARBITLEN(result) = Min(bitlen, atttypmod);
     500             : 
     501        1428 :     r = VARBITS(result);
     502        1428 :     if (bit_not_hex)
     503             :     {
     504             :         /* Parse the bit representation of the string */
     505             :         /* We know it fits, as bitlen was compared to atttypmod */
     506        1348 :         x = HIGHBIT;
     507       64998 :         for (; *sp; sp++)
     508             :         {
     509       63650 :             if (*sp == '1')
     510       31710 :                 *r |= x;
     511       31940 :             else if (*sp != '0')
     512           0 :                 ereport(ERROR,
     513             :                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     514             :                          errmsg("\"%c\" is not a valid binary digit",
     515             :                                 *sp)));
     516             : 
     517       63650 :             x >>= 1;
     518       63650 :             if (x == 0)
     519             :             {
     520        7402 :                 x = HIGHBIT;
     521        7402 :                 r++;
     522             :             }
     523             :         }
     524             :     }
     525             :     else
     526             :     {
     527             :         /* Parse the hex representation of the string */
     528         320 :         for (bc = 0; *sp; sp++)
     529             :         {
     530         240 :             if (*sp >= '0' && *sp <= '9')
     531         172 :                 x = (bits8) (*sp - '0');
     532          68 :             else if (*sp >= 'A' && *sp <= 'F')
     533          68 :                 x = (bits8) (*sp - 'A') + 10;
     534           0 :             else if (*sp >= 'a' && *sp <= 'f')
     535           0 :                 x = (bits8) (*sp - 'a') + 10;
     536             :             else
     537           0 :                 ereport(ERROR,
     538             :                         (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
     539             :                          errmsg("\"%c\" is not a valid hexadecimal digit",
     540             :                                 *sp)));
     541             : 
     542         240 :             if (bc)
     543             :             {
     544         120 :                 *r++ |= x;
     545         120 :                 bc = 0;
     546             :             }
     547             :             else
     548             :             {
     549         120 :                 *r = x << 4;
     550         120 :                 bc = 1;
     551             :             }
     552             :         }
     553             :     }
     554             : 
     555        1428 :     PG_RETURN_VARBIT_P(result);
     556             : }
     557             : 
     558             : /*
     559             :  * varbit_out -
     560             :  *    Prints the string as bits to preserve length accurately
     561             :  *
     562             :  * XXX varbit_recv() and hex input to varbit_in() can load a value that this
     563             :  * cannot emit.  Consider using hex output for such values.
     564             :  */
     565             : Datum
     566        2624 : varbit_out(PG_FUNCTION_ARGS)
     567             : {
     568        2624 :     VarBit     *s = PG_GETARG_VARBIT_P(0);
     569             :     char       *result,
     570             :                *r;
     571             :     bits8      *sp;
     572             :     bits8       x;
     573             :     int         i,
     574             :                 k,
     575             :                 len;
     576             : 
     577        2624 :     len = VARBITLEN(s);
     578        2624 :     result = (char *) palloc(len + 1);
     579        2624 :     sp = VARBITS(s);
     580        2624 :     r = result;
     581        6148 :     for (i = 0; i <= len - BITS_PER_BYTE; i += BITS_PER_BYTE, sp++)
     582             :     {
     583             :         /* print full bytes */
     584        3524 :         x = *sp;
     585       31716 :         for (k = 0; k < BITS_PER_BYTE; k++)
     586             :         {
     587       28192 :             *r++ = IS_HIGHBIT_SET(x) ? '1' : '0';
     588       28192 :             x <<= 1;
     589             :         }
     590             :     }
     591        2624 :     if (i < len)
     592             :     {
     593             :         /* print the last partial byte */
     594        1056 :         x = *sp;
     595        4172 :         for (k = i; k < len; k++)
     596             :         {
     597        3116 :             *r++ = IS_HIGHBIT_SET(x) ? '1' : '0';
     598        3116 :             x <<= 1;
     599             :         }
     600             :     }
     601        2624 :     *r = '\0';
     602             : 
     603        2624 :     PG_RETURN_CSTRING(result);
     604             : }
     605             : 
     606             : /*
     607             :  *      varbit_recv         - converts external binary format to varbit
     608             :  *
     609             :  * External format is the bitlen as an int32, then the byte array.
     610             :  */
     611             : Datum
     612           0 : varbit_recv(PG_FUNCTION_ARGS)
     613             : {
     614           0 :     StringInfo  buf = (StringInfo) PG_GETARG_POINTER(0);
     615             : 
     616             : #ifdef NOT_USED
     617             :     Oid         typelem = PG_GETARG_OID(1);
     618             : #endif
     619           0 :     int32       atttypmod = PG_GETARG_INT32(2);
     620             :     VarBit     *result;
     621             :     int         len,
     622             :                 bitlen;
     623             :     int         ipad;
     624             :     bits8       mask;
     625             : 
     626           0 :     bitlen = pq_getmsgint(buf, sizeof(int32));
     627           0 :     if (bitlen < 0 || bitlen > VARBITMAXLEN)
     628           0 :         ereport(ERROR,
     629             :                 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
     630             :                  errmsg("invalid length in external bit string")));
     631             : 
     632             :     /*
     633             :      * Sometimes atttypmod is not supplied. If it is supplied we need to make
     634             :      * sure that the bitstring fits.
     635             :      */
     636           0 :     if (atttypmod > 0 && bitlen > atttypmod)
     637           0 :         ereport(ERROR,
     638             :                 (errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
     639             :                  errmsg("bit string too long for type bit varying(%d)",
     640             :                         atttypmod)));
     641             : 
     642           0 :     len = VARBITTOTALLEN(bitlen);
     643           0 :     result = (VarBit *) palloc(len);
     644           0 :     SET_VARSIZE(result, len);
     645           0 :     VARBITLEN(result) = bitlen;
     646             : 
     647           0 :     pq_copymsgbytes(buf, (char *) VARBITS(result), VARBITBYTES(result));
     648             : 
     649             :     /* Make sure last byte is zero-padded if needed */
     650           0 :     ipad = VARBITPAD(result);
     651           0 :     if (ipad > 0)
     652             :     {
     653           0 :         mask = BITMASK << ipad;
     654           0 :         *(VARBITS(result) + VARBITBYTES(result) - 1) &= mask;
     655             :     }
     656             : 
     657           0 :     PG_RETURN_VARBIT_P(result);
     658             : }
     659             : 
     660             : /*
     661             :  *      varbit_send         - converts varbit to binary format
     662             :  */
     663             : Datum
     664           0 : varbit_send(PG_FUNCTION_ARGS)
     665             : {
     666           0 :     VarBit     *s = PG_GETARG_VARBIT_P(0);
     667             :     StringInfoData buf;
     668             : 
     669           0 :     pq_begintypsend(&buf);
     670           0 :     pq_sendint32(&buf, VARBITLEN(s));
     671           0 :     pq_sendbytes(&buf, (char *) VARBITS(s), VARBITBYTES(s));
     672           0 :     PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
     673             : }
     674             : 
     675             : /*
     676             :  * varbit_support()
     677             :  *
     678             :  * Planner support function for the varbit() length coercion function.
     679             :  *
     680             :  * Currently, the only interesting thing we can do is flatten calls that set
     681             :  * the new maximum length >= the previous maximum length.  We can ignore the
     682             :  * isExplicit argument, since that only affects truncation cases.
     683             :  */
     684             : Datum
     685          80 : varbit_support(PG_FUNCTION_ARGS)
     686             : {
     687          80 :     Node       *rawreq = (Node *) PG_GETARG_POINTER(0);
     688          80 :     Node       *ret = NULL;
     689             : 
     690          80 :     if (IsA(rawreq, SupportRequestSimplify))
     691             :     {
     692          40 :         SupportRequestSimplify *req = (SupportRequestSimplify *) rawreq;
     693          40 :         FuncExpr   *expr = req->fcall;
     694             :         Node       *typmod;
     695             : 
     696             :         Assert(list_length(expr->args) >= 2);
     697             : 
     698          40 :         typmod = (Node *) lsecond(expr->args);
     699             : 
     700          40 :         if (IsA(typmod, Const) &&!((Const *) typmod)->constisnull)
     701             :         {
     702          40 :             Node       *source = (Node *) linitial(expr->args);
     703          40 :             int32       new_typmod = DatumGetInt32(((Const *) typmod)->constvalue);
     704          40 :             int32       old_max = exprTypmod(source);
     705          40 :             int32       new_max = new_typmod;
     706             : 
     707             :             /* Note: varbit() treats typmod 0 as invalid, so we do too */
     708          40 :             if (new_max <= 0 || (old_max > 0 && old_max <= new_max))
     709           0 :                 ret = relabel_to_typmod(source, new_typmod);
     710             :         }
     711             :     }
     712             : 
     713          80 :     PG_RETURN_POINTER(ret);
     714             : }
     715             : 
     716             : /*
     717             :  * varbit()
     718             :  * Converts a varbit() type to a specific internal length.
     719             :  * len is the maximum bitlength specified in the column definition.
     720             :  *
     721             :  * If doing implicit cast, raise error when source data is too long.
     722             :  * If doing explicit cast, silently truncate to max length.
     723             :  */
     724             : Datum
     725         652 : varbit(PG_FUNCTION_ARGS)
     726             : {
     727         652 :     VarBit     *arg = PG_GETARG_VARBIT_P(0);
     728         652 :     int32       len = PG_GETARG_INT32(1);
     729         652 :     bool        isExplicit = PG_GETARG_BOOL(2);
     730             :     VarBit     *result;
     731             :     int         rlen;
     732             :     int         ipad;
     733             :     bits8       mask;
     734             : 
     735             :     /* No work if typmod is invalid or supplied data matches it already */
     736         652 :     if (len <= 0 || len >= VARBITLEN(arg))
     737         648 :         PG_RETURN_VARBIT_P(arg);
     738             : 
     739           4 :     if (!isExplicit)
     740           4 :         ereport(ERROR,
     741             :                 (errcode(ERRCODE_STRING_DATA_RIGHT_TRUNCATION),
     742             :                  errmsg("bit string too long for type bit varying(%d)",
     743             :                         len)));
     744             : 
     745           0 :     rlen = VARBITTOTALLEN(len);
     746           0 :     result = (VarBit *) palloc(rlen);
     747           0 :     SET_VARSIZE(result, rlen);
     748           0 :     VARBITLEN(result) = len;
     749             : 
     750           0 :     memcpy(VARBITS(result), VARBITS(arg), VARBITBYTES(result));
     751             : 
     752             :     /* Make sure last byte is zero-padded if needed */
     753           0 :     ipad = VARBITPAD(result);
     754           0 :     if (ipad > 0)
     755             :     {
     756           0 :         mask = BITMASK << ipad;
     757           0 :         *(VARBITS(result) + VARBITBYTES(result) - 1) &= mask;
     758             :     }
     759             : 
     760           0 :     PG_RETURN_VARBIT_P(result);
     761             : }
     762             : 
     763             : Datum
     764         168 : varbittypmodin(PG_FUNCTION_ARGS)
     765             : {
     766         168 :     ArrayType  *ta = PG_GETARG_ARRAYTYPE_P(0);
     767             : 
     768         168 :     PG_RETURN_INT32(anybit_typmodin(ta, "varbit"));
     769             : }
     770             : 
     771             : Datum
     772          86 : varbittypmodout(PG_FUNCTION_ARGS)
     773             : {
     774          86 :     int32       typmod = PG_GETARG_INT32(0);
     775             : 
     776          86 :     PG_RETURN_CSTRING(anybit_typmodout(typmod));
     777             : }
     778             : 
     779             : 
     780             : /*
     781             :  * Comparison operators
     782             :  *
     783             :  * We only need one set of comparison operators for bitstrings, as the lengths
     784             :  * are stored in the same way for zero-padded and varying bit strings.
     785             :  *
     786             :  * Note that the standard is not unambiguous about the comparison between
     787             :  * zero-padded bit strings and varying bitstrings. If the same value is written
     788             :  * into a zero padded bitstring as into a varying bitstring, but the zero
     789             :  * padded bitstring has greater length, it will be bigger.
     790             :  *
     791             :  * Zeros from the beginning of a bitstring cannot simply be ignored, as they
     792             :  * may be part of a bit string and may be significant.
     793             :  *
     794             :  * Note: btree indexes need these routines not to leak memory; therefore,
     795             :  * be careful to free working copies of toasted datums.  Most places don't
     796             :  * need to be so careful.
     797             :  */
     798             : 
     799             : /*
     800             :  * bit_cmp
     801             :  *
     802             :  * Compares two bitstrings and returns <0, 0, >0 depending on whether the first
     803             :  * string is smaller, equal, or bigger than the second. All bits are considered
     804             :  * and additional zero bits may make one string smaller/larger than the other,
     805             :  * even if their zero-padded values would be the same.
     806             :  */
     807             : static int32
     808       48952 : bit_cmp(VarBit *arg1, VarBit *arg2)
     809             : {
     810             :     int         bitlen1,
     811             :                 bytelen1,
     812             :                 bitlen2,
     813             :                 bytelen2;
     814             :     int32       cmp;
     815             : 
     816       48952 :     bytelen1 = VARBITBYTES(arg1);
     817       48952 :     bytelen2 = VARBITBYTES(arg2);
     818             : 
     819       48952 :     cmp = memcmp(VARBITS(arg1), VARBITS(arg2), Min(bytelen1, bytelen2));
     820       48952 :     if (cmp == 0)
     821             :     {
     822        4278 :         bitlen1 = VARBITLEN(arg1);
     823        4278 :         bitlen2 = VARBITLEN(arg2);
     824        4278 :         if (bitlen1 != bitlen2)
     825          36 :             cmp = (bitlen1 < bitlen2) ? -1 : 1;
     826             :     }
     827       48952 :     return cmp;
     828             : }
     829             : 
     830             : Datum
     831        4476 : biteq(PG_FUNCTION_ARGS)
     832             : {
     833        4476 :     VarBit     *arg1 = PG_GETARG_VARBIT_P(0);
     834        4476 :     VarBit     *arg2 = PG_GETARG_VARBIT_P(1);
     835             :     bool        result;
     836             :     int         bitlen1,
     837             :                 bitlen2;
     838             : 
     839        4476 :     bitlen1 = VARBITLEN(arg1);
     840        4476 :     bitlen2 = VARBITLEN(arg2);
     841             : 
     842             :     /* fast path for different-length inputs */
     843        4476 :     if (bitlen1 != bitlen2)
     844        1502 :         result = false;
     845             :     else
     846        2974 :         result = (bit_cmp(arg1, arg2) == 0);
     847             : 
     848        4476 :     PG_FREE_IF_COPY(arg1, 0);
     849        4476 :     PG_FREE_IF_COPY(arg2, 1);
     850             : 
     851        4476 :     PG_RETURN_BOOL(result);
     852             : }
     853             : 
     854             : Datum
     855         612 : bitne(PG_FUNCTION_ARGS)
     856             : {
     857         612 :     VarBit     *arg1 = PG_GETARG_VARBIT_P(0);
     858         612 :     VarBit     *arg2 = PG_GETARG_VARBIT_P(1);
     859             :     bool        result;
     860             :     int         bitlen1,
     861             :                 bitlen2;
     862             : 
     863         612 :     bitlen1 = VARBITLEN(arg1);
     864         612 :     bitlen2 = VARBITLEN(arg2);
     865             : 
     866             :     /* fast path for different-length inputs */
     867         612 :     if (bitlen1 != bitlen2)
     868           0 :         result = true;
     869             :     else
     870         612 :         result = (bit_cmp(arg1, arg2) != 0);
     871             : 
     872         612 :     PG_FREE_IF_COPY(arg1, 0);
     873         612 :     PG_FREE_IF_COPY(arg2, 1);
     874             : 
     875         612 :     PG_RETURN_BOOL(result);
     876             : }
     877             : 
     878             : Datum
     879        7812 : bitlt(PG_FUNCTION_ARGS)
     880             : {
     881        7812 :     VarBit     *arg1 = PG_GETARG_VARBIT_P(0);
     882        7812 :     VarBit     *arg2 = PG_GETARG_VARBIT_P(1);
     883             :     bool        result;
     884             : 
     885        7812 :     result = (bit_cmp(arg1, arg2) < 0);
     886             : 
     887        7812 :     PG_FREE_IF_COPY(arg1, 0);
     888        7812 :     PG_FREE_IF_COPY(arg2, 1);
     889             : 
     890        7812 :     PG_RETURN_BOOL(result);
     891             : }
     892             : 
     893             : Datum
     894        6916 : bitle(PG_FUNCTION_ARGS)
     895             : {
     896        6916 :     VarBit     *arg1 = PG_GETARG_VARBIT_P(0);
     897        6916 :     VarBit     *arg2 = PG_GETARG_VARBIT_P(1);
     898             :     bool        result;
     899             : 
     900        6916 :     result = (bit_cmp(arg1, arg2) <= 0);
     901             : 
     902        6916 :     PG_FREE_IF_COPY(arg1, 0);
     903        6916 :     PG_FREE_IF_COPY(arg2, 1);
     904             : 
     905        6916 :     PG_RETURN_BOOL(result);
     906             : }
     907             : 
     908             : Datum
     909        8336 : bitgt(PG_FUNCTION_ARGS)
     910             : {
     911        8336 :     VarBit     *arg1 = PG_GETARG_VARBIT_P(0);
     912        8336 :     VarBit     *arg2 = PG_GETARG_VARBIT_P(1);
     913             :     bool        result;
     914             : 
     915        8336 :     result = (bit_cmp(arg1, arg2) > 0);
     916             : 
     917        8336 :     PG_FREE_IF_COPY(arg1, 0);
     918        8336 :     PG_FREE_IF_COPY(arg2, 1);
     919             : 
     920        8336 :     PG_RETURN_BOOL(result);
     921             : }
     922             : 
     923             : Datum
     924        6944 : bitge(PG_FUNCTION_ARGS)
     925             : {
     926        6944 :     VarBit     *arg1 = PG_GETARG_VARBIT_P(0);
     927        6944 :     VarBit     *arg2 = PG_GETARG_VARBIT_P(1);
     928             :     bool        result;
     929             : 
     930        6944 :     result = (bit_cmp(arg1, arg2) >= 0);
     931             : 
     932        6944 :     PG_FREE_IF_COPY(arg1, 0);
     933        6944 :     PG_FREE_IF_COPY(arg2, 1);
     934             : 
     935        6944 :     PG_RETURN_BOOL(result);
     936             : }
     937             : 
     938             : Datum
     939       15358 : bitcmp(PG_FUNCTION_ARGS)
     940             : {
     941       15358 :     VarBit     *arg1 = PG_GETARG_VARBIT_P(0);
     942       15358 :     VarBit     *arg2 = PG_GETARG_VARBIT_P(1);
     943             :     int32       result;
     944             : 
     945       15358 :     result = bit_cmp(arg1, arg2);
     946             : 
     947       15358 :     PG_FREE_IF_COPY(arg1, 0);
     948       15358 :     PG_FREE_IF_COPY(arg2, 1);
     949             : 
     950       15358 :     PG_RETURN_INT32(result);
     951             : }
     952             : 
     953             : /*
     954             :  * bitcat
     955             :  * Concatenation of bit strings
     956             :  */
     957             : Datum
     958         108 : bitcat(PG_FUNCTION_ARGS)
     959             : {
     960         108 :     VarBit     *arg1 = PG_GETARG_VARBIT_P(0);
     961         108 :     VarBit     *arg2 = PG_GETARG_VARBIT_P(1);
     962             : 
     963         108 :     PG_RETURN_VARBIT_P(bit_catenate(arg1, arg2));
     964             : }
     965             : 
     966             : static VarBit *
     967         140 : bit_catenate(VarBit *arg1, VarBit *arg2)
     968             : {
     969             :     VarBit     *result;
     970             :     int         bitlen1,
     971             :                 bitlen2,
     972             :                 bytelen,
     973             :                 bit1pad,
     974             :                 bit2shift;
     975             :     bits8      *pr,
     976             :                *pa;
     977             : 
     978         140 :     bitlen1 = VARBITLEN(arg1);
     979         140 :     bitlen2 = VARBITLEN(arg2);
     980             : 
     981         140 :     if (bitlen1 > VARBITMAXLEN - bitlen2)
     982           0 :         ereport(ERROR,
     983             :                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
     984             :                  errmsg("bit string length exceeds the maximum allowed (%d)",
     985             :                         VARBITMAXLEN)));
     986         140 :     bytelen = VARBITTOTALLEN(bitlen1 + bitlen2);
     987             : 
     988         140 :     result = (VarBit *) palloc(bytelen);
     989         140 :     SET_VARSIZE(result, bytelen);
     990         140 :     VARBITLEN(result) = bitlen1 + bitlen2;
     991             : 
     992             :     /* Copy the first bitstring in */
     993         140 :     memcpy(VARBITS(result), VARBITS(arg1), VARBITBYTES(arg1));
     994             : 
     995             :     /* Copy the second bit string */
     996         140 :     bit1pad = VARBITPAD(arg1);
     997         140 :     if (bit1pad == 0)
     998             :     {
     999          24 :         memcpy(VARBITS(result) + VARBITBYTES(arg1), VARBITS(arg2),
    1000          24 :                VARBITBYTES(arg2));
    1001             :     }
    1002         116 :     else if (bitlen2 > 0)
    1003             :     {
    1004             :         /* We need to shift all the bits to fit */
    1005         108 :         bit2shift = BITS_PER_BYTE - bit1pad;
    1006         108 :         pr = VARBITS(result) + VARBITBYTES(arg1) - 1;
    1007         252 :         for (pa = VARBITS(arg2); pa < VARBITEND(arg2); pa++)
    1008             :         {
    1009         144 :             *pr |= ((*pa >> bit2shift) & BITMASK);
    1010         144 :             pr++;
    1011         144 :             if (pr < VARBITEND(result))
    1012          92 :                 *pr = (*pa << bit1pad) & BITMASK;
    1013             :         }
    1014             :     }
    1015             : 
    1016         140 :     return result;
    1017             : }
    1018             : 
    1019             : /*
    1020             :  * bitsubstr
    1021             :  * retrieve a substring from the bit string.
    1022             :  * Note, s is 1-based.
    1023             :  * SQL draft 6.10 9)
    1024             :  */
    1025             : Datum
    1026          56 : bitsubstr(PG_FUNCTION_ARGS)
    1027             : {
    1028          56 :     PG_RETURN_VARBIT_P(bitsubstring(PG_GETARG_VARBIT_P(0),
    1029             :                                     PG_GETARG_INT32(1),
    1030             :                                     PG_GETARG_INT32(2),
    1031             :                                     false));
    1032             : }
    1033             : 
    1034             : Datum
    1035          28 : bitsubstr_no_len(PG_FUNCTION_ARGS)
    1036             : {
    1037          28 :     PG_RETURN_VARBIT_P(bitsubstring(PG_GETARG_VARBIT_P(0),
    1038             :                                     PG_GETARG_INT32(1),
    1039             :                                     -1, true));
    1040             : }
    1041             : 
    1042             : static VarBit *
    1043         116 : bitsubstring(VarBit *arg, int32 s, int32 l, bool length_not_specified)
    1044             : {
    1045             :     VarBit     *result;
    1046             :     int         bitlen,
    1047             :                 rbitlen,
    1048             :                 len,
    1049         116 :                 ipad = 0,
    1050             :                 ishift,
    1051             :                 i;
    1052             :     int         e,
    1053             :                 s1,
    1054             :                 e1;
    1055             :     bits8       mask,
    1056             :                *r,
    1057             :                *ps;
    1058             : 
    1059         116 :     bitlen = VARBITLEN(arg);
    1060         116 :     s1 = Max(s, 1);
    1061             :     /* If we do not have an upper bound, use end of string */
    1062         116 :     if (length_not_specified)
    1063             :     {
    1064          44 :         e1 = bitlen + 1;
    1065             :     }
    1066             :     else
    1067             :     {
    1068          72 :         e = s + l;
    1069             : 
    1070             :         /*
    1071             :          * A negative value for L is the only way for the end position to be
    1072             :          * before the start. SQL99 says to throw an error.
    1073             :          */
    1074          72 :         if (e < s)
    1075           0 :             ereport(ERROR,
    1076             :                     (errcode(ERRCODE_SUBSTRING_ERROR),
    1077             :                      errmsg("negative substring length not allowed")));
    1078          72 :         e1 = Min(e, bitlen + 1);
    1079             :     }
    1080         116 :     if (s1 > bitlen || e1 <= s1)
    1081             :     {
    1082             :         /* Need to return a zero-length bitstring */
    1083          36 :         len = VARBITTOTALLEN(0);
    1084          36 :         result = (VarBit *) palloc(len);
    1085          36 :         SET_VARSIZE(result, len);
    1086          36 :         VARBITLEN(result) = 0;
    1087             :     }
    1088             :     else
    1089             :     {
    1090             :         /*
    1091             :          * OK, we've got a true substring starting at position s1-1 and ending
    1092             :          * at position e1-1
    1093             :          */
    1094          80 :         rbitlen = e1 - s1;
    1095          80 :         len = VARBITTOTALLEN(rbitlen);
    1096          80 :         result = (VarBit *) palloc(len);
    1097          80 :         SET_VARSIZE(result, len);
    1098          80 :         VARBITLEN(result) = rbitlen;
    1099          80 :         len -= VARHDRSZ + VARBITHDRSZ;
    1100             :         /* Are we copying from a byte boundary? */
    1101          80 :         if ((s1 - 1) % BITS_PER_BYTE == 0)
    1102             :         {
    1103             :             /* Yep, we are copying bytes */
    1104          20 :             memcpy(VARBITS(result), VARBITS(arg) + (s1 - 1) / BITS_PER_BYTE,
    1105             :                    len);
    1106             :         }
    1107             :         else
    1108             :         {
    1109             :             /* Figure out how much we need to shift the sequence by */
    1110          60 :             ishift = (s1 - 1) % BITS_PER_BYTE;
    1111          60 :             r = VARBITS(result);
    1112          60 :             ps = VARBITS(arg) + (s1 - 1) / BITS_PER_BYTE;
    1113         120 :             for (i = 0; i < len; i++)
    1114             :             {
    1115          60 :                 *r = (*ps << ishift) & BITMASK;
    1116          60 :                 if ((++ps) < VARBITEND(arg))
    1117          52 :                     *r |= *ps >> (BITS_PER_BYTE - ishift);
    1118          60 :                 r++;
    1119             :             }
    1120             :         }
    1121             :         /* Do we need to pad at the end? */
    1122          80 :         ipad = VARBITPAD(result);
    1123          80 :         if (ipad > 0)
    1124             :         {
    1125          80 :             mask = BITMASK << ipad;
    1126          80 :             *(VARBITS(result) + len - 1) &= mask;
    1127             :         }
    1128             :     }
    1129             : 
    1130         116 :     return result;
    1131             : }
    1132             : 
    1133             : /*
    1134             :  * bitoverlay
    1135             :  *  Replace specified substring of first string with second
    1136             :  *
    1137             :  * The SQL standard defines OVERLAY() in terms of substring and concatenation.
    1138             :  * This code is a direct implementation of what the standard says.
    1139             :  */
    1140             : Datum
    1141           4 : bitoverlay(PG_FUNCTION_ARGS)
    1142             : {
    1143           4 :     VarBit     *t1 = PG_GETARG_VARBIT_P(0);
    1144           4 :     VarBit     *t2 = PG_GETARG_VARBIT_P(1);
    1145           4 :     int         sp = PG_GETARG_INT32(2);    /* substring start position */
    1146           4 :     int         sl = PG_GETARG_INT32(3);    /* substring length */
    1147             : 
    1148           4 :     PG_RETURN_VARBIT_P(bit_overlay(t1, t2, sp, sl));
    1149             : }
    1150             : 
    1151             : Datum
    1152          12 : bitoverlay_no_len(PG_FUNCTION_ARGS)
    1153             : {
    1154          12 :     VarBit     *t1 = PG_GETARG_VARBIT_P(0);
    1155          12 :     VarBit     *t2 = PG_GETARG_VARBIT_P(1);
    1156          12 :     int         sp = PG_GETARG_INT32(2);    /* substring start position */
    1157             :     int         sl;
    1158             : 
    1159          12 :     sl = VARBITLEN(t2);         /* defaults to length(t2) */
    1160          12 :     PG_RETURN_VARBIT_P(bit_overlay(t1, t2, sp, sl));
    1161             : }
    1162             : 
    1163             : static VarBit *
    1164          16 : bit_overlay(VarBit *t1, VarBit *t2, int sp, int sl)
    1165             : {
    1166             :     VarBit     *result;
    1167             :     VarBit     *s1;
    1168             :     VarBit     *s2;
    1169             :     int         sp_pl_sl;
    1170             : 
    1171             :     /*
    1172             :      * Check for possible integer-overflow cases.  For negative sp, throw a
    1173             :      * "substring length" error because that's what should be expected
    1174             :      * according to the spec's definition of OVERLAY().
    1175             :      */
    1176          16 :     if (sp <= 0)
    1177           0 :         ereport(ERROR,
    1178             :                 (errcode(ERRCODE_SUBSTRING_ERROR),
    1179             :                  errmsg("negative substring length not allowed")));
    1180          16 :     if (pg_add_s32_overflow(sp, sl, &sp_pl_sl))
    1181           0 :         ereport(ERROR,
    1182             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    1183             :                  errmsg("integer out of range")));
    1184             : 
    1185          16 :     s1 = bitsubstring(t1, 1, sp - 1, false);
    1186          16 :     s2 = bitsubstring(t1, sp_pl_sl, -1, true);
    1187          16 :     result = bit_catenate(s1, t2);
    1188          16 :     result = bit_catenate(result, s2);
    1189             : 
    1190          16 :     return result;
    1191             : }
    1192             : 
    1193             : /*
    1194             :  * bitlength, bitoctetlength
    1195             :  * Return the length of a bit string
    1196             :  */
    1197             : Datum
    1198          28 : bitlength(PG_FUNCTION_ARGS)
    1199             : {
    1200          28 :     VarBit     *arg = PG_GETARG_VARBIT_P(0);
    1201             : 
    1202          28 :     PG_RETURN_INT32(VARBITLEN(arg));
    1203             : }
    1204             : 
    1205             : Datum
    1206           0 : bitoctetlength(PG_FUNCTION_ARGS)
    1207             : {
    1208           0 :     VarBit     *arg = PG_GETARG_VARBIT_P(0);
    1209             : 
    1210           0 :     PG_RETURN_INT32(VARBITBYTES(arg));
    1211             : }
    1212             : 
    1213             : /*
    1214             :  * bit_and
    1215             :  * perform a logical AND on two bit strings.
    1216             :  */
    1217             : Datum
    1218          92 : bit_and(PG_FUNCTION_ARGS)
    1219             : {
    1220          92 :     VarBit     *arg1 = PG_GETARG_VARBIT_P(0);
    1221          92 :     VarBit     *arg2 = PG_GETARG_VARBIT_P(1);
    1222             :     VarBit     *result;
    1223             :     int         len,
    1224             :                 bitlen1,
    1225             :                 bitlen2,
    1226             :                 i;
    1227             :     bits8      *p1,
    1228             :                *p2,
    1229             :                *r;
    1230             : 
    1231          92 :     bitlen1 = VARBITLEN(arg1);
    1232          92 :     bitlen2 = VARBITLEN(arg2);
    1233          92 :     if (bitlen1 != bitlen2)
    1234           4 :         ereport(ERROR,
    1235             :                 (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH),
    1236             :                  errmsg("cannot AND bit strings of different sizes")));
    1237             : 
    1238          88 :     len = VARSIZE(arg1);
    1239          88 :     result = (VarBit *) palloc(len);
    1240          88 :     SET_VARSIZE(result, len);
    1241          88 :     VARBITLEN(result) = bitlen1;
    1242             : 
    1243          88 :     p1 = VARBITS(arg1);
    1244          88 :     p2 = VARBITS(arg2);
    1245          88 :     r = VARBITS(result);
    1246         236 :     for (i = 0; i < VARBITBYTES(arg1); i++)
    1247         148 :         *r++ = *p1++ & *p2++;
    1248             : 
    1249             :     /* Padding is not needed as & of 0 pad is 0 */
    1250             : 
    1251          88 :     PG_RETURN_VARBIT_P(result);
    1252             : }
    1253             : 
    1254             : /*
    1255             :  * bit_or
    1256             :  * perform a logical OR on two bit strings.
    1257             :  */
    1258             : Datum
    1259         112 : bit_or(PG_FUNCTION_ARGS)
    1260             : {
    1261         112 :     VarBit     *arg1 = PG_GETARG_VARBIT_P(0);
    1262         112 :     VarBit     *arg2 = PG_GETARG_VARBIT_P(1);
    1263             :     VarBit     *result;
    1264             :     int         len,
    1265             :                 bitlen1,
    1266             :                 bitlen2,
    1267             :                 i;
    1268             :     bits8      *p1,
    1269             :                *p2,
    1270             :                *r;
    1271             :     bits8       mask;
    1272             : 
    1273         112 :     bitlen1 = VARBITLEN(arg1);
    1274         112 :     bitlen2 = VARBITLEN(arg2);
    1275         112 :     if (bitlen1 != bitlen2)
    1276           4 :         ereport(ERROR,
    1277             :                 (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH),
    1278             :                  errmsg("cannot OR bit strings of different sizes")));
    1279         108 :     len = VARSIZE(arg1);
    1280         108 :     result = (VarBit *) palloc(len);
    1281         108 :     SET_VARSIZE(result, len);
    1282         108 :     VARBITLEN(result) = bitlen1;
    1283             : 
    1284         108 :     p1 = VARBITS(arg1);
    1285         108 :     p2 = VARBITS(arg2);
    1286         108 :     r = VARBITS(result);
    1287         316 :     for (i = 0; i < VARBITBYTES(arg1); i++)
    1288         208 :         *r++ = *p1++ | *p2++;
    1289             : 
    1290             :     /* Pad the result */
    1291         108 :     mask = BITMASK << VARBITPAD(result);
    1292         108 :     if (mask)
    1293             :     {
    1294         108 :         r--;
    1295         108 :         *r &= mask;
    1296             :     }
    1297             : 
    1298         108 :     PG_RETURN_VARBIT_P(result);
    1299             : }
    1300             : 
    1301             : /*
    1302             :  * bitxor
    1303             :  * perform a logical XOR on two bit strings.
    1304             :  */
    1305             : Datum
    1306          84 : bitxor(PG_FUNCTION_ARGS)
    1307             : {
    1308          84 :     VarBit     *arg1 = PG_GETARG_VARBIT_P(0);
    1309          84 :     VarBit     *arg2 = PG_GETARG_VARBIT_P(1);
    1310             :     VarBit     *result;
    1311             :     int         len,
    1312             :                 bitlen1,
    1313             :                 bitlen2,
    1314             :                 i;
    1315             :     bits8      *p1,
    1316             :                *p2,
    1317             :                *r;
    1318             :     bits8       mask;
    1319             : 
    1320          84 :     bitlen1 = VARBITLEN(arg1);
    1321          84 :     bitlen2 = VARBITLEN(arg2);
    1322          84 :     if (bitlen1 != bitlen2)
    1323           4 :         ereport(ERROR,
    1324             :                 (errcode(ERRCODE_STRING_DATA_LENGTH_MISMATCH),
    1325             :                  errmsg("cannot XOR bit strings of different sizes")));
    1326             : 
    1327          80 :     len = VARSIZE(arg1);
    1328          80 :     result = (VarBit *) palloc(len);
    1329          80 :     SET_VARSIZE(result, len);
    1330          80 :     VARBITLEN(result) = bitlen1;
    1331             : 
    1332          80 :     p1 = VARBITS(arg1);
    1333          80 :     p2 = VARBITS(arg2);
    1334          80 :     r = VARBITS(result);
    1335         220 :     for (i = 0; i < VARBITBYTES(arg1); i++)
    1336         140 :         *r++ = *p1++ ^ *p2++;
    1337             : 
    1338             :     /* Pad the result */
    1339          80 :     mask = BITMASK << VARBITPAD(result);
    1340          80 :     if (mask)
    1341             :     {
    1342          80 :         r--;
    1343          80 :         *r &= mask;
    1344             :     }
    1345             : 
    1346          80 :     PG_RETURN_VARBIT_P(result);
    1347             : }
    1348             : 
    1349             : /*
    1350             :  * bitnot
    1351             :  * perform a logical NOT on a bit string.
    1352             :  */
    1353             : Datum
    1354          80 : bitnot(PG_FUNCTION_ARGS)
    1355             : {
    1356          80 :     VarBit     *arg = PG_GETARG_VARBIT_P(0);
    1357             :     VarBit     *result;
    1358             :     bits8      *p,
    1359             :                *r;
    1360             :     bits8       mask;
    1361             : 
    1362          80 :     result = (VarBit *) palloc(VARSIZE(arg));
    1363          80 :     SET_VARSIZE(result, VARSIZE(arg));
    1364          80 :     VARBITLEN(result) = VARBITLEN(arg);
    1365             : 
    1366          80 :     p = VARBITS(arg);
    1367          80 :     r = VARBITS(result);
    1368         220 :     for (; p < VARBITEND(arg); p++)
    1369         140 :         *r++ = ~*p;
    1370             : 
    1371             :     /* Pad the result */
    1372          80 :     mask = BITMASK << VARBITPAD(result);
    1373          80 :     if (mask)
    1374             :     {
    1375          80 :         r--;
    1376          80 :         *r &= mask;
    1377             :     }
    1378             : 
    1379          80 :     PG_RETURN_VARBIT_P(result);
    1380             : }
    1381             : 
    1382             : /*
    1383             :  * bitshiftleft
    1384             :  * do a left shift (i.e. towards the beginning of the string)
    1385             :  */
    1386             : Datum
    1387          80 : bitshiftleft(PG_FUNCTION_ARGS)
    1388             : {
    1389          80 :     VarBit     *arg = PG_GETARG_VARBIT_P(0);
    1390          80 :     int32       shft = PG_GETARG_INT32(1);
    1391             :     VarBit     *result;
    1392             :     int         byte_shift,
    1393             :                 ishift,
    1394             :                 len;
    1395             :     bits8      *p,
    1396             :                *r;
    1397             : 
    1398             :     /* Negative shift is a shift to the right */
    1399          80 :     if (shft < 0)
    1400             :     {
    1401             :         /* Prevent integer overflow in negation */
    1402           0 :         if (shft < -VARBITMAXLEN)
    1403           0 :             shft = -VARBITMAXLEN;
    1404           0 :         PG_RETURN_DATUM(DirectFunctionCall2(bitshiftright,
    1405             :                                             VarBitPGetDatum(arg),
    1406             :                                             Int32GetDatum(-shft)));
    1407             :     }
    1408             : 
    1409          80 :     result = (VarBit *) palloc(VARSIZE(arg));
    1410          80 :     SET_VARSIZE(result, VARSIZE(arg));
    1411          80 :     VARBITLEN(result) = VARBITLEN(arg);
    1412          80 :     r = VARBITS(result);
    1413             : 
    1414             :     /* If we shifted all the bits out, return an all-zero string */
    1415          80 :     if (shft >= VARBITLEN(arg))
    1416             :     {
    1417           0 :         MemSet(r, 0, VARBITBYTES(arg));
    1418           0 :         PG_RETURN_VARBIT_P(result);
    1419             :     }
    1420             : 
    1421          80 :     byte_shift = shft / BITS_PER_BYTE;
    1422          80 :     ishift = shft % BITS_PER_BYTE;
    1423          80 :     p = VARBITS(arg) + byte_shift;
    1424             : 
    1425          80 :     if (ishift == 0)
    1426             :     {
    1427             :         /* Special case: we can do a memcpy */
    1428           0 :         len = VARBITBYTES(arg) - byte_shift;
    1429           0 :         memcpy(r, p, len);
    1430           0 :         MemSet(r + len, 0, byte_shift);
    1431             :     }
    1432             :     else
    1433             :     {
    1434         220 :         for (; p < VARBITEND(arg); r++)
    1435             :         {
    1436         140 :             *r = *p << ishift;
    1437         140 :             if ((++p) < VARBITEND(arg))
    1438          60 :                 *r |= *p >> (BITS_PER_BYTE - ishift);
    1439             :         }
    1440          80 :         for (; r < VARBITEND(result); r++)
    1441           0 :             *r = 0;
    1442             :     }
    1443             : 
    1444          80 :     PG_RETURN_VARBIT_P(result);
    1445             : }
    1446             : 
    1447             : /*
    1448             :  * bitshiftright
    1449             :  * do a right shift (i.e. towards the end of the string)
    1450             :  */
    1451             : Datum
    1452         200 : bitshiftright(PG_FUNCTION_ARGS)
    1453             : {
    1454         200 :     VarBit     *arg = PG_GETARG_VARBIT_P(0);
    1455         200 :     int32       shft = PG_GETARG_INT32(1);
    1456             :     VarBit     *result;
    1457             :     int         byte_shift,
    1458             :                 ishift,
    1459             :                 len;
    1460             :     bits8      *p,
    1461             :                *r;
    1462             : 
    1463             :     /* Negative shift is a shift to the left */
    1464         200 :     if (shft < 0)
    1465             :     {
    1466             :         /* Prevent integer overflow in negation */
    1467           0 :         if (shft < -VARBITMAXLEN)
    1468           0 :             shft = -VARBITMAXLEN;
    1469           0 :         PG_RETURN_DATUM(DirectFunctionCall2(bitshiftleft,
    1470             :                                             VarBitPGetDatum(arg),
    1471             :                                             Int32GetDatum(-shft)));
    1472             :     }
    1473             : 
    1474         200 :     result = (VarBit *) palloc(VARSIZE(arg));
    1475         200 :     SET_VARSIZE(result, VARSIZE(arg));
    1476         200 :     VARBITLEN(result) = VARBITLEN(arg);
    1477         200 :     r = VARBITS(result);
    1478             : 
    1479             :     /* If we shifted all the bits out, return an all-zero string */
    1480         200 :     if (shft >= VARBITLEN(arg))
    1481             :     {
    1482           0 :         MemSet(r, 0, VARBITBYTES(arg));
    1483           0 :         PG_RETURN_VARBIT_P(result);
    1484             :     }
    1485             : 
    1486         200 :     byte_shift = shft / BITS_PER_BYTE;
    1487         200 :     ishift = shft % BITS_PER_BYTE;
    1488         200 :     p = VARBITS(arg);
    1489             : 
    1490             :     /* Set the first part of the result to 0 */
    1491         200 :     MemSet(r, 0, byte_shift);
    1492         200 :     r += byte_shift;
    1493             : 
    1494         200 :     if (ishift == 0)
    1495             :     {
    1496             :         /* Special case: we can do a memcpy */
    1497          64 :         len = VARBITBYTES(arg) - byte_shift;
    1498          64 :         memcpy(r, p, len);
    1499             :     }
    1500             :     else
    1501             :     {
    1502         136 :         if (r < VARBITEND(result))
    1503         136 :             *r = 0;             /* initialize first byte */
    1504         376 :         for (; r < VARBITEND(result); p++)
    1505             :         {
    1506         240 :             *r |= *p >> ishift;
    1507         240 :             if ((++r) < VARBITEND(result))
    1508         104 :                 *r = (*p << (BITS_PER_BYTE - ishift)) & BITMASK;
    1509             :         }
    1510             :     }
    1511             : 
    1512         200 :     PG_RETURN_VARBIT_P(result);
    1513             : }
    1514             : 
    1515             : /*
    1516             :  * This is not defined in any standard. We retain the natural ordering of
    1517             :  * bits here, as it just seems more intuitive.
    1518             :  */
    1519             : Datum
    1520        1944 : bitfromint4(PG_FUNCTION_ARGS)
    1521             : {
    1522        1944 :     int32       a = PG_GETARG_INT32(0);
    1523        1944 :     int32       typmod = PG_GETARG_INT32(1);
    1524             :     VarBit     *result;
    1525             :     bits8      *r;
    1526             :     int         rlen;
    1527             :     int         destbitsleft,
    1528             :                 srcbitsleft;
    1529             : 
    1530        1944 :     if (typmod <= 0 || typmod > VARBITMAXLEN)
    1531           0 :         typmod = 1;             /* default bit length */
    1532             : 
    1533        1944 :     rlen = VARBITTOTALLEN(typmod);
    1534        1944 :     result = (VarBit *) palloc(rlen);
    1535        1944 :     SET_VARSIZE(result, rlen);
    1536        1944 :     VARBITLEN(result) = typmod;
    1537             : 
    1538        1944 :     r = VARBITS(result);
    1539        1944 :     destbitsleft = typmod;
    1540        1944 :     srcbitsleft = 32;
    1541             :     /* drop any input bits that don't fit */
    1542        1944 :     srcbitsleft = Min(srcbitsleft, destbitsleft);
    1543             :     /* sign-fill any excess bytes in output */
    1544        3888 :     while (destbitsleft >= srcbitsleft + 8)
    1545             :     {
    1546           0 :         *r++ = (bits8) ((a < 0) ? BITMASK : 0);
    1547           0 :         destbitsleft -= 8;
    1548             :     }
    1549             :     /* store first fractional byte */
    1550        1944 :     if (destbitsleft > srcbitsleft)
    1551             :     {
    1552           0 :         unsigned int val = (unsigned int) (a >> (destbitsleft - 8));
    1553             : 
    1554             :         /* Force sign-fill in case the compiler implements >> as zero-fill */
    1555           0 :         if (a < 0)
    1556           0 :             val |= ((unsigned int) -1) << (srcbitsleft + 8 - destbitsleft);
    1557           0 :         *r++ = (bits8) (val & BITMASK);
    1558           0 :         destbitsleft -= 8;
    1559             :     }
    1560             :     /* Now srcbitsleft and destbitsleft are the same, need not track both */
    1561             :     /* store whole bytes */
    1562        9464 :     while (destbitsleft >= 8)
    1563             :     {
    1564        5576 :         *r++ = (bits8) ((a >> (destbitsleft - 8)) & BITMASK);
    1565        5576 :         destbitsleft -= 8;
    1566             :     }
    1567             :     /* store last fractional byte */
    1568        1944 :     if (destbitsleft > 0)
    1569         440 :         *r = (bits8) ((a << (8 - destbitsleft)) & BITMASK);
    1570             : 
    1571        1944 :     PG_RETURN_VARBIT_P(result);
    1572             : }
    1573             : 
    1574             : Datum
    1575        1238 : bittoint4(PG_FUNCTION_ARGS)
    1576             : {
    1577        1238 :     VarBit     *arg = PG_GETARG_VARBIT_P(0);
    1578             :     uint32      result;
    1579             :     bits8      *r;
    1580             : 
    1581             :     /* Check that the bit string is not too long */
    1582        1238 :     if (VARBITLEN(arg) > sizeof(result) * BITS_PER_BYTE)
    1583           0 :         ereport(ERROR,
    1584             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    1585             :                  errmsg("integer out of range")));
    1586             : 
    1587        1238 :     result = 0;
    1588        6082 :     for (r = VARBITS(arg); r < VARBITEND(arg); r++)
    1589             :     {
    1590        4844 :         result <<= BITS_PER_BYTE;
    1591        4844 :         result |= *r;
    1592             :     }
    1593             :     /* Now shift the result to take account of the padding at the end */
    1594        1238 :     result >>= VARBITPAD(arg);
    1595             : 
    1596        1238 :     PG_RETURN_INT32(result);
    1597             : }
    1598             : 
    1599             : Datum
    1600        1064 : bitfromint8(PG_FUNCTION_ARGS)
    1601             : {
    1602        1064 :     int64       a = PG_GETARG_INT64(0);
    1603        1064 :     int32       typmod = PG_GETARG_INT32(1);
    1604             :     VarBit     *result;
    1605             :     bits8      *r;
    1606             :     int         rlen;
    1607             :     int         destbitsleft,
    1608             :                 srcbitsleft;
    1609             : 
    1610        1064 :     if (typmod <= 0 || typmod > VARBITMAXLEN)
    1611           0 :         typmod = 1;             /* default bit length */
    1612             : 
    1613        1064 :     rlen = VARBITTOTALLEN(typmod);
    1614        1064 :     result = (VarBit *) palloc(rlen);
    1615        1064 :     SET_VARSIZE(result, rlen);
    1616        1064 :     VARBITLEN(result) = typmod;
    1617             : 
    1618        1064 :     r = VARBITS(result);
    1619        1064 :     destbitsleft = typmod;
    1620        1064 :     srcbitsleft = 64;
    1621             :     /* drop any input bits that don't fit */
    1622        1064 :     srcbitsleft = Min(srcbitsleft, destbitsleft);
    1623             :     /* sign-fill any excess bytes in output */
    1624        2128 :     while (destbitsleft >= srcbitsleft + 8)
    1625             :     {
    1626           0 :         *r++ = (bits8) ((a < 0) ? BITMASK : 0);
    1627           0 :         destbitsleft -= 8;
    1628             :     }
    1629             :     /* store first fractional byte */
    1630        1064 :     if (destbitsleft > srcbitsleft)
    1631             :     {
    1632           0 :         unsigned int val = (unsigned int) (a >> (destbitsleft - 8));
    1633             : 
    1634             :         /* Force sign-fill in case the compiler implements >> as zero-fill */
    1635           0 :         if (a < 0)
    1636           0 :             val |= ((unsigned int) -1) << (srcbitsleft + 8 - destbitsleft);
    1637           0 :         *r++ = (bits8) (val & BITMASK);
    1638           0 :         destbitsleft -= 8;
    1639             :     }
    1640             :     /* Now srcbitsleft and destbitsleft are the same, need not track both */
    1641             :     /* store whole bytes */
    1642        6384 :     while (destbitsleft >= 8)
    1643             :     {
    1644        4256 :         *r++ = (bits8) ((a >> (destbitsleft - 8)) & BITMASK);
    1645        4256 :         destbitsleft -= 8;
    1646             :     }
    1647             :     /* store last fractional byte */
    1648        1064 :     if (destbitsleft > 0)
    1649           0 :         *r = (bits8) ((a << (8 - destbitsleft)) & BITMASK);
    1650             : 
    1651        1064 :     PG_RETURN_VARBIT_P(result);
    1652             : }
    1653             : 
    1654             : Datum
    1655         908 : bittoint8(PG_FUNCTION_ARGS)
    1656             : {
    1657         908 :     VarBit     *arg = PG_GETARG_VARBIT_P(0);
    1658             :     uint64      result;
    1659             :     bits8      *r;
    1660             : 
    1661             :     /* Check that the bit string is not too long */
    1662         908 :     if (VARBITLEN(arg) > sizeof(result) * BITS_PER_BYTE)
    1663           0 :         ereport(ERROR,
    1664             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
    1665             :                  errmsg("bigint out of range")));
    1666             : 
    1667         908 :     result = 0;
    1668        8172 :     for (r = VARBITS(arg); r < VARBITEND(arg); r++)
    1669             :     {
    1670        7264 :         result <<= BITS_PER_BYTE;
    1671        7264 :         result |= *r;
    1672             :     }
    1673             :     /* Now shift the result to take account of the padding at the end */
    1674         908 :     result >>= VARBITPAD(arg);
    1675             : 
    1676         908 :     PG_RETURN_INT64(result);
    1677             : }
    1678             : 
    1679             : 
    1680             : /*
    1681             :  * Determines the position of S2 in the bitstring S1 (1-based string).
    1682             :  * If S2 does not appear in S1 this function returns 0.
    1683             :  * If S2 is of length 0 this function returns 1.
    1684             :  * Compatible in usage with POSITION() functions for other data types.
    1685             :  */
    1686             : Datum
    1687         408 : bitposition(PG_FUNCTION_ARGS)
    1688             : {
    1689         408 :     VarBit     *str = PG_GETARG_VARBIT_P(0);
    1690         408 :     VarBit     *substr = PG_GETARG_VARBIT_P(1);
    1691             :     int         substr_length,
    1692             :                 str_length,
    1693             :                 i,
    1694             :                 is;
    1695             :     bits8      *s,              /* pointer into substring */
    1696             :                *p;              /* pointer into str */
    1697             :     bits8       cmp,            /* shifted substring byte to compare */
    1698             :                 mask1,          /* mask for substring byte shifted right */
    1699             :                 mask2,          /* mask for substring byte shifted left */
    1700             :                 end_mask,       /* pad mask for last substring byte */
    1701             :                 str_mask;       /* pad mask for last string byte */
    1702             :     bool        is_match;
    1703             : 
    1704             :     /* Get the substring length */
    1705         408 :     substr_length = VARBITLEN(substr);
    1706         408 :     str_length = VARBITLEN(str);
    1707             : 
    1708             :     /* String has zero length or substring longer than string, return 0 */
    1709         408 :     if ((str_length == 0) || (substr_length > str_length))
    1710          16 :         PG_RETURN_INT32(0);
    1711             : 
    1712             :     /* zero-length substring means return 1 */
    1713         392 :     if (substr_length == 0)
    1714           4 :         PG_RETURN_INT32(1);
    1715             : 
    1716             :     /* Initialise the padding masks */
    1717         388 :     end_mask = BITMASK << VARBITPAD(substr);
    1718         388 :     str_mask = BITMASK << VARBITPAD(str);
    1719         624 :     for (i = 0; i < VARBITBYTES(str) - VARBITBYTES(substr) + 1; i++)
    1720             :     {
    1721        3424 :         for (is = 0; is < BITS_PER_BYTE; is++)
    1722             :         {
    1723        3188 :             is_match = true;
    1724        3188 :             p = VARBITS(str) + i;
    1725        3188 :             mask1 = BITMASK >> is;
    1726        3188 :             mask2 = ~mask1;
    1727        6748 :             for (s = VARBITS(substr);
    1728        3856 :                  is_match && s < VARBITEND(substr); s++)
    1729             :             {
    1730        3328 :                 cmp = *s >> is;
    1731        3328 :                 if (s == VARBITEND(substr) - 1)
    1732             :                 {
    1733        2516 :                     mask1 &= end_mask >> is;
    1734        2516 :                     if (p == VARBITEND(str) - 1)
    1735             :                     {
    1736             :                         /* Check that there is enough of str left */
    1737         660 :                         if (mask1 & ~str_mask)
    1738             :                         {
    1739          40 :                             is_match = false;
    1740          40 :                             break;
    1741             :                         }
    1742         620 :                         mask1 &= str_mask;
    1743             :                     }
    1744             :                 }
    1745        3288 :                 is_match = ((cmp ^ *p) & mask1) == 0;
    1746        3288 :                 if (!is_match)
    1747        2700 :                     break;
    1748             :                 /* Move on to the next byte */
    1749         588 :                 p++;
    1750         588 :                 if (p == VARBITEND(str))
    1751             :                 {
    1752         216 :                     mask2 = end_mask << (BITS_PER_BYTE - is);
    1753         216 :                     is_match = mask2 == 0;
    1754             : #if 0
    1755             :                     elog(DEBUG4, "S. %d %d em=%2x sm=%2x r=%d",
    1756             :                          i, is, end_mask, mask2, is_match);
    1757             : #endif
    1758         216 :                     break;
    1759             :                 }
    1760         372 :                 cmp = *s << (BITS_PER_BYTE - is);
    1761         372 :                 if (s == VARBITEND(substr) - 1)
    1762             :                 {
    1763         156 :                     mask2 &= end_mask << (BITS_PER_BYTE - is);
    1764         156 :                     if (p == VARBITEND(str) - 1)
    1765             :                     {
    1766         152 :                         if (mask2 & ~str_mask)
    1767             :                         {
    1768           0 :                             is_match = false;
    1769           0 :                             break;
    1770             :                         }
    1771         152 :                         mask2 &= str_mask;
    1772             :                     }
    1773             :                 }
    1774         372 :                 is_match = ((cmp ^ *p) & mask2) == 0;
    1775             :             }
    1776             :             /* Have we found a match? */
    1777        3188 :             if (is_match)
    1778         324 :                 PG_RETURN_INT32(i * BITS_PER_BYTE + is + 1);
    1779             :         }
    1780             :     }
    1781          64 :     PG_RETURN_INT32(0);
    1782             : }
    1783             : 
    1784             : 
    1785             : /*
    1786             :  * bitsetbit
    1787             :  *
    1788             :  * Given an instance of type 'bit' creates a new one with
    1789             :  * the Nth bit set to the given value.
    1790             :  *
    1791             :  * The bit location is specified left-to-right in a zero-based fashion
    1792             :  * consistent with the other get_bit and set_bit functions, but
    1793             :  * inconsistent with the standard substring, position, overlay functions
    1794             :  */
    1795             : Datum
    1796           8 : bitsetbit(PG_FUNCTION_ARGS)
    1797             : {
    1798           8 :     VarBit     *arg1 = PG_GETARG_VARBIT_P(0);
    1799           8 :     int32       n = PG_GETARG_INT32(1);
    1800           8 :     int32       newBit = PG_GETARG_INT32(2);
    1801             :     VarBit     *result;
    1802             :     int         len,
    1803             :                 bitlen;
    1804             :     bits8      *r,
    1805             :                *p;
    1806             :     int         byteNo,
    1807             :                 bitNo;
    1808             : 
    1809           8 :     bitlen = VARBITLEN(arg1);
    1810           8 :     if (n < 0 || n >= bitlen)
    1811           4 :         ereport(ERROR,
    1812             :                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    1813             :                  errmsg("bit index %d out of valid range (0..%d)",
    1814             :                         n, bitlen - 1)));
    1815             : 
    1816             :     /*
    1817             :      * sanity check!
    1818             :      */
    1819           4 :     if (newBit != 0 && newBit != 1)
    1820           0 :         ereport(ERROR,
    1821             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1822             :                  errmsg("new bit must be 0 or 1")));
    1823             : 
    1824           4 :     len = VARSIZE(arg1);
    1825           4 :     result = (VarBit *) palloc(len);
    1826           4 :     SET_VARSIZE(result, len);
    1827           4 :     VARBITLEN(result) = bitlen;
    1828             : 
    1829           4 :     p = VARBITS(arg1);
    1830           4 :     r = VARBITS(result);
    1831             : 
    1832           4 :     memcpy(r, p, VARBITBYTES(arg1));
    1833             : 
    1834           4 :     byteNo = n / BITS_PER_BYTE;
    1835           4 :     bitNo = BITS_PER_BYTE - 1 - (n % BITS_PER_BYTE);
    1836             : 
    1837             :     /*
    1838             :      * Update the byte.
    1839             :      */
    1840           4 :     if (newBit == 0)
    1841           0 :         r[byteNo] &= (~(1 << bitNo));
    1842             :     else
    1843           4 :         r[byteNo] |= (1 << bitNo);
    1844             : 
    1845           4 :     PG_RETURN_VARBIT_P(result);
    1846             : }
    1847             : 
    1848             : /*
    1849             :  * bitgetbit
    1850             :  *
    1851             :  * returns the value of the Nth bit of a bit array (0 or 1).
    1852             :  *
    1853             :  * The bit location is specified left-to-right in a zero-based fashion
    1854             :  * consistent with the other get_bit and set_bit functions, but
    1855             :  * inconsistent with the standard substring, position, overlay functions
    1856             :  */
    1857             : Datum
    1858           4 : bitgetbit(PG_FUNCTION_ARGS)
    1859             : {
    1860           4 :     VarBit     *arg1 = PG_GETARG_VARBIT_P(0);
    1861           4 :     int32       n = PG_GETARG_INT32(1);
    1862             :     int         bitlen;
    1863             :     bits8      *p;
    1864             :     int         byteNo,
    1865             :                 bitNo;
    1866             : 
    1867           4 :     bitlen = VARBITLEN(arg1);
    1868           4 :     if (n < 0 || n >= bitlen)
    1869           0 :         ereport(ERROR,
    1870             :                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    1871             :                  errmsg("bit index %d out of valid range (0..%d)",
    1872             :                         n, bitlen - 1)));
    1873             : 
    1874           4 :     p = VARBITS(arg1);
    1875             : 
    1876           4 :     byteNo = n / BITS_PER_BYTE;
    1877           4 :     bitNo = BITS_PER_BYTE - 1 - (n % BITS_PER_BYTE);
    1878             : 
    1879           4 :     if (p[byteNo] & (1 << bitNo))
    1880           4 :         PG_RETURN_INT32(1);
    1881             :     else
    1882           0 :         PG_RETURN_INT32(0);
    1883             : }

Generated by: LCOV version 1.13