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