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