/*
 * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package java.lang;

import java.util.Arrays;
import java.util.Locale;
import java.util.Objects;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import jdk.internal.lang.CaseFolding;
import jdk.internal.util.ArraysSupport;
import jdk.internal.vm.annotation.IntrinsicCandidate;

import static java.lang.String.LATIN1;
import static java.lang.String.UTF16;

/**
 * Latin-1 string operations.
 * <p>
 * Unless stated otherwise, all methods assume that
 * <ul>
 * <li>{@code byte[]} arguments denote a Latin-1 string byte array
 * <li>indices, offsets, and lengths (typically of type {@code int}) are in
 * number of characters, i.e., the number of {@code byte}s/{@code char}s for
 * Latin-1 strings, and the number of <a href="Character.html#unicode">Unicode
 * code units</a> for UTF-16 strings
 * </ul>
 */
final class StringLatin1 {
    static char charAt(byte[] value, int index) {
        String.checkIndex(index, value.length);
        return (char)(value[index] & 0xff);
    }

    static boolean canEncode(char cp) {
        return cp <= 0xff;
    }

    static boolean canEncode(int cp) {
        return cp >=0 && cp <= 0xff;
    }

    static byte coderFromChar(char cp) {
        return (byte)((0xff - cp) >>> (Integer.SIZE - 1));
    }

    static int length(byte[] value) {
        return value.length;
    }

    static char[] toChars(byte[] value) {
        char[] dst = new char[value.length];
        inflate(value, 0, dst, 0, value.length);
        return dst;
    }

    static byte[] inflate(byte[] value, int off, int len) {
        byte[] ret = StringUTF16.newBytesFor(len);
        inflate(value, off, ret, 0, len);
        return ret;
    }

