RFR: 8369564: Provide a MemorySegment API to read strings with known lengths [v12]
Maurizio Cimadamore
mcimadamore at openjdk.org
Mon Nov 24 15:10:00 UTC 2025
On Mon, 24 Nov 2025 09:45:45 GMT, Liam Miller-Cushon <cushon at openjdk.org> wrote:
> I have tentatively updated the new `MemorySegment#copy` to return the number of bytes that were written.
I think I understand the use case. E.g. say a client wants to write a bunch of variable length string to a segment, where the string is prefixed by length (a la protobuf). So what they can do is:
* write length at offset S
* write string at offset S + 4, this writes N bytes
* write next length at offset S + 4 + N
* write next string at offset S + 4 + N + 4, this writes M bytes
* ...
Effectively, this unifies `copy` with `setString` -- in the sense that now `setString` is just a string-based copy + a terminator write (at the correct offset) -- the size of the terminator is charset dependent.
I think overall it makes sense -- I believe @JornVernee proposed something similar in the past. It's true it's inconsistent with other `copy` method and, in hindsight, it would have perhaps been useful to always return a length (given that in other cases length is expressed in "elements" -- either array elements, or elements expressed in a given layout) -- although in the other cases the copy length can usually be computed using a shift operation.
-------------
PR Comment: https://git.openjdk.org/jdk/pull/28043#issuecomment-3571253487
More information about the core-libs-dev
mailing list