001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 * 
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 * 
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.lang3.text.translate;
018
019import java.io.IOException;
020import java.io.StringWriter;
021import java.io.Writer;
022import java.util.Locale;
023
024/**
025 * An API for translating text. 
026 * Its core use is to escape and unescape text. Because escaping and unescaping 
027 * is completely contextual, the API does not present two separate signatures.
028 * 
029 * @since 3.0
030 * @version $Id: CharSequenceTranslator.java 1666535 2015-03-13 18:18:59Z britter $
031 */
032public abstract class CharSequenceTranslator {
033
034    static final char[] HEX_DIGITS = new char[] {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
035
036    /**
037     * Translate a set of codepoints, represented by an int index into a CharSequence, 
038     * into another set of codepoints. The number of codepoints consumed must be returned, 
039     * and the only IOExceptions thrown must be from interacting with the Writer so that 
040     * the top level API may reliably ignore StringWriter IOExceptions. 
041     *
042     * @param input CharSequence that is being translated
043     * @param index int representing the current point of translation
044     * @param out Writer to translate the text to
045     * @return int count of codepoints consumed
046     * @throws IOException if and only if the Writer produces an IOException
047     */
048    public abstract int translate(CharSequence input, int index, Writer out) throws IOException;
049
050    /**
051     * Helper for non-Writer usage. 
052     * @param input CharSequence to be translated
053     * @return String output of translation
054     */
055    public final String translate(final CharSequence input) {
056        if (input == null) {
057            return null;
058        }
059        try {
060            final StringWriter writer = new StringWriter(input.length() * 2);
061            translate(input, writer);
062            return writer.toString();
063        } catch (final IOException ioe) {
064            // this should never ever happen while writing to a StringWriter
065            throw new RuntimeException(ioe);
066        }
067    }
068
069    /**
070     * Translate an input onto a Writer. This is intentionally final as its algorithm is 
071     * tightly coupled with the abstract method of this class. 
072     *
073     * @param input CharSequence that is being translated
074     * @param out Writer to translate the text to
075     * @throws IOException if and only if the Writer produces an IOException
076     */
077    public final void translate(final CharSequence input, final Writer out) throws IOException {
078        if (out == null) {
079            throw new IllegalArgumentException("The Writer must not be null");
080        }
081        if (input == null) {
082            return;
083        }
084        int pos = 0;
085        final int len = input.length();
086        while (pos < len) {
087            final int consumed = translate(input, pos, out);
088            if (consumed == 0) {
089                // inlined implementation of Character.toChars(Character.codePointAt(input, pos))
090                // avoids allocating temp char arrays and duplicate checks
091                char c1 = input.charAt(pos);
092                out.write(c1);
093                pos++;
094                if (Character.isHighSurrogate(c1) && pos < len) {
095                    char c2 = input.charAt(pos);
096                    if (Character.isLowSurrogate(c2)) {
097                      out.write(c2);
098                      pos++;
099                    }
100                }
101                continue;
102            }
103            // contract with translators is that they have to understand codepoints
104            // and they just took care of a surrogate pair
105            for (int pt = 0; pt < consumed; pt++) {
106                pos += Character.charCount(Character.codePointAt(input, pos));
107            }
108        }
109    }
110
111    /**
112     * Helper method to create a merger of this translator with another set of 
113     * translators. Useful in customizing the standard functionality.
114     *
115     * @param translators CharSequenceTranslator array of translators to merge with this one
116     * @return CharSequenceTranslator merging this translator with the others
117     */
118    public final CharSequenceTranslator with(final CharSequenceTranslator... translators) {
119        final CharSequenceTranslator[] newArray = new CharSequenceTranslator[translators.length + 1];
120        newArray[0] = this;
121        System.arraycopy(translators, 0, newArray, 1, translators.length);
122        return new AggregateTranslator(newArray);
123    }
124
125    /**
126     * <p>Returns an upper case hexadecimal <code>String</code> for the given
127     * character.</p>
128     *
129     * @param codepoint The codepoint to convert.
130     * @return An upper case hexadecimal <code>String</code>
131     */
132    public static String hex(final int codepoint) {
133        return Integer.toHexString(codepoint).toUpperCase(Locale.ENGLISH);
134    }
135
136}