在JRuby Java扩展中,byte[]为RubyString



我正在尝试实现JRuby的Java扩展来执行字符串xors。我只是不确定如何将字节数组类型转换为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?
}

同样,如何在原地执行相同的操作(即更新x的值)?

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

首先需要将字节包装在ByteList: new ByteList(xBytes, false)中。最后一个参数(Boolean copy)指示是否包装Byte数组的副本。

要更新字符串,使用[RubyString#setValue()][2]:

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

要返回一个新的RubyString,您可以将该列表传递给当前运行时的#newString():

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

最新更新