westonplatter/phashion — pull request #27 by tenderlove (2013-12-18 21:44:22+00:00)
Title: add a sqlite3 extension for calculating hamming distance in the db

Hi,

I'm storing many hashes in a sqlite3 database, and I'd like to calculate the hamming distance in my SQL queries. I've added a sqlite3 extension that will install a `hamming_distance` function.

To try it out at home, do (system SQLite3 on OSX doesn't support extensions):

```
$ brew install sqlite3
$ gem install sqlite3 -- --with-sqlite3-dir=/usr/local/opt/sqlite`
```

Then:

```ruby
require 'sqlite3'
require 'phashion'

def split hash
[(hash >> 32) & 0xFFFFFFFF, hash & 0xFFFFFFFF]
end

db = SQLite3::Database.new ':memory:'
db.enable_load_extension true
db.load_extension Phashion.so_file

hash1 = Phashion.image_hash_for ARGV[0]
hash2 = Phashion.image_hash_for ARGV[1]

l1, r1 = split hash1
l2, r2 = split hash2

p Phashion.hamming_distance hash1, hash2
p db.execute "SELECT hamming_distance(#{l1}, #{r1}, #{l2}, #{r2})"
```

SQLite3 can't store a ulong64, so I split it in to two 32bit ints.