001/*
002 * Copyright (C) 2013 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.base;
016
017import static com.google.common.base.Preconditions.checkPositionIndexes;
018import static java.lang.Character.MAX_SURROGATE;
019import static java.lang.Character.MIN_SURROGATE;
020
021import com.google.common.annotations.GwtCompatible;
022
023/**
024 * Low-level, high-performance utility methods related to the {@linkplain Charsets#UTF_8 UTF-8}
025 * character encoding. UTF-8 is defined in section D92 of <a
026 * href="http://www.unicode.org/versions/Unicode6.2.0/ch03.pdf">The Unicode Standard Core
027 * Specification, Chapter 3</a>.
028 *
029 * <p>The variant of UTF-8 implemented by this class is the restricted definition of UTF-8
030 * introduced in Unicode 3.1. One implication of this is that it rejects <a
031 * href="http://www.unicode.org/versions/corrigendum1.html">"non-shortest form"</a> byte sequences,
032 * even though the JDK decoder may accept them.
033 *
034 * @author Martin Buchholz
035 * @author Clément Roux
036 * @since 16.0
037 */
038@GwtCompatible(emulated = true)
039public final class Utf8 {
040  /**
041   * Returns the number of bytes in the UTF-8-encoded form of {@code sequence}. For a string, this
042   * method is equivalent to {@code string.getBytes(UTF_8).length}, but is more efficient in both
043   * time and space.
044   *
045   * @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired
046   *     surrogates)
047   */
048  public static int encodedLength(CharSequence sequence) {
049    // Warning to maintainers: this implementation is highly optimized.
050    int utf16Length = sequence.length();
051    int utf8Length = utf16Length;
052    int i = 0;
053
054    // This loop optimizes for pure ASCII.
055    while (i < utf16Length && sequence.charAt(i) < 0x80) {
056      i++;
057    }
058
059    // This loop optimizes for chars less than 0x800.
060    for (; i < utf16Length; i++) {
061      char c = sequence.charAt(i);
062      if (c < 0x800) {
063        utf8Length += ((0x7f - c) >>> 31); // branch free!
064      } else {
065        utf8Length += encodedLengthGeneral(sequence, i);
066        break;
067      }
068    }
069
070    if (utf8Length < utf16Length) {
071      // Necessary and sufficient condition for overflow because of maximum 3x expansion
072      throw new IllegalArgumentException(
073          "UTF-8 length does not fit in int: " + (utf8Length + (1L << 32)));
074    }
075    return utf8Length;
076  }
077
078  private static int encodedLengthGeneral(CharSequence sequence, int start) {
079    int utf16Length = sequence.length();
080    int utf8Length = 0;
081    for (int i = start; i < utf16Length; i++) {
082      char c = sequence.charAt(i);
083      if (c < 0x800) {
084        utf8Length += (0x7f - c) >>> 31; // branch free!
085      } else {
086        utf8Length += 2;
087        // We can't use Character.isSurrogate(c) here and below because of GWT.
088        if (MIN_SURROGATE <= c && c <= MAX_SURROGATE) {
089          // Check that we have a well-formed surrogate pair.
090          if (Character.codePointAt(sequence, i) == c) {
091            throw new IllegalArgumentException(unpairedSurrogateMsg(i));
092          }
093          i++;
094        }
095      }
096    }
097    return utf8Length;
098  }
099
100  /**
101   * Returns {@code true} if {@code bytes} is a <i>well-formed</i> UTF-8 byte sequence according to
102   * Unicode 6.0. Note that this is a stronger criterion than simply whether the bytes can be
103   * decoded. For example, some versions of the JDK decoder will accept "non-shortest form" byte
104   * sequences, but encoding never reproduces these. Such byte sequences are <i>not</i> considered
105   * well-formed.
106   *
107   * <p>This method returns {@code true} if and only if {@code Arrays.equals(bytes, new
108   * String(bytes, UTF_8).getBytes(UTF_8))} does, but is more efficient in both time and space.
109   */
110  public static boolean isWellFormed(byte[] bytes) {
111    return isWellFormed(bytes, 0, bytes.length);
112  }
113
114  /**
115   * Returns whether the given byte array slice is a well-formed UTF-8 byte sequence, as defined by
116   * {@link #isWellFormed(byte[])}. Note that this can be false even when {@code
117   * isWellFormed(bytes)} is true.
118   *
119   * @param bytes the input buffer
120   * @param off the offset in the buffer of the first byte to read
121   * @param len the number of bytes to read from the buffer
122   */
123  public static boolean isWellFormed(byte[] bytes, int off, int len) {
124    int end = off + len;
125    checkPositionIndexes(off, end, bytes.length);
126    // Look for the first non-ASCII character.
127    for (int i = off; i < end; i++) {
128      if (bytes[i] < 0) {
129        return isWellFormedSlowPath(bytes, i, end);
130      }
131    }
132    return true;
133  }
134
135  private static boolean isWellFormedSlowPath(byte[] bytes, int off, int end) {
136    int index = off;
137    while (true) {
138      int byte1;
139
140      // Optimize for interior runs of ASCII bytes.
141      do {
142        if (index >= end) {
143          return true;
144        }
145      } while ((byte1 = bytes[index++]) >= 0);
146
147      if (byte1 < (byte) 0xE0) {
148        // Two-byte form.
149        if (index == end) {
150          return false;
151        }
152        // Simultaneously check for illegal trailing-byte in leading position
153        // and overlong 2-byte form.
154        if (byte1 < (byte) 0xC2 || bytes[index++] > (byte) 0xBF) {
155          return false;
156        }
157      } else if (byte1 < (byte) 0xF0) {
158        // Three-byte form.
159        if (index + 1 >= end) {
160          return false;
161        }
162        int byte2 = bytes[index++];
163        if (byte2 > (byte) 0xBF
164            // Overlong? 5 most significant bits must not all be zero.
165            || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0)
166            // Check for illegal surrogate codepoints.
167            || (byte1 == (byte) 0xED && (byte) 0xA0 <= byte2)
168            // Third byte trailing-byte test.
169            || bytes[index++] > (byte) 0xBF) {
170          return false;
171        }
172      } else {
173        // Four-byte form.
174        if (index + 2 >= end) {
175          return false;
176        }
177        int byte2 = bytes[index++];
178        if (byte2 > (byte) 0xBF
179            // Check that 1 <= plane <= 16. Tricky optimized form of:
180            // if (byte1 > (byte) 0xF4
181            //     || byte1 == (byte) 0xF0 && byte2 < (byte) 0x90
182            //     || byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F)
183            || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0
184            // Third byte trailing-byte test
185            || bytes[index++] > (byte) 0xBF
186            // Fourth byte trailing-byte test
187            || bytes[index++] > (byte) 0xBF) {
188          return false;
189        }
190      }
191    }
192  }
193
194  private static String unpairedSurrogateMsg(int i) {
195    return "Unpaired surrogate at index " + i;
196  }
197
198  private Utf8() {}
199}