Last active
June 4, 2018 16:10
-
-
Save brewski/c50595f454a6c8e57ac6c34a108a8429 to your computer and use it in GitHub Desktop.
piece spec hash implementation in php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
error_reporting(E_ALL); | |
class AV { | |
function __construct($id, $qualifier_1, $qualifier_2) { | |
$this->id = $id; | |
$this->qualifier_1 = $qualifier_1; | |
$this->qualifier_2 = $qualifier_2; | |
} | |
public function components() { | |
return array(pack_64be($this->id), $this->qualifier_1, $this->qualifier_2); | |
} | |
public function hash_62bit() { | |
$sha256 = hash_init("sha256"); | |
foreach ($this->components() as $component) { | |
hash_update($sha256, hash("sha256", $component, true)); | |
} | |
return unpack_64be(hash_final($sha256, true))[1] & 0x3fffffffffffffff; | |
} | |
} | |
function pack_64be($value) { | |
return pack("N", ($value >> 32)) . pack("N", 0xffffffff & $value); | |
} | |
function unpack_64be($value) { | |
$ints = unpack("N2", $value); | |
return array(1 => ($ints[1] << 32) + $ints[2]); | |
} | |
function piece_spec_hash($sku_id, $avs) { | |
if (count($avs) == 0) { | |
return $sku_id; | |
} | |
$av_hashes = array_unique(array_map(function($av) { return $av->hash_62bit(); }, $avs)); | |
sort($av_hashes); | |
$sha256 = hash_init("sha256"); | |
hash_update($sha256, pack_64be($sku_id)); | |
foreach ($av_hashes as $hash) { | |
hash_update($sha256, pack_64be($hash)); | |
} | |
return unpack("N", hash_final($sha256, true))[1]; | |
} | |
$avs = array( | |
new AV(4242, "", ""), | |
new AV(2, "qualifier 1 value", "qualifier 2 value") | |
); | |
echo "av1 62-bit hash: " . $avs[0]->hash_62bit() . "\n"; | |
echo "av2 62-bit hash: " . $avs[1]->hash_62bit() . "\n"; | |
echo "piece_spec_hash: " . piece_spec_hash(88662, $avs) . "\n"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment