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