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 */
031public abstract class CharSequenceTranslator {
032
033    static final char[] HEX_DIGITS = new char[] {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
034
035    /**
036     * Translate a set of codepoints, represented by an int index into a CharSequence, 
037     * into another set of codepoints. The number of codepoints consumed must be returned, 
038     * and the only IOExceptions thrown must be from interacting with the Writer so that 
039     * the top level API may reliably ignore StringWriter IOExceptions. 
040     *
041     * @param input CharSequence that is being translated
042     * @param index int representing the current point of translation
043     * @param out Writer to translate the text to
044     * @return int count of codepoints consumed
045     * @throws IOException if and only if the Writer produces an IOException
046     */
047    public abstract int translate(CharSequence input, int index, Writer out) throws IOException;
048
049    /**
050     * Helper for non-Writer usage. 
051     * @param input CharSequence to be translated
052     * @return String output of translation
053     */
054    public final String translate(final CharSequence input) {
055        if (input == null) {
056            return null;
057        }
058        try {
059            final StringWriter writer = new StringWriter(input.length() * 2);
060            translate(input, writer);
061            return writer.toString();
062        } catch (final IOException ioe) {
063            // this should never ever happen while writing to a StringWriter
064            throw new RuntimeException(ioe);
065        }
066    }
067
068    /**
069     * Translate an input onto a Writer. This is intentionally final as its algorithm is 
070     * tightly coupled with the abstract method of this class. 
071     *
072     * @param input CharSequence that is being translated
073     * @param out Writer to translate the text to
074     * @throws IOException if and only if the Writer produces an IOException
075     */
076    public final void translate(final CharSequence input, final Writer out) throws IOException {
077        if (out == null) {
078            throw new IllegalArgumentException("The Writer must not be null");
079        }
080        if (input == null) {
081            return;
082        }
083        int pos = 0;
084        final int len = input.length();
085        while (pos < len) {
086            final int consumed = translate(input, pos, out);
087            if (consumed == 0) {
088                // inlined implementation of Character.toChars(Character.codePointAt(input, pos))
089                // avoids allocating temp char arrays and duplicate checks
090                char c1 = input.charAt(pos);
091                out.write(c1);
092                pos++;
093                if (Character.isHighSurrogate(c1) && pos < len) {
094                    char c2 = input.charAt(pos);
095                    if (Character.isLowSurrogate(c2)) {
096                      out.write(c2);
097                      pos++;
098                    }
099                }
100                continue;
101            }
102            // contract with translators is that they have to understand codepoints
103            // and they just took care of a surrogate pair
104            for (int pt = 0; pt < consumed; pt++) {
105                pos += Character.charCount(Character.codePointAt(input, pos));
106            }
107        }
108    }
109
110    /**
111     * Helper method to create a merger of this translator with another set of 
112     * translators. Useful in customizing the standard functionality.
113     *
114     * @param translators CharSequenceTranslator array of translators to merge with this one
115     * @return CharSequenceTranslator merging this translator with the others
116     */
117    public final CharSequenceTranslator with(final CharSequenceTranslator... translators) {
118        final CharSequenceTranslator[] newArray = new CharSequenceTranslator[translators.length + 1];
119        newArray[0] = this;
120        System.arraycopy(translators, 0, newArray, 1, translators.length);
121        return new AggregateTranslator(newArray);
122    }
123
124    /**
125     * <p>Returns an upper case hexadecimal <code>String</code> for the given
126     * character.</p>
127     *
128     * @param codepoint The codepoint to convert.
129     * @return An upper case hexadecimal <code>String</code>
130     */
131    public static String hex(final int codepoint) {
132        return Integer.toHexString(codepoint).toUpperCase(Locale.ENGLISH);
133    }
134
135}