Using Layouts on heap - JDK18

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Fri Jun 3 17:06:20 UTC 2022


Hi Lee,
in terms of heap allocation, how is your "allocate" different from this:

```
MemorySegment segment = MemorySegment.ofArray(new byte[layout.byteSize()]);
```

The above doesn't do any copy, it just creates a segment view over the 
array. (note that the carrier type used is important here - e.g. a 
segment that wraps a byte[] has different properties when it comes to 
alignment, than a segment that wraps long[]).

But then you bring up the slice method, which makes me think that, 
perhaps you aren't after allocation at all - you have an existing 
segment and you want to slice it, using a layout.

I think the slicing API overload you describe is a nice one (and one 
that I found myself wanting at times too). Is "layout-oriented" slicing 
the main use case you are referring to here?

If we do this the "right" way, the slicing method would have to take 
into account the required alignment of the provided layout and either:

* throw if the slice is not compatible with the layout alignment 
constraints, or
* align the slice

Of these I would probably prefer the former, because it's "less magic".

Maurizio

On 03/06/2022 17:56, leerho wrote:
> Hi,
> It is straightforward to create a native MemorySegment governed by a
> layout, but I can't see a way to create a heap segment governed by a layout
> (without a copy).  We need to be able to read and write to structs on-heap
> as well as off-heap.  Being able to overlay a Layout on a segment derived
> from a ByteBuffer or from a mapped file would also be useful. Perhaps these
> could be implemented via a slice?
>
> What I would like to see is something like:
>
> *MemorySegment *allocate*(MemoryLayout layout);  //base resource is byte[]*
>
> OR
>
>> *MemorySegment *asSlice*(long offset, MemoryLayout layout)*
>
> The second could be applied to any base resource, not just off-heap.
>
> Am I missing something?
>
> Cheers,
> Lee.


More information about the panama-dev mailing list