Allocating an Array segment of a primitive type with 1 initialized element.
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Mon Jul 10 09:10:58 UTC 2023
Note that there's also SegmentAllocator.allocate(JAVA_LONG, 10) which
does what you want (e.g, one-element with value 10).
But yes, there is some overlapping between these methods. Echoing some
comments in this thread we could:
* come up with a new name for the "initializing" variants (e.g.
allocateAndSet, allocateOf, allocateFrom)
* remove duplication between one-element and many-elements
initialization methods (e.g. use varargs for all)
Maurizio
On 05/07/2023 20:24, Philip Race wrote:
> MemorySegment.allocateArray() has these variants
>
> default MemorySegment allocateArray(MemoryLayout elementLayout, long
> count)
> and
> default MemorySegment allocateArray(ValueLayout.OfLong elementLayout,
> long... elements)
> default MemorySegment allocateArray(ValueLayout.OfInt elementLayout,
> long... elements)
> (etc)
> and in all cases the first arg is a MemoryLayout
>
> eg it could be this
> ValueLayout.OfLong JAVA_LONG;
> where
> ValueLayout.OfLong extends ValueLayout
> ValueLayout extends MemoryLayout
>
> So what happens if you want to allocate an array of length 1 with
> value 10 ?
>
> You'll try something like
> MemorySegment.allocateArray(JAVA_LONG, 10);
> but that doesn't get you what you expected
>
> import java.lang.foreign.*;
> import static java.lang.foreign.ValueLayout.*;
>
> public class AllocArray {
>
> public static void main(String[] args) {
> try (Arena arena = Arena.ofConfined()) {
> MemorySegment lseg1 = arena.allocateArray(JAVA_LONG, 10L);
> MemorySegment lseg2 = arena.allocateArray(JAVA_LONG, 10L, 20L);
> MemorySegment iseg1 = arena.allocateArray(JAVA_INT, 10);
> MemorySegment iseg2 = arena.allocateArray(JAVA_INT, 10, 20);
> System.out.println("long seg1 size = " + lseg1.byteSize());
> System.out.println("long seg2 size = " + lseg2.byteSize());
> System.out.println("int seg1 size = " + iseg1.byteSize());
> System.out.println("int seg2 size = " + iseg2.byteSize());
> } catch (Throwable t) {
> t.printStackTrace();
> }
> }
> }
>
> % javac --enable-preview -source 22 AllocArray.java
> % java --enable-preview AllocArray
> long seg1 size = 80
> long seg2 size = 16
> int seg1 size = 40
> int seg2 size = 8
>
>
> I get that allocating an array of length 1 is not common but it still
> seems a bit off, and
> I'm surprised the compiler didn't prefer the more specific case.
> Unless I am missing something it seems to me that for the sake of
> clarity that
> the first version should be renamed allocateArrayOfLength(), or
> the second renamed to something like allocateArrayFromValues()
>
>
More information about the panama-dev
mailing list