diff --git a/src/main/java/com/esaulpaugh/headlong/util/Strings.java b/src/main/java/com/esaulpaugh/headlong/util/Strings.java index ceeb6959..ff1927f0 100644 --- a/src/main/java/com/esaulpaugh/headlong/util/Strings.java +++ b/src/main/java/com/esaulpaugh/headlong/util/Strings.java @@ -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) { diff --git a/src/test/java/com/esaulpaugh/headlong/util/StringsTest.java b/src/test/java/com/esaulpaugh/headlong/util/StringsTest.java index 1f4cb30b..70d10015 100644 --- a/src/test/java/com/esaulpaugh/headlong/util/StringsTest.java +++ b/src/test/java/com/esaulpaugh/headlong/util/StringsTest.java @@ -49,24 +49,20 @@ private static void testEncoding(int n, int encoding, Supplier 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') {