001/*
002 * Copyright (C) 2009 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.escape;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018
019import com.google.common.annotations.Beta;
020import com.google.common.annotations.GwtCompatible;
021import java.util.Map;
022import org.checkerframework.checker.nullness.qual.Nullable;
023
024/**
025 * A {@link UnicodeEscaper} that uses an array to quickly look up replacement characters for a given
026 * code point. An additional safe range is provided that determines whether code points without
027 * specific replacements are to be considered safe and left unescaped or should be escaped in a
028 * general way.
029 *
030 * <p>A good example of usage of this class is for HTML escaping where the replacement array
031 * contains information about the named HTML entities such as {@code &amp;} and {@code &quot;} while
032 * {@link #escapeUnsafe} is overridden to handle general escaping of the form {@code &#NNNNN;}.
033 *
034 * <p>The size of the data structure used by {@link ArrayBasedUnicodeEscaper} is proportional to the
035 * highest valued code point that requires escaping. For example a replacement map containing the
036 * single character '{@code \}{@code u1000}' will require approximately 16K of memory. If you need
037 * to create multiple escaper instances that have the same character replacement mapping consider
038 * using {@link ArrayBasedEscaperMap}.
039 *
040 * @author David Beaumont
041 * @since 15.0
042 */
043@Beta
044@GwtCompatible
045public abstract class ArrayBasedUnicodeEscaper extends UnicodeEscaper {
046  // The replacement array (see ArrayBasedEscaperMap).
047  private final char[][] replacements;
048  // The number of elements in the replacement array.
049  private final int replacementsLength;
050  // The first code point in the safe range.
051  private final int safeMin;
052  // The last code point in the safe range.
053  private final int safeMax;
054
055  // Cropped values used in the fast path range checks.
056  private final char safeMinChar;
057  private final char safeMaxChar;
058
059  /**
060   * Creates a new ArrayBasedUnicodeEscaper instance with the given replacement map and specified
061   * safe range. If {@code safeMax < safeMin} then no code points are considered safe.
062   *
063   * <p>If a code point has no mapped replacement then it is checked against the safe range. If it
064   * lies outside that, then {@link #escapeUnsafe} is called, otherwise no escaping is performed.
065   *
066   * @param replacementMap a map of characters to their escaped representations
067   * @param safeMin the lowest character value in the safe range
068   * @param safeMax the highest character value in the safe range
069   * @param unsafeReplacement the default replacement for unsafe characters or null if no default
070   *     replacement is required
071   */
072  protected ArrayBasedUnicodeEscaper(
073      Map<Character, String> replacementMap,
074      int safeMin,
075      int safeMax,
076      @Nullable String unsafeReplacement) {
077    this(ArrayBasedEscaperMap.create(replacementMap), safeMin, safeMax, unsafeReplacement);
078  }
079
080  /**
081   * Creates a new ArrayBasedUnicodeEscaper instance with the given replacement map and specified
082   * safe range. If {@code safeMax < safeMin} then no code points are considered safe. This
083   * initializer is useful when explicit instances of ArrayBasedEscaperMap are used to allow the
084   * sharing of large replacement mappings.
085   *
086   * <p>If a code point has no mapped replacement then it is checked against the safe range. If it
087   * lies outside that, then {@link #escapeUnsafe} is called, otherwise no escaping is performed.
088   *
089   * @param escaperMap the map of replacements
090   * @param safeMin the lowest character value in the safe range
091   * @param safeMax the highest character value in the safe range
092   * @param unsafeReplacement the default replacement for unsafe characters or null if no default
093   *     replacement is required
094   */
095  protected ArrayBasedUnicodeEscaper(
096      ArrayBasedEscaperMap escaperMap,
097      int safeMin,
098      int safeMax,
099      @Nullable String unsafeReplacement) {
100    checkNotNull(escaperMap); // GWT specific check (do not optimize)
101    this.replacements = escaperMap.getReplacementArray();
102    this.replacementsLength = replacements.length;
103    if (safeMax < safeMin) {
104      // If the safe range is empty, set the range limits to opposite extremes
105      // to ensure the first test of either value will fail.
106      safeMax = -1;
107      safeMin = Integer.MAX_VALUE;
108    }
109    this.safeMin = safeMin;
110    this.safeMax = safeMax;
111
112    // This is a bit of a hack but lets us do quicker per-character checks in
113    // the fast path code. The safe min/max values are very unlikely to extend
114    // into the range of surrogate characters, but if they do we must not test
115    // any values in that range. To see why, consider the case where:
116    // safeMin <= {hi,lo} <= safeMax
117    // where {hi,lo} are characters forming a surrogate pair such that:
118    // codePointOf(hi, lo) > safeMax
119    // which would result in the surrogate pair being (wrongly) considered safe.
120    // If we clip the safe range used during the per-character tests so it is
121    // below the values of characters in surrogate pairs, this cannot occur.
122    // This approach does mean that we break out of the fast path code in cases
123    // where we don't strictly need to, but this situation will almost never
124    // occur in practice.
125    if (safeMin >= Character.MIN_HIGH_SURROGATE) {
126      // The safe range is empty or the all safe code points lie in or above the
127      // surrogate range. Either way the character range is empty.
128      this.safeMinChar = Character.MAX_VALUE;
129      this.safeMaxChar = 0;
130    } else {
131      // The safe range is non empty and contains values below the surrogate
132      // range but may extend above it. We may need to clip the maximum value.
133      this.safeMinChar = (char) safeMin;
134      this.safeMaxChar = (char) Math.min(safeMax, Character.MIN_HIGH_SURROGATE - 1);
135    }
136  }
137
138  /*
139   * This is overridden to improve performance. Rough benchmarking shows that this almost doubles
140   * the speed when processing strings that do not require any escaping.
141   */
142  @Override
143  public final String escape(String s) {
144    checkNotNull(s); // GWT specific check (do not optimize)
145    for (int i = 0; i < s.length(); i++) {
146      char c = s.charAt(i);
147      if ((c < replacementsLength && replacements[c] != null)
148          || c > safeMaxChar
149          || c < safeMinChar) {
150        return escapeSlow(s, i);
151      }
152    }
153    return s;
154  }
155
156  /**
157   * Escapes a single Unicode code point using the replacement array and safe range values. If the
158   * given character does not have an explicit replacement and lies outside the safe range then
159   * {@link #escapeUnsafe} is called.
160   */
161  @Override
162  protected final char[] escape(int cp) {
163    if (cp < replacementsLength) {
164      char[] chars = replacements[cp];
165      if (chars != null) {
166        return chars;
167      }
168    }
169    if (cp >= safeMin && cp <= safeMax) {
170      return null;
171    }
172    return escapeUnsafe(cp);
173  }
174
175  /* Overridden for performance. */
176  @Override
177  protected final int nextEscapeIndex(CharSequence csq, int index, int end) {
178    while (index < end) {
179      char c = csq.charAt(index);
180      if ((c < replacementsLength && replacements[c] != null)
181          || c > safeMaxChar
182          || c < safeMinChar) {
183        break;
184      }
185      index++;
186    }
187    return index;
188  }
189
190  /**
191   * Escapes a code point that has no direct explicit value in the replacement array and lies
192   * outside the stated safe range. Subclasses should override this method to provide generalized
193   * escaping for code points if required.
194   *
195   * <p>Note that arrays returned by this method must not be modified once they have been returned.
196   * However it is acceptable to return the same array multiple times (even for different input
197   * characters).
198   *
199   * @param cp the Unicode code point to escape
200   * @return the replacement characters, or {@code null} if no escaping was required
201   */
202  protected abstract char[] escapeUnsafe(int cp);
203}