Search code examples
javajrubyjruby-java-interop

byte[] to RubyString for string xor in JRuby Java Extension


I'm trying to implement a Java extension for JRuby to perform string xors. I'm just uncertain how to type cast a byte array into a RubyString:

public static RubyString xor(ThreadContext context,  IRubyObject self, RubyString x, RubyString y) {
    byte[] xBytes = x.getBytes();
    byte[] yBytes = y.getBytes();

    int length = yBytes.length < xBytes.length ? yBytes.length : xBytes.length;

    for(int i = 0; i < length; i++) {
        xBytes[i] = (byte) (xBytes[i] ^ yBytes[i]);
    }

    // How to return a RubyString with xBytes as its content?
}

Also, how would one perform the same operation in-place (i.e. xs value is updated)?


Solution

  • return context.runtime.newString(new ByteList(xBytes, false));