Span vs. MemorySegment

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Thu Aug 8 21:07:40 UTC 2019


Thanks for the analysis. The info is correct - Spans are more sugary, 
segments are more low-level - but I think a bit more powerful where 
layouts meet dereference varhandles.

As for copy operations, we do have them - just not on MemorySegment - 
but on MemoryAddress:

http://cr.openjdk.java.net/~mcimadamore/panama/memaccess_javadoc/jdk/incubator/foreign/MemoryAddress.html#copy(jdk.incubator.foreign.MemoryAddress,jdk.incubator.foreign.MemoryAddress,long)

As for type-ful ness, it was a deliberate choice to make segments and 
addresses type-less, as when you work with heterogeneous buffers, having 
sticky type info is a downside rather than a plus - that was the lesson 
learned from the Pointer API. So, if you want low-level, ByteBuffer-like 
kind of access, type-less is the way to go IMHO (and, you can build 
typeful abstractions on top).

Maurizio

On 08/08/2019 20:17, John Rose wrote:
> Here’s a quick comparison of the Microsoft “Span<T>” type [1] vs. the Panama MemorySegment type [2].
>
> [1]: https://docs.microsoft.com/en-us/dotnet/api/system.span-1?view=netstandard-2.1
>
> [2]: http://cr.openjdk.java.net/~mcimadamore/panama/memaccess_javadoc/jdk/incubator/foreign/MemorySegment.html
>
> Corrections invited.
>
> Differences:
>
> MS is untyped, and sized in bytes, like a ByteBuffer.  Span<T> is a sequence of T, like an X-Buffer.
>
> Span has a richer set of logical operations for searching and comparison, such as ToString, Equals, StartsWith.  In this it is like CharSequence or String or the jul.Arrays methods.
>
> Span has more sugary tie-ins to arrays and array-like notations, such as for-loop integration, operator[], and implicit conversion from T[] to Span<T>.
>
> MS uses a dynamic liveness check to enforce temporal confinement (avoiding use-after-free); this requires special optimizer logic but no special language rules.
> Span uses special language rules to statically confine span access to the defining stack frame and its callees.  These rules also interact with the “unsafe” status of code blocks.
>
> Span supports low-level copy operations, CopyTo and TryCopyTo.  This seems like a good option for MS as well.
>
> Similarities:
>
> Both are contiguous.  There is no virtualized scatter/gather; you can only “slice” a larger sequence, not combine two smaller ones.
>
> Both are designed to support provably safe access to underlying storage, via spatial and temporal confinement checks.
>
> Both support (spatial) bounds checking as a runtime check throwing some kind of IndexOutOfRangeException.
>
> Temporal and spatial bounds checking can be turned off with sufficient privilege.  (The details differ between MS and Span.)
>
> Both support read-only views.
>
> Both are designed to support divide-and-conquer multiprocessing algorithms.
>


More information about the panama-dev mailing list