Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8370882

MemorySegment support for writing strings without null terminators

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Unresolved
    • Icon: P4 P4
    • None
    • None
    • core-libs

      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 in JDK-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.)

            Unassigned Unassigned
            cushon Liam Miller-Cushon
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated: