Skip to content

Instantly share code, notes, and snippets.

@michaelbernstein
Created March 27, 2011 19:55
Show Gist options
  • Save michaelbernstein/889540 to your computer and use it in GitHub Desktop.
Save michaelbernstein/889540 to your computer and use it in GitHub Desktop.
My snappy wrapper from earlier in the week to show igrigorik
require 'mkmf'
# Give it a name
extension_name = 'lrsnappy'
# The destination
dir_config(extension_name)
$LIBS << " -lstdc++ -lsnappy"
# Do the work
create_makefile(extension_name)
#include <ruby.h>
#include <snappy.h>
using namespace snappy;
typedef VALUE (ruby_method)(...);
extern "C" VALUE compress(VALUE self, VALUE input, VALUE length) {
string *out = new string();
char *in = StringValuePtr(input);
size_t sz = snappy::Compress(in, NUM2INT(length), out);
VALUE ret = rb_str_new(out->c_str(), sz);
delete out;
return ret;
}
extern "C" VALUE uncompress(VALUE self, VALUE input, VALUE length) {
VALUE ret;
string *out = new string();
char* str = StringValuePtr(input);
bool pass = snappy::Uncompress(str, NUM2INT(length), out);
if (pass)
ret = rb_str_new(out->c_str(), out->length());
else
ret = Qnil;
delete out;
return ret;
}
extern "C" VALUE init(VALUE self)
{
return self;
}
static VALUE RSnappy;
extern "C" void Init_lrsnappy()
{
RSnappy = rb_define_class("LRSnappy", rb_cObject);
rb_define_method(RSnappy, "initialize", (ruby_method*) &init, /*n_args*/0);
rb_define_method(RSnappy, "_compress", (ruby_method*) &compress, 2);
rb_define_method(RSnappy, "_uncompress", (ruby_method*) &uncompress, 2);
}
require 'lrsnappy'
class RSnappy
def self.compress(value)
LRSnappy.new._compress(value, value.length)
end
def self.uncompress(value)
LRSnappy.new._uncompress(value, value.length)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment