View Javadoc
1   /*
2    * Copyright (C) 2009 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5    * in compliance with the License. You may obtain a copy of the License at
6    *
7    * http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software distributed under the License
10   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11   * or implied. See the License for the specific language governing permissions and limitations under
12   * the License.
13   */
14  
15  package com.google.common.escape;
16  
17  import static com.google.common.base.Preconditions.checkNotNull;
18  
19  import com.google.common.annotations.Beta;
20  import com.google.common.annotations.GwtCompatible;
21  import java.util.Map;
22  import javax.annotation.Nullable;
23  
24  /**
25   * A {@link UnicodeEscaper} that uses an array to quickly look up replacement characters for a given
26   * code point. An additional safe range is provided that determines whether code points without
27   * specific replacements are to be considered safe and left unescaped or should be escaped in a
28   * general way.
29   *
30   * <p>A good example of usage of this class is for HTML escaping where the replacement array
31   * contains information about the named HTML entities such as {@code &amp;} and {@code &quot;} while
32   * {@link #escapeUnsafe} is overridden to handle general escaping of the form {@code &#NNNNN;}.
33   *
34   * <p>The size of the data structure used by {@link ArrayBasedUnicodeEscaper} is proportional to the
35   * highest valued code point that requires escaping. For example a replacement map containing the
36   * single character '{@code \}{@code u1000}' will require approximately 16K of memory. If you need
37   * to create multiple escaper instances that have the same character replacement mapping consider
38   * using {@link ArrayBasedEscaperMap}.
39   *
40   * @author David Beaumont
41   * @since 15.0
42   */
43  @Beta
44  @GwtCompatible
45  public abstract class ArrayBasedUnicodeEscaper extends UnicodeEscaper {
46    // The replacement array (see ArrayBasedEscaperMap).
47    private final char[][] replacements;
48    // The number of elements in the replacement array.
49    private final int replacementsLength;
50    // The first code point in the safe range.
51    private final int safeMin;
52    // The last code point in the safe range.
53    private final int safeMax;
54  
55    // Cropped values used in the fast path range checks.
56    private final char safeMinChar;
57    private final char safeMaxChar;
58  
59    /**
60     * Creates a new ArrayBasedUnicodeEscaper instance with the given replacement map and specified
61     * safe range. If {@code safeMax < safeMin} then no code points are considered safe.
62     *
63     * <p>If a code point has no mapped replacement then it is checked against the safe range. If it
64     * lies outside that, then {@link #escapeUnsafe} is called, otherwise no escaping is performed.
65     *
66     * @param replacementMap a map of characters to their escaped representations
67     * @param safeMin the lowest character value in the safe range
68     * @param safeMax the highest character value in the safe range
69     * @param unsafeReplacement the default replacement for unsafe characters or null if no default
70     *     replacement is required
71     */
72    protected ArrayBasedUnicodeEscaper(
73        Map<Character, String> replacementMap,
74        int safeMin,
75        int safeMax,
76        @Nullable String unsafeReplacement) {
77      this(ArrayBasedEscaperMap.create(replacementMap), safeMin, safeMax, unsafeReplacement);
78    }
79  
80    /**
81     * Creates a new ArrayBasedUnicodeEscaper instance with the given replacement map and specified
82     * safe range. If {@code safeMax < safeMin} then no code points are considered safe. This
83     * initializer is useful when explicit instances of ArrayBasedEscaperMap are used to allow the
84     * sharing of large replacement mappings.
85     *
86     * <p>If a code point has no mapped replacement then it is checked against the safe range. If it
87     * lies outside that, then {@link #escapeUnsafe} is called, otherwise no escaping is performed.
88     *
89     * @param escaperMap the map of replacements
90     * @param safeMin the lowest character value in the safe range
91     * @param safeMax the highest character value in the safe range
92     * @param unsafeReplacement the default replacement for unsafe characters or null if no default
93     *     replacement is required
94     */
95    protected ArrayBasedUnicodeEscaper(
96        ArrayBasedEscaperMap escaperMap,
97        int safeMin,
98        int safeMax,
99        @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   /* Overridden for performance. */
157   @Override
158   protected final int nextEscapeIndex(CharSequence csq, int index, int end) {
159     while (index < end) {
160       char c = csq.charAt(index);
161       if ((c < replacementsLength && replacements[c] != null)
162           || c > safeMaxChar
163           || c < safeMinChar) {
164         break;
165       }
166       index++;
167     }
168     return index;
169   }
170 
171   /**
172    * Escapes a single Unicode code point using the replacement array and safe range values. If the
173    * given character does not have an explicit replacement and lies outside the safe range then
174    * {@link #escapeUnsafe} is called.
175    */
176   @Override
177   protected final char[] escape(int cp) {
178     if (cp < replacementsLength) {
179       char[] chars = replacements[cp];
180       if (chars != null) {
181         return chars;
182       }
183     }
184     if (cp >= safeMin && cp <= safeMax) {
185       return null;
186     }
187     return escapeUnsafe(cp);
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 }