Skip to content

Commit

Permalink
8316190: Improve MemorySegment::toString
Browse files Browse the repository at this point in the history
Reviewed-by: rriggs
  • Loading branch information
minborg committed Sep 15, 2023
1 parent 783e44d commit 8dc2d92
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,11 @@ public int characteristics() {

@Override
public String toString() {
return "MemorySegment{ heapBase: " + heapBase() + " address: 0x" + Long.toHexString(address()) + " byteSize: " + length + " }";
return "MemorySegment{ " +
heapBase().map(hb -> "heapBase: " + hb + ", ").orElse("") +
"address: " + Utils.toHexString(address()) +
", byteSize: " + length +
" }";
}

@Override
Expand Down
5 changes: 5 additions & 0 deletions src/java.base/share/classes/jdk/internal/foreign/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -273,4 +273,9 @@ public static <L extends MemoryLayout> L wrapOverflow(Supplier<L> layoutSupplier
public static boolean containsNullChars(String s) {
return s.indexOf('\u0000') >= 0;
}

public static String toHexString(long value) {
return "0x" + Long.toHexString(value);
}

}
17 changes: 16 additions & 1 deletion test/jdk/java/foreign/TestSegments.java
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,21 @@ public void testIsAccessibleBy(Arena arena, boolean isConfined) {
assertTrue(segment.isAccessibleBy(new Thread()) != isConfined);
}

@Test(dataProvider = "segmentFactories")
public void testToString(Supplier<MemorySegment> segmentSupplier) {
var segment = segmentSupplier.get();
String s = segment.toString();
assertTrue(s.startsWith("MemorySegment{"));
assertTrue(s.contains("address: 0x"));
assertTrue(s.contains("byteSize: "));
if (segment.heapBase().isPresent()) {
assertTrue(s.contains("heapBase: ["));
} else {
assertFalse(s.contains("heapBase: "));
}
assertFalse(s.contains("Optional"));
}

@DataProvider(name = "segmentFactories")
public Object[][] segmentFactories() {
List<Supplier<MemorySegment>> l = List.of(
Expand All @@ -233,7 +248,7 @@ public Object[][] segmentFactories() {
() -> MemorySegment.ofArray(new double[] { 1d, 2d, 3d, 4d} ),
() -> MemorySegment.ofArray(new float[] { 1.0f, 2.0f, 3.0f, 4.0f }),
() -> MemorySegment.ofArray(new int[] { 1, 2, 3, 4 }),
() -> MemorySegment.ofArray(new long[] { 1l, 2l, 3l, 4l } ),
() -> MemorySegment.ofArray(new long[] { 1L, 2L, 3L, 4L } ),
() -> MemorySegment.ofArray(new short[] { 1, 2, 3, 4 } ),
() -> Arena.ofAuto().allocate(4L, 1),
() -> Arena.ofAuto().allocate(4L, 8),
Expand Down

1 comment on commit 8dc2d92

@openjdk-notifier
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.