3 * This is a port of D.J. Bernstein's CDB to PHP. It's based on the copy that
4 * appears in PHP 5.3. Changes are:
5 * * Error returns replaced with exceptions
6 * * Exception thrown if sizes or offsets are between 2GB and 4GB
7 * * Some variables renamed
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * Common functions for readers and writers
32 * Take a modulo of a signed integer as if it were an unsigned integer.
33 * $b must be less than 0x40000000 and greater than 0
40 public static function unsignedMod( $a, $b ) {
41 if ( $a & 0x80000000 ) {
42 $m = ( $a & 0x7fffffff ) %
$b +
2 * ( 0x40000000 %
$b );
50 * Shift a signed integer right as if it were unsigned
55 public static function unsignedShiftRight( $a, $b ) {
59 if ( $a & 0x80000000 ) {
60 return ( ( $a & 0x7fffffff ) >> $b ) |
( 0x40000000 >> ( $b - 1 ) );
67 * The CDB hash function.
73 public static function hash( $s ) {
75 for ( $i = 0; $i < strlen( $s ); $i++
) {
76 $h5 = ($h << 5) & 0xffffffff;
78 // Inlined here for speed
79 $sum = ($h & 0x3fffffff) +
($h5 & 0x3fffffff);
82 ( $sum & 0x40000000 ?
1 : 0 )
83 +
( $h & 0x80000000 ?
2 : 0 )
84 +
( $h & 0x40000000 ?
1 : 0 )
85 +
( $h5 & 0x80000000 ?
2 : 0 )
86 +
( $h5 & 0x40000000 ?
1 : 0 )
88 |
( $sum & 0x3fffffff );
99 class CdbReader_PHP
extends CdbReader
{
103 /** The file handle */
106 /* number of hash slots searched under this key */
109 /* initialized if loop is nonzero */
112 /* initialized if loop is nonzero */
115 /* initialized if loop is nonzero */
118 /* initialized if loop is nonzero */
121 /* initialized if findNext() returns true */
124 /* initialized if cdb_findnext() returns 1 */
128 * @param $fileName string
129 * @throws MWException
131 function __construct( $fileName ) {
132 $this->fileName
= $fileName;
133 $this->handle
= fopen( $fileName, 'rb' );
134 if ( !$this->handle
) {
135 throw new MWException( 'Unable to open CDB file "' . $this->fileName
. '".' );
141 if( isset( $this->handle
) ) {
142 fclose( $this->handle
);
144 unset( $this->handle
);
149 * @return bool|string
151 public function get( $key ) {
152 // strval is required
153 if ( $this->find( strval( $key ) ) ) {
154 return $this->read( $this->dlen
, $this->dpos
);
165 protected function match( $key, $pos ) {
166 $buf = $this->read( strlen( $key ), $pos );
167 return $buf === $key;
170 protected function findStart() {
175 * @throws MWException
180 protected function read( $length, $pos ) {
181 if ( fseek( $this->handle
, $pos ) == -1 ) {
182 // This can easily happen if the internal pointers are incorrect
183 throw new MWException(
184 'Seek failed, file "' . $this->fileName
. '" may be corrupted.' );
187 if ( $length == 0 ) {
191 $buf = fread( $this->handle
, $length );
192 if ( $buf === false ||
strlen( $buf ) !== $length ) {
193 throw new MWException(
194 'Read from CDB file failed, file "' . $this->fileName
. '" may be corrupted.' );
200 * Unpack an unsigned integer and throw an exception if it needs more than 31 bits
202 * @throws MWException
205 protected function unpack31( $s ) {
206 $data = unpack( 'V', $s );
207 if ( $data[1] > 0x7fffffff ) {
208 throw new MWException(
209 'Error in CDB file "' . $this->fileName
. '", integer too big.' );
215 * Unpack a 32-bit signed integer
219 protected function unpackSigned( $s ) {
220 $data = unpack( 'va/vb', $s );
221 return $data['a'] |
( $data['b'] << 16 );
228 protected function findNext( $key ) {
229 if ( !$this->loop
) {
230 $u = CdbFunctions
::hash( $key );
231 $buf = $this->read( 8, ( $u << 3 ) & 2047 );
232 $this->hslots
= $this->unpack31( substr( $buf, 4 ) );
233 if ( !$this->hslots
) {
236 $this->hpos
= $this->unpack31( substr( $buf, 0, 4 ) );
238 $u = CdbFunctions
::unsignedShiftRight( $u, 8 );
239 $u = CdbFunctions
::unsignedMod( $u, $this->hslots
);
241 $this->kpos
= $this->hpos +
$u;
244 while ( $this->loop
< $this->hslots
) {
245 $buf = $this->read( 8, $this->kpos
);
246 $pos = $this->unpack31( substr( $buf, 4 ) );
252 if ( $this->kpos
== $this->hpos +
( $this->hslots
<< 3 ) ) {
253 $this->kpos
= $this->hpos
;
255 $u = $this->unpackSigned( substr( $buf, 0, 4 ) );
256 if ( $u === $this->khash
) {
257 $buf = $this->read( 8, $pos );
258 $keyLen = $this->unpack31( substr( $buf, 0, 4 ) );
259 if ( $keyLen == strlen( $key ) && $this->match( $key, $pos +
8 ) ) {
261 $this->dlen
= $this->unpack31( substr( $buf, 4 ) );
262 $this->dpos
= $pos +
8 +
$keyLen;
274 protected function find( $key ) {
276 return $this->findNext( $key );
283 class CdbWriter_PHP
extends CdbWriter
{
284 var $handle, $realFileName, $tmpFileName;
287 var $numentries, $pos;
290 * @param $fileName string
292 function __construct( $fileName ) {
293 $this->realFileName
= $fileName;
294 $this->tmpFileName
= $fileName . '.tmp.' . mt_rand( 0, 0x7fffffff );
295 $this->handle
= fopen( $this->tmpFileName
, 'wb' );
296 if ( !$this->handle
) {
297 $this->throwException(
298 'Unable to open CDB file "' . $this->tmpFileName
. '" for write.' );
300 $this->hplist
= array();
301 $this->numentries
= 0;
302 $this->pos
= 2048; // leaving space for the pointer array, 256 * 8
303 if ( fseek( $this->handle
, $this->pos
) == -1 ) {
304 $this->throwException( 'fseek failed in file "' . $this->tmpFileName
. '".' );
308 function __destruct() {
309 if ( isset( $this->handle
) ) {
319 public function set( $key, $value ) {
320 if ( strval( $key ) === '' ) {
321 // DBA cross-check hack
324 $this->addbegin( strlen( $key ), strlen( $value ) );
325 $this->write( $key );
326 $this->write( $value );
327 $this->addend( strlen( $key ), strlen( $value ), CdbFunctions
::hash( $key ) );
331 * @throws MWException
333 public function close() {
335 if( isset( $this->handle
) ) {
336 fclose( $this->handle
);
338 if ( wfIsWindows() && file_exists( $this->realFileName
) ) {
339 unlink( $this->realFileName
);
341 if ( !rename( $this->tmpFileName
, $this->realFileName
) ) {
342 $this->throwException( 'Unable to move the new CDB file into place.' );
344 unset( $this->handle
);
348 * @throws MWException
351 protected function write( $buf ) {
352 $len = fwrite( $this->handle
, $buf );
353 if ( $len !== strlen( $buf ) ) {
354 $this->throwException( 'Error writing to CDB file "' . $this->tmpFileName
. '".' );
359 * @throws MWException
362 protected function posplus( $len ) {
363 $newpos = $this->pos +
$len;
364 if ( $newpos > 0x7fffffff ) {
365 $this->throwException(
366 'A value in the CDB file "' . $this->tmpFileName
. '" is too large.' );
368 $this->pos
= $newpos;
376 protected function addend( $keylen, $datalen, $h ) {
377 $this->hplist
[] = array(
384 $this->posplus( $keylen );
385 $this->posplus( $datalen );
389 * @throws MWException
393 protected function addbegin( $keylen, $datalen ) {
394 if ( $keylen > 0x7fffffff ) {
395 $this->throwException( 'Key length too long in file "' . $this->tmpFileName
. '".' );
397 if ( $datalen > 0x7fffffff ) {
398 $this->throwException( 'Data length too long in file "' . $this->tmpFileName
. '".' );
400 $buf = pack( 'VV', $keylen, $datalen );
401 $this->write( $buf );
405 * @throws MWException
407 protected function finish() {
408 // Hack for DBA cross-check
409 $this->hplist
= array_reverse( $this->hplist
);
411 // Calculate the number of items that will be in each hashtable
412 $counts = array_fill( 0, 256, 0 );
413 foreach ( $this->hplist
as $item ) {
414 ++
$counts[255 & $item['h']];
417 // Fill in $starts with the *end* indexes
420 for ( $i = 0; $i < 256; ++
$i ) {
425 // Excessively clever and indulgent code to simultaneously fill $packedTables
426 // with the packed hashtables, and adjust the elements of $starts
427 // to actually point to the starts instead of the ends.
428 $packedTables = array_fill( 0, $this->numentries
, false );
429 foreach ( $this->hplist
as $item ) {
430 $packedTables[--$starts[255 & $item['h']]] = $item;
434 for ( $i = 0; $i < 256; ++
$i ) {
435 $count = $counts[$i];
437 // The size of the hashtable will be double the item count.
438 // The rest of the slots will be empty.
439 $len = $count +
$count;
440 $final .= pack( 'VV', $this->pos
, $len );
442 $hashtable = array();
443 for ( $u = 0; $u < $len; ++
$u ) {
444 $hashtable[$u] = array( 'h' => 0, 'p' => 0 );
447 // Fill the hashtable, using the next empty slot if the hashed slot
449 for ( $u = 0; $u < $count; ++
$u ) {
450 $hp = $packedTables[$starts[$i] +
$u];
451 $where = CdbFunctions
::unsignedMod(
452 CdbFunctions
::unsignedShiftRight( $hp['h'], 8 ), $len );
453 while ( $hashtable[$where]['p'] )
454 if ( ++
$where == $len )
456 $hashtable[$where] = $hp;
459 // Write the hashtable
460 for ( $u = 0; $u < $len; ++
$u ) {
462 $hashtable[$u]['h'] & 0xffff,
463 CdbFunctions
::unsignedShiftRight( $hashtable[$u]['h'], 16 ),
464 $hashtable[$u]['p'] );
465 $this->write( $buf );
470 // Write the pointer array at the start of the file
471 rewind( $this->handle
);
472 if ( ftell( $this->handle
) != 0 ) {
473 $this->throwException( 'Error rewinding to start of file "' . $this->tmpFileName
. '".' );
475 $this->write( $final );
479 * Clean up the temp file and throw an exception
482 * @throws MWException
484 protected function throwException( $msg ) {
485 if ( $this->handle
) {
486 fclose( $this->handle
);
487 unlink( $this->tmpFileName
);
489 throw new MWException( $msg );