- 
    Enhancement 
- 
    Resolution: Unresolved
- 
     P4 P4
- 
    None
- 
    None
                    MemorySegment#setString includes a null terminator in the output.
For use-cases that don't want a null terminator, it is possible to express that by calling getBytes, e.g.
byte[] bytes = string.getBytes(charset);
MemorySegment.copy(bytes, 0, segment, JAVA_BYTE, 0, bytes.length);
However that misses out on the fast path in setString that avoids the copy:
https://github.com/openjdk/jdk/blob/2c07214d7c075da5dd4a4e872aef29f58cef2bae/src/java.base/share/classes/jdk/internal/foreign/StringSupport.java#L353-L355
If there is extra space in the output buffer it's possible to just use setString and the overwrite the null terminator, but that doesn't work if the output buffer is exactly sized.
One straw person API design would be something like `setString(long offset, int bytesLength, String str)`, but as discussed in the comments inJDK-8333843 passing an explicit length for writes could be a footgun.
Another potential approach would be to not have general support for an explicit length (or writing a subset of the encoded bytes), and instead have an explicit choice about whether or not a null terminator is included, for example `setStringWithoutNullTerminator(long offset, String str)`. (I'm not advocating for that specific name, just trying to explain the idea.)
For use-cases that don't want a null terminator, it is possible to express that by calling getBytes, e.g.
byte[] bytes = string.getBytes(charset);
MemorySegment.copy(bytes, 0, segment, JAVA_BYTE, 0, bytes.length);
However that misses out on the fast path in setString that avoids the copy:
https://github.com/openjdk/jdk/blob/2c07214d7c075da5dd4a4e872aef29f58cef2bae/src/java.base/share/classes/jdk/internal/foreign/StringSupport.java#L353-L355
If there is extra space in the output buffer it's possible to just use setString and the overwrite the null terminator, but that doesn't work if the output buffer is exactly sized.
One straw person API design would be something like `setString(long offset, int bytesLength, String str)`, but as discussed in the comments in
Another potential approach would be to not have general support for an explicit length (or writing a subset of the encoded bytes), and instead have an explicit choice about whether or not a null terminator is included, for example `setStringWithoutNullTerminator(long offset, String str)`. (I'm not advocating for that specific name, just trying to explain the idea.)
- relates to
- 
                    JDK-8333843 Provide guidelines on MemorySegment to read strings with known lengths -           
- Resolved
 
-         
- 
                    JDK-8369564 Provide a MemorySegment API to read strings with known lengths -           
- New
 
-