javajava-ffm

Is there a way to get the logical length of a MemorySegment without doing byte arithmetic?


One of the great benefits of the new FFM API in Java 22 is the MemoryLayout class, which obviates the need for nearly all byte arithmetic. However, there is one remaining place where I can't seem to avoid it: getting the logical size of an allocated MemorySegment. As far as I can tell, the only MemorySegment API returning the amount of memory allocated is the byteSize operator, which does not take a MemoryLayout or ValueLayout instance. So, if I have this code:

Arena allocator = Arena.ofAuto();
ValueLayout.OfLong layout = ValueLayout.JAVA_LONG;
MemorySegment segment = allocator.allocate(layout, 100L);

Then the only way I can get the number of longs allocated in the segment is by:

segment.byteSize() / layout.byteSize()

which is a bit unsatisfying given how thoroughly effective MemoryLayout is at obviating this sort of byte arithmetic everywhere else. Is there no other way?


Solution

  • You could create a stream of elements, and then call count():

    segment.elements(layout).count()
    

    Note that since the size of the stream is known, count() is short-cutting, and none of the elements of the stream will actually be evaluated.