Skip to content

Instantly share code, notes, and snippets.

@apeiros
Created May 16, 2016 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apeiros/6e2b2ff645083c731235a7601df4e077 to your computer and use it in GitHub Desktop.
Save apeiros/6e2b2ff645083c731235a7601df4e077 to your computer and use it in GitHub Desktop.
Native C implementation for String#^

put both files into a directory run ruby extconfig.rb, then make in the directory. You should get a .so or .bundle as a result.

require 'mkmf'
create_makefile 'string_xor'
#include <ruby.h>
#include <ruby/encoding.h>
VALUE
rb_string_xor(VALUE str1, VALUE str2)
{
StringValue(str2);
if (RSTRING_LEN(str1) != RSTRING_LEN(str2)) rb_raise(rb_eArgError, "Both strings must have the same length");
VALUE str3 = rb_enc_str_new(0, RSTRING_LEN(str1), rb_ascii8bit_encoding());
char *c1 = RSTRING_PTR(str1);
char *c2 = RSTRING_PTR(str2);
char *c3 = RSTRING_PTR(str3);
long len = RSTRING_LEN(str1);
for(long i=0; i<len; i++) {
c3[i] = c1[i] ^ c2[i];
}
RSTRING_PTR(str3)[RSTRING_LEN(str3)] = '\0';
return str3;
}
void
Init_string_xor()
{
rb_cString = rb_define_class("String", rb_cObject);
rb_define_method(rb_cString, "^", rb_string_xor, 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment