fny
fny

Reputation: 33605

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)?

Upvotes: 3

Views: 150

Answers (2)

kares
kares

Reputation: 7181

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

Upvotes: 1

fny
fny

Reputation: 33605

You'll first need to wrap the bytes in a ByteList: new ByteList(xBytes, false). The last parameter (Boolean copy) dictates whether to wrap a copy of the Byte array.

To update the string in place, use [RubyString#setValue()][2]:

x.setValue(new ByteList(xBytes, false);
return x;

To return a new RubyString, you can pass that list to the current runtime's #newString():

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

Upvotes: 0

Related Questions