RFR: 8333843: Provide methods on MemorySegment to read strings with known lengths
Maurizio Cimadamore
mcimadamore at openjdk.org
Wed Aug 28 10:00:19 UTC 2024
On Wed, 28 Aug 2024 09:52:10 GMT, Maurizio Cimadamore <mcimadamore at openjdk.org> wrote:
>> This PR proposes to add a new overload to `MemorySegment::getString` whereby it is possible to pass in a known byte length of the content in a segment that should be converted to a String. This is useful in case one already knows the byte length and thereby does not need to scan for a null terminator.
>
> src/java.base/share/classes/java/lang/foreign/MemorySegment.java line 1316:
>
>> 1314:
>> 1315: /**
>> 1316: * Reads a string using the given byte length from this segment at the given offset,
>
> What happens is there's a null terminator before `length` ? Seems like we're just copying it? IMHO, this is the tension with this API.
Overall, I guess I'm not overly convinced that it's worth adding a method like this for:
byte[] bytes = new byte[len];
MemorySegment.copy(segment, JAVA_BYTE, offset, bytes, 0, len);
return new String(bytes, charset);
e.g. the API provides string shortcuts for the common case. The more convoluted case can still be achieve via `copy`. Is there anything I'm missing here?
-------------
PR Review Comment: https://git.openjdk.org/jdk/pull/20725#discussion_r1734367933
More information about the core-libs-dev
mailing list