001/* 002 * Copyright (C) 2008 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.google.common.escape; 018 019import static com.google.common.base.Preconditions.checkNotNull; 020 021import com.google.common.annotations.Beta; 022import com.google.common.annotations.GwtCompatible; 023 024/** 025 * An {@link Escaper} that converts literal text into a format safe for 026 * inclusion in a particular context (such as an XML document). Typically (but 027 * not always), the inverse process of "unescaping" the text is performed 028 * automatically by the relevant parser. 029 * 030 * <p>For example, an XML escaper would convert the literal string {@code 031 * "Foo<Bar>"} into {@code "Foo<Bar>"} to prevent {@code "<Bar>"} from 032 * being confused with an XML tag. When the resulting XML document is parsed, 033 * the parser API will return this text as the original literal string {@code 034 * "Foo<Bar>"}. 035 * 036 * <p><b>Note:</b> This class is similar to {@link CharEscaper} but with one 037 * very important difference. A CharEscaper can only process Java 038 * <a href="http://en.wikipedia.org/wiki/UTF-16">UTF16</a> characters in 039 * isolation and may not cope when it encounters surrogate pairs. This class 040 * facilitates the correct escaping of all Unicode characters. 041 * 042 * <p>As there are important reasons, including potential security issues, to 043 * handle Unicode correctly if you are considering implementing a new escaper 044 * you should favor using UnicodeEscaper wherever possible. 045 * 046 * <p>A {@code UnicodeEscaper} instance is required to be stateless, and safe 047 * when used concurrently by multiple threads. 048 * 049 * <p>Popular escapers are defined as constants in classes like {@link 050 * com.google.common.html.HtmlEscapers} and {@link com.google.common.xml.XmlEscapers}. 051 * To create your own escapers extend this class and implement the {@link #escape(int)} 052 * method. 053 * 054 * @author David Beaumont 055 * @since 15.0 056 */ 057@Beta 058@GwtCompatible 059public abstract class UnicodeEscaper extends Escaper { 060 /** The amount of padding (chars) to use when growing the escape buffer. */ 061 private static final int DEST_PAD = 32; 062 063 /** Constructor for use by subclasses. */ 064 protected UnicodeEscaper() {} 065 066 /** 067 * Returns the escaped form of the given Unicode code point, or {@code null} 068 * if this code point does not need to be escaped. When called as part of an 069 * escaping operation, the given code point is guaranteed to be in the range 070 * {@code 0 <= cp <= Character#MAX_CODE_POINT}. 071 * 072 * <p>If an empty array is returned, this effectively strips the input 073 * character from the resulting text. 074 * 075 * <p>If the character does not need to be escaped, this method should return 076 * {@code null}, rather than an array containing the character representation 077 * of the code point. This enables the escaping algorithm to perform more 078 * efficiently. 079 * 080 * <p>If the implementation of this method cannot correctly handle a 081 * particular code point then it should either throw an appropriate runtime 082 * exception or return a suitable replacement character. It must never 083 * silently discard invalid input as this may constitute a security risk. 084 * 085 * @param cp the Unicode code point to escape if necessary 086 * @return the replacement characters, or {@code null} if no escaping was 087 * needed 088 */ 089 protected abstract char[] escape(int cp); 090 091 /** 092 * Scans a sub-sequence of characters from a given {@link CharSequence}, 093 * returning the index of the next character that requires escaping. 094 * 095 * <p><b>Note:</b> When implementing an escaper, it is a good idea to override 096 * this method for efficiency. The base class implementation determines 097 * successive Unicode code points and invokes {@link #escape(int)} for each of 098 * them. If the semantics of your escaper are such that code points in the 099 * supplementary range are either all escaped or all unescaped, this method 100 * can be implemented more efficiently using {@link CharSequence#charAt(int)}. 101 * 102 * <p>Note however that if your escaper does not escape characters in the 103 * supplementary range, you should either continue to validate the correctness 104 * of any surrogate characters encountered or provide a clear warning to users 105 * that your escaper does not validate its input. 106 * 107 * <p>See {@link com.google.common.net.PercentEscaper} for an example. 108 * 109 * @param csq a sequence of characters 110 * @param start the index of the first character to be scanned 111 * @param end the index immediately after the last character to be scanned 112 * @throws IllegalArgumentException if the scanned sub-sequence of {@code csq} 113 * contains invalid surrogate pairs 114 */ 115 protected int nextEscapeIndex(CharSequence csq, int start, int end) { 116 int index = start; 117 while (index < end) { 118 int cp = codePointAt(csq, index, end); 119 if (cp < 0 || escape(cp) != null) { 120 break; 121 } 122 index += Character.isSupplementaryCodePoint(cp) ? 2 : 1; 123 } 124 return index; 125 } 126 127 /** 128 * Returns the escaped form of a given literal string. 129 * 130 * <p>If you are escaping input in arbitrary successive chunks, then it is not 131 * generally safe to use this method. If an input string ends with an 132 * unmatched high surrogate character, then this method will throw 133 * {@link IllegalArgumentException}. You should ensure your input is valid <a 134 * href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a> before calling this 135 * method. 136 * 137 * <p><b>Note:</b> When implementing an escaper it is a good idea to override 138 * this method for efficiency by inlining the implementation of 139 * {@link #nextEscapeIndex(CharSequence, int, int)} directly. Doing this for 140 * {@link com.google.common.net.PercentEscaper} more than doubled the 141 * performance for unescaped strings (as measured by {@link 142 * CharEscapersBenchmark}). 143 * 144 * @param string the literal string to be escaped 145 * @return the escaped form of {@code string} 146 * @throws NullPointerException if {@code string} is null 147 * @throws IllegalArgumentException if invalid surrogate characters are 148 * encountered 149 */ 150 @Override 151 public String escape(String string) { 152 checkNotNull(string); 153 int end = string.length(); 154 int index = nextEscapeIndex(string, 0, end); 155 return index == end ? string : escapeSlow(string, index); 156 } 157 158 /** 159 * Returns the escaped form of a given literal string, starting at the given 160 * index. This method is called by the {@link #escape(String)} method when it 161 * discovers that escaping is required. It is protected to allow subclasses 162 * to override the fastpath escaping function to inline their escaping test. 163 * See {@link CharEscaperBuilder} for an example usage. 164 * 165 * <p>This method is not reentrant and may only be invoked by the top level 166 * {@link #escape(String)} method. 167 * 168 * @param s the literal string to be escaped 169 * @param index the index to start escaping from 170 * @return the escaped form of {@code string} 171 * @throws NullPointerException if {@code string} is null 172 * @throws IllegalArgumentException if invalid surrogate characters are 173 * encountered 174 */ 175 protected final String escapeSlow(String s, int index) { 176 int end = s.length(); 177 178 // Get a destination buffer and setup some loop variables. 179 char[] dest = Platform.charBufferFromThreadLocal(); 180 int destIndex = 0; 181 int unescapedChunkStart = 0; 182 183 while (index < end) { 184 int cp = codePointAt(s, index, end); 185 if (cp < 0) { 186 throw new IllegalArgumentException( 187 "Trailing high surrogate at end of input"); 188 } 189 // It is possible for this to return null because nextEscapeIndex() may 190 // (for performance reasons) yield some false positives but it must never 191 // give false negatives. 192 char[] escaped = escape(cp); 193 int nextIndex = index + (Character.isSupplementaryCodePoint(cp) ? 2 : 1); 194 if (escaped != null) { 195 int charsSkipped = index - unescapedChunkStart; 196 197 // This is the size needed to add the replacement, not the full 198 // size needed by the string. We only regrow when we absolutely must. 199 int sizeNeeded = destIndex + charsSkipped + escaped.length; 200 if (dest.length < sizeNeeded) { 201 int destLength = sizeNeeded + (end - index) + DEST_PAD; 202 dest = growBuffer(dest, destIndex, destLength); 203 } 204 // If we have skipped any characters, we need to copy them now. 205 if (charsSkipped > 0) { 206 s.getChars(unescapedChunkStart, index, dest, destIndex); 207 destIndex += charsSkipped; 208 } 209 if (escaped.length > 0) { 210 System.arraycopy(escaped, 0, dest, destIndex, escaped.length); 211 destIndex += escaped.length; 212 } 213 // If we dealt with an escaped character, reset the unescaped range. 214 unescapedChunkStart = nextIndex; 215 } 216 index = nextEscapeIndex(s, nextIndex, end); 217 } 218 219 // Process trailing unescaped characters - no need to account for escaped 220 // length or padding the allocation. 221 int charsSkipped = end - unescapedChunkStart; 222 if (charsSkipped > 0) { 223 int endIndex = destIndex + charsSkipped; 224 if (dest.length < endIndex) { 225 dest = growBuffer(dest, destIndex, endIndex); 226 } 227 s.getChars(unescapedChunkStart, end, dest, destIndex); 228 destIndex = endIndex; 229 } 230 return new String(dest, 0, destIndex); 231 } 232 233 /** 234 * Returns the Unicode code point of the character at the given index. 235 * 236 * <p>Unlike {@link Character#codePointAt(CharSequence, int)} or 237 * {@link String#codePointAt(int)} this method will never fail silently when 238 * encountering an invalid surrogate pair. 239 * 240 * <p>The behaviour of this method is as follows: 241 * <ol> 242 * <li>If {@code index >= end}, {@link IndexOutOfBoundsException} is thrown. 243 * <li><b>If the character at the specified index is not a surrogate, it is 244 * returned.</b> 245 * <li>If the first character was a high surrogate value, then an attempt is 246 * made to read the next character. 247 * <ol> 248 * <li><b>If the end of the sequence was reached, the negated value of 249 * the trailing high surrogate is returned.</b> 250 * <li><b>If the next character was a valid low surrogate, the code point 251 * value of the high/low surrogate pair is returned.</b> 252 * <li>If the next character was not a low surrogate value, then 253 * {@link IllegalArgumentException} is thrown. 254 * </ol> 255 * <li>If the first character was a low surrogate value, 256 * {@link IllegalArgumentException} is thrown. 257 * </ol> 258 * 259 * @param seq the sequence of characters from which to decode the code point 260 * @param index the index of the first character to decode 261 * @param end the index beyond the last valid character to decode 262 * @return the Unicode code point for the given index or the negated value of 263 * the trailing high surrogate character at the end of the sequence 264 */ 265 protected static int codePointAt(CharSequence seq, int index, int end) { 266 checkNotNull(seq); 267 if (index < end) { 268 char c1 = seq.charAt(index++); 269 if (c1 < Character.MIN_HIGH_SURROGATE || 270 c1 > Character.MAX_LOW_SURROGATE) { 271 // Fast path (first test is probably all we need to do) 272 return c1; 273 } else if (c1 <= Character.MAX_HIGH_SURROGATE) { 274 // If the high surrogate was the last character, return its inverse 275 if (index == end) { 276 return -c1; 277 } 278 // Otherwise look for the low surrogate following it 279 char c2 = seq.charAt(index); 280 if (Character.isLowSurrogate(c2)) { 281 return Character.toCodePoint(c1, c2); 282 } 283 throw new IllegalArgumentException( 284 "Expected low surrogate but got char '" + c2 + 285 "' with value " + (int) c2 + " at index " + index + 286 " in '" + seq + "'"); 287 } else { 288 throw new IllegalArgumentException( 289 "Unexpected low surrogate character '" + c1 + 290 "' with value " + (int) c1 + " at index " + (index - 1) + 291 " in '" + seq + "'"); 292 } 293 } 294 throw new IndexOutOfBoundsException("Index exceeds specified range"); 295 } 296 297 /** 298 * Helper method to grow the character buffer as needed, this only happens 299 * once in a while so it's ok if it's in a method call. If the index passed 300 * in is 0 then no copying will be done. 301 */ 302 private static char[] growBuffer(char[] dest, int index, int size) { 303 char[] copy = new char[size]; 304 if (index > 0) { 305 System.arraycopy(dest, 0, copy, 0, index); 306 } 307 return copy; 308 } 309}