8259634: MemorySegment::asByteBuffer does not respect spatial bounds

Reviewed-by: alanb, chegar
This commit is contained in:
Maurizio Cimadamore 2021-01-12 17:09:05 +00:00
parent 8a81cf154f
commit b03880e33b
2 changed files with 30 additions and 2 deletions

View File

@ -793,7 +793,7 @@ public abstract class Buffer {
@Override
public ByteBuffer newHeapByteBuffer(byte[] hb, int offset, int capacity, MemorySegmentProxy segment) {
return new HeapByteBuffer(hb, offset, capacity, segment);
return new HeapByteBuffer(hb, -1, 0, capacity, capacity, offset, segment);
}
@Override

View File

@ -64,6 +64,7 @@ import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
@ -71,6 +72,7 @@ import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;
import jdk.internal.foreign.HeapMemorySegmentImpl;
@ -635,7 +637,8 @@ public class TestByteBuffer {
}
}
public void testIOOnClosedConfinedSegment() throws IOException {
@Test
public void testIOOnConfinedSegment() throws IOException {
File tmp = File.createTempFile("tmp", "txt");
tmp.deleteOnExit();
try (FileChannel channel = FileChannel.open(tmp.toPath(), StandardOpenOption.WRITE)) {
@ -648,6 +651,31 @@ public class TestByteBuffer {
}
}
@Test(dataProvider="segments")
public void buffersAndArraysFromSlices(Supplier<MemorySegment> segmentSupplier) {
try (MemorySegment segment = segmentSupplier.get()) {
int newSize = 8;
var slice = segment.asSlice(4, newSize);
var bytes = slice.toByteArray();
assertEquals(newSize, bytes.length);
var buffer = slice.asByteBuffer();
// Fails for heap segments, but passes for native segments:
assertEquals(0, buffer.position());
assertEquals(newSize, buffer.limit());
assertEquals(newSize, buffer.capacity());
}
}
@DataProvider(name = "segments")
public static Object[][] segments() throws Throwable {
return new Object[][] {
{ (Supplier<MemorySegment>) () -> MemorySegment.allocateNative(16) },
{ (Supplier<MemorySegment>) () -> MemorySegment.ofArray(new byte[16]) }
};
}
@DataProvider(name = "bufferOps")
public static Object[][] bufferOps() throws Throwable {
List<Object[]> args = new ArrayList<>();