简体   繁体   English

byte []到RubyString,用于JRuby Java Extension中的字符串xor

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

I'm trying to implement a Java extension for JRuby to perform string xors. 我正在尝试为JRuby实现Java扩展来执行字符串xors。 I'm just uncertain how to type cast a byte array into a RubyString : 我只是不确定如何在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 (ie x s value is updated)? 另外,如何在原地执行相同的操作(即更新x s值)?

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

You'll first need to wrap the bytes in a ByteList : new ByteList(xBytes, false) . 您首先需要将字节包装在ByteListnew ByteList(xBytes, false) The last parameter ( Boolean copy ) dictates whether to wrap a copy of the Byte array. 最后一个参数( Boolean copy )指示是否包装Byte数组的副本。

To update the string in place, use [RubyString#setValue()][2] : 要更新字符串,请使用[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() : 要返回新的RubyString ,可以将该列表传递给当前运行时的#newString()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM