Last active
August 29, 2015 14:08
-
-
Save tlux/3c1c87673512d12c4948 to your computer and use it in GitHub Desktop.
Freelancer Hash Encoder
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
| require 'active_support/all' | |
| require 'singleton' | |
| class FLHash | |
| include Singleton | |
| FLHASH_POLYNOMIAL = 0xa001; | |
| LOGICAL_BITS = 30; | |
| PHYSICAL_BITS = 32; | |
| class << self | |
| delegate :encode, to: :instance | |
| end | |
| def initialize | |
| @table = [] | |
| 256.times do |index| | |
| x = index | |
| 8.times do |bit| | |
| x = ((x & 1) == 1) ? (x >> 1) ^ (FLHASH_POLYNOMIAL << (LOGICAL_BITS - 16)) : x >> 1 | |
| end | |
| @table[index] = x | |
| end | |
| end | |
| def encode(str) | |
| str = str.to_s.downcase.encode(Encoding::ASCII) | |
| hash = 0 | |
| str.each_byte.with_index do |byte, index| | |
| hash = int32cast((hash >> 8) ^ @table[bytecast(hash) ^ byte]) | |
| end | |
| hash = int32cast((hash >> 24) | ((hash >> 8) & 0x0000ff00) | ((hash << 8) & 0x00ff0000) | (hash << 24)) | |
| hash = int32cast((hash >> (PHYSICAL_BITS - LOGICAL_BITS)) | 0x80000000) | |
| hash | |
| end | |
| private | |
| def bytecast(value) | |
| value & 0xff | |
| end | |
| def int32cast(value) | |
| value & 0xffffffff | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment