bitvec.c

Go to the documentation of this file.
00001 /*
00002 ** 2008 February 16
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** This file implements an object that represents a fixed-length
00013 ** bitmap.  Bits are numbered starting with 1.
00014 **
00015 ** A bitmap is used to record which pages of a database file have been
00016 ** journalled during a transaction, or which pages have the "dont-write"
00017 ** property.  Usually only a few pages are meet either condition.
00018 ** So the bitmap is usually sparse and has low cardinality.
00019 ** But sometimes (for example when during a DROP of a large table) most
00020 ** or all of the pages in a database can get journalled.  In those cases, 
00021 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
00022 ** to handle both cases well.
00023 **
00024 ** The size of the bitmap is fixed when the object is created.
00025 **
00026 ** All bits are clear when the bitmap is created.  Individual bits
00027 ** may be set or cleared one at a time.
00028 **
00029 ** Test operations are about 100 times more common that set operations.
00030 ** Clear operations are exceedingly rare.  There are usually between
00031 ** 5 and 500 set operations per Bitvec object, though the number of sets can
00032 ** sometimes grow into tens of thousands or larger.  The size of the
00033 ** Bitvec object is the number of pages in the database file at the
00034 ** start of a transaction, and is thus usually less than a few thousand,
00035 ** but can be as large as 2 billion for a really big database.
00036 **
00037 ** @(#) $Id: bitvec.c,v 1.8 2008/11/11 15:48:48 drh Exp $
00038 */
00039 #include "sqliteInt.h"
00040 
00041 #define BITVEC_SZ        512
00042 /* Round the union size down to the nearest pointer boundary, since that's how 
00043 ** it will be aligned within the Bitvec struct. */
00044 #define BITVEC_USIZE     (((BITVEC_SZ-12)/sizeof(Bitvec*))*sizeof(Bitvec*))
00045 #define BITVEC_NCHAR     BITVEC_USIZE
00046 #define BITVEC_NBIT      (BITVEC_NCHAR*8)
00047 #define BITVEC_NINT      (BITVEC_USIZE/4)
00048 #define BITVEC_MXHASH    (BITVEC_NINT/2)
00049 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
00050 
00051 #define BITVEC_HASH(X)   (((X)*37)%BITVEC_NINT)
00052 
00053 /*
00054 ** A bitmap is an instance of the following structure.
00055 **
00056 ** This bitmap records the existance of zero or more bits
00057 ** with values between 1 and iSize, inclusive.
00058 **
00059 ** There are three possible representations of the bitmap.
00060 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
00061 ** bitmap.  The least significant bit is bit 1.
00062 **
00063 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
00064 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
00065 **
00066 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
00067 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
00068 ** handles up to iDivisor separate values of i.  apSub[0] holds
00069 ** values between 1 and iDivisor.  apSub[1] holds values between
00070 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
00071 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
00072 ** to hold deal with values between 1 and iDivisor.
00073 */
00074 struct Bitvec {
00075   u32 iSize;      /* Maximum bit index */
00076   u32 nSet;       /* Number of bits that are set */
00077   u32 iDivisor;   /* Number of bits handled by each apSub[] entry */
00078   union {
00079     u8 aBitmap[BITVEC_NCHAR];    /* Bitmap representation */
00080     u32 aHash[BITVEC_NINT];      /* Hash table representation */
00081     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
00082   } u;
00083 };
00084 
00085 /*
00086 ** Create a new bitmap object able to handle bits between 0 and iSize,
00087 ** inclusive.  Return a pointer to the new object.  Return NULL if 
00088 ** malloc fails.
00089 */
00090 Bitvec *sqlite3BitvecCreate(u32 iSize){
00091   Bitvec *p;
00092   assert( sizeof(*p)==BITVEC_SZ );
00093   p = sqlite3MallocZero( sizeof(*p) );
00094   if( p ){
00095     p->iSize = iSize;
00096   }
00097   return p;
00098 }
00099 
00100 /*
00101 ** Check to see if the i-th bit is set.  Return true or false.
00102 ** If p is NULL (if the bitmap has not been created) or if
00103 ** i is out of range, then return false.
00104 */
00105 int sqlite3BitvecTest(Bitvec *p, u32 i){
00106   if( p==0 ) return 0;
00107   if( i>p->iSize || i==0 ) return 0;
00108   if( p->iSize<=BITVEC_NBIT ){
00109     i--;
00110     return (p->u.aBitmap[i/8] & (1<<(i&7)))!=0;
00111   }
00112   if( p->iDivisor>0 ){
00113     u32 bin = (i-1)/p->iDivisor;
00114     i = (i-1)%p->iDivisor + 1;
00115     return sqlite3BitvecTest(p->u.apSub[bin], i);
00116   }else{
00117     u32 h = BITVEC_HASH(i);
00118     while( p->u.aHash[h] ){
00119       if( p->u.aHash[h]==i ) return 1;
00120       h++;
00121       if( h>=BITVEC_NINT ) h = 0;
00122     }
00123     return 0;
00124   }
00125 }
00126 
00127 /*
00128 ** Set the i-th bit.  Return 0 on success and an error code if
00129 ** anything goes wrong.
00130 **
00131 ** This routine might cause sub-bitmaps to be allocated.  Failing
00132 ** to get the memory needed to hold the sub-bitmap is the only
00133 ** that can go wrong with an insert, assuming p and i are valid.
00134 **
00135 ** The calling function must ensure that p is a valid Bitvec object
00136 ** and that the value for "i" is within range of the Bitvec object.
00137 ** Otherwise the behavior is undefined.
00138 */
00139 int sqlite3BitvecSet(Bitvec *p, u32 i){
00140   u32 h;
00141   assert( p!=0 );
00142   assert( i>0 );
00143   assert( i<=p->iSize );
00144   if( p->iSize<=BITVEC_NBIT ){
00145     i--;
00146     p->u.aBitmap[i/8] |= 1 << (i&7);
00147     return SQLITE_OK;
00148   }
00149   if( p->iDivisor ){
00150     u32 bin = (i-1)/p->iDivisor;
00151     i = (i-1)%p->iDivisor + 1;
00152     if( p->u.apSub[bin]==0 ){
00153       sqlite3BeginBenignMalloc();
00154       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
00155       sqlite3EndBenignMalloc();
00156       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
00157     }
00158     return sqlite3BitvecSet(p->u.apSub[bin], i);
00159   }
00160   h = BITVEC_HASH(i);
00161   while( p->u.aHash[h] ){
00162     if( p->u.aHash[h]==i ) return SQLITE_OK;
00163     h++;
00164     if( h==BITVEC_NINT ) h = 0;
00165   }
00166   p->nSet++;
00167   if( p->nSet>=BITVEC_MXHASH ){
00168     unsigned int j;
00169     int rc;
00170     u32 aiValues[BITVEC_NINT];
00171     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
00172     memset(p->u.apSub, 0, sizeof(p->u.apSub[0])*BITVEC_NPTR);
00173     p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
00174     rc = sqlite3BitvecSet(p, i);
00175     for(j=0; j<BITVEC_NINT; j++){
00176       if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
00177     }
00178     return rc;
00179   }
00180   p->u.aHash[h] = i;
00181   return SQLITE_OK;
00182 }
00183 
00184 /*
00185 ** Clear the i-th bit.  Return 0 on success and an error code if
00186 ** anything goes wrong.
00187 */
00188 void sqlite3BitvecClear(Bitvec *p, u32 i){
00189   assert( p!=0 );
00190   assert( i>0 );
00191   if( p->iSize<=BITVEC_NBIT ){
00192     i--;
00193     p->u.aBitmap[i/8] &= ~(1 << (i&7));
00194   }else if( p->iDivisor ){
00195     u32 bin = (i-1)/p->iDivisor;
00196     i = (i-1)%p->iDivisor + 1;
00197     if( p->u.apSub[bin] ){
00198       sqlite3BitvecClear(p->u.apSub[bin], i);
00199     }
00200   }else{
00201     unsigned int j;
00202     u32 aiValues[BITVEC_NINT];
00203     memcpy(aiValues, p->u.aHash, sizeof(aiValues));
00204     memset(p->u.aHash, 0, sizeof(p->u.aHash[0])*BITVEC_NINT);
00205     p->nSet = 0;
00206     for(j=0; j<BITVEC_NINT; j++){
00207       if( aiValues[j] && aiValues[j]!=i ){
00208         sqlite3BitvecSet(p, aiValues[j]);
00209       }
00210     }
00211   }
00212 }
00213 
00214 /*
00215 ** Destroy a bitmap object.  Reclaim all memory used.
00216 */
00217 void sqlite3BitvecDestroy(Bitvec *p){
00218   if( p==0 ) return;
00219   if( p->iDivisor ){
00220     unsigned int i;
00221     for(i=0; i<BITVEC_NPTR; i++){
00222       sqlite3BitvecDestroy(p->u.apSub[i]);
00223     }
00224   }
00225   sqlite3_free(p);
00226 }
00227 
00228 #ifndef SQLITE_OMIT_BUILTIN_TEST
00229 /*
00230 ** Let V[] be an array of unsigned characters sufficient to hold
00231 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
00232 ** Then the following macros can be used to set, clear, or test
00233 ** individual bits within V.
00234 */
00235 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
00236 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
00237 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
00238 
00239 /*
00240 ** This routine runs an extensive test of the Bitvec code.
00241 **
00242 ** The input is an array of integers that acts as a program
00243 ** to test the Bitvec.  The integers are opcodes followed
00244 ** by 0, 1, or 3 operands, depending on the opcode.  Another
00245 ** opcode follows immediately after the last operand.
00246 **
00247 ** There are 6 opcodes numbered from 0 through 5.  0 is the
00248 ** "halt" opcode and causes the test to end.
00249 **
00250 **    0          Halt and return the number of errors
00251 **    1 N S X    Set N bits beginning with S and incrementing by X
00252 **    2 N S X    Clear N bits beginning with S and incrementing by X
00253 **    3 N        Set N randomly chosen bits
00254 **    4 N        Clear N randomly chosen bits
00255 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
00256 **
00257 ** The opcodes 1 through 4 perform set and clear operations are performed
00258 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
00259 ** Opcode 5 works on the linear array only, not on the Bitvec.
00260 ** Opcode 5 is used to deliberately induce a fault in order to
00261 ** confirm that error detection works.
00262 **
00263 ** At the conclusion of the test the linear array is compared
00264 ** against the Bitvec object.  If there are any differences,
00265 ** an error is returned.  If they are the same, zero is returned.
00266 **
00267 ** If a memory allocation error occurs, return -1.
00268 */
00269 int sqlite3BitvecBuiltinTest(int sz, int *aOp){
00270   Bitvec *pBitvec = 0;
00271   unsigned char *pV = 0;
00272   int rc = -1;
00273   int i, nx, pc, op;
00274 
00275   /* Allocate the Bitvec to be tested and a linear array of
00276   ** bits to act as the reference */
00277   pBitvec = sqlite3BitvecCreate( sz );
00278   pV = sqlite3_malloc( (sz+7)/8 + 1 );
00279   if( pBitvec==0 || pV==0 ) goto bitvec_end;
00280   memset(pV, 0, (sz+7)/8 + 1);
00281 
00282   /* Run the program */
00283   pc = 0;
00284   while( (op = aOp[pc])!=0 ){
00285     switch( op ){
00286       case 1:
00287       case 2:
00288       case 5: {
00289         nx = 4;
00290         i = aOp[pc+2] - 1;
00291         aOp[pc+2] += aOp[pc+3];
00292         break;
00293       }
00294       case 3:
00295       case 4: 
00296       default: {
00297         nx = 2;
00298         sqlite3_randomness(sizeof(i), &i);
00299         break;
00300       }
00301     }
00302     if( (--aOp[pc+1]) > 0 ) nx = 0;
00303     pc += nx;
00304     i = (i & 0x7fffffff)%sz;
00305     if( (op & 1)!=0 ){
00306       SETBIT(pV, (i+1));
00307       if( op!=5 ){
00308         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
00309       }
00310     }else{
00311       CLEARBIT(pV, (i+1));
00312       sqlite3BitvecClear(pBitvec, i+1);
00313     }
00314   }
00315 
00316   /* Test to make sure the linear array exactly matches the
00317   ** Bitvec object.  Start with the assumption that they do
00318   ** match (rc==0).  Change rc to non-zero if a discrepancy
00319   ** is found.
00320   */
00321   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
00322           + sqlite3BitvecTest(pBitvec, 0);
00323   for(i=1; i<=sz; i++){
00324     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
00325       rc = i;
00326       break;
00327     }
00328   }
00329 
00330   /* Free allocated structure */
00331 bitvec_end:
00332   sqlite3_free(pV);
00333   sqlite3BitvecDestroy(pBitvec);
00334   return rc;
00335 }
00336 #endif /* SQLITE_OMIT_BUILTIN_TEST */

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:51 2011 by Doxygen 1.6.1