Debian Codegraph @

vendor/wikimedia/cdb/src/Util.php

raw
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 */
18
19 namespace Cdb;
20
21 /**
22 * Common functions for readers and writers
23 *
24 * This is a port of D.J. Bernstein's CDB to PHP. It's based on the copy that
25 * appears in PHP 5.3.
26 */
27 class Util {
28 /**
29 * Take a modulo of a signed integer as if it were an unsigned integer.
30 * $b must be less than 0x40000000 and greater than 0
31 *
32 * @param int $a
33 * @param int $b
34 * @return int
35 */
36 public static function unsignedMod( $a, $b ): int {
37 if ( $a & 0x80000000 ) {
38 $m = ( $a & 0x7fffffff ) % $b + 2 * ( 0x40000000 % $b );
39
40 return $m % $b;
41 } else {
42 return $a % $b;
43 }
44 }
45
46 /**
47 * Shift a signed integer right as if it were unsigned
48 *
49 * @param int $a
50 * @param int $b
51 * @return int
52 */
53 public static function unsignedShiftRight( $a, $b ): int {
54 if ( $b == 0 ) {
55 return $a;
56 }
57 if ( $a & 0x80000000 ) {
58 return ( ( $a & 0x7fffffff ) >> $b ) | ( 0x40000000 >> ( $b - 1 ) );
59 } else {
60 return $a >> $b;
61 }
62 }
63
64 /**
65 * The CDB hash function.
66 *
67 * @param string $s
68 * @return int
69 */
70 public static function hash( $s ): int {
71 $h = 5381;
72 $len = strlen( $s );
73 for ( $i = 0; $i < $len; $i++ ) {
74 $h5 = ( $h << 5 ) & 0xffffffff;
75 // Do a 32-bit sum
76 // Inlined here for speed
77 $sum = ( $h & 0x3fffffff ) + ( $h5 & 0x3fffffff );
78 $h = (
79 ( $sum & 0x40000000 ? 1 : 0 )
80 + ( $h & 0x80000000 ? 2 : 0 )
81 + ( $h & 0x40000000 ? 1 : 0 )
82 + ( $h5 & 0x80000000 ? 2 : 0 )
83 + ( $h5 & 0x40000000 ? 1 : 0 )
84 ) << 30 | ( $sum & 0x3fffffff );
85 $h ^= ord( $s[$i] );
86 $h &= 0xffffffff;
87 }
88
89 return $h;
90 }
91 }