    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 */
    017
    018package org.apache.commons.text.translate;
    019
    020import java.io.IOException;
    021import java.io.Writer;
    022import java.util.BitSet;
    023import java.util.HashMap;
    024import java.util.Map;
    025import java.util.Objects;
    026
    027/**
    028 * Translates a value using a lookup table.
    029 *
    030 * @since 1.0
    031 */
    032public class LookupTranslator extends CharSequenceTranslator {
    033
    034    /** The mapping to be used in translation. */
    035    private final Map<String, String> lookupMap;
    036    /** The first character of each key in the lookupMap. */
    037    private final BitSet prefixSet;
    038    /** The length of the shortest key in the lookupMap. */
    039    private final int shortest;
    040    /** The length of the longest key in the lookupMap. */
    041    private final int longest;
    042
    043    /**
    044     * Constructs the lookup table to be used in translation.
    045     *
    046     * Note that, as of Lang 3.1 (the origin of this code), the key to the lookup table is converted to a java.lang.String. This is because we need the key to
    047     * support hashCode and equals(Object), allowing it to be the key for a HashMap. See LANG-882.
    048     *
    049     * @param lookupMap Map&lt;CharSequence, CharSequence&gt; table of translator mappings, may not be null.
    050     */
    051    public LookupTranslator(final Map<CharSequence, CharSequence> lookupMap) {
    052        Objects.requireNonNull(lookupMap, "lookupMap");
    053        this.lookupMap = new HashMap<>();
    054        this.prefixSet = new BitSet();
    055        int currentShortest = Integer.MAX_VALUE;
    056        int currentLongest = 0;
    057        for (final Map.Entry<CharSequence, CharSequence> pair : lookupMap.entrySet()) {
    058            this.lookupMap.put(pair.getKey().toString(), pair.getValue().toString());
    059            this.prefixSet.set(pair.getKey().charAt(0));
    060            final int sz = pair.getKey().length();
    061            if (sz < currentShortest) {
    062                currentShortest = sz;
    063            }
    064            if (sz > currentLongest) {
    065                currentLongest = sz;
    066            }
    067        }
    068        this.shortest = currentShortest;
    069        this.longest = currentLongest;
    070    }
    071
    072    /**
    073     * {@inheritDoc}
    074     */
    075    @Override
    076    public int translate(final CharSequence input, final int index, final Writer writer) throws IOException {
    077        // check if translation exists for the input at position index
    078        if (prefixSet.get(input.charAt(index))) {
    079            int max = longest;
    080            if (index + longest > input.length()) {
    081                max = input.length() - index;
    082            }
    083            // implement greedy algorithm by trying maximum match first
    084            for (int i = max; i >= shortest; i--) {
    085                final CharSequence subSeq = input.subSequence(index, index + i);
    086                final String result = lookupMap.get(subSeq.toString());
    087                if (result != null) {
    088                    writer.write(result);
    089                    return Character.codePointCount(subSeq, 0, subSeq.length());
    090                }
    091            }
    092        }
    093        return 0;
    094    }
    095}