    static void getChars(byte[] value, int srcBegin, int srcEnd, char[] dst, int dstBegin) {
        inflate(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
    }

    static void getBytes(byte[] value, int srcBegin, int srcEnd, byte[] dst, int dstBegin) {
        System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
    }

    /**
     * {@return {@code true} if provided byte arrays contain identical content; {@code false} otherwise}.
     *
     * @param value a byte array
     * @param other a byte array
     *
     * @throws NullPointerException if {@code value} or {@code other} is null
     */
    static boolean equals(byte[] value, byte[] other) {
        Objects.requireNonNull(value);
        Objects.requireNonNull(other);
        return equals0(value, other);
    }

    // vmIntrinsics::_equalsL
    @IntrinsicCandidate
    private static boolean equals0(byte[] value, byte[] other) {
        if (value.length == other.length) {
            for (int i = 0; i < value.length; i++) {
                if (value[i] != other[i]) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    /**
     * Lexicographically compares two Latin-1 strings as specified in
     * {@link String#compareTo(String) String::compareTo}.
     *
     * @param value a Latin-1 string byte array
     * @param other a Latin-1 string byte array
     *
     * @return {@code 0} if {@code value} is equal to {@code other}, a value
     * less than {@code 0} if {@code value} is lexicographically less than
     * {@code other}; a value greater than {@code 0} otherwise.
     *
     * @throws NullPointerException if {@code value} or {@code other} is null
     */
    static int compareTo(byte[] value, byte[] other) {
        Objects.requireNonNull(value);
        Objects.requireNonNull(other);
        return compareTo0(value, other);
    }

    // vmIntrinsics::_compareToL
    @IntrinsicCandidate
    private static int compareTo0(byte[] value, byte[] other) {
        return compareTo(value, other, value.length, other.length);
    }

    /**
     * Lexicographically compares two Latin-1 string prefixes as specified in
     * {@link String#compareTo(String) String::compareTo}.
     *
     * @param value a Latin-1 string byte array
     * @param other a Latin-1 string byte array
     * @param len1 the number of characters in {@code value} to compare
     * @param len2 the number of characters in {@code other} to compare
     *
     * @return {@code 0} if the {@code value} prefix is equal to the
     * {@code other} prefix, a value less than {@code 0} if the {@code value}
     * prefix is lexicographically less than the {@code other} prefix; a
     * value greater than {@code 0} otherwise.
     *
     * @throws NullPointerException if {@code value} or {@code other} is null
     * @throws StringIndexOutOfBoundsException if the sub-ranges are out of bounds
     */
    static int compareTo(byte[] value, byte[] other, int len1, int len2) {
        Objects.requireNonNull(value);
        Objects.requireNonNull(other);
        String.checkOffset(len1, length(value));
        String.checkOffset(len2, length(other));
        int lim = Math.min(len1, len2);
        int k = ArraysSupport.mismatch(value, other, lim);
        return (k < 0) ? len1 - len2 : getChar(value, k) - getChar(other, k);
    }

    /**
     * Lexicographically compares a Latin-1 string to a UTF-16 string as
     * specified in {@link String#compareTo(String) String::compareTo}.
     *
     * @param value a Latin-1 string byte array
     * @param other a UTF-16 string byte array
     *
     * @return {@code 0} if the {@code value} is equal to the {@code other}, a
     * value less than {@code 0} if the {@code value} is lexicographically less
     * than the {@code other}; a value greater than {@code 0} otherwise.
     *
     * @throws NullPointerException if {@code value} or {@code other} is null
     */
    static int compareToUTF16(byte[] value, byte[] other) {
        Objects.requireNonNull(value);
        Objects.requireNonNull(other);
        return compareToUTF16_0(value, other);
    }

    // vmIntrinsics::_compareToLU
    @IntrinsicCandidate
    private static int compareToUTF16_0(byte[] value, byte[] other) {
        int len1 = length(value);
        int len2 = StringUTF16.length(other);
        return compareToUTF16Values(value, other, len1, len2);
    }

    /**
     * Lexicographically compares a Latin-1 string prefix to a UTF-16 one as
     * specified in {@link String#compareTo(String) String::compareTo}.
     *
     * @param value a Latin-1 string byte array
     * @param other a UTF-16 string byte array
     * @param len1 the number of characters in {@code value} to compare
     * @param len2 the number of characters in {@code other} to compare
     *
     * @throws NullPointerException if {@code value} or {@code other} is null
     * @throws StringIndexOutOfBoundsException if the sub-ranges are out of bounds
     */
    static int compareToUTF16(byte[] value, byte[] other, int len1, int len2) {
        Objects.requireNonNull(value);
        Objects.requireNonNull(other);
        String.checkOffset(len1, length(value));
        String.checkOffset(len2, StringUTF16.length(other));
        return compareToUTF16Values(value, other, len1, len2);
    }

    private static int compareToUTF16Values(byte[] value, byte[] other, int len1, int len2) {
        int lim = Math.min(len1, len2);
        for (int k = 0; k < lim; k++) {
            char c1 = getChar(value, k);
            char c2 = StringUTF16.getChar(other, k);
            if (c1 != c2) {
                return c1 - c2;
            }
        }
        return len1 - len2;
    }

    /**
     * Case-insensitive {@link #compareTo(byte[], byte[]) compareTo}.
     */
    static int compareToCI(byte[] value, byte[] other) {
        int len1 = value.length;    // Implicit null check on `value`
        int len2 = other.length;    // Implicit null check on `other`
        int lim = Math.min(len1, len2);
        for (int k = 0; k < lim; k++) {
            if (value[k] != other[k]) {
                char c1 = (char) CharacterDataLatin1.instance.toUpperCase(getChar(value, k));
                char c2 = (char) CharacterDataLatin1.instance.toUpperCase(getChar(other, k));
                if (c1 != c2) {
                    c1 = Character.toLowerCase(c1);
                    c2 = Character.toLowerCase(c2);
                    if (c1 != c2) {
                        return c1 - c2;
                    }
                }
            }
        }
        return len1 - len2;
    }

    /**
     * Case-insensitive {@link #compareToUTF16(byte[], byte[]) compareToUTF16}.
     */
    static int compareToCI_UTF16(byte[] value, byte[] other) {
        Objects.requireNonNull(value);
        Objects.requireNonNull(other);
        int len1 = length(value);
        int len2 = StringUTF16.length(other);
        int lim = Math.min(len1, len2);
        for (int k = 0; k < lim; k++) {
            char c1 = getChar(value, k);
            char c2 = StringUTF16.getChar(other, k);
            if (c1 != c2) {
                c1 = (char) CharacterDataLatin1.instance.toUpperCase(c1);
                c2 = Character.toUpperCase(c2);
                if (c1 != c2) {
                    c1 = Character.toLowerCase(c1);
                    c2 = Character.toLowerCase(c2);
                    if (c1 != c2) {
                        return c1 - c2;
                    }
                }
            }
        }
        return len1 - len2;
    }

    private static int compareToFC0(byte[] value, int off, int last, byte[] other, int ooff, int olast) {
        int k1 = off, k2 = ooff;
        boolean lo1 = false, lo2 = false;  // true if we have a leftover 's' from u+00df -> ss
        while ((k1 < last || lo1) && (k2 < olast || lo2)) {
            int c1, c2;
            if (lo1) {
                c1 = 0x73; // leftover 's'
                lo1 = false;
            } else {
                c1 = getChar(value, k1++);
                if (c1 == 0xdf) {
                    c1 = 0x73;
                    lo1 = true;
                }
            }
            if (lo2) {
                c2 = 0x73; // 's'
                lo2 = false;
            } else {
                c2 = getChar(other, k2++);
                if (c2 == 0xdf) {
                    c2 = 0x73;
                    lo2 = true;
                }
            }
            if (!CharacterDataLatin1.equalsIgnoreCase((byte)c1, (byte)c2)) {
                return Character.toLowerCase(c1) - Character.toLowerCase(c2);
            }
        }
        if (k1 < last || lo1) {
            return 1;
        }
        if (k2 < olast || lo2) {
            return -1;
        }
        return 0;
    }

    static int compareToFC(byte[] value, byte[] other) {
        int len = value.length;
        int olen = other.length;
        int lim = Math.min(len, olen);
        for (int k = 0; k < lim; k++) {
            byte b1 = value[k];
            byte b2 = other[k];
            if (!CharacterDataLatin1.equalsIgnoreCase(b1, b2)) {
                int c1 = b1 & 0xff;
                int c2 = b2 & 0xff;
                if (c1 == 0xdf || c2 == 0xdf) {  // 0xdf is the only 1:M in latin1 range
                    return compareToFC0(value, k, len, other, k, olen);
                }
                return Character.toLowerCase(c1) - Character.toLowerCase(c2);
            }
        }
        return len - olen;
    }

    private static int compareToFC0_UTF16(byte[] value, int off, int last, byte[] other, int ooff, int olast) {
        int f1 = 0, f2 = 0;
        int k1 = off, k2 = ooff;
        while ((k1 < last || f1 != 0) && (k2 < olast || f2 != 0)) {
            int c1, c2;
            if (f1 != 0) {
                c1 = (f1 & 0xffff); f1 >>>= 16;
            } else {
                c1 = getChar(value, k1++);
                var f = CaseFolding.fold(c1);
                if (CaseFolding.isSingleCodePoint(f)) {
                    c1 = (int)(f & 0xfffff);
                } else {
                    c1 = (int)f & 0xffff;
                    f1 = (int)(f >>> 16);
                }
            }
            if (f2 != 0) {
                c2 = f2 & 0xffff; f2 >>>= 16;
            } else {
                c2 = StringUTF16.codePointAt(other, k2, olast, true);
                k2 += Character.charCount(c2);
                var f = CaseFolding.fold(c2);
                if (CaseFolding.isSingleCodePoint(f)) {
                    c2 = (int)(f & 0xfffff);
                } else {
                    c2 = (int)(f & 0xffff);
                    f2 = (int)(f >>> 16);
                }
            }
            if (c1 != c2) {
                return c1 - c2;
            }
        }
        if (k1 < last || f1 != 0) {
            return 1;
        }
        if (k2 < olast || f2 != 0) {
            return -1;
        }
        return 0;
    }

    // latin1 vs utf16
    static int compareToFC_UTF16(byte[] value, byte[] other) {
        int last = length(value);
        int olast = StringUTF16.length(other);
        int lim = Math.min(last, olast);
        for (int k = 0; k < lim; k++) {
            int cp1 = getChar(value, k);
            int cp2 = StringUTF16.codePointAt(other, k, olast, true);
            if (cp1 != cp2) {
                long cf1 = CaseFolding.fold(cp1);
                long cf2 = CaseFolding.fold(cp2);
                if (cf1 != cf2) {
                    if (!CaseFolding.isSingleCodePoint(cf1) || !CaseFolding.isSingleCodePoint(cf2)) {
                        return compareToFC0_UTF16(value, k, last, other, k, olast);
                    }
                    return (int)(cf1 - cf2);
                }
            }
        }
        return last - olast;
    }

    static int hashCode(byte[] value) {
        return ArraysSupport.hashCodeOfUnsigned(value, 0, value.length, 0);
    }

    /**
     * Finds the index of the first character matching the provided one in the
     * given Latin-1 string byte array sub-range. {@code -1} is returned if the
     * provided character cannot be encoded in Latin-1, or cannot be found in
     * the target string sub-range.
     *
     * @param value a Latin-1 string byte array to search in
     * @param ch a character to search for
     * @param fromIndex the index (inclusive) of the first character in the sub-range
     * @param toIndex the index (exclusive) of the last character in the sub-range
     *
     * @return the index of the first character matching the provided one in the
     * given target string sub-range; {@code -1} otherwise
     *
     * @throws NullPointerException if {@code value} is null
     * @throws StringIndexOutOfBoundsException if the sub-range is out of bounds
     */
    static int indexOf(byte[] value, int ch, int fromIndex, int toIndex) {
        String.checkBoundsBeginEnd(fromIndex, toIndex, value.length);   // Implicit null check on `value`
        if (!canEncode(ch)) {
            return -1;
        }
        return indexOfChar0(value, ch, fromIndex, toIndex);
    }

    // vmIntrinsics::_indexOfL_char
    @IntrinsicCandidate
    private static int indexOfChar0(byte[] value, int ch, int fromIndex, int max) {
        byte c = (byte)ch;
        for (int i = fromIndex; i < max; i++) {
            if (value[i] == c) {
               return i;
            }
        }
        return -1;
    }

    /**
     * Searches for the first occurrence of {@code str} in {@code value}, and,
     * if found, returns the index of the first character of the matching
     * {@code value} sub-range; {@code -1} otherwise.
     *
     * @param value a Latin-1 string byte array to search in
     * @param str a Latin-1 string byte array to search for
     *
     * @return the index of the first character of the matching {@code value}
     * sub-range if a match is found; {@code -1} otherwise
     *
     * @throws NullPointerException if {@code value} or {@code str} is null
     */
    static int indexOf(byte[] value, byte[] str) {
        Objects.requireNonNull(value);
        Objects.requireNonNull(str);
        return indexOf0(value, str);
    }

    // vmIntrinsics::_indexOfL
    @IntrinsicCandidate
    private static int indexOf0(byte[] value, byte[] str) {
        return indexOf0(value, value.length, str, str.length, 0);
    }

    /**
     * Searches for the first occurrence of the given {@code str} sub-range in
     * the given {@code value} sub-range, and, if found, returns the index of
     * the first character of the matching {@code value} sub-range; {@code -1}
     * otherwise.
     *
     * @param value a Latin-1 string byte array to search in
     * @param valueToIndex the index (exclusive) of the last character in {@code value}
     * @param str a Latin-1 string byte array to search for
     * @param strToIndex the index (exclusive) of the last character in {@code str}
     * @param valueFromIndex the index (inclusive) of the first character in {@code value}
     *
     * @return the index of the first character of the matching {@code value}
     * sub-range if a match is found; {@code -1} otherwise
     *
     * @throws NullPointerException if {@code value} or {@code str} is null
     * @throws StringIndexOutOfBoundsException if the sub-ranges are out of bounds
     */
    static int indexOf(byte[] value, int valueToIndex, byte[] str, int strToIndex, int valueFromIndex) {
        String.checkBoundsBeginEnd(valueFromIndex, valueToIndex, value.length);    // Implicit null check on `value`
        String.checkBoundsBeginEnd(0, strToIndex, str.length);                     // Implicit null check on `str`
        return indexOf0(value, valueToIndex, str, strToIndex, valueFromIndex);
    }

    // vmIntrinsics::_indexOfIL
    @IntrinsicCandidate
    private static int indexOf0(byte[] value, int valueToIndex, byte[] str, int strToIndex, int valueFromIndex) {
        if (strToIndex == 0) {
            return 0;
        }
        if ((valueToIndex - valueFromIndex) < strToIndex) {
            return -1;
        }
        byte first = str[0];
        int max = (valueToIndex - strToIndex);
        for (int i = valueFromIndex; i <= max; i++) {
            // Look for first character.
            if (value[i] != first) {
                while (++i <= max && value[i] != first);
            }
            // Found first character, now look at the rest of value
            if (i <= max) {
                int j = i + 1;
                int end = j + strToIndex - 1;
                for (int k = 1; j < end && value[j] == str[k]; j++, k++);
                if (j == end) {
                    // Found whole string.
                    return i;
                }
            }
        }
        return -1;
    }

    static int lastIndexOf(byte[] src, int srcCount,
                           byte[] tgt, int tgtCount, int fromIndex) {
        int min = tgtCount - 1;
        int i = min + fromIndex;
        int strLastIndex = tgtCount - 1;
        char strLastChar = (char)(tgt[strLastIndex] & 0xff);

  startSearchForLastChar:
        while (true) {
            while (i >= min && (src[i] & 0xff) != strLastChar) {
                i--;
            }
            if (i < min) {
                return -1;
            }
            int j = i - 1;
            int start = j - strLastIndex;
            int k = strLastIndex - 1;
            while (j > start) {
                if ((src[j--] & 0xff) != (tgt[k--] & 0xff)) {
                    i--;
                    continue startSearchForLastChar;
                }
            }
            return start + 1;
        }
    }

    static int lastIndexOf(final byte[] value, int ch, int fromIndex) {
        if (!canEncode(ch)) {
            return -1;
        }
        int off  = Math.min(fromIndex, value.length - 1);
        for (; off >= 0; off--) {
            if (value[off] == (byte)ch) {
                return off;
            }
        }
        return -1;
    }

    static String replace(byte[] value, char oldChar, char newChar) {
        if (canEncode(oldChar)) {
            int len = value.length;
            int i = -1;
            while (++i < len) {
                if (value[i] == (byte)oldChar) {
                    break;
                }
            }
            if (i < len) {
                if (canEncode(newChar)) {
                    byte[] buf = StringConcatHelper.newArray(len);
                    for (int j = 0; j < i; j++) {    // TBD arraycopy?
                        buf[j] = value[j];
                    }
                    while (i < len) {
                        byte c = value[i];
                        buf[i] = (c == (byte)oldChar) ? (byte)newChar : c;
                        i++;
                    }
                    return new String(buf, LATIN1);
                } else {
                    byte[] buf = StringUTF16.newBytesFor(len);
                    // inflate from latin1 to UTF16
                    inflate(value, 0, buf, 0, i);
                    while (i < len) {
                        char c = (char)(value[i] & 0xff);
                        StringUTF16.putChar(buf, i, (c == oldChar) ? newChar : c);
                        i++;
                    }
                    return new String(buf, UTF16);
                }
            }
        }
        return null; // for string to return this;
    }

    static String replace(byte[] value, int valLen, byte[] targ,
                          int targLen, byte[] repl, int replLen)
    {
        assert targLen > 0;
        int i, j, p = 0;
        if (valLen == 0 || (i = indexOf(value, valLen, targ, targLen, 0)) < 0) {
            return null; // for string to return this;
        }

        // find and store indices of substrings to replace
        int[] pos = new int[16];
        pos[0] = i;
        i += targLen;
        while ((j = indexOf(value, valLen, targ, targLen, i)) > 0) {
            if (++p == pos.length) {
                pos = Arrays.copyOf(pos, ArraysSupport.newLength(p, 1, p >> 1));
            }
            pos[p] = j;
            i = j + targLen;
        }

        int resultLen;
        try {
            resultLen = Math.addExact(valLen,
                    Math.multiplyExact(++p, replLen - targLen));
        } catch (ArithmeticException ignored) {
            throw new OutOfMemoryError("Required length exceeds implementation limit");
        }
        if (resultLen == 0) {
            return "";
        }

        byte[] result = StringConcatHelper.newArray(resultLen);
        int posFrom = 0, posTo = 0;
        for (int q = 0; q < p; ++q) {
            int nextPos = pos[q];
            while (posFrom < nextPos) {
                result[posTo++] = value[posFrom++];
            }
            posFrom += targLen;
            for (int k = 0; k < replLen; ++k) {
                result[posTo++] = repl[k];
            }
        }
        while (posFrom < valLen) {
            result[posTo++] = value[posFrom++];
        }
        return new String(result, LATIN1);
    }

    // case insensitive
    static boolean regionMatchesCI(byte[] value, int toffset,
                                   byte[] other, int ooffset, int len) {
        int last = toffset + len;
        while (toffset < last) {
            byte b1 = value[toffset++];
            byte b2 = other[ooffset++];
            if (CharacterDataLatin1.equalsIgnoreCase(b1, b2)) {
                continue;
            }
            return false;
        }
        return true;
    }

    static boolean regionMatchesCI_UTF16(byte[] value, int toffset,
                                         byte[] other, int ooffset, int len) {
        int last = toffset + len;
        while (toffset < last) {
            char c1 = (char)(value[toffset++] & 0xff);
            char c2 = StringUTF16.getChar(other, ooffset++);
            if (c1 == c2) {
                continue;
            }
            char u1 = (char) CharacterDataLatin1.instance.toUpperCase(c1);
            char u2 = Character.toUpperCase(c2);
            if (u1 == u2) {
                continue;
            }
            if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
                continue;
            }
            return false;
        }
        return true;
    }

    static String toLowerCase(String str, byte[] value, Locale locale) {
        if (locale == null) {
            throw new NullPointerException();
        }
        int first;
        final int len = value.length;
        // Now check if there are any characters that need to be changed
        for (first = 0 ; first < len; first++) {
            if (CharacterDataLatin1.instance.isUpperCase(value[first] & 0xff)) {
                break;
            }
        }
        if (first == len)
            return str;
        String lang = locale.getLanguage();
        if (lang == "tr" || lang == "az" || lang == "lt") {
            return toLowerCaseEx(str, value, first, locale, true);
        }
        byte[] result = new byte[len];
        System.arraycopy(value, 0, result, 0, first);  // Just copy the first few
                                                       // lowerCase characters.
        for (int i = first; i < len; i++) {
            result[i] = (byte)CharacterDataLatin1.instance.toLowerCase(value[i] & 0xff);
        }
        return new String(result, LATIN1);
    }

    private static String toLowerCaseEx(String str, byte[] value,
                                        int first, Locale locale, boolean localeDependent)
    {
        byte[] result = StringUTF16.newBytesFor(value.length);
        int resultOffset = 0;
        for (int i = 0; i < first; i++) {
            StringUTF16.putChar(result, resultOffset++, value[i] & 0xff);
        }
        for (int i = first; i < value.length; i++) {
            int srcChar = value[i] & 0xff;
            int lowerChar;
            char[] lowerCharArray;
            if (localeDependent) {
                lowerChar = ConditionalSpecialCasing.toLowerCaseEx(str, i, locale);
            } else {
                lowerChar = CharacterDataLatin1.instance.toLowerCase(srcChar);
            }
            if (Character.isBmpCodePoint(lowerChar)) {    // Character.ERROR is not a bmp
                StringUTF16.putChar(result, resultOffset++, lowerChar);
            } else {
                if (lowerChar == Character.ERROR) {
                    lowerCharArray = ConditionalSpecialCasing.toLowerCaseCharArray(str, i, locale);
                } else {
                    lowerCharArray = Character.toChars(lowerChar);
                }
                /* Grow result if needed */
                int mapLen = lowerCharArray.length;
                if (mapLen > 1) {
                    byte[] result2 = StringUTF16.newBytesFor((result.length >> 1) + mapLen - 1);
                    System.arraycopy(result, 0, result2, 0, resultOffset << 1);
                    result = result2;
                }
                for (int x = 0; x < mapLen; ++x) {
                    StringUTF16.putChar(result, resultOffset++, lowerCharArray[x]);
                }
            }
        }
        return StringUTF16.newString(result, 0, resultOffset);
    }

    static String toUpperCase(String str, byte[] value, Locale locale) {
        if (locale == null) {
            throw new NullPointerException();
        }
        int first;
        final int len = value.length;

        // Now check if there are any characters that need to be changed
        for (first = 0 ; first < len; first++ ) {
            int cp = value[first] & 0xff;
            boolean notUpperCaseEx = cp >= 'a' && (cp <= 'z' || cp == 0xb5 || (cp >= 0xdf && cp != 0xf7));
            if (notUpperCaseEx) {
                break;
            }
        }
        if (first == len) {
            return str;
        }
        String lang = locale.getLanguage();
        if (lang == "tr" || lang == "az" || lang == "lt") {
            return toUpperCaseEx(str, value, first, locale, true);
        }
        byte[] result = new byte[len];
        System.arraycopy(value, 0, result, 0, first);  // Just copy the first few
                                                       // upperCase characters.
        for (int i = first; i < len; i++) {
            int cp = CharacterDataLatin1.instance.toUpperCaseEx(value[i] & 0xff);
            if (!canEncode(cp)) {                      // not a latin1 character
                return toUpperCaseEx(str, value, first, locale, false);
            }
            result[i] = (byte)cp;
        }
        return new String(result, LATIN1);
    }

    private static String toUpperCaseEx(String str, byte[] value,
                                        int first, Locale locale, boolean localeDependent)
    {
        byte[] result = StringUTF16.newBytesFor(value.length);
        int resultOffset = 0;
        for (int i = 0; i < first; i++) {
            StringUTF16.putChar(result, resultOffset++, value[i] & 0xff);
        }
        for (int i = first; i < value.length; i++) {
            int srcChar = value[i] & 0xff;
            int upperChar;
            char[] upperCharArray;
            if (localeDependent) {
                upperChar = ConditionalSpecialCasing.toUpperCaseEx(str, i, locale);
            } else {
                upperChar = CharacterDataLatin1.instance.toUpperCaseEx(srcChar);
            }
            if (Character.isBmpCodePoint(upperChar)) {
                StringUTF16.putChar(result, resultOffset++, upperChar);
            } else {
                if (upperChar == Character.ERROR) {
                    if (localeDependent) {
                        upperCharArray =
                            ConditionalSpecialCasing.toUpperCaseCharArray(str, i, locale);
                    } else {
                        upperCharArray = CharacterDataLatin1.instance.toUpperCaseCharArray(srcChar);
                    }
                } else {
                    upperCharArray = Character.toChars(upperChar);
                }
                /* Grow result if needed */
                int mapLen = upperCharArray.length;
                if (mapLen > 1) {
                    byte[] result2 = StringUTF16.newBytesFor((result.length >> 1) + mapLen - 1);
                    System.arraycopy(result, 0, result2, 0, resultOffset << 1);
                    result = result2;
                }
                for (int x = 0; x < mapLen; ++x) {
                    StringUTF16.putChar(result, resultOffset++, upperCharArray[x]);
                }
            }
        }
        return StringUTF16.newString(result, 0, resultOffset);
    }

    static String trim(byte[] value) {
        int len = value.length;
        int st = 0;
        while ((st < len) && ((value[st] & 0xff) <= ' ')) {
            st++;
        }
        while ((st < len) && ((value[len - 1] & 0xff) <= ' ')) {
            len--;
        }
        return ((st > 0) || (len < value.length)) ?
            newString(value, st, len - st) : null;
    }

    static int indexOfNonWhitespace(byte[] value) {
        int length = value.length;
        int left = 0;
        while (left < length) {
            char ch = getChar(value, left);
            if (ch != ' ' && ch != '\t' && !CharacterDataLatin1.instance.isWhitespace(ch)) {
                break;
            }
            left++;
        }
        return left;
    }

    static int lastIndexOfNonWhitespace(byte[] value) {
        int right = value.length;
        while (0 < right) {
            char ch = getChar(value, right - 1);
            if (ch != ' ' && ch != '\t' && !CharacterDataLatin1.instance.isWhitespace(ch)) {
                break;
            }
            right--;
        }
        return right;
    }

    static String strip(byte[] value) {
        int left = indexOfNonWhitespace(value);
        if (left == value.length) {
            return "";
        }
        int right = lastIndexOfNonWhitespace(value);
        boolean ifChanged = (left > 0) || (right < value.length);
        return ifChanged ? newString(value, left, right - left) : null;
    }

    static String stripLeading(byte[] value) {
        int left = indexOfNonWhitespace(value);
        return (left != 0) ? newString(value, left, value.length - left) : null;
    }

    static String stripTrailing(byte[] value) {
        int right = lastIndexOfNonWhitespace(value);
        return (right != value.length) ? newString(value, 0, right) : null;
    }

    private static final class LinesSpliterator implements Spliterator<String> {
        private byte[] value;
        private int index;        // current index, modified on advance/split
        private final int fence;  // one past last index

        private LinesSpliterator(byte[] value, int start, int length) {
            this.value = value;
            this.index = start;
            this.fence = start + length;
        }

        private int indexOfLineSeparator(int start) {
            for (int current = start; current < fence; current++) {
                char ch = getChar(value, current);
                if (ch == '\n' || ch == '\r') {
                    return current;
                }
            }
            return fence;
        }

        private int skipLineSeparator(int start) {
            if (start < fence) {
                if (getChar(value, start) == '\r') {
                    int next = start + 1;
                    if (next < fence && getChar(value, next) == '\n') {
                        return next + 1;
                    }
                }
                return start + 1;
            }
            return fence;
        }

        private String next() {
            int start = index;
            int end = indexOfLineSeparator(start);
            index = skipLineSeparator(end);
            return newString(value, start, end - start);
        }

        @Override
        public boolean tryAdvance(Consumer<? super String> action) {
            if (action == null) {
                throw new NullPointerException("tryAdvance action missing");
            }
            if (index != fence) {
                action.accept(next());
                return true;
            }
            return false;
        }

        @Override
        public void forEachRemaining(Consumer<? super String> action) {
            if (action == null) {
                throw new NullPointerException("forEachRemaining action missing");
            }
            while (index != fence) {
                action.accept(next());
            }
        }

        @Override
        public Spliterator<String> trySplit() {
            int half = (fence + index) >>> 1;
            int mid = skipLineSeparator(indexOfLineSeparator(half));
            if (mid < fence) {
                int start = index;
                index = mid;
                return new LinesSpliterator(value, start, mid - start);
            }
            return null;
        }

        @Override
        public long estimateSize() {
            return fence - index + 1;
        }

        @Override
        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL;
        }

        static LinesSpliterator spliterator(byte[] value) {
            return new LinesSpliterator(value, 0, value.length);
        }
    }

    static Stream<String> lines(byte[] value) {
        return StreamSupport.stream(LinesSpliterator.spliterator(value), false);
    }

    static void putCharsAt(byte[] value, int i, char c1, char c2, char c3, char c4) {
        value[i] = (byte)c1;
        value[i + 1] = (byte)c2;
        value[i + 2] = (byte)c3;
        value[i + 3] = (byte)c4;
    }

    static void putCharsAt(byte[] value, int i, char c1, char c2, char c3, char c4, char c5) {
        value[i] = (byte)c1;
        value[i + 1] = (byte)c2;
        value[i + 2] = (byte)c3;
        value[i + 3] = (byte)c4;
        value[i + 4] = (byte)c5;
    }

    static char getChar(byte[] val, int index) {
        return (char)(val[index] & 0xff);
    }

    static byte[] toBytes(char c) {
        return new byte[] { (byte)c };
    }

    static String newString(byte[] val, int index, int len) {
        if (len == 0) {
            return "";
        }
        return new String(Arrays.copyOfRange(val, index, index + len),
                          LATIN1);
    }

    /**
     * Copies characters from a Latin-1 string byte array sub-range to the
     * given {@code char} array sub-range.
     * <p>
     * This effectively <em>inflates</em> the content from a 1 byte per
     * character representation to a 2 byte one.
     *
     * @param src the source Latin-1 string byte array
     * @param srcOff the index (inclusive) of the first character in {@code src}
     * @param dst the target {@code char} array
     * @param dstOff the index (inclusive) of the first character in {@code dst}
     * @param len the maximum number of characters to copy
     *
     * @throws NullPointerException if {@code src} or {@code dst} is null
     * @throws StringIndexOutOfBoundsException if the sub-ranges are out of bounds
     */
    static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
        String.checkBoundsOffCount(srcOff, len, src.length);    // Implicit null check on `src`
        String.checkBoundsOffCount(dstOff, len, dst.length);    // Implicit null check on `dst`
        inflate0(src, srcOff, dst, dstOff, len);
    }

    // vmIntrinsics::_inflateStringC
    @IntrinsicCandidate
    private static void inflate0(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
        for (int i = 0; i < len; i++) {
            dst[dstOff++] = (char)(src[srcOff++] & 0xff);
        }
    }

    /**
     * Copies characters from a Latin-1 string byte array sub-range to a UTF-16
     * one.
     * <p>
     * This effectively <em>inflates</em> the content from a 1 byte per
     * character representation to a 2 byte one.
     *
     * @param src the source Latin-1 string byte array
     * @param srcOff the index (inclusive) of the first character in {@code src}
     * @param dst the target UTF-16 string byte array
     * @param dstOff the index (inclusive) of the first character in {@code dst}
     * @param len the maximum number of characters to copy
     *
     * @throws NullPointerException if {@code src} or {@code dst} is null
     * @throws StringIndexOutOfBoundsException if the sub-ranges are out of bounds
     */
    static void inflate(byte[] src, int srcOff, byte[] dst, int dstOff, int len) {
        String.checkBoundsOffCount(srcOff, len, src.length);    // Implicit null check on `src`
        Objects.requireNonNull(dst);
        String.checkBoundsOffCount(dstOff, len, StringUTF16.length(dst));
        inflate0(src, srcOff, dst, dstOff, len);
    }

    // vmIntrinsics::_inflateStringB
    @IntrinsicCandidate
    private static void inflate0(byte[] src, int srcOff, byte[] dst, int dstOff, int len) {
        for (int i = 0; i < len; i++) {
            StringUTF16.putChar(dst, dstOff++, src[srcOff++] & 0xff);
        }
    }

    static class CharsSpliterator implements Spliterator.OfInt {
        private final byte[] array;
        private int index;        // current index, modified on advance/split
        private final int fence;  // one past last index
        private final int cs;

        CharsSpliterator(byte[] array, int acs) {
            this(array, 0, array.length, acs);
        }

        CharsSpliterator(byte[] array, int origin, int fence, int acs) {
            this.array = array;
            this.index = origin;
            this.fence = fence;
            this.cs = acs | Spliterator.ORDERED | Spliterator.SIZED
                      | Spliterator.SUBSIZED;
        }

        @Override
        public OfInt trySplit() {
            int lo = index, mid = (lo + fence) >>> 1;
            return (lo >= mid)
                   ? null
                   : new CharsSpliterator(array, lo, index = mid, cs);
        }

        @Override
        public void forEachRemaining(IntConsumer action) {
            byte[] a; int i, hi; // hoist accesses and checks from loop
            if (action == null)
                throw new NullPointerException();
            if ((a = array).length >= (hi = fence) &&
                (i = index) >= 0 && i < (index = hi)) {
                do { action.accept(a[i] & 0xff); } while (++i < hi);
            }
        }

        @Override
        public boolean tryAdvance(IntConsumer action) {
            if (action == null)
                throw new NullPointerException();
            if (index >= 0 && index < fence) {
                action.accept(array[index++] & 0xff);
                return true;
            }
            return false;
        }

        @Override
        public long estimateSize() { return fence - index; }

        @Override
        public int characteristics() {
            return cs;
        }
    }
}
