Skip to content

Commit

Permalink
Update native extension to use RubyInline rather than a gem extension.
Browse files Browse the repository at this point in the history
Allows the gem to install on JRuby and other non-native platforms.
  • Loading branch information
mperham committed Feb 11, 2009
1 parent cc0fe00 commit f7b53d8
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 32 deletions.
8 changes: 0 additions & 8 deletions Manifest.txt

This file was deleted.

77 changes: 54 additions & 23 deletions lib/continuum.rb
@@ -1,31 +1,62 @@
module Continuum
POINTS_PER_SERVER = 160 # this is the default in libmemcached

begin
require 'binary_search' # try to load native extension
rescue LoadError => e
puts "Unable to load fast binary search, falling back to pure Ruby: #{e.message}"

# slow but pure ruby version
# Find the closest index in Continuum with value <= the given value
def self.binary_search(ary, value, &block)
upper = ary.size - 1
lower = 0
idx = 0

while(lower <= upper) do
idx = (lower + upper) / 2
comp = ary[idx].value <=> value

if comp == 0
return idx
elsif comp > 0
upper = idx - 1
else
lower = idx + 1
class << self

begin
require 'inline'
inline do |builder|
builder.c <<-EOM
int binary_search(VALUE ary, unsigned int r) {
int upper = RARRAY_LEN(ary) - 1;
int lower = 0;
int idx = 0;
ID value = rb_intern("value");
while (lower <= upper) {
idx = (lower + upper) / 2;
VALUE continuumValue = rb_funcall(RARRAY_PTR(ary)[idx], value, 0);
unsigned int l = NUM2UINT(continuumValue);
if (l == r) {
return idx;
}
else if (l > r) {
upper = idx - 1;
}
else {
lower = idx + 1;
}
}
return upper;
}
EOM
end
rescue Exception => e
puts "Unable to generate native code, falling back to Ruby: #{e.message}"

# slow but pure ruby version
# Find the closest index in Continuum with value <= the given value
def binary_search(ary, value, &block)
upper = ary.size - 1
lower = 0
idx = 0

while(lower <= upper) do
idx = (lower + upper) / 2
comp = ary[idx].value <=> value

if comp == 0
return idx
elsif comp > 0
upper = idx - 1
else
lower = idx + 1
end
end
return upper
end
return upper

end
end

Expand Down
2 changes: 1 addition & 1 deletion memcache-client.gemspec
Expand Up @@ -12,5 +12,5 @@ Gem::Specification.new do |s|

s.files = ["README.rdoc", "LICENSE.txt", "History.txt", "Rakefile", "lib/continuum.rb", "lib/memcache.rb", "lib/memcache_util.rb", 'ext/memcache/binary_search.c']
s.test_files = ["test/test_mem_cache.rb"]
s.extensions = ['ext/memcache/extconf.rb']
s.add_runtime_dependency ['RubyInline']
end

0 comments on commit f7b53d8

Please sign in to comment.