This change generalizes `String#bytesCompatible` and `String#copyToSegmentRaw` to support UTF-16, see this comment in the existing code:
https://github.com/openjdk/jdk/blob/479d43dc63674e9d7e6b543a899e76e070a632fc/src/java.base/share/classes/java/lang/String.java#L2135-L2137 Those APIs are used to avoid copies in `SegmentAllocator#allocateFrom` and `MemorySegment#copy` when `String` data is compatible with the destination charset. This is possible for UTF-16 when the platform and target charset endianness match (UTF-16LE on little endian platforms, or UTF-16BE on big endian) and when the UTF-16 string contains no unpaired surrogates (which require copying the data and handling replacement characters). * Test coverage has been added in `test/jdk/java/foreign/TestStringEncoding.java`, and existing coverage was generalized to exercise multi-byte charsets like UTF-16. * UTF-16 constants were added in `sun.nio.cs` to allow reference comparisons of charsets, similar to existing handling of other charsets. * An allocation-free fast path was added to `encodedLength` for UTF-16. (This is partly related to [this panama-dev@ thread](https://mail.openjdk.org/archives/list/[email protected]/thread/YSPX3TBXZTZEFZNXWDYOZCWLUQPC62P6/). UTF-16 is a less widely used charset for data outside the JVM, which is why the existing `bytesCompatible` / `copyToSegmentRaw` fast paths focused on UTF-8. Having fast paths for UTF-16 is interesting inside the JVM because of UTF-16's treatment in the String APIs, it's the only option for zero-copy String operations on non-latin1 Strings.) --------- - [x] I confirm that I make this contribution in accordance with the [OpenJDK Interim AI Policy](https://openjdk.org/legal/ai). ------------- Commit messages: - 8390026: Add UTF-16 fast paths to avoid copies in String Changes: https://git.openjdk.org/jdk/pull/32268/files Webrev: https://webrevs.openjdk.org/?repo=jdk&pr=32268&range=00 Issue: https://bugs.openjdk.org/browse/JDK-8390026 Stats: 181 lines in 10 files changed: 127 ins; 12 del; 42 mod Patch: https://git.openjdk.org/jdk/pull/32268.diff Fetch: git fetch https://git.openjdk.org/jdk.git pull/32268/head:pull/32268 PR: https://git.openjdk.org/jdk/pull/32268
