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.GwtCompatible;
020import java.util.Map;
021import javax.annotation.CheckForNull;
022
023/**
024 * A {@link CharEscaper} that uses an array to quickly look up replacement characters for a given
025 * {@code char} value. An additional safe range is provided that determines whether {@code char}
026 * values without specific replacements are to be considered safe and left unescaped or should be
027 * escaped in a general way.
028 *
029 * <p>A good example of usage of this class is for Java source code escaping where the replacement
030 * array contains information about special ASCII characters such as {@code \\t} and {@code \\n}
031 * while {@link #escapeUnsafe} is overridden to handle general escaping of the form {@code \\uxxxx}.
032 *
033 * <p>The size of the data structure used by {@link ArrayBasedCharEscaper} is proportional to the
034 * highest valued character that requires escaping. For example a replacement map containing the
035 * single character '{@code \}{@code u1000}' will require approximately 16K of memory. If you need
036 * to create multiple escaper instances that have the same character replacement mapping consider
037 * using {@link ArrayBasedEscaperMap}.
038 *
039 * @author Sven Mawson
040 * @author David Beaumont
041 * @since 15.0
042 */
043@GwtCompatible
044@ElementTypesAreNonnullByDefault
045public abstract class ArrayBasedCharEscaper extends CharEscaper {
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 character in the safe range.
051  private final char safeMin;
052  // The last character in the safe range.
053  private final char safeMax;
054
055  /**
056   * Creates a new ArrayBasedCharEscaper instance with the given replacement map and specified safe
057   * range. If {@code safeMax < safeMin} then no characters are considered safe.
058   *
059   * <p>If a character has no mapped replacement then it is checked against the safe range. If it
060   * lies outside that, then {@link #escapeUnsafe} is called, otherwise no escaping is performed.
061   *
062   * @param replacementMap a map of characters to their escaped representations
063   * @param safeMin the lowest character value in the safe range
064   * @param safeMax the highest character value in the safe range
065   */
066  protected ArrayBasedCharEscaper(
067      Map<Character, String> replacementMap, char safeMin, char safeMax) {
068
069    this(ArrayBasedEscaperMap.create(replacementMap), safeMin, safeMax);
070  }
071
072  /**
073   * Creates a new ArrayBasedCharEscaper instance with the given replacement map and specified safe
074   * range. If {@code safeMax < safeMin} then no characters are considered safe. This initializer is
075   * useful when explicit instances of ArrayBasedEscaperMap are used to allow the sharing of large
076   * replacement mappings.
077   *
078   * <p>If a character has no mapped replacement then it is checked against the safe range. If it
079   * lies outside that, then {@link #escapeUnsafe} is called, otherwise no escaping is performed.
080   *
081   * @param escaperMap the mapping of characters to be escaped
082   * @param safeMin the lowest character value in the safe range
083   * @param safeMax the highest character value in the safe range
084   */
085  protected ArrayBasedCharEscaper(ArrayBasedEscaperMap escaperMap, char safeMin, char safeMax) {
086
087    checkNotNull(escaperMap); // GWT specific check (do not optimize)
088    this.replacements = escaperMap.getReplacementArray();
089    this.replacementsLength = replacements.length;
090    if (safeMax < safeMin) {
091      // If the safe range is empty, set the range limits to opposite extremes
092      // to ensure the first test of either value will (almost certainly) fail.
093      safeMax = Character.MIN_VALUE;
094      safeMin = Character.MAX_VALUE;
095    }
096    this.safeMin = safeMin;
097    this.safeMax = safeMax;
098  }
099
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
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
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
152  protected abstract char[] escapeUnsafe(char c);
153}