Skip to content

Commit f4b89a7

Browse files
committed
utf-16/32 support for getCharSequence()
1 parent b4ab181 commit f4b89a7

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

src/main/java/jnr/ffi/util/BufferUtil.java

+34-1
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,8 @@ public static CharSequence getCharSequence(ByteBuffer buf, Charset charset) {
6464
final ByteBuffer buffer = buf.slice();
6565
// Find the NUL terminator and limit to that, so the
6666
// StringBuffer/StringBuilder does not have superfluous NUL chars
67-
int end = indexOf(buffer, (byte) 0);
67+
final byte[] nullCharBytes = new String("\0").getBytes(charset);
68+
int end = indexOf(buffer, nullCharBytes);
6869
if (end < 0) {
6970
end = buffer.limit();
7071
}
@@ -141,6 +142,38 @@ public static int indexOf(ByteBuffer buf, byte value) {
141142
return -1;
142143
}
143144

145+
public static int indexOf(ByteBuffer buf, byte[] value) {
146+
byte[] array = null;
147+
int matchingBytesCount = 0;
148+
int i;
149+
int limit;
150+
if (buf.hasArray()) {
151+
i = 0;
152+
array = buf.array();
153+
limit = array.length;
154+
} else {
155+
i = buf.position();
156+
limit = buf.limit();
157+
}
158+
159+
while(i < limit){
160+
byte it = buf.hasArray() ? array[i] : buf.get(i);
161+
if(it == value[matchingBytesCount]){
162+
matchingBytesCount++;
163+
i++;
164+
} else {
165+
matchingBytesCount = 0;
166+
i += value.length - (i%value.length);//jump to start of next character
167+
continue;
168+
}
169+
170+
if(matchingBytesCount == value.length){
171+
return i;
172+
}
173+
}
174+
return -1;
175+
}
176+
144177
public static int indexOf(ByteBuffer buf, int offset, byte value) {
145178
if (buf.hasArray()) {
146179
byte[] array = buf.array();

0 commit comments

Comments
 (0)