• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.GwtCompatible;
20 import java.util.Map;
21 import javax.annotation.CheckForNull;
22 
23 /**
24  * A {@link CharEscaper} that uses an array to quickly look up replacement characters for a given
25  * {@code char} value. An additional safe range is provided that determines whether {@code char}
26  * values without specific replacements are to be considered safe and left unescaped or should be
27  * escaped in a general way.
28  *
29  * <p>A good example of usage of this class is for Java source code escaping where the replacement
30  * array contains information about special ASCII characters such as {@code \\t} and {@code \\n}
31  * while {@link #escapeUnsafe} is overridden to handle general escaping of the form {@code \\uxxxx}.
32  *
33  * <p>The size of the data structure used by {@link ArrayBasedCharEscaper} is proportional to the
34  * highest valued character that requires escaping. For example a replacement map containing the
35  * single character '{@code \}{@code u1000}' will require approximately 16K of memory. If you need
36  * to create multiple escaper instances that have the same character replacement mapping consider
37  * using {@link ArrayBasedEscaperMap}.
38  *
39  * @author Sven Mawson
40  * @author David Beaumont
41  * @since 15.0
42  */
43 @GwtCompatible
44 @ElementTypesAreNonnullByDefault
45 public abstract class ArrayBasedCharEscaper extends CharEscaper {
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 character in the safe range.
51   private final char safeMin;
52   // The last character in the safe range.
53   private final char safeMax;
54 
55   /**
56    * Creates a new ArrayBasedCharEscaper instance with the given replacement map and specified safe
57    * range. If {@code safeMax < safeMin} then no characters are considered safe.
58    *
59    * <p>If a character has no mapped replacement then it is checked against the safe range. If it
60    * lies outside that, then {@link #escapeUnsafe} is called, otherwise no escaping is performed.
61    *
62    * @param replacementMap a map of characters to their escaped representations
63    * @param safeMin the lowest character value in the safe range
64    * @param safeMax the highest character value in the safe range
65    */
ArrayBasedCharEscaper( Map<Character, String> replacementMap, char safeMin, char safeMax)66   protected ArrayBasedCharEscaper(
67       Map<Character, String> replacementMap, char safeMin, char safeMax) {
68 
69     this(ArrayBasedEscaperMap.create(replacementMap), safeMin, safeMax);
70   }
71 
72   /**
73    * Creates a new ArrayBasedCharEscaper instance with the given replacement map and specified safe
74    * range. If {@code safeMax < safeMin} then no characters are considered safe. This initializer is
75    * useful when explicit instances of ArrayBasedEscaperMap are used to allow the sharing of large
76    * replacement mappings.
77    *
78    * <p>If a character has no mapped replacement then it is checked against the safe range. If it
79    * lies outside that, then {@link #escapeUnsafe} is called, otherwise no escaping is performed.
80    *
81    * @param escaperMap the mapping of characters to be escaped
82    * @param safeMin the lowest character value in the safe range
83    * @param safeMax the highest character value in the safe range
84    */
ArrayBasedCharEscaper(ArrayBasedEscaperMap escaperMap, char safeMin, char safeMax)85   protected ArrayBasedCharEscaper(ArrayBasedEscaperMap escaperMap, char safeMin, char safeMax) {
86 
87     checkNotNull(escaperMap); // GWT specific check (do not optimize)
88     this.replacements = escaperMap.getReplacementArray();
89     this.replacementsLength = replacements.length;
90     if (safeMax < safeMin) {
91       // If the safe range is empty, set the range limits to opposite extremes
92       // to ensure the first test of either value will (almost certainly) fail.
93       safeMax = Character.MIN_VALUE;
94       safeMin = Character.MAX_VALUE;
95     }
96     this.safeMin = safeMin;
97     this.safeMax = safeMax;
98   }
99 
100   /*
101    * This is overridden to improve performance. Rough benchmarking shows that this almost doubles
102    * the speed when processing strings that do not require any escaping.
103    */
104   @Override
escape(String s)105   public final String escape(String s) {
106     checkNotNull(s); // GWT specific check (do not optimize).
107     for (int i = 0; i < s.length(); i++) {
108       char c = s.charAt(i);
109       if ((c < replacementsLength && replacements[c] != null) || c > safeMax || c < safeMin) {
110         return escapeSlow(s, i);
111       }
112     }
113     return s;
114   }
115 
116   /**
117    * Escapes a single character using the replacement array and safe range values. If the given
118    * character does not have an explicit replacement and lies outside the safe range then {@link
119    * #escapeUnsafe} is called.
120    *
121    * @return the replacement characters, or {@code null} if no escaping was required
122    */
123   @Override
124   @CheckForNull
escape(char c)125   protected final char[] escape(char c) {
126     if (c < replacementsLength) {
127       char[] chars = replacements[c];
128       if (chars != null) {
129         return chars;
130       }
131     }
132     if (c >= safeMin && c <= safeMax) {
133       return null;
134     }
135     return escapeUnsafe(c);
136   }
137 
138   /**
139    * Escapes a {@code char} value that has no direct explicit value in the replacement array and
140    * lies outside the stated safe range. Subclasses should override this method to provide
141    * generalized escaping for characters.
142    *
143    * <p>Note that arrays returned by this method must not be modified once they have been returned.
144    * However it is acceptable to return the same array multiple times (even for different input
145    * characters).
146    *
147    * @param c the character to escape
148    * @return the replacement characters, or {@code null} if no escaping was required
149    */
150   // TODO(dbeaumont,cpovirk): Rename this something better once refactoring done
151   @CheckForNull
escapeUnsafe(char c)152   protected abstract char[] escapeUnsafe(char c);
153 }
154