Skip to content

Commit

Permalink
reset position in Strings.encode
Browse files Browse the repository at this point in the history
  • Loading branch information
esaulpaugh committed Aug 21, 2024
1 parent 9604408 commit 1a4606b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 22 deletions.
15 changes: 7 additions & 8 deletions src/main/java/com/esaulpaugh/headlong/util/Strings.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,15 @@ public static String encode(byte b) {
return encode(new byte[] { b });
}

public static String encode(ByteBuffer buffer) {
final byte[] bytes;
if (buffer.hasArray()) {
bytes = buffer.array();
public static String encode(ByteBuffer buf) {
if (buf.hasArray()) {
return encode(buf.array());
} else {
buffer.position(0);
bytes = new byte[buffer.capacity()];
buffer.get(bytes);
final int pos = buf.position();
byte[] bytes = new byte[buf.position(0).limit()];
buf.get(bytes).position(pos);
return encode(bytes);
}
return encode(bytes);
}

public static String encode(byte[] bytes) {
Expand Down
24 changes: 10 additions & 14 deletions src/test/java/com/esaulpaugh/headlong/util/StringsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,24 +49,20 @@ private static void testEncoding(int n, int encoding, Supplier<byte[]> supplier)

@Test
public void testEncodeDirectBuffer() {
final int len = RAND.nextInt(257);
final ByteBuffer ro = ByteBuffer.allocateDirect(len);
assertTrue(ro.isDirect());
final String hex = Strings.encode(ro);
assertEquals(len * 2, hex.length());
for (int i = 0; i < len; i += 2) {
if (hex.charAt(i) != '0' || hex.charAt(i + 1) != '0') {
throw new AssertionError("" + i);
}
}
testEncodeBuffer(ByteBuffer.allocateDirect(RAND.nextInt(257)));
}

@Test
public void testEncodeReadOnlyBuffer() {
final int len = RAND.nextInt(257);
final ByteBuffer ro = ByteBuffer.allocate(len).asReadOnlyBuffer();
assertTrue(ro.isReadOnly());
final String hex = Strings.encode(ro);
testEncodeBuffer(ByteBuffer.allocate(RAND.nextInt(257)).asReadOnlyBuffer());
}

private void testEncodeBuffer(ByteBuffer bb) {
final int len = bb.capacity();
final int pos = RAND.nextInt(len + 1);
bb.position(pos);
final String hex = Strings.encode(bb);
assertEquals(pos, bb.position());
assertEquals(len * 2, hex.length());
for (int i = 0; i < len; i += 2) {
if (hex.charAt(i) != '0' || hex.charAt(i + 1) != '0') {
Expand Down

0 comments on commit 1a4606b

Please sign in to comment.