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