Skip to content

Commit

Permalink
utf-16/32 support for getCharSequence()
Browse files Browse the repository at this point in the history
  • Loading branch information
demon36 committed Aug 12, 2021
1 parent b4ab181 commit d1658b9
Showing 1 changed file with 43 additions and 1 deletion.
44 changes: 43 additions & 1 deletion src/main/java/jnr/ffi/util/BufferUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ public static CharSequence getCharSequence(ByteBuffer buf, Charset charset) {
final ByteBuffer buffer = buf.slice();
// Find the NUL terminator and limit to that, so the
// StringBuffer/StringBuilder does not have superfluous NUL chars
int end = indexOf(buffer, (byte) 0);
final byte[] nullCharBytes = new String("\0").getBytes(charset);
int end = indexOf(buffer, nullCharBytes) - nullCharBytes.length;
if (end < 0) {
end = buffer.limit();
}
Expand Down Expand Up @@ -141,6 +142,47 @@ public static int indexOf(ByteBuffer buf, byte value) {
return -1;
}

public static int indexOf(ByteBuffer buf, byte[] value) {
int matchingBytesCount = 0;
int offset = 0;
if (buf.hasArray()) {
byte[] array = buf.array();
int begin = buf.arrayOffset() + buf.position();
int end = buf.arrayOffset() + buf.limit();
while(offset < end && offset > -1){
if(array[begin + offset] == value[matchingBytesCount]){
matchingBytesCount++;
offset++;
} else {
matchingBytesCount = 0;
offset += value.length - (offset%value.length);//jump to start of next character
continue;
}

if(matchingBytesCount == value.length){
return offset;
}
}
} else {
int begin = buf.position();
while(offset < buf.limit()){
if(buf.get(begin + offset) == value[matchingBytesCount]){
matchingBytesCount++;
offset++;
} else {
matchingBytesCount = 0;
offset += value.length - (offset%value.length);//jump to start of next character
continue;
}

if(matchingBytesCount == value.length){
return offset;
}
}
}
return -1;
}

public static int indexOf(ByteBuffer buf, int offset, byte value) {
if (buf.hasArray()) {
byte[] array = buf.array();
Expand Down

0 comments on commit d1658b9

Please sign in to comment.