Chemistry Reference
In-Depth Information
shared object file output by the complier is then placed in the PostgreSQL
library. The following code implements the nbits _ set function that
returns the number of bits set in a bit string. This function is also shown
in a python version earlier in this Appendix.
#include "postgres.h" /* general Postgres declarations */
#include "fmgr.h" /* for argument/result macros */
#include "executor/executor.h" /* for GetAttributeByName() */
#include "utils/varbit.h"
/* These prototypes just prevent possible warnings from gcc. */
Datum nbits_set(PG_FUNCTION_ARGS);
PG_FUNCTION_INFO_V1(nbits_set);
Datum
nbits_set(PG_FUNCTION_ARGS)
{
/* how many bits are set in a bitstring? */
VarBit *a = PG_GETARG_VARBIT_P(0);
int n=0;
/*
* VARBITLENTOTAL is the total size of the struct in bytes.
* VARBITLEN is the size of the string in bits.
* VARBITBYTES is the size of the string in bytes.
* VARBITHDRSZ is the total size of the header in bytes.
* VARBITS is a pointer to the data region of the struct.
*/
int i;
unsigned char *ap = VARBITS(a);
unsigned char aval;
for (i=0; i < VARBITBYTES(a); ++i) {
aval = *ap; ++ap;
if (aval == 0) continue;
if (aval & 1) ++n;
if (aval & 2) ++n;
if (aval & 4) ++n;
if (aval & 8) ++n;
if (aval & 16) ++n;
if (aval & 32) ++n;
if (aval & 64) ++n;
if (aval & 128) ++n;
}
PG_RETURN_INT32(n);
}
Suppose this code exists in a file bits.c. The following linux commands
will process this file and make it useable as a new PostgreSQL function.
> gcc -shared -o bits.so -I/usr/include/postgresql/8.2/server bits.c
> cp bits.so /usr/lib/postgresql/8.2/lib/bits.so
Search WWH ::




Custom Search