Skip to content

Commit

Permalink
java-native-access#466: Improve performance of Pointer.dump for large…
Browse files Browse the repository at this point in the history
… dumps. Added simle unit test for Pointer.dump.
  • Loading branch information
ck2510 committed Oct 6, 2015
1 parent 3e4d298 commit 274e312
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 15 deletions.
37 changes: 22 additions & 15 deletions src/com/sun/jna/Pointer.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
*/
package com.sun.jna;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Array;
import java.nio.Buffer;
import java.nio.ByteBuffer;
Expand Down Expand Up @@ -1271,22 +1273,27 @@ public void setString(long offset, String value, String encoding) {

/** Dump memory for debugging purposes. */
public String dump(long offset, int size) {
String LS = System.getProperty("line.separator");
String contents = "memory dump" + LS;
final int BYTES_PER_ROW = 4;
byte[] buf = getByteArray(offset, size);
for (int i=0;i < buf.length;i++) {
if ((i % BYTES_PER_ROW) == 0) contents += "[";
if (buf[i] >=0 && buf[i] < 16)
contents += "0";
contents += Integer.toHexString(buf[i] & 0xFF);
if ((i % BYTES_PER_ROW) == BYTES_PER_ROW-1 && i < buf.length-1)
contents += "]" + LS;
}
if (!contents.endsWith("]" + LS)) {
contents += "]" + LS;
}
return contents;
final String TITLE = "memory dump";
// estimate initial size assuming a 2 char line separator
StringWriter sw = new StringWriter(TITLE.length() + 2 + size * 2 + (size / BYTES_PER_ROW * 4));
PrintWriter out = new PrintWriter(sw);
out.println(TITLE);
// byte[] buf = getByteArray(offset, size);
for (int i=0;i < size;i++) {
// byte b = buf[i];
byte b = getByte(offset + i);
if ((i % BYTES_PER_ROW) == 0) out.print("[");
if (b >=0 && b < 16)
out.print("0");
out.print(Integer.toHexString(b & 0xFF));
if ((i % BYTES_PER_ROW) == BYTES_PER_ROW-1 && i < size-1)
out.println("]");
}
if (sw.getBuffer().charAt(sw.getBuffer().length() - 2) != ']') {
out.println("]");
}
return sw.toString();
}

public String toString() {
Expand Down
19 changes: 19 additions & 0 deletions test/com/sun/jna/MemoryTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,25 @@ public void testAvoidGCWithExtantBuffer() throws Exception {
assertNull("Memory not GC'd after buffer GC'd\n", ref.get());
}

public void testDump() {
// test with 15 bytes so last line has less than 4 bytes
int n = 15;

Memory m = new Memory(n);

for (int i = 0; i < n; i++) {
m.setByte(i, (byte) i);
}

String ls = System.getProperty("line.separator");

assertEquals("memory dump" + ls +
"[00010203]" + ls +
"[04050607]" + ls +
"[08090a0b]" + ls +
"[0c0d0e]" + ls, m.dump());
}

public static void main(String[] args) {
junit.textui.TestRunner.run(MemoryTest.class);
}
Expand Down

0 comments on commit 274e312

Please sign in to comment